Beispiel #1
0
 /**
  *
  * Builds the form. (Ie: adds all of the fields, sets the default values, etc..)
  *
  */
 function _build()
 {
     if ($this->_isBuilt) {
         /*
          *
          * We only need to build the form once.  If it is already build, just return.
          *
          */
         return;
     }
     /*
      * Now to figure out which fields will be displayed on the form.
      */
     if ($this->_fieldnames === null or !is_array($this->_fieldnames) or count($this->_fieldnames) == 0) {
         /*
          * No fieldnames were explicitly provided (or they were improperly provided
          * so we use all of the fields in the table.
          */
         // if ( isset( $query['--tab'] ) and !$new ){
         // 	$flds =& $this->_table->fields(true);
         // 	$this->_fieldnames = array_keys($flds[$query['--tab']]);
         // } else {
         $this->_fieldnames = array();
         foreach ($this->_fields as $field) {
             if (isset($this->tab) and $this->tab != @$field['tab']) {
                 continue;
             }
             // If we are using tabs, and this field isn't in the current tab, then
             // we skip it.
             $this->_fieldnames[] = $field['name'];
             //$this->_fieldnames = array_keys($this->_fields);
         }
         //}
     }
     $this->_isBuilt = true;
     // set flag to indicate that the form has already been built.
     if (!$this->_record || !is_a($this->_record, 'Dataface_Record')) {
         return PEAR::raiseError(Dataface_LanguageTool::translate('Cannot build quickform with no record', 'Attempt to build quickform with no record set.'), E_USER_ERROR);
     }
     $relationships =& $this->_table->relationships();
     // reference to relationship descriptors for this table.
     $formTool =& Dataface_FormTool::getInstance();
     $groups = $formTool->groupFields($this->_fields);
     foreach ($groups as $sectionName => $fields) {
         unset($group);
         $group =& $this->_record->_table->getFieldgroup($sectionName);
         if (PEAR::isError($group)) {
             unset($group);
             $group = array('label' => df_translate('scripts.Dataface_QuickForm.LABEL_EDIT_DETAILS', 'Edit Details'), 'order' => 1);
         }
         $groupEmpty = true;
         // A flag to check when the group has at least one element
         if (!$fields) {
             continue;
         }
         foreach ($fields as $field) {
             if (!in_array($field['name'], $this->_fieldnames)) {
                 continue;
             }
             //if ( isset($this->tab) and ($this->tab != @$field['tab']) and ($this->tab != @$group['tab']) ) continue;
             // If we are using tabs, and this field isn't in the current tab, then
             // we skip it.
             $name = $field['name'];
             // reference to field descriptor array.
             $widget =& $field['widget'];
             // reference to widget descriptor array
             $vocabulary = $field['vocabulary'];
             // reference to field's vocabulary
             /*
              * 
              * If the user does not have permission to view this field, we should not generate this widget.
              *
              */
             if (!Dataface_PermissionsTool::view($this->_record, array('field' => $name)) and !($this->_new and Dataface_PermissionsTool::checkPermission('new', $this->_record->getPermissions(array('field' => $name))))) {
                 unset($widget);
                 continue;
             }
             if ($groupEmpty) {
                 // This is the first field in the group, so we add a header for the
                 // group.
                 $headerel =& $this->addElement('header', $group['label'], $group['label']);
                 $headerel->setFieldDef($group);
                 unset($headerel);
                 $groupEmpty = false;
             }
             /*
              *
              * Build the widget for this field.  Note that we pass the permissions array
              * to the method to help it know which widget to build.
              *
              */
             $el = $this->_buildWidget($field, $this->_record->getPermissions(array('field' => $name)));
             if (PEAR::isError($el)) {
                 $el->addUserInfo(df_translate('scripts.Dataface.QuickForm._build.ERROR_FAILED_TO_BUILD_WIDGET', "Failed to build widget for field {$name} ", array('name' => $name, 'line' => 0, 'file' => '_')));
                 return $el;
             }
             //$this->addElement($el);
             unset($field);
             unset($el);
             unset($widget);
         }
     }
     // end foreach $groups
     /*
      *
      * We need to add elements to the form to specifically store the keys for the current
      * record.  These elements should not be changeable by the user as they are used upon 
      * submission to find out which record is currently being updated.  We will store
      * the keys for this record in a group of hidden fields where a key named "ID" would 
      * be stored in a hidden field as follows:
      * <input type="hidden" name="__keys__[ID]" value="10"/>  (assuming the value of the ID field for this record is 10)
      *
      */
     $factory = new HTML_QuickForm('factory');
     // a dummy quickform object to be used tgo create elements.
     $keyEls = array();
     //
     $keyDefaults = array();
     foreach (array_keys($this->_table->keys()) as $key) {
         $keyEls[] = $factory->addElement('hidden', $key);
     }
     $this->addGroup($keyEls, '__keys__');
     /*
      *
      * We add a field to flag whether or not we are creating a new record.
      * This does not mean that we are always creating a new record.  That will
      * depend on the value that is placed in this field as a default.
      *
      */
     $this->addElement('hidden', '-new');
     $this->setDefaults(array('-new' => $this->_new));
     if ($this->_new and Dataface_PermissionsTool::checkPermission('new', $this->_table) or !$this->_new and Dataface_PermissionsTool::edit($this->_record)) {
         $saveButtonLabel = df_translate('tables.' . $this->_table->tablename . '.save_button_label', '');
         if (!$saveButtonLabel) {
             $saveButtonLabel = df_translate('save_button_label', 'Save');
         }
         $this->addElement('submit', '--session:save', $saveButtonLabel);
         //$this->addGroup($formTool->createRecordButtons($this->_record, $this->tab));
     }
     if ($this->_new and !$this->overrideNoQuery) {
         $this->addElement('hidden', '--no-query', 1);
     }
     // add the submit button.
     /*
      *
      * We need to set the default values for this form now.
      *
      */
     $keys = $this->getKeys();
     // may not be necessary -- not sure....
     if ($this->isSubmitted() and !$this->_new) {
         /*
          *
          * This part is unnecessary because the record is not populated
          * in the Dataface_QuickForm constructor.
          *
          */
         $key_vals = $this->exportValues('__keys__');
         $query = $key_vals['__keys__'];
         //$io = new Dataface_IO($this->tablename, $this->db);
         //$io->read($query, $this->_record);
     } else {
         if (!$this->_new) {
             /*
              *
              * The form has not been submitted yet and we are not creating a new
              * record, so we need to populate the form with values from the record.
              *
              */
             foreach (array_keys($this->_table->keys()) as $key) {
                 $keyDefaults[$key] = $this->_record->strval($key);
             }
             $this->setConstants(array('__keys__' => $keyDefaults));
             $this->pull();
         } else {
             // $this->_new
             $defaults = array();
             foreach (array_keys($this->_fields) as $key) {
                 $defaultValue = $this->_table->getDefaultValue($key);
                 if (isset($defaultValue)) {
                     //if ( isset($this->_fields[$key]['group']) and $this->_fields[$key]['group'] ){
                     //	$defaults[$this->_fields[$key]['group']][$key] = $defaultValue;
                     //} else {
                     $defaults[$key] = $defaultValue;
                     //}
                 }
             }
             $this->setDefaults($defaults);
         }
     }
 }
Beispiel #2
0
 function df_load_realm($realm, $lang = null)
 {
     Dataface_LanguageTool::getInstance($lang)->loadRealm($realm);
 }
Beispiel #3
0
    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;
    }
Beispiel #4
0
    /**
     * @brief Loads the delegate file.
     * @private
     */
    function _loadDelegate()
    {
        if ($this->_hasDelegateFile()) {
            import($this->_delegateFilePath());
            $delegate_name = "tables_" . $this->tablename;
            $this->_delegate = new $delegate_name();
            if (isset($this->_delegate) and method_exists($this->_delegate, 'getDelegate')) {
                $del = $this->_delegate->getDelegate();
                if (isset($del)) {
                    $this->_delegate = $del;
                }
            }
            if (method_exists($this->_delegate, 'tablePermissions')) {
                // table permissions are now just done inside the getPermissions() method.
                // so the tablePermissions() method is no longer supported.  Let the developer
                // know in case he has old code.
                throw new Exception(Dataface_LanguageTool::translate('tablePermissions method no longer supported', 'Dataface noticed that the delegate class for the table "' . $this->tablename . '" contains a tablePermissions() method.  This method is no longer supported as of Dataface version 0.6.  Please use the getPermissions() method instead with first parameter null to achieve the same results.
						For example:
						function getPermissions(&$record, $params){
							if ( $record === null ){
								// return generic table permissions
							} else {
								// return record-specific permissions
							}
						}', array('table' => $this->tablename)), E_USER_NOTICE);
            }
            return true;
        } else {
            return false;
        }
    }
Beispiel #5
0
 /**
  * Returns the permissions that are assigned to a certain role.  This allows a set of permissions
  * to be grouped together and returned by getPermissions() methods.  A role is essentially just
  * a list of permissions that are associated with the name of the role.  Roles can be defined in the
  * permissions.ini files which are located in any table configuration folder, the application folder,
  * or the dataface folder.  Try to place the roles in the appropriate folder based on what it is 
  * most closely related to.  For example, if the role is specifically related to one table then place
  * it in the permissions.ini file for that table, but if it is more general you can place it in the
  * permissions.ini file for the application.  This will allow for better modularization and re-use
  * of useful table definitions between applications.  The goal here is to allow you to distribute
  * your tables to others so that they can be added easily to other applications.  If everything 
  * relating to the table is located in one folder then this becomes much easier.
  * @param $roleName The name of the role.
  *
  * @returns An array of permissions (the keys are the permission names, and the values are the permission
  * labels.
  */
 function &getRolePermissions($roleName)
 {
     $me =& $this;
     if (!isset($me->rolePermissions[$roleName])) {
         // it looks like the role has not been defined
         throw new Exception(Dataface_LanguageTool::translate('Role not found', 'The role "' . $roleName . '" is not a registered role.', array('role' => $roleName)), E_USER_ERROR);
     }
     return $me->rolePermissions[$roleName];
 }
Beispiel #6
0
 /**
  * Builds the query that is used to delete records.
  */
 function _buildDeleteQuery($values = array())
 {
     $query = array();
     if (isset($values['-delete-one'])) {
         $keys = array_keys($this->_table->keys());
         foreach ($keys as $key) {
             if (!isset($values[$key])) {
                 return PEAR::raiseError(Dataface_LanguageTool::translate('Missing key while trying to delete record', 'Attempt to delete single record when not all keys were specified.  Missing key \'' . $key . '\'', array('key' => $key)), DATAFACE_E_MISSING_KEY);
             }
             $val = $values[$key];
             if ($val[0] != '=') {
                 $val = '=' . $val;
             }
             $query[$key] = $val;
         }
     } else {
         $query['-limit'] = 9999;
         //isset($values['-limit']) ? $values['-limit'] : 1;
         $query['-skip'] = 0;
         //isset($values['-skip']) ? $values['-skip'] : 0;
         if (isset($values['-search'])) {
             $query['-search'] = $values['-search'];
         }
         if (isset($values['-sort'])) {
             $query['-sort'] = $values['-sort'];
         }
         foreach ($values as $key => $value) {
             if (strpos($key, '-') === 0) {
                 continue;
             }
             $query[$key] = $value;
         }
     }
     return $query;
 }
Beispiel #7
0
    function handle(&$params)
    {
        import('Dataface/RemoveRelatedRecordForm.php');
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        $record = null;
        //& new Dataface_Record($this->_tablename, $_REQUEST['--__keys__']);
        // let the form handle the loading of the record
        $form = new Dataface_RemoveRelatedRecordForm($record, $query['-relationship']);
        if (!$form->_record) {
            // the record could not be loaded
            return PEAR::raiseError(Dataface_LanguageTool::translate('Specified record could not be loaded', 'The specified record could not be loaded'), DATAFACE_E_NOTICE);
        }
        unset($app->currentRecord);
        $app->currentRecord =& $form->_record;
        if (!Dataface_PermissionsTool::checkPermission('remove related record', $form->_record, array('relationship' => $query['-relationship']))) {
            return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate('Insufficient permissions to delete record', 'Permission Denied.  You do not have permissions to remove related records from the relationship "' . $query['-relationship'] . '" for this record.  
					Requires permission "remove related record" but you only have the following permissions: "' . df_permission_names_as_string($form->_record->getPermissions(array('relationship' => $query['-relationship']))) . '"', array('relationship' => $query['-relationship'], 'required_permission' => 'remove related record', 'granted_permissions' => df_permission_names_as_string($form->_record->getPermissions(array('relationship' => $query['-relationship']))))));
            //$this->_vars['error'] =  "<div class=\"error\">Error.  Permission Denied.<!-- At line ".__LINE__." of file ".__FILE__." --></div>";
            //return;
        }
        if (@$_POST['-confirm_delete_hidden'] and $form->validate()) {
            $res = $form->process(array(&$form, 'delete'), true);
            $response =& Dataface_Application::getResponse();
            if (PEAR::isError($res) && !Dataface_Error::isNotice($res)) {
                return $res;
                //$this->_vars['error'] = "<div class=\"error\">Error.  ".$res->toString()."<!-- At line ".__LINE__." of file ".__FILE__." --></div>";
                //return;
            } else {
                if (count($res['warnings']) > 0) {
                    //Dataface_Error::isNotice($res) ){
                    foreach ($res['warnings'] as $warning) {
                        $app->addError($warning);
                        $response['--msg'] = 'Errors occurred trying to remove records';
                    }
                } else {
                    $response['--msg'] = df_translate('Records successfully deleted from relationship', ' Records successfully removed from relationship') . "<br>" . @$response['--msg'];
                }
            }
            if (count($res['warnings']) > 0) {
                foreach (array_merge($res['confirmations'], $res['warnings']) as $confirmation) {
                    $response['--msg'] .= "<br>" . $confirmation;
                }
            }
            $msg = urlencode(trim(@$response['--msg']));
            header("Location: " . $form->_record->getURL(array('-action' => 'related_records_list', '-relationship' => $query['-relationship'])) . '&--msg=' . $msg);
            //header("Location: ".$_SERVER['HOST_URI'].$_SERVER['PHP_SELF'].'?'.$_COOKIE['dataface_lastpage'].'&--msg='.$msg);
            exit;
        }
        ob_start();
        $form->display();
        $out = ob_get_contents();
        ob_end_clean();
        $context = array('form' => $out);
        if (isset($query['-template'])) {
            $template = $query['-template'];
        } else {
            if (isset($params['action']['template'])) {
                $template = $params['action']['template'];
            } else {
                $template = 'Dataface_Remove_Related_Record.html';
            }
        }
        df_display($context, $template, true);
    }
Beispiel #8
0
 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);
 }
Beispiel #9
0
 function handle(&$params)
 {
     import('Dataface/DeleteForm.php');
     import('Dataface/LanguageTool.php');
     import('Dataface/Record.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $record = new Dataface_Record($query['-table'], @$_REQUEST['--__keys__']);
     // 		if ( !Dataface_PermissionsTool::delete($record) ) {
     // 			return Dataface_Error::permissionDenied(
     // 				Dataface_LanguageTool::translate(
     // 					/* i18n id */
     // 					'No delete permissions',
     // 					/* Default error message */
     // 					'Insufficient Permissions to delete this record',
     // 					/* i18n parameters */
     // 					array('record'=>$record->getTitle())
     // 				)
     // 			);
     //
     //
     // 		}
     $form = new Dataface_DeleteForm($query['-table'], $app->db(), $query);
     $form->_build();
     $form->addElement('hidden', '-table');
     $form->setDefaults(array('-table' => $query['-table']));
     $msg = '';
     if ($form->validate()) {
         $res = $form->process(array(&$form, 'delete'), true);
         $response =& Dataface_Application::getResponse();
         if (!isset($response['--msg'])) {
             $response['--msg'] = '';
         }
         $failed = false;
         if (PEAR::isError($res) && !Dataface_Error::isNotice($res)) {
             return $res;
             //$error = $res->getMessage();
             //$msg .= "\n". $res->getUserInfo();
         } else {
             if (Dataface_Error::isNotice($res)) {
                 $app->addError($res);
                 //$response['--msg'] = @$response['--msg'] ."\n".$res->getMessage();
                 $failed = true;
             } else {
                 if (is_array($res)) {
                     $msg = df_translate('Some errors occurred while deleting records', 'Some errors occurred while deleting records');
                     foreach ($res as $warning) {
                         $response['--msg'] .= "\n" . $warning->getMessage();
                     }
                 } else {
                     $msg = Dataface_LanguageTool::translate('Records successfully deleted', 'Records successfully deleted.');
                 }
             }
         }
         $msg = urlencode(trim($msg . "\n" . $response['--msg']));
         if (!$failed) {
             import('Dataface/Utilities.php');
             Dataface_Utilities::fireEvent('after_action_delete', array('record' => &$record));
             header('Location: ' . $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?-table=' . $query['-table'] . '&--msg=' . $msg);
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('form' => $out);
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             $template = 'Dataface_Delete_Record.html';
         }
     }
     df_display($context, $template, true);
 }
Beispiel #10
0
 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);
 }
Beispiel #11
0
 function _writeRelationship($relname, $record)
 {
     $s =& $this->_table;
     $rel =& $s->getRelationship($relname);
     if (PEAR::isError($rel)) {
         $rel->addUserInfo(df_translate('scripts.Dataface.IO._writeRelationship.ERROR_OBTAINING_RELATIONSHIP', "Error obtaining relationship {$relname} in IO::_writeRelationship() on line " . __LINE__ . " of file " . __FILE__, array('relname' => $relname, 'line' => __LINE__, 'file' => __FILE__)));
         return $rel;
     }
     $tables =& $rel['selected_tables'];
     $columns =& $rel['columns'];
     if (count($tables) == 0) {
         return PEAR::raiseError(Dataface_LanguageTool::translate("Failed to write relationship because not table was selected", "Error writing relationship '{$relname}'.  No tables were selected on line " . __LINE__ . " of file " . __FILE__, array('relationship' => $relname)), DATAFACE_E_NO_TABLE_SPECIFIED);
     }
     $records =& $record->getRelatedRecords($relname);
     $record_keys = array_keys($records);
     if (PEAR::isError($records)) {
         $records->addUserInfo(df_translate('scripts.Dataface.IO._writeRelationship.ERROR_GETTING_RELATED_RECORDS', "Error getting related records in IO::_writeRelationship() on line " . __LINE__ . " of file " . __FILE__, array('line' => __LINE__, 'file' => __FILE__)));
         return $records;
     }
     foreach ($tables as $table) {
         $rs =& Dataface_Table::loadTable($table, $s->db);
         $keys = array_keys($rs->keys());
         $cols = array();
         foreach ($columns as $column) {
             if (preg_match('/^' . $table . '\\.(\\w+)/', $column, $matches)) {
                 $cols[] = $matches[1];
             }
         }
         foreach ($record_keys as $record_key) {
             $changed = false;
             // flag whether this record has been changed
             $update_cols = array();
             // store the columns that have been changed and require update
             foreach ($cols as $column) {
                 // check each column to see if it has been changed
                 if ($s->valueChanged($relname . '.' . $column, $record_key)) {
                     $changed = true;
                     $update_cols[] = $column;
                 } else {
                 }
             }
             if (!$changed) {
                 continue;
             }
             // if this record has not been changed with respect to the
             // columns of the current table, then we ignore it.
             $sql = "UPDATE `{$table}` ";
             $set = '';
             foreach ($update_cols as $column) {
                 $set .= "SET {$column} = '" . addslashes($rs->getSerializedValue($column, $records[$record_key][$column])) . "',";
             }
             $set = trim(substr($set, 0, strlen($set) - 1));
             $where = 'WHERE ';
             foreach ($keys as $key) {
                 $where .= "`{$key}` = '" . addslashes($rs->getSerializedValue($key, $records[$record_key][$key])) . "' AND ";
             }
             $where = trim(substr($where, 0, strlen($where) - 5));
             if (strlen($where) > 0) {
                 $where = ' ' . $where;
             }
             if (strlen($set) > 0) {
                 $set = ' ' . $set;
             }
             $sql = $sql . $set . $where . ' LIMIT 1';
             //$res = mysql_query($sql, $s->db);
             $res = $this->dbObj->query($sql, $s->db, $this->lang);
             if (!$res || PEAR::isError($res)) {
                 trigger_error(df_translate('scripts.Dataface.IO._writeRelationship.ERROR_UPDATING_DATABASE', "Error updating database with query '{$sql}': " . mysql_error($s->db), array('sql' => $sql, 'mysql_error' => mysql_error($s->db))) . Dataface_Error::printStackTrace(), E_USER_ERROR);
             }
         }
         unset($rs);
     }
 }
Beispiel #12
0
 /**
  * Handle a request.  This method is the starting point for all Dataface application requests.
  * It will delegate the request to the appropriate handler.
  * The order of delegation is as follows:
  *  0. Uses the ActionTool to check permissions for the action.  If permissions are not granted,
  *		dispatch the error handler.  If permissions are granted then we continue down the delegation
  *		chain.
  *  1. If the current table's delegate class defines a handleRequest() method, then call that.
  *	2. If the current table's delegate class does not have a handleRequest() method or that method
  *		returns a PEAR_Error object with code E_DATAFACE_REQUEST_NOT_HANDLED, then check for a handler
  *		bearing the name of the action in one of the actions directories.  Check the directories 
  *		in the following order:
  *		a. <site url>/tables/<table name>/actions
  *		b. <site url>/actions
  *		b. <dataface url>/actions
  *	3. If no handler can be found then use the default handler.  The default handler can be quite 
  *		powerful as it accepts the '-template' query parameter to use a specific template for display.
  */
 function handleRequest($disableCache = false)
 {
     if (!$disableCache and @$_GET['-action'] != 'getBlob' and isset($this->_conf['_output_cache']) and @$this->_conf['_output_cache']['enabled'] and count($_POST) == 0) {
         import('Dataface/OutputCache.php');
         $oc = new Dataface_OutputCache($this->_conf['_output_cache']);
         $oc->ob_start();
     }
     import('Dataface/ActionTool.php');
     import('Dataface/PermissionsTool.php');
     import('Dataface/Table.php');
     $applicationDelegate = $this->getDelegate();
     if (isset($applicationDelegate) and method_exists($applicationDelegate, 'beforeHandleRequest')) {
         // Do whatever we need to do before the request is handled.
         $applicationDelegate->beforeHandleRequest();
     }
     // Set up security filters
     $query =& $this->getQuery();
     $table = Dataface_Table::loadTable($query['-table']);
     //$table->setSecurityFilter();
     /*
      * Set up some preferences for the display of the application.
      * These can be overridden by the getPreferences() method in the
      * application delegate class.
      */
     if (isset($this->_conf['_prefs']) and is_array($this->_conf['_prefs'])) {
         $this->prefs = array_merge($this->prefs, $this->_conf['_prefs']);
     }
     if (@$this->_conf['hide_nav_menu']) {
         $this->prefs['show_tables_menu'] = 0;
     }
     if (@$this->_conf['hide_view_tabs']) {
         $this->prefs['show_table_tabs'] = 0;
     }
     if (@$this->_conf['hide_result_controller']) {
         $this->prefs['show_result_controller'] = 0;
     }
     if (@$this->_conf['hide_table_result_stats']) {
         $this->prefs['show_result_stats'] = 0;
     }
     if (@$this->_conf['hide_search']) {
         $this->prefs['show_search'] = 0;
     }
     if (!isset($this->prefs['disable_ajax_record_details'])) {
         $this->prefs['disable_ajax_record_details'] = 1;
     }
     if ($query['-action'] == 'login_prompt') {
         $this->prefs['no_history'] = 1;
     }
     if (isset($applicationDelegate) and method_exists($applicationDelegate, 'getPreferences')) {
         $this->prefs = array_merge($this->prefs, $applicationDelegate->getPreferences());
     }
     // Check to make sure that this table hasn't been disallowed
     $disallowed = false;
     if (isset($this->_conf['_disallowed_tables'])) {
         foreach ($this->_conf['_disallowed_tables'] as $name => $pattern) {
             if ($pattern[0] == '/' and preg_match($pattern, $query['-table'])) {
                 $disallowed = true;
                 break;
             } else {
                 if ($pattern == $query['-table']) {
                     $disallowed = true;
                     break;
                 }
             }
         }
     }
     if ($disallowed and isset($this->_conf['_allowed_tables'])) {
         foreach ($this->_conf['_allowed_tables'] as $name => $pattern) {
             if ($pattern[0] == '/' and preg_match($pattern, $query['-table'])) {
                 $disallowed = false;
                 break;
             } else {
                 if ($pattern == $query['-table']) {
                     $disallowed = false;
                     break;
                 }
             }
         }
     }
     if ($disallowed) {
         return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate("Permission Denied. This table has been disallowed in the conf.ini file", "Permission denied because this table has been disallowed in the conf.ini file '"));
     }
     $actionTool = Dataface_ActionTool::getInstance();
     //if ( $this->_conf['multilingual_content'] ){
     //import('I18Nv2/I18Nv2.php');
     //I18Nv2::autoConv();
     //}
     $params = array('table' => $query['-table'], 'name' => $query['-action']);
     if (strpos($query['-action'], 'custom_') === 0) {
         $action = array('name' => $query['-action'], 'page' => substr($query['-action'], 7), 'permission' => 'view', 'mode' => 'browse', 'custom' => true);
     } else {
         $action = $actionTool->getAction($params);
         if (is_array($action) and @$action['related'] and @$query['-relationship'] and preg_match('/relationships\\.ini/', @$action['allow_override'])) {
             // This action is to be performed on the currently selected relationship.
             $raction = $table->getRelationshipsAsActions(array(), $query['-relationship']);
             if (is_array($raction)) {
                 $action = array_merge($action, $raction);
             }
         }
         if (is_array($action) and isset($action['delegate'])) {
             $params['name'] = $query['-action'] = $action['delegate'];
             $tmp = $actionTool->getActions($params);
             unset($action);
             $action =& $tmp;
             unset($tmp);
         }
         if (is_array($action) and isset($action['auth_type'])) {
             $authTool = $this->getAuthenticationTool();
             $authTool->setAuthType($action['auth_type']);
         }
     }
     if ((PEAR::isError($action) or !@$action['permission']) and $this->_conf['security_level'] >= DATAFACE_STRICT_PERMISSIONS) {
         // The only reason getAction() will return an error is if the specified action could not be found.
         // If the application is set to use strict permissions and no action was defined in the ini file
         // then this action cannot be performed.  Strict permissions mode requires that permissions be
         // strictly set or permission will be denied.
         return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate("Permission Denied. No action found in strict permissions mode", "Permission denied for action '" . $query['-action'] . "'.  No entry for this action was found in the actions.ini file.  \n\t\t\t\t\tYou are currently using strict permissions mode which requires that you define all actions that you want to use in the actions.ini file with appropriate permissions information.", array('action' => $query['-action'])));
     } else {
         if (PEAR::isError($action)) {
             $action = array('name' => $query['-action'], 'label' => $query['-action']);
         }
     }
     // Step 1:  See if the delegate class has a handler.
     $delegate = $table->getDelegate();
     $handled = false;
     if (method_exists($delegate, 'handleRequest')) {
         $result = $delegate->handleRequest();
         if (PEAR::isError($result) and $result->getCode() === DATAFACE_E_REQUEST_NOT_HANDLED) {
             $handled = false;
         } else {
             if (PEAR::isError($result)) {
                 return $result;
             } else {
                 $handled = true;
             }
         }
     }
     if (isset($action['mode']) and $action['mode']) {
         $query['-mode'] = $action['mode'];
     }
     // Step 2: Look to see if there is a handler defined
     if (isset($action['custom'])) {
         $locations = array(DATAFACE_PATH . '/actions/custom.php' => 'dataface_actions_custom');
     } else {
         $locations = array();
         $locations[DATAFACE_SITE_PATH . '/tables/' . basename($query['-table']) . '/actions/' . basename($query['-action']) . '.php'] = 'tables_' . $query['-table'] . '_actions_' . $query['-action'];
         $locations[DATAFACE_SITE_PATH . '/actions/' . basename($query['-action']) . '.php'] = 'actions_' . $query['-action'];
         if (isset($this->_conf['_modules']) and count($this->_conf['_modules']) > 0) {
             $mt = Dataface_ModuleTool::getInstance();
             foreach ($this->_conf['_modules'] as $modname => $modpath) {
                 $mt->loadModule($modname);
                 if ($modpath[0] == '/') {
                     $locations[dirname($modpath) . '/actions/' . basename($query['-action']) . '.php'] = 'actions_' . $query['-action'];
                 } else {
                     $locations[DATAFACE_SITE_PATH . '/' . dirname($modpath) . '/actions/' . basename($query['-action']) . '.php'] = 'actions_' . $query['-action'];
                     $locations[DATAFACE_PATH . '/' . dirname($modpath) . '/actions/' . basename($query['-action']) . '.php'] = 'actions_' . $query['-action'];
                 }
             }
         }
         $locations[DATAFACE_PATH . '/actions/' . basename($query['-action']) . '.php'] = 'dataface_actions_' . $query['-action'];
         $locations[DATAFACE_PATH . '/actions/default.php'] = 'dataface_actions_default';
     }
     $doParams = array('action' => &$action);
     //parameters to be passed to the do method of the handler
     foreach ($locations as $handlerPath => $handlerClassName) {
         if (is_readable($handlerPath)) {
             import($handlerPath);
             $handler = new $handlerClassName();
             $params = array();
             if (is_array($action) and @$action['related'] and @$query['-relationship']) {
                 $params['relationship'] = $query['-relationship'];
             }
             if (!PEAR::isError($action) and method_exists($handler, 'getPermissions')) {
                 // check the permissions on this action to make sure that we are 'allowed' to perform it
                 // this method will return an array of Strings that are names of permissions granted to
                 // the current user.
                 //echo "Checking permissions:";
                 //print_r($params);
                 $permissions = $handler->getPermissions($params);
                 //} else if ( $applicationDelegate !== null and method_exists($applicationDelegate, 'getPermissions') ){
                 //	$permissions =& $applicationDelegate->getPermissions($params);
             } else {
                 //print_r($params);
                 //print_r($action);
                 $permissions = $this->getPermissions($params);
             }
             if (isset($action['permission']) && !(isset($permissions[$action['permission']]) and $permissions[$action['permission']])) {
                 return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate("Permission Denied for action.", "Permission to perform action '" . $action['name'] . "' denied.  \n\t\t\t\t\t\t\tRequires permission '" . $action['permission'] . "' but only granted '" . Dataface_PermissionsTool::namesAsString($permissions) . "'.", array('action' => $action, 'permissions_granted' => Dataface_PermissionsTool::namesAsString($permissions))));
             }
             if (method_exists($handler, 'handle')) {
                 $result = $handler->handle($doParams);
                 if (PEAR::isError($result) and $result->getCode() === DATAFACE_E_REQUEST_NOT_HANDLED) {
                     continue;
                 }
                 return $result;
             }
         }
     }
     trigger_error(df_translate('scripts.Dataface.Application.handleRequest.NO_HANDLER_FOUND', "No handler found for request.  This should never happen because, at the very least, the default handler at dataface/actions/default.php should be called.  Check the permissions on dataface/actions/default.php to make sure that it is readable by the web server.") . Dataface_Error::printStackTrace(), E_USER_ERROR);
 }
Beispiel #13
0
 function translate($__translation_id, $__defaultText = null, $params = array(), $lang = null)
 {
     if (isset($this) and is_a($this, 'Dataface_LanguageTool') and $this->lang == $lang) {
         $tool =& $this;
     } else {
         $tool =& Dataface_LanguageTool::getInstance($lang);
     }
     $__found_text = null;
     foreach (array_reverse(array_keys($tool->realms)) as $realmName) {
         if (isset($tool->realms[$realmName][$__translation_id])) {
             $__found_text = $tool->realms[$realmName][$__translation_id];
             break;
         }
     }
     if (!isset($__found_text) and isset($tool->dictionary[$__translation_id])) {
         $__found_text = $tool->dictionary[$__translation_id];
     }
     if (isset($__found_text)) {
         if (!$params or @$params['__noreplace__']) {
             return $__found_text;
         }
         // make sure that there are no conflicting variable names as we are about to extract the params
         // array into local scope.
         if (isset($params['__translation_id'])) {
             unset($params['__translation_id']);
         }
         if (isset($params['tool'])) {
             unset($params['tool']);
         }
         if (isset($params['__defaultText'])) {
             unset($params['__defaultText']);
         }
         if (isset($params['params'])) {
             unset($params['params']);
         }
         if (isset($params['__found_text'])) {
             unset($params['__found_text']);
         }
         extract($params);
         @eval('$parsed = <<<END' . "\n" . $__found_text . "\nEND\n;");
         if (!isset($parsed)) {
             return $__defaultText;
         }
         return $parsed;
     }
     if ($tool->lang != $tool->app->_conf['default_language']) {
         return $tool->translate($__translation_id, $__defaultText, $params, $tool->app->_conf['default_language']);
     }
     return $__defaultText;
 }
Beispiel #14
0
 /**
  * Returns a specified action without evaluating the permissions or condition fields.
  * @param $params Associative array:
  *			Options:  name => The name of the action to retrieve
  *					  table => The name of the table on which the action is defined.
  *  @returns Action associative array.
  */
 function &getAction($params, $action = null)
 {
     $app =& Dataface_Application::getInstance();
     if (!isset($action)) {
         if (isset($params['table']) and $params['table']) {
             $this->_loadTableActions($params['table']);
         }
         if (!isset($params['name']) or !$params['name']) {
             trigger_error("ActionTool::getAction() requires 'name' parameter to be specified.", E_USER_ERROR);
         }
         if (!isset($this->actions[$params['name']])) {
             $err = PEAR::raiseError(Dataface_LanguageTool::translate("No action found", "No action found named '" . $params['name'] . "'", array('name' => $params['name'])));
             return $err;
         }
         $action = $this->actions[$params['name']];
     }
     if (isset($action['selected_condition'])) {
         $action['selected'] = $app->testCondition($action['selected_condition'], $params);
     }
     //if ( isset($action['visible']) and !$action['visible']) continue;
     // Filter based on a condition
     foreach (array_keys($action) as $attribute) {
         // Some entries may have variables that need to be evaluated.  We use Dataface_Application::eval()
         // to evaluate these entries. The eval method will replace variables such as $site_url, $site_href
         // $dataface_url with the appropriate real values.  Also if $params['record'] contains a
         // Record object or a related record object its values are treated as php variables that can be
         // replaced.  For example if a Profile record has fields 'ProfileID' and 'ProfileName' with
         // ProfileID=10 and ProfileName = 'John Smith', then:
         // $app->parseString('ID is ${ProfileID} and Name is ${ProfileName}') === 'ID is 10 and Name is John Smith'
         if (preg_match('/condition/i', $attribute)) {
             continue;
         }
         if (isset($action[$attribute . '_condition']) and !$app->testCondition($action[$attribute . '_condition'], $params)) {
             $action[$attribute] = null;
         } else {
             $action[$attribute] = $app->parseString($action[$attribute], $params);
         }
     }
     return $action;
 }
Beispiel #15
0
 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(&$params)
 {
     import('Dataface/ExistingRelatedRecordForm.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     //$record =& $app->getRecord();	// loads the current record
     if (!isset($query['-relationship'])) {
         return PEAR::raiseError(Dataface_LanguageTool::translate('Error: No relationship specified', 'Error.  No relationship was specified when trying to add existing related record.'), DATAFACE_E_NOTICE);
     }
     $record = null;
     $form = new Dataface_ExistingRelatedRecordForm($record, $query['-relationship']);
     $res = $form->_build();
     if (PEAR::isError($res)) {
         return Dataface_Error::permissionDenied($res->getMessage());
     }
     /*
      *
      * 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']));
     if (!$form->_record || !is_a($form->_record, 'Dataface_Record')) {
         trigger_error(Dataface_LanguageTool::translate('Fatal Error', 'Fatal Error: Form should have loaded record but the record was null. ' . Dataface_Error::printStackTrace(), array('stack_trace' => Dataface_Error::printStackTrace(), 'msg' => 'Form should have loaded record but the record was null.')), E_USER_ERROR);
     }
     if (!Dataface_PermissionsTool::checkPermission('add existing related record', $form->_record)) {
         return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate('Error: Permission denied adding existing related record', 'Permission Denied.  You do not have sufficient permissions to add an existing related record.  Required permission: "add existing related record", but you have only been granted permissions: "' . implode(',', $form->_record->getPermissions()) . '".', array('required_permission' => 'add existing related record', 'granted_permissions' => implode(',', $form->_record->getPermissions()))));
     }
     if ($form->validate()) {
         $res = $form->process(array(&$form, 'save'), true);
         $response =& Dataface_Application::getResponse();
         if (PEAR::isError($res) && !Dataface_Error::isNotice($res)) {
             return $res;
         } else {
             if (Dataface_Error::isNotice($res)) {
                 //$response['--msg'] = @$response['--msg'] . "\n".$res->getMessage();
                 $app->addError(PEAR::raiseError(df_translate('Failed to add record because of errors', 'Failed to add record to relationship because of the following errors:'), DATAFACE_E_NOTICE));
                 $app->addError($res);
                 $success = false;
             } else {
                 $success = true;
             }
         }
         if ($success) {
             import('Dataface/Utilities.php');
             Dataface_Utilities::fireEvent('after_action_existing_related_record');
             $fquery = array('-action' => 'browse');
             $msg = Dataface_LanguageTool::translate('Record successfully added to relationship', "The record has been successfully added to the " . $query['-relationship'] . " relationship.\n", array('relationship' => $query['-relationship']));
             $msg = urlencode(trim(($success ? $msg : '') . @$response['--msg']));
             $vals = $form->exportValues();
             if (isset($vals['--redirect'])) {
                 $qmark = strpos($vals['--redirect'], '?') !== false ? '&' : '?';
                 header('Location: ' . $vals['--redirect'] . $qmark . '--msg=' . $msg);
                 exit;
             }
             foreach ($vals['__keys__'] as $key => $value) {
                 $fquery[$key] = "=" . $value;
             }
             $link = Dataface_LinkTool::buildLink($fquery);
             header("Location: {$link}" . "&--msg=" . $msg);
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('form' => $out);
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             $template = 'Dataface_Add_Existing_Related_Record.html';
         }
     }
     df_display($context, $template, true);
 }
Beispiel #17
0
 /**
  * Returns the permissions that are assigned to a certain role.  This allows a set of permissions
  * to be grouped together and returned by getPermissions() methods.  A role is essentially just
  * a list of permissions that are associated with the name of the role.  Roles can be defined in the
  * permissions.ini files which are located in any table configuration folder, the application folder,
  * or the dataface folder.  Try to place the roles in the appropriate folder based on what it is 
  * most closely related to.  For example, if the role is specifically related to one table then place
  * it in the permissions.ini file for that table, but if it is more general you can place it in the
  * permissions.ini file for the application.  This will allow for better modularization and re-use
  * of useful table definitions between applications.  The goal here is to allow you to distribute
  * your tables to others so that they can be added easily to other applications.  If everything 
  * relating to the table is located in one folder then this becomes much easier.
  * @param $roleName The name of the role.
  *
  * @returns An array of permissions (the keys are the permission names, and the values are the permission
  * labels.
  */
 function &getRolePermissions($roleName)
 {
     $me =& $this;
     if (!isset($me->rolePermissions[$roleName])) {
         // it looks like the role has not been defined
         trigger_error(Dataface_LanguageTool::translate('Role not found', 'The role "' . $roleName . '" is not a registered role.' . Dataface_Error::printStackTrace(), array('role' => $roleName)), E_USER_ERROR);
     }
     return $me->rolePermissions[$roleName];
 }
Beispiel #18
0
 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);
 }
Beispiel #19
0
 function language_selector($params, &$smarty)
 {
     $languageTool =& Dataface_LanguageTool::getInstance();
     echo $languageTool->getLanguageSelectorHtml($params);
 }
Beispiel #20
0
 /**
  * Returns an array of column names that are available in a given language.
  * @param $name The 2-digit language code for the translation.
  * @returns Array of column names - if translation exists.  Null if translation
  *          does not exist.
  */
 function &getTranslation($name)
 {
     $translations =& $this->getTranslations();
     if (isset($translations[$name])) {
         // the translation exists
         if (!$translations[$name]) {
             // the columns are not loaded yet, we need to load them.
             $res = mysql_query("SHOW COLUMNS FROM `" . addslashes($this->tablename) . "_" . addslashes($name) . "`", $this->db);
             if (!$res) {
                 trigger_error(Dataface_LanguageTool::translate('Problem loading columns from translation table', 'Problem loading columns from translation table for table "' . $this->tablename . '" in language "' . $name . '". ' . mysql_error($this->db) . Dataface_Error::printStackTrace(), array('table' => $this->tablename, 'langauge' => $name, 'stack_trace' => Dataface_Error::printStackTrace(), 'sql_error' => mysql_error($this->db))), E_USER_ERROR);
             }
             $translations[$name] = array();
             while ($row = mysql_fetch_assoc($res)) {
                 $translations[$name][] = $row['Field'];
             }
             mysql_free_result($res);
         }
         return $translations[$name];
     }
     $null = null;
     return $null;
 }
 function handle(&$params)
 {
     //global $myctr;
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     //$record =& $app->getRecord();	// loads the current record
     import('Dataface/ShortRelatedRecordForm.php');
     if (!isset($query['-relationship'])) {
         return PEAR::raiseError(Dataface_LanguageTool::translate('No relationship specified in new related record', 'No relationship was specified while trying to create new related record.  Please specify a relationship.'), DATAFACE_E_ERROR);
     }
     $record = null;
     // we let the Form automatically handle loading of record.
     $form = new Dataface_ShortRelatedRecordForm($record, $query['-relationship']);
     $form->_build();
     /*
      *
      * 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.
      *
      */
     //$myctr = 0;
     foreach ($query as $key => $value) {
         //echo "doing $key";
         if (strpos($key, '-') === 0) {
             $form->addElement('hidden', $key);
             $form->setDefaults(array($key => $value));
             //if ( $myctr == 2 ) exit;
         }
         //$myctr++;
     }
     /*
      * 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']));
     if (!Dataface_PermissionsTool::checkPermission('add new related record', $form->_record, array('relationship' => $query['-relationship']))) {
         return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate('Permission denied while trying to add new related record', 'Permission Denied: You do not have permission to add related records to the current record.'));
         //$this->_vars['error'] =  "<div class=\"error\">Error.  Permission Denied.<!-- At line ".__LINE__." of file ".__FILE__." --></div>";
         //return;
     }
     if ($form->validate()) {
         $vals = $form->exportValues();
         $res = $form->process(array(&$form, 'save'), true);
         $response =& Dataface_Application::getResponse();
         if (PEAR::isError($res) && !Dataface_Error::isNotice($res)) {
             return $res;
             //$this->_vars['error'] = "<div class=\"error\">Error.  ".$res->toString()."<!-- At line ".__LINE__." of file ".__FILE__." --></div>";
             //return;
         } else {
             if (Dataface_Error::isNotice($res)) {
                 $success = false;
                 $app->addError($res);
                 //$response['--msg'] = @$response['--msg'] . "\n".$res->getMessage();
             } else {
                 $success = true;
             }
         }
         if ($success) {
             import('Dataface/Utilities.php');
             Dataface_Utilities::fireEvent('after_action_new_related_record');
             $fquery = array('-action' => 'browse');
             $table = Dataface_Table::loadTable($query['-table']);
             $rel = $table->getRelationship($query['-relationship']);
             $msg = urlencode(trim(Dataface_LanguageTool::translate("Record successfully added to relationship", "Record successfully added to " . $rel->getLabel() . " relationship.\n", array('relationship' => $rel->getLabel())) . (isset($response['--msg']) ? $response['--msg'] : '')));
             foreach ($vals['__keys__'] as $key => $value) {
                 $fquery[$key] = "=" . $value;
             }
             $fquery['-relationship'] = $query['-relationship'];
             $fquery['-action'] = 'related_records_list';
             $link = Dataface_LinkTool::buildLink($fquery);
             $app->redirect("{$link}" . "&--msg=" . $msg);
         }
     }
     ob_start();
     $gdefs = array();
     foreach ($_GET as $gkey => $gval) {
         if (substr($gkey, 0, 4) == '--q:') {
             $gdefs[substr($gkey, 4)] = $gval;
         }
     }
     if (count($gdefs) > 0) {
         $form->setDefaults($gdefs);
     }
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('form' => $out);
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             $template = 'Dataface_Add_New_Related_Record.html';
         }
     }
     df_display($context, $template, true);
 }