Esempio n. 1
0
 function test_groupBy()
 {
     $record =& df_get_record('People', array('PersonID' => 1));
     $pubs = $record->getRelatedRecords('Publications', 'all');
     $categories = Dataface_Utilities::groupBy('PubType', $pubs);
     $this->assertEquals(array('Refereed Journal', 'Book Chapter', 'Conference'), array_keys($categories));
     $this->assertEquals(64, sizeof($categories['Refereed Journal']));
     $this->assertEquals(64, sizeof($categories['Book Chapter']));
     $this->assertEquals(63, sizeof($categories['Conference']));
 }
Esempio n. 2
0
 /**
  * Renders the entire treetable as HTML.
  */
 function toHtml($depth = 3, $treetableid = 'treetable')
 {
     $app =& Dataface_Application::getInstance();
     if (isset($this->relationship)) {
         $rel =& $this->record->_table->getRelationship($this->relationship);
         $table = $rel->getDomainTable();
         if (PEAR::isError($table)) {
             $destTables =& $rel->getDestinationTables();
             $table = $destTables[0]->tablename;
         }
     } else {
         $table = $this->record->_table->tablename;
         $rel =& $this->record->_table->getChildrenRelationship();
     }
     //echo "Def order col = $default_order_column";
     //ob_start();
     //$moveUpForm = ob_get_contents();
     //ob_end_clean();
     $resultList = new Dataface_ResultList($table);
     $columns = $resultList->_columns;
     ob_start();
     $default_order_column = $rel->getOrderColumn();
     if (isset($default_order_column)) {
         //echo "<script language=\"javascript\" type=\"text/javascript\"><!--";
         df_display(array('redirectUrl' => $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']), 'Dataface_MoveUpForm.html');
         //echo "//--></script>";
     }
     if (!defined('Dataface_TreeTable_JAVASCRIPT_LOADED')) {
         define('Dataface_TreeTable_JAVASCRIPT_LOADED', true);
         echo '<script language="javascript" type="text/javascript" src="' . DATAFACE_URL . '/js/TreeTable.js"></script>';
     }
     echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="GET" onsubmit="return validateTTForm(this);">';
     echo "<table width=\"100%\" id=\"{$treetableid}\" class=\"treetable\">";
     echo "<thead><tr><th><!-- checkbox column --></th><th><!-- Icon column --></th><th>Title</th>";
     foreach ($columns as $col) {
         echo "<th>{$col}</th>";
     }
     echo "</tr></thead><tbody>";
     echo $this->getSubrowsAsHTML('', $depth, $treetableid);
     echo "</tbody></table>";
     import('Dataface/ActionTool.php');
     $actionsTool =& Dataface_ActionTool::getInstance();
     $actions = $actionsTool->getActions(array('category' => 'selected_records_actions'));
     if (count($actions) > 0) {
         echo "   Perform on selected records:\n\t\t\t<select name=\"-action\">";
         foreach (array_keys($actions) as $i) {
             echo "<option value=\"" . $actions[$i]['name'] . "\">" . $actions[$i]['label'] . "</option>\n\t\t\t\t";
         }
         echo "\n\t\t\t\n\t\t\t</select>\n\t\t\t\n\t\t\t";
         echo "<input type=\"submit\" value=\"Submit\"/>";
     }
     import('Dataface/Utilities.php');
     // We need to build a query.
     $q = array('-table' => $this->record->_table->tablename);
     foreach (array_keys($this->record->_table->keys()) as $tkey) {
         $q['--__keys__'][$tkey] = '=' . $this->record->strval($tkey);
     }
     $q['-relationship'] = $this->relationship;
     echo Dataface_Utilities::query2html($q, array('-action'));
     echo '<input type="hidden" name="-redirect" value="' . $_SERVER['REQUEST_URI'] . '"/>';
     echo "</form>";
     echo "\n\t\t<script language=\"javascript\" type=\"text/javascript\t\"><!--\n\t\t\tTreeTable.prototype.trees['{$treetableid}'] = new TreeTable('{$treetableid}','');\n\t\t//--></script>\n\t\t";
     $out = ob_get_contents();
     ob_end_clean();
     return $out;
 }
Esempio n. 3
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);
 }
Esempio n. 4
0
 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);
 }
Esempio n. 5
0
 function handle(&$params)
 {
     $app = Dataface_Application::getInstance();
     if (!isset($_GET['code'])) {
         // We need this parameter or we can do nothing.
         return PEAR::raiseError(df_translate('actions.activate.MESSAGE_MISSING_CODE_PARAMETER', 'The code parameter is missing from your request.  Validation cannot take place.  Please check your url and try again.'), DATAFACE_E_ERROR);
     }
     // Step 0:  Find out what the redirect URL will be
     // We accept --redirect markers to specify which page to redirect
     // to after we're done.  This will usually be the page that the
     // user was on before they went to the login page.
     if (isset($_SESSION['--redirect'])) {
         $url = $_SESSION['--redirect'];
     } else {
         if (isset($_SESSION['-redirect'])) {
             $url = $_SESSION['-redirect'];
         } else {
             if (isset($_REQUEST['--redirect'])) {
                 $url = $_REQUEST['--redirect'];
             } else {
                 if (isset($_REQUEST['-redirect'])) {
                     $url = $_REQUEST['-redirect'];
                 } else {
                     $url = $app->url('-action=' . $app->_conf['default_action']);
                 }
             }
         }
     }
     if (strpos($url, '?') === false) {
         $url .= '?';
     }
     // Step 1: Delete all registrations older than time limit
     $time_limit = 24 * 60 * 60;
     // 1 day
     if (isset($params['time_limit'])) {
         $time_limit = intval($params['time_limit']);
     }
     $res = xf_db_query("delete from dataface__registrations \n\t\t\t\twhere registration_date < '" . addslashes(date('Y-m-d H:i:s', time() - $time_limit)) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to delete registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     // Step 2: Load the specified registration information
     $res = xf_db_query("select registration_data from dataface__registrations\n\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to load registration information due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     if (xf_db_num_rows($res) == 0) {
         // We didn't find any records matching the prescribed code, so
         // we redirect the user to their desired page and inform them
         // that the registration didn't work.
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_NOT_FOUND', 'No registration information could be found to match this code.  Please try registering again.');
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
     // Step 3: Check to make sure that there are no other users with the
     // same name.
     list($raw_data) = xf_db_fetch_row($res);
     $values = unserialize($raw_data);
     $appdel = $app->getDelegate();
     if (isset($appdel) and method_exists($appdel, 'validateRegistrationForm')) {
         $res = $appdel->validateRegistrationForm($values);
         if (PEAR::isError($res)) {
             $msg = $res->getMessage();
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     } else {
         $res = xf_db_query("select count(*) from \n\t\t\t\t`" . str_replace('`', '', $app->_conf['_auth']['users_table']) . "` \n\t\t\t\twhere `" . str_replace('`', '', $app->_conf['_auth']['username_column']) . "` = '" . addslashes($values[$app->_conf['_auth']['username_column']]) . "'\n\t\t\t\t", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to find user records due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         list($num) = xf_db_fetch_row($res);
         if ($num > 0) {
             $msg = df_translate('actions.activate.MESSAGE_DUPLICATE_USER', 'Registration failed because a user already exists by that name.  Try registering again with a different name.');
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     }
     // Step 4: Save the registration data and log the user in.
     $record = new Dataface_Record($app->_conf['_auth']['users_table'], array());
     $record->setValues($values);
     $res = $record->save();
     if (PEAR::isError($res)) {
         $app->redirect($url . '&--msg=' . urlencode($res->getMessage()));
     } else {
         $res = xf_db_query("delete from dataface__registrations\n\t\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to clean up old registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_COMPLETE', 'Registration complete.  You are now logged in.');
         $_SESSION['UserName'] = $record->strval($app->_conf['_auth']['username_column']);
         import('Dataface/Utilities.php');
         Dataface_Utilities::fireEvent('after_action_activate', array('record' => $record));
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
 }
Esempio n. 6
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;
    }
Esempio n. 7
0
 /**
  * Groups an array of Records (or associative arrays) together based on a specific field.
  * @param array $params Array of parameters
  * @param Dataface_SkinTool &$smarty Reference to Smarty template engine.
  * @param array $params[from] The array that is to be grouped.
  * @param string $params[var] The name of the variable to assign the grouped structure to.
  * @param string $params[on] The name of the field on which to group the records.
  * @param string $params[order] A comma-delimited string of order directives to specify the 
  *		order in which the records should be displayed.
  * @param string $params[titles] Titles for the groups in a format similar to css attributes.
  *
  */
 function group($params, &$smarty)
 {
     import('Dataface/Utilities.php');
     if (empty($params['from'])) {
         throw new Exception('group: Please specify a from parameter.', E_USER_ERROR);
     }
     if (empty($params['var'])) {
         throw new Exception('group: Please specify a var parameter.', E_USER_ERROR);
     }
     if (empty($params['on'])) {
         throw new Exception('group: Please specify a field parameter.', E_USER_ERROR);
     }
     if (!empty($params['order'])) {
         $order = explode(',', $params['order']);
     } else {
         $order = array();
     }
     if (!empty($params['titles'])) {
         $titles = array_map('trim', explode(';', $params['titles']));
         $titles2 = array();
         foreach ($titles as $title) {
             list($titleKey, $titleValue) = array_map('trim', explode(':', $title));
             $titles2[$titleKey] = $titleValue;
         }
     } else {
         $titles2 = array();
     }
     $cats = Dataface_Utilities::groupBy($params['on'], $params['from'], $order, $titles2);
     $context = array($params['var'] => &$cats);
     $smarty->assign($context);
 }
Esempio n. 8
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);
 }
Esempio n. 9
0
File: new.php Progetto: promoso/HVAC
 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);
 }
Esempio n. 10
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);
 }
Esempio n. 11
0
 function authenticate()
 {
     $app =& Dataface_Application::getInstance();
     if (!$this->authEnabled) {
         return true;
     }
     $app->startSession($this->conf);
     $appdel =& $app->getDelegate();
     // Fire a trigger before we authenticate
     if (isset($appdel) and method_exists($appdel, 'before_authenticate')) {
         $appdel->before_authenticate();
     }
     if (isset($_REQUEST['-action']) and $_REQUEST['-action'] == 'logout') {
         // the user has invoked a logout request.
         if (isset($appdel) and method_exists($appdel, 'before_action_logout')) {
             $res = $appdel->before_action_logout();
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
         $username = @$_SESSION['UserName'];
         session_destroy();
         import('Dataface/Utilities.php');
         Dataface_Utilities::fireEvent('after_action_logout', array('UserName' => $username));
         if (isset($this->delegate) and method_exists($this->delegate, 'logout')) {
             $this->delegate->logout();
         }
         if (isset($_REQUEST['-redirect']) and !empty($_REQUEST['-redirect'])) {
             header('Location: ' . $_REQUEST['-redirect']);
         } else {
             if (isset($_SESSION['-redirect'])) {
                 $redirect = $_SESSION['-redirect'];
                 unset($_SESSION['-redirect']);
                 header('Location: ' . $redirect);
                 exit;
             } else {
                 header('Location: ' . DATAFACE_SITE_HREF);
             }
         }
         // forward to the current page again now that we are logged out
         exit;
     }
     if (isset($_REQUEST['-action']) and $_REQUEST['-action'] == 'login') {
         if ($this->isLoggedIn()) {
             header('Location: ' . DATAFACE_SITE_HREF . '?--msg=' . urlencode("You are logged in"));
             exit;
         }
         if ($this->isLockedOut()) {
             header('Location: ' . DATAFACE_SITE_HREF . '?--msg=' . urlencode("Sorry, you are currently locked out of the site due to failed login attempts.  Please try again later, or contact a system administrator for help."));
             exit;
         }
         // The user is attempting to log in.
         $creds = $this->getCredentials();
         $approved = $this->checkCredentials();
         if (isset($creds['UserName']) and !$approved) {
             $this->flagFailedAttempt($creds);
             return PEAR::raiseError(df_translate('Incorrect Password', 'Sorry, you have entered an incorrect username /password combination.  Please try again.'), DATAFACE_E_LOGIN_FAILURE);
         } else {
             if (!$approved) {
                 $this->showLoginPrompt();
                 exit;
             }
         }
         $this->clearFailedAttempts();
         // If we are this far, then the login worked..  We will store the
         // userid in the session.
         $_SESSION['UserName'] = $creds['UserName'];
         import('Dataface/Utilities.php');
         Dataface_Utilities::fireEvent('after_action_login', array('UserName' => $_SESSION['UserName']));
         if (isset($_REQUEST['-redirect']) and !empty($_REQUEST['-redirect'])) {
             header('Location: ' . $_REQUEST['-redirect']);
             exit;
         } else {
             if (isset($_SESSION['-redirect'])) {
                 $redirect = $_SESSION['-redirect'];
                 unset($_SESSION['-redirect']);
                 header('Location: ' . $redirect);
                 exit;
             }
         }
         // Now we forward to the homepage:
         header('Location: ' . $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF);
         exit;
     }
     if (isset($this->delegate) and method_exists($this->delegate, 'authenticate')) {
         $res = $this->delegate->authenticate();
         if (PEAR::isError($res) and $res->getCode() == DATAFACE_E_REQUEST_NOT_HANDLED) {
             // we just pass the buck
         } else {
             return $res;
         }
     }
     if (isset($this->conf['pre_auth_types'])) {
         $pauthtypes = explode(',', $this->conf['pre_auth_types']);
         if ($pauthtypes) {
             $oldType = $this->authType;
             foreach ($pauthtypes as $pauthtype) {
                 $this->setAuthType($pauthtype);
                 if (isset($this->delegate) and method_exists($this->delegate, 'authenticate')) {
                     $res = $this->delegate->authenticate();
                     if (PEAR::isError($res) and $res->getCode() == DATAFACE_E_REQUEST_NOT_HANDLED) {
                         // pass the buck
                     } else {
                         return $res;
                     }
                 }
             }
             $this->setAuthType($oldType);
         }
     }
 }
Esempio n. 12
0
 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);
 }
Esempio n. 13
0
 /**
  * Flattens the variables of a query so that they can be written safely
  * to an HTML form.
  *
  * <p>E.g.:
  * <code> [
  *			'userid'=>10,
  *			'FirstName'=>'Steve',
  *			'LastName'=>'Hannah',
  *			'Address'=> [
  *				'Country'=>'Canada',
  *				'Province'=>'BC'
  *			]
  *		  ]
  * </code>
  * would be converted to:
  * <code>
  *			[
  *				'userid'=>10,
  *				'FirstName'=>'Steve',
  *				'LastName'=>'Hannah',
  *				'Address[Country]'=>'Canada',
  *				'Address[Province]'=>'BC'
  *			]
  *	</code>
  *
  * @param array $in The input query array.
  * @param array &$out The output query array.
  * @param $path $path An array representing the path of the current element
  *		since this method uses itself recursively.
  *
  * @return void
  */
 public static function flattenQuery($in, &$out, $path = array())
 {
     $origPath = $path;
     if (!empty($path)) {
         $prefix = array_shift($path);
         if (!empty($path)) {
             $prefix .= '[' . implode('][', $path) . ']';
         }
     } else {
         $prefix = '';
     }
     $hasprefix = !empty($prefix);
     foreach ($in as $key => $value) {
         //if ( substr($key,0,2) == '--' ) continue;
         if (is_array($value)) {
             $origPath[] = $key;
             Dataface_Utilities::flattenQuery($value, $out, $origPath);
         } else {
             if ($hasprefix) {
                 $out[$prefix . '[' . $key . ']'] = $value;
             } else {
                 $out[$key] = $value;
             }
         }
     }
 }