function handle(&$params) { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $formTool =& Dataface_FormTool::getInstance(); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $resultSet =& $app->getResultSet(); $currentRecord =& $app->getRecord(); $currentTable =& Dataface_Table::loadTable($query['-table']); if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) { $tabs = $currentTable->tabs($currentRecord); uasort($tabs, array($formTool, '_sortTabs')); list($query['--tab']) = array_keys($tabs); } else { if (count($currentTable->tabs($currentRecord)) <= 1) { unset($query['--tab']); } } $includedFields = null; // Null for all fields if (@$query['-fields']) { $includedFields = explode(' ', $query['-fields']); } /* * * Create the quickform for the current record. * */ //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query); if ($resultSet->found() > @$query['-cursor']) { $form = $formTool->createRecordForm($currentRecord, false, @$query['--tab'], $query, $includedFields); /* * There is either a result to edit, or we are creating a new record. * */ $res = $form->_build(); if (PEAR::isError($res)) { error_log($res->toString() . implode("\n", $res->getBacktrace())); throw new Exception("An error occurred while building the edit form. See error log for details.", E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, false, @$query['--tab']); /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($formTool->validateRecordForm($currentRecord, $form, false, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']); if (!isset($query['--tab'])) { // If we aren't using tabs we just do it the old way. // (If it ain't broke don't fix it $result = $form->process(array(&$form, 'save')); } else { // If we are using tabs, we will use the formtool's // session aware saving function $result = $formTool->saveSession($currentRecord); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace()); throw new Exception("An error occurred while attempting to save the record. See error log for details.", E_USER_ERROR); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { if (Dataface_Error::isDuplicateEntry($result)) { $app->addError($result); $success = false; } else { error_log($result->toString() . implode("\n", $result->getBacktrace())); throw new Exception("An error occurred while attempting to save the record. See error log for details.", E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage(); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: text/html; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); $rvals['__id__'] = $currentRecord->getId(); echo df_escape(json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved')))); return; } import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_edit', array('record' => $form->_record)); /* * * The original query string will have the -new flag set. We need to remove this * flag so that we don't redirect the user to create another new record. * */ $vals = $form->exportValues(); $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']); $_SESSION['--last_modified_record_url'] = $form->_record->getURL(); $_SESSION['--last_modified_record_title'] = $form->_record->getTitle(); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg); if (preg_match('/[&\\?]-action=edit&/', $vals['-query']) and !$form->_record->checkPermission('edit')) { $vals['-query'] = preg_replace('/([&\\?])-action=edit&/', '$1-action=view&', $vals['-query']); } else { if (preg_match('/[&\\?]-action=edit$/', $vals['-query']) and !$form->_record->checkPermission('edit')) { $vals['-query'] = preg_replace('/([&\\?])-action=edit$/', '$1-action=view', $vals['-query']); } } $vals['-query'] = preg_replace('/&?--msg=[^&]*/', '', $vals['-query']); if (@$query['--lang']) { $vals['-query'] .= '&--lang=' . $query['--lang']; } $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--saved=1&--msg=' . $msg; /* * * Redirect the user to the appropriate record. * */ $app->redirect("{$link}"); } } ob_start(); $form->display(); $out = ob_get_contents(); ob_end_clean(); if (count($form->_errors) > 0) { $app->clearMessages(); $app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>" . implode('</li><li>', $form->_errors) . "</li></ul>")); } $context = array('form' => $out); // Now let's add the tabs to the context $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); } else { // no records were found $context = array('form' => ''); if (isset($_SESSION['--last_modified_record_url'])) { $lastModifiedURL = $_SESSION['--last_modified_record_url']; $lastModifiedTitle = $_SESSION['--last_modified_record_title']; unset($_SESSION['--last_modified_record_title']); unset($_SESSION['--last_modified_record_url']); $app->addMessage(df_translate('Return to last modified record', 'No records matched your request. Click <a href="' . $lastModifiedURL . '">here</a> to return to <em>' . df_escape($lastModifiedTitle) . '</em>.', array('lastModifiedURL' => $lastModifiedURL, 'lastModifiedTitle' => $lastModifiedTitle))); } else { $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request')); } $query['-template'] = 'Dataface_Main_Template.html'; } if (isset($query['-template'])) { $template = $query['-template']; } else { if (@$query['-headless']) { $template = 'Dataface_Edit_Record_headless.html'; } else { if (isset($params['action']['template'])) { $template = $params['action']['template']; } else { $template = 'Dataface_Edit_Record.html'; } } } df_display($context, $template, true); }
function handle(&$params) { import('Dataface/TranslationForm.php'); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $resultSet =& $app->getResultSet(); $source = isset($_REQUEST['-sourceLanguage']) ? $_REQUEST['-sourceLanguage'] : $app->_conf['default_language']; $dest = isset($_REQUEST['-destinationLanguage']) ? $_REQUEST['-destinationLanguage'] : null; if ($resultSet->found() > 0) { $form = new Dataface_TranslationForm($query['-table'], $source, $dest); /* * There is either a result to edit, or we are creating a new record. * */ $res = $form->_build(); if (PEAR::isError($res)) { throw new Exception($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($form->validate()) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $result = $form->process(array(&$form, 'save')); $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace()); throw new Exception("Error occurred in save. See error log for details."); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { return $result; } else { //echo "not dup entry"; exit; throw new Exception($result->toString(), E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage(); $success = false; } } } if ($success) { /* * * The original query string will have the -new flag set. We need to remove this * flag so that we don't redirect the user to create another new record. * */ $vals = $form->exportValues(); $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully translated', "Record successfully translated.<br>") . $msg); $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--msg=' . $msg; /* * * Redirect the user to the appropriate record. * */ $app->redirect($link); } } ob_start(); $form->display(); $out = ob_get_contents(); ob_end_clean(); $context = array('form' => $out, 'formObj' => $form); } else { // no records were found $context = array('form' => '', 'formObj' => $form); $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request')); } if (isset($query['-template'])) { $template = $query['-template']; } else { if (isset($params['action']['template'])) { $template = $params['action']['template']; } else { $template = 'Dataface_Translate_Record.html'; } } df_display($context, $template, true); }
function handle(&$params) { $app = Dataface_Application::getInstance(); header('Content-type: text/html; charset=' . $app->_conf['oe']); $record =& $app->getRecord(); $query =& $app->getQuery(); if (isset($_REQUEST['-form-id'])) { $formid = $_REQUEST['-form-id']; } else { $formid = 'ajax-form-' . rand(); } // First let's figure out what kind of form this is $form_type = @$_REQUEST['-form-type']; $form = null; if (isset($_REQUEST['-fields'])) { $fields = explode(',', $_REQUEST['-fields']); } else { $fields = null; } switch ($form_type) { case 'new': $form = df_create_new_record_form($query['-table'], $fields); $form->_build(); break; case 'edit': $form = df_create_edit_record_form($query['-table'], $fields); break; case 'new_related_record': $form = df_create_new_related_record_form($record, $query['-relationship'], $fields); break; case 'existing_related_record': $form = df_create_existing_related_record_form($record, $query['-relationship']); break; case 'composite': import('Dataface/CompositeForm.php'); $form = new Dataface_CompositeForm($fields); $form->build(); break; default: @(include_once 'forms/' . $form_type . '.php'); if (!class_exists('forms_' . $form_type)) { return PEAR::raiseError('Could not find form of type "' . $form_type . '".', DATAFACE_E_ERROR); } $classname = 'forms_' . $form_type; $form = new $classname($fields); break; } // We want the form to be submitted to the embedded iframe $form->updateAttributes(array('target' => $formid . '-target', 'accept-charset' => $app->_conf['ie'])); $formparams = preg_grep('/^-[^\\-].*/', array_keys($query)); foreach ($formparams as $param) { $form->addElement('hidden', $param); $form->setDefaults(array($param => $query[$param])); } $form->addElement('hidden', '-form-id'); $form->setDefaults(array('-form-id' => $formid)); // Now that we have our form, we can do our thing with it. if ($form->validate()) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $result = $form->process(array(&$form, 'save')); $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { trigger_error("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { if (Dataface_Error::isDuplicateEntry($result)) { return $result; } else { trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_ajax_form'); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg); // We need to output the success content. // This could be in any of the following formats: // 1. HTML --- actually not yet.. let's just do JSON // 2. JSON // 3. XML --- not yet.. just JSON for now. $targetid = @$_REQUEST['-target-id']; // This should: // 1. Get the target element. // 2. Go through the element's subtree and replace // values that have been changed. How do we know what // values have been changed. // if (method_exists($form, 'htmlValues')) { if (method_exists($form, 'changedFields')) { $changed_fields = $form->changedFields(); } else { $changed_fields = null; } // Convert the values to JSON $changed_values = $form->htmlValues($changed_fields); import('Services/JSON.php'); $json = new Services_JSON(); $changed_values_json = $json->encode($changed_values); } else { $changed_values_json = '{}'; } echo <<<END <html><body><script language="javascript"><!-- \t \t//self.onload = function(){ \t\t//parent.handleEditableResponse('{$targetid}', {$changed_values_json}); \t\tvar targetel = parent.document.getElementById('{$targetid}'); \t\ttargetel.handleResponse('{$targetid}', {$changed_values_json}); \t\ttargetel.onclick=parent.makeEditable; \t\ttargetel.onmouseover=targetel.old_onmouseover; \t\ttargetel.edit_form.parentNode.removeChild(targetel.edit_form); \t \t//} \t \t //--></script></body></html> END; exit; } } import('Dataface/FormTool.php'); $formTool = new Dataface_FormTool(); ob_start(); if (is_array($fields) and count($fields) == 1 and strpos($fields[0], '#') !== false) { $singleField = $fields[0]; } else { $singleField = false; } $formTool->display($form, null, $singleField); $out = ob_get_contents(); ob_end_clean(); echo <<<END \t\t \t\t<div id="{$formid}-wrapper"> \t\t\t<iframe id="{$formid}-target" name="{$formid}-target" style="width:0px; height:0px; border: 0px"></iframe> \t\t\t{$out} \t\t</div> END; if ($form->isSubmitted()) { // The form has already been submitted so we must be displaying some // errors. We need to remove this stuff from inside the iframe // that we are going to be inside of, and place them on the page // in the correct place echo <<<END <script language="javascript"><!-- var targetel = parent.document.getElementById('{$formid}-wrapper'); var sourceel = document.getElementById('{$formid}-wrapper'); targetel.innerHTML = sourceel.innerHTML; //--></script> END; } exit; }
function save($values) { // First let's find out if we should SAVE the data or if we should just be // storing it in the session or if we are saving the data to the database if (!$this->_new) { // Make sure that the correct form is being submitted. if (!isset($values['__keys__'])) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } if (array_keys($values['__keys__']) != array_keys($this->_table->keys())) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } } if ($this->_new) { $this->_record->clearValues(); } $res = $this->push(); if (!$this->_new) { if ($this->_record->snapshotExists()) { $tempRecord = new Dataface_Record($this->_record->_table->tablename, $this->_record->getSnapshot()); } else { $tempRecord =& $this->_record; } if ($values['__keys__'] != $tempRecord->strvals(array_keys($this->_record->_table->keys()))) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } } if (PEAR::isError($res)) { $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_PUSHING_DATA', "Error pushing data from form onto table in QuickForm::save() ", array('line' => 0, 'file' => "_"))); return $res; } // Let's take an inventory of which fields were changed.. because // we are going to make their values available in the htmlValues() // method which is used by the ajax form to gather updates. foreach ($this->_fields as $changedfield) { if ($this->_record->valueChanged($changedfield['name'])) { $this->_changed_fields[] = $changedfield['name']; } } $io = new Dataface_IO($this->tablename, $this->db); $io->lang = $this->_lang; if ($this->_new) { $keys = null; } else { $keys = $values['__keys__']; } $res = $io->write($this->_record, $keys, null, true, $this->_new); if (PEAR::isError($res)) { if (Dataface_Error::isDuplicateEntry($res)) { /* * If this is a duplicate entry (or just a notice - not fatal), we will propogate the exception up to let the application * decide what to do with it. */ return $res; } if (Dataface_Error::isNotice($res)) { return $res; } $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving form in QuickForm::save()", array('line' => 0, 'file' => "_"))); throw new Exception($res->toString(), E_USER_ERROR); } if (isset($io->insertIds[$this->tablename]) and $this->_table->getAutoIncrementField()) { $this->_record->setValue($this->_table->getAutoIncrementField(), $io->insertIds[$this->tablename]); $this->_record->setSnapshot(); } return true; }
function handle() { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $formTool =& Dataface_FormTool::getInstance(); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $new = true; $includedFields = null; // Null for all fields if (@$query['-fields']) { $includedFields = explode(' ', $query['-fields']); } $currentRecord = new Dataface_Record($query['-table'], array()); $currentTable =& Dataface_Table::loadTable($query['-table']); $app->setPageTitle(df_translate('actions.new.label', 'New ' . $currentTable->getSingularLabel(), array('tableObj' => $currentTable))); if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) { $tabs = $currentTable->tabs($currentRecord); uasort($tabs, array($formTool, '_sortTabs')); list($query['--tab']) = array_keys($tabs); } else { if (count($currentTable->tabs($currentRecord)) <= 1) { unset($query['--tab']); } } $form = $formTool->createRecordForm($currentRecord, true, @$query['--tab'], $query, $includedFields); //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query, '',$new); $res = $form->_build(); if (PEAR::isError($res)) { error_log($res->toString() . Dataface_Error::printStackTrace()); throw new Exception("Error occurred while building the new record form. See error log for details.", E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, true, @$query['--tab']); /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($formTool->validateRecordForm($currentRecord, $form, true, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']); if (!isset($query['--tab'])) { // If we aren't using tabs we just do it the old way. // (If it ain't broke don't fix it $result = $form->process(array(&$form, 'save')); } else { // If we are using tabs, we will use the formtool's // session aware saving function $result = $formTool->saveSession($currentRecord, true); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { throw new Exception("Error occurred in save: " . xf_db_error($app->db()), E_USER_ERROR); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { $success = false; $form->_errors[] = $result->getMessage(); } else { //echo "not dup entry"; exit; error_log($result->toString() . "\n" . implode("\n", $result->getBacktrace())); throw new Exception("An error occurred while attempting to save the record. See server error log for details.", E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: application/json; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); $rvals['__id__'] = $currentRecord->getId(); echo json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved'))); return; } import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_new', array('record' => $currentRecord)); /* * * Since the form created a new record, then it makes more sense to redirect to this newly * created record than to the old record. We used the 'keys' of the new record to generate * a redirect link. * */ //$query = $form->_record->getValues(array_keys($form->_record->_table->keys())); $currentRecord->secureDisplay = false; if ($currentRecord->checkPermission('edit')) { $nextAction = 'edit'; } else { $nextAction = 'view'; } $urlParams = array('-action' => $nextAction); // Some parameters we'll want to pass to our edit action // so that the edit form is consistent with the display // of the new form. E.g. if the form was headless or // has only particular fields, then the edit form should // include the same fields and also be headless. $passedParams = array('-fields', '-headless', '-xf-hide-fields'); foreach ($passedParams as $passedParam) { if (@$query[$passedParam]) { $urlParams[$passedParam] = $query[$passedParam]; } } $url = $currentRecord->getURL($urlParams); if (@$query['--lang']) { $url .= '&--lang=' . $query['--lang']; } //echo $url;exit; $msg = implode("\n", $app->getMessages()); //@$response['--msg']; $msg = urlencode(trim(Dataface_LanguageTool::translate("Record successfully saved", "Record successfully saved.") . "\n" . $msg)); if (strpos($url, '?') === false) { $url .= '?'; } $link = $url . '&--saved=1&--msg=' . $msg; //echo "$link";exit; $app->redirect("{$link}"); } else { $app->addHeadContent('<meta id="quickform-error" name="quickform-error" value="Save failed"/>'); } } ob_start(); $form->setDefaults($_GET); $form->display(); $out = ob_get_contents(); ob_end_clean(); if (count($form->_errors) > 0) { //$app->clearMessages(); //$app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>".implode('</li><li>', $form->_errors)."</li></ul>")); } $context = array('form' => &$out); $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); if (isset($query['-template'])) { $template = $query['-template']; } else { if (@$query['-headless']) { $template = 'Dataface_New_Record_headless.html'; } else { $template = 'Dataface_New_Record.html'; } } df_display($context, $template, true); }
function handle() { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $new = true; $currentRecord = new Dataface_Record($query['-table'], array()); $currentTable =& Dataface_Table::loadTable($query['-table']); if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) { list($query['--tab']) = array_keys($currentTable->tabs($currentRecord)); } else { if (count($currentTable->tabs($currentRecord)) <= 1) { unset($query['--tab']); } } $formTool =& Dataface_FormTool::getInstance(); $form = $formTool->createRecordForm($currentRecord, true, @$query['--tab'], $query); //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query, '',$new); $res = $form->_build(); if (PEAR::isError($res)) { trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, true, @$query['--tab']); /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($formTool->validateRecordForm($currentRecord, $form, true, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']); if (!isset($query['--tab'])) { // If we aren't using tabs we just do it the old way. // (If it ain't broke don't fix it $result = $form->process(array(&$form, 'save')); } else { // If we are using tabs, we will use the formtool's // session aware saving function $result = $formTool->saveSession($currentRecord, true); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { trigger_error("Error occurred in save: " . mysql_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { $success = false; $form->_errors[] = $result->getMessage(); } else { //echo "not dup entry"; exit; trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: text/json; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); echo json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved'))); exit; } import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_new', array('record' => $currentRecord)); /* * * Since the form created a new record, then it makes more sense to redirect to this newly * created record than to the old record. We used the 'keys' of the new record to generate * a redirect link. * */ //$query = $form->_record->getValues(array_keys($form->_record->_table->keys())); $currentRecord->secureDisplay = false; if ($currentRecord->checkPermission('edit')) { $nextAction = 'edit'; } else { $nextAction = 'view'; } $url = $currentRecord->getURL(array('-action' => $nextAction)); $msg = implode("\n", $app->getMessages()); //@$response['--msg']; $msg = urlencode(trim(Dataface_LanguageTool::translate("Record successfully saved", "Record successfully saved.") . "\n" . $msg)); if (strpos($url, '?') === false) { $url .= '?'; } $link = $url . '&--msg=' . $msg; header("Location: {$link}"); exit; } } ob_start(); $form->setDefaults($_GET); $form->display(); $out = ob_get_contents(); ob_end_clean(); if (count($form->_errors) > 0) { $app->clearMessages(); $app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>" . implode('</li><li>', $form->_errors) . "</li></ul>")); } $context = array('form' => &$out); $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); df_display($context, 'Dataface_New_Record.html', true); }
/** * Writes the values in the table to the database. * * @param tablename An optional tablename in case this record is not being placed in * the standard table. For example, the record could be placed into an import * table. * @param array $keys Optional array of keys to look up record to write to. * @param string $tablename The name of the table to write to, if not this table. * This is useful for writing to import tables or other * tables with identical schema. * @param boolean $secure Whether to check permissions or not. */ function write(&$record, $keys = null, $tablename = null, $secure = false) { // The vetoSecurity flag allows us to make changes to a record without // the fields being filtered for security checks when they are saved. // Since we may want to change or add values to a record in the // beforeSave type triggers, and we probably don't want these changes // checked by security, we should use this flag to make all changes // in these triggers immune to security checks. // We return the veto setting to its former state after this method // finishes. //$oldVeto = $record->vetoSecurity; //$record->vetoSecurity = true; //$parentRecord =& $record->getParentRecord(); $app =& Dataface_Application::getInstance(); //$parentIO =& $this->getParentIO(); if (!is_a($record, "Dataface_Record")) { trigger_error(df_translate('scripts.Dataface.IO.write.ERROR_PARAMETER_1', "Dataface_IO::write() requires first parameter to be of type 'Dataface_Record' but received '" . get_class($record) . "\n<br>", array('class' => get_class($record))) . Dataface_Error::printStackTrace(), E_USER_ERROR); } if ($tablename === null and $this->_altTablename !== null) { $tablename = $this->_altTablename; } if ($this->fireTriggers) { $res = $this->fireBeforeSave($record); if (PEAR::isError($res)) { //$record->vetoSecurity = $oldVeto; return $res; } } if ($this->recordExists($record, $keys, $this->tablename($tablename))) { $res = $this->_update($record, $keys, $this->tablename($tablename), $secure); } else { $res = $this->_insert($record, $this->tablename($tablename), $secure); } if (PEAR::isError($res)) { if (Dataface_Error::isDuplicateEntry($res)) { /* * Duplicate entries we will propogate up so that the application can decide what to do. */ //$record->vetoSecurity = $oldVeto; return $res; } $res->addUserInfo(df_translate('scripts.Dataface.IO.write.ERROR_SAVING', "Error while saving record of table '" . $this->_table->tablename . "' in Dataface_IO::write() on line " . __LINE__ . " of file " . __FILE__, array('tablename' => $this->_table->tablename, 'line' => __LINE__, 'file' => __FILE__))); //$record->vetoSecurity = $oldVeto; return $res; } // Now we take care of the transient relationship fields. // Transient relationship fields aren't actually stored in the record // itself, they are stored as related records. foreach ($record->_table->transientFields() as $tfield) { if (!isset($tfield['relationship'])) { continue; } if (!$record->valueChanged($tfield['name'])) { continue; } $trelationship =& $record->_table->getRelationship($tfield['relationship']); if (!$trelationship or PEAR::isError($trelationship)) { // We couldn't find the specified relationship. //$record->vetoSecurity = $oldVeto; return $trelationship; } $orderCol = $trelationship->getOrderColumn(); if (PEAR::isError($orderCol)) { $orderCol = null; } $tval = $record->getValue($tfield['name']); if ($tfield['widget']['type'] == 'grid') { //echo "here";exit; $tval_existing = array(); $tval_new = array(); $tval_new_existing = array(); $torder = 0; foreach ($tval as $trow) { $trow['__order__'] = $torder++; if (isset($trow['__id__']) and preg_match('/^new:/', $trow['__id__'])) { $tval_new_existing[] = $trow; } else { if (isset($trow['__id__']) and $trow['__id__'] != 'new') { $tval_existing[$trow['__id__']] = $trow; } else { if (isset($trow['__id__']) and $trow['__id__'] == 'new') { $tval_new[] = $trow; } } } } // The transient field was loaded so we can go about saving the // changes/ $trecords =& $record->getRelatedRecordObjects($tfield['relationship'], 'all'); if (!is_array($trecords) or PEAR::isError($trecords)) { error_log('Failed to get related records for record ' . $record->getId() . ' in its relationship ' . $tfield['relationship']); unset($tval); unset($orderCol); unset($tval_new); unset($torder); unset($trelationship); unset($tval_existing); continue; } // Update the existing records in the relationship. // We use the __id__ parameter in each row for this. //echo "About to save related records"; foreach ($trecords as $trec) { $tid = $trec->getId(); if (isset($tval_existing[$tid])) { $tmp = new Dataface_RelatedRecord($trec->_record, $tfield['relationship'], $trec->getValues()); $tmp->setValues($tval_existing[$tid]); $changed = false; foreach ($tval_existing[$tid] as $k1 => $v1) { if ($tmp->isDirty($k1)) { $changed = true; break; } } if ($changed) { $trec->setValues($tval_existing[$tid]); if ($orderCol) { $trec->setValue($orderCol, $tval_existing[$tid]['__order__']); } //echo "Saving ";print_r($trec->vals()); $res_t = $trec->save($this->lang, $secure); if (PEAR::isError($res_t)) { return $res_t; error_log('Failed to save related record ' . $trec->getId() . ' while saving transient field ' . $tfield['name'] . ' in record ' . $record->getId() . '. The error returned was : ' . $res_t->getMessage()); } } else { if ($orderCol and $record->checkPermission('reorder_related_records', array('relationship' => $tfield['relationship']))) { $trec->setValue($orderCol, $tval_existing[$tid]['__order__']); $res_t = $trec->save($this->lang, false); // we don't need this to be secure if (PEAR::isError($res_t)) { return $res_t; error_log('Failed to save related record ' . $trec->getId() . ' while saving transient field ' . $tfield['name'] . ' in record ' . $record->getId() . '. The error returned was : ' . $res_t->getMessage()); } } } unset($tmp); } else { } unset($trec); unset($tid); unset($res_t); } //exit; // Now add new records (specified by __id__ field being 'new' foreach ($tval_new as $tval_to_add) { $temp_rrecord = new Dataface_RelatedRecord($record, $tfield['relationship'], array()); $temp_rrecord->setValues($tval_to_add); if ($orderCol) { $temp_rrecord->setValue($orderCol, $tval_to_add['__order__']); } $res_t = $this->addRelatedRecord($temp_rrecord, $secure); if (PEAR::isError($res_t)) { error_log('Failed to save related record ' . $temp_rrecord->getId() . ' while saving transient field ' . $tfield['name'] . ' in record ' . $record->getId() . '. The error returned was : ' . $res_t->getMessage()); } unset($temp_rrecord); unset($res_t); } // Now add new existing records (specified by __id__ field being 'new:<recordid>' foreach ($tval_new_existing as $tval_to_add) { $tid = preg_replace('/^new:/', '', $tval_to_add['__id__']); $temp_record = df_get_record_by_id($tid); if (PEAR::isError($temp_record)) { return $temp_record; } if (!$temp_record) { return PEAR::raiseError("Failed to load existing record with ID {$tid}."); } $temp_rrecord = new Dataface_RelatedRecord($record, $tfield['relationship'], $temp_record->vals()); $temp_rrecord->setValues($tval_to_add); if ($orderCol) { $temp_rrecord->setValue($orderCol, $tval_to_add['__order__']); } $res_t = $this->addExistingRelatedRecord($temp_rrecord, $secure); if (PEAR::isError($res_t)) { error_log('Failed to save related record ' . $temp_rrecord->getId() . ' while saving transient field ' . $tfield['name'] . ' in record ' . $record->getId() . '. The error returned was : ' . $res_t->getMessage()); } unset($temp_rrecord); unset($res_t); } // Now we delete the records that were deleted // we use the __deleted__ field. if (isset($tval['__deleted__']) and is_array($tval['__deleted__']) and $trelationship->supportsRemove()) { $tdelete_record = $trelationship->isOneToMany(); foreach ($tval['__deleted__'] as $del_id) { if ($del_id == 'new') { continue; } $drec = Dataface_IO::getByID($del_id); if (PEAR::isError($drec) or !$drec) { unset($drec); continue; } $this->removeRelatedRecord($drec, $tdelete_record, $secure); unset($drec); } } unset($trecords); } else { if ($tfield['widget']['type'] == 'checkbox') { // Load existing records in the relationship $texisting =& $record->getRelatedRecordObjects($tfield['relationship'], 'all'); if (!is_array($texisting) or PEAR::isError($texisting)) { error_log('Failed to get related records for record ' . $record->getId() . ' in its relationship ' . $tfield['relationship']); unset($tval); unset($orderCol); unset($tval_new); unset($torder); unset($trelationship); unset($tval_existing); continue; } $texistingIds = array(); foreach ($texisting as $terec) { $texistingIds[] = $terec->getId(); } // Load currently checked records $tchecked = array(); $tcheckedRecords = array(); $tcheckedIds = array(); $tcheckedId2ValsMap = array(); foreach ($tval as $trkey => $trval) { // $trval is in the form key1=val1&size=key2=val2 parse_str($trval, $trquery); $trRecord = new Dataface_RelatedRecord($record, $tfield['relationship'], $trquery); $trRecords[] =& $trRecord; $tcheckedIds[] = $tid = $trRecord->getId(); $checkedId2ValsMap[$tid] = $trquery; unset($trRecord); unset($trquery); } // Now we have existing ids in $texistingIds // and checked ids in $tcheckedIds // See which records we need to have removed $tremoves = array_diff($texistingIds, $tcheckedIds); $tadds = array_diff($tcheckedIds, $texistingIds); foreach ($tremoves as $tid) { $trec = df_get_record_by_id($tid); $res = $this->removeRelatedRecord($trec, false, $secure); if (PEAR::isError($res)) { return $res; } unset($trec); } foreach ($tadds as $tid) { $trecvals = $checkedId2ValsMap[$tid]; $trec = new Dataface_RelatedRecord($record, $tfield['relationship'], $trecvals); $res = $this->addExistingRelatedRecord($trec, $secure); if (PEAR::isError($res)) { return $res; } unset($trec, $trecvals); } unset($tadds); unset($tremoves); unset($tcheckedIds, $tcheckedId2ValsMap); unset($tcheckedRecords); unset($tchecked); unset($texistingIds); unset($texisting); } } unset($tval); unset($trelationship); } if ($this->fireTriggers) { $res2 = $this->fireAfterSave($record); if (PEAR::isError($res2)) { //$record->vetoSecurity = $oldVeto; return $res2; } } if (isset($app->_conf['history']) and @$app->_conf['history']['enabled'] || !isset($app->_conf['history']['enabled'])) { // History is enabled ... let's save this record in our history. import('Dataface/HistoryTool.php'); $historyTool = new Dataface_HistoryTool(); $historyTool->logRecord($record, $this->getHistoryComments($record), $this->lang); } if (isset($app->_conf['_index']) and @$app->_conf['_index'][$record->table()->tablename]) { // If indexing is enabled, we index the record so that it is // searchable by natural language searching. // The Dataface_Index class takes care of whether or not this // record should be indexed. import('Dataface/Index.php'); $index = new Dataface_Index(); $index->indexRecord($record); } // It seems to me that we should be setting a new snapshot at this point. //$record->clearSnapshot(); $record->setSnapshot(); self::touchTable($this->_table->tablename); //$record->vetoSecurity = $oldVeto; return $res; }
/** * * Initialization for the browse action. This method is called before any html is output * to the browser. It handles form creation and validation. * */ function _browse_init() { import('Dataface/QuickForm.php'); /* * * If we are not creating a new record, then we'll record this as the last * valid page visited. This will be useful for forwarding to the last page * visited when the form is validated. * */ if (!isset($this->_params['new'])) { setcookie('dataface_lastpage', $_SERVER['QUERY_STRING']); } /* * * Default functionality ('-relationship' flag is not set) is to show or validate * the quickform. If the -new flag is specified, it overrides the -relationship flag. * */ if (!isset($this->_params['relationship']) or isset($this->_params['new'])) { $new = (isset($this->_params['new']) and $this->_params['new']); /* * * Create the quickform for the current record. * */ $form = new Dataface_QuickForm($this->_tablename, $this->_db, $this->_query, '', $new); if ($this->_resultSet->found() > 0 or $new) { /* * There is either a result to edit, or we are creating a new record. * */ $res = $form->_build(); if (PEAR::isError($res)) { trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($this->_query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $this->_currentAction, '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($form->validate()) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $result = $form->process(array(&$form, 'save')); $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { trigger_error("Error occurred in save: " . mysql_error($this->_db) . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { //echo "dup entry"; exit; $query = array('-action' => 'error'); $response =& Dataface_Application::getResponse(); $msg = @$response['--msg']; $msg = urlencode(trim("Failed to save record because another record with the same keys already exists.\n" . $msg)); $link = Dataface_LinkTool::buildLink($query, false) . '&--msg=' . $msg; header('Location: ' . $link); exit; } else { //echo "not dup entry"; exit; trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } } else { if (Dataface_Error::isNotice($result)) { $response['--msg'] = @$response['--msg'] . "\n" . $result->getMessage(); $success = false; } } } if ($new) { /* * * If the form created a new record, then it makes more sense to redirect to this newly * created record than to the old record. We used the 'keys' of the new record to generate * a redirect link. * */ $query = $form->_record->getValues(array_keys($form->_record->_table->keys())); $msg = @$response['--msg']; $msg = urlencode(trim(($success ? "Record successfully saved.\n" : '') . $msg)); $link = Dataface_LinkTool::buildLink($query, false) . '&--msg=' . $msg; } else { /* * * The original query string will have the -new flag set. We need to remove this * flag so that we don't redirect the user to create another new record. * */ $vals = $form->exportValues(); $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']); $msg = @$response['--msg']; $msg = urlencode(trim(($success ? "Record successfully saved.\n" : '') . $msg)); $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--msg=' . $msg; } /* * * Redirect the user to the appropriate record. * */ header("Location: {$link}"); exit; } } $this->_vars['form'] =& $form; } }
/** * Writes the values in the table to the database. * * @param tablename An optional tablename in case this record is not being placed in * the standard table. For example, the record could be placed into an import * table. * @param array $keys Optional array of keys to look up record to write to. * @param string $tablename The name of the table to write to, if not this table. * This is useful for writing to import tables or other * tables with identical schema. * @param boolean $secure Whether to check permissions or not. * @param boolean $forceNew If true, it forces an insert rather than an update. */ function write(&$record, $keys = null, $tablename = null, $secure = false, $forceNew = false) { // The vetoSecurity flag allows us to make changes to a record without // the fields being filtered for security checks when they are saved. // Since we may want to change or add values to a record in the // beforeSave type triggers, and we probably don't want these changes // checked by security, we should use this flag to make all changes // in these triggers immune to security checks. // We return the veto setting to its former state after this method // finishes. //$oldVeto = $record->vetoSecurity; //$record->vetoSecurity = true; //$parentRecord =& $record->getParentRecord(); $app =& Dataface_Application::getInstance(); //$parentIO =& $this->getParentIO(); if (!is_a($record, "Dataface_Record")) { throw new Exception(df_translate('scripts.Dataface.IO.write.ERROR_PARAMETER_1', "Dataface_IO::write() requires first parameter to be of type 'Dataface_Record' but received '" . get_class($record) . "\n<br>", array('class' => get_class($record))), E_USER_ERROR); } if ($tablename === null and $this->_altTablename !== null) { $tablename = $this->_altTablename; } if ($this->fireTriggers) { $res = $this->fireBeforeSave($record); if (PEAR::isError($res)) { //$record->vetoSecurity = $oldVeto; return $res; } } if (!$forceNew and $this->recordExists($record, $keys, $this->tablename($tablename))) { $res = $this->_update($record, $keys, $this->tablename($tablename), $secure); } else { $res = $this->_insert($record, $this->tablename($tablename), $secure); } if (PEAR::isError($res)) { if (Dataface_Error::isDuplicateEntry($res)) { /* * Duplicate entries we will propogate up so that the application can decide what to do. */ //$record->vetoSecurity = $oldVeto; return $res; } $res->addUserInfo(df_translate('scripts.Dataface.IO.write.ERROR_SAVING', "Error while saving record of table '" . $this->_table->tablename . "' in Dataface_IO::write() ", array('tablename' => $this->_table->tablename, 'line' => 0, 'file' => '_'))); //$record->vetoSecurity = $oldVeto; return $res; } $res = $this->saveTransients($record, $keys, $tablename, $secure); if (PEAR::isError($res)) { return $res; } if ($this->fireTriggers) { $res2 = $this->fireAfterSave($record); if (PEAR::isError($res2)) { //$record->vetoSecurity = $oldVeto; return $res2; } } if (isset($app->_conf['history']) and @$app->_conf['history']['enabled'] || !isset($app->_conf['history']['enabled'])) { // History is enabled ... let's save this record in our history. import('Dataface/HistoryTool.php'); $historyTool = new Dataface_HistoryTool(); $historyTool->logRecord($record, $this->getHistoryComments($record), $this->lang); } if (isset($app->_conf['_index']) and @$app->_conf['_index'][$record->table()->tablename]) { // If indexing is enabled, we index the record so that it is // searchable by natural language searching. // The Dataface_Index class takes care of whether or not this // record should be indexed. import('Dataface/Index.php'); $index = new Dataface_Index(); $index->indexRecord($record); } // It seems to me that we should be setting a new snapshot at this point. //$record->clearSnapshot(); $record->setSnapshot(); self::touchTable($this->_table->tablename); self::touchRecord($record); //$record->vetoSecurity = $oldVeto; return $res; }