function handle($params)
 {
     try {
         if (@$_POST) {
             $this->do_post();
         } else {
             $this->do_get();
         }
     } catch (Exception $ex) {
         error_log(__FILE__ . '[' . __LINE__ . ']:' . $ex->getMessage());
         if (@$_REQUEST['--format'] === 'json') {
             if ($ex->getCode() === 400) {
                 $this->json_out(array('code' => 400, 'message' => 'You don\'t have permission to hide and show columns.'));
             } else {
                 $this->json_out(array('code' => 500, 'message' => 'An error occurred while updating the column preferences.  See server error log for details.'));
             }
         } else {
             if ($ex->getCode() === 400) {
                 return Dataface_Error::permissionDenied();
             } else {
                 throw $ex;
             }
         }
     }
 }
 function handle($params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (!isset($query['-relationship'])) {
         return PEAR::raiseError("No relationship specified.");
     }
     $table =& Dataface_Table::loadTable($query['-table']);
     $record =& $app->getRecord();
     if (!$record) {
         return Dataface_Error::permissionDenied("No record found");
     }
     $perms = $record->getPermissions(array('relationship' => $query['-relationship']));
     if (!@$perms['view related records']) {
         return Dataface_Error::permissionDenied('You don\'t have permission to view this relationship.');
     }
     $action = $table->getRelationshipsAsActions(array(), $query['-relationship']);
     if (isset($query['-template'])) {
         df_display(array('record' => $record), $query['-template']);
     } else {
         if (isset($action['template'])) {
             df_display(array('record' => $record), $action['template']);
         } else {
             df_display(array('record' => $record), 'Dataface_Related_Records_List.html');
         }
     }
 }
 function handle($params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $record =& $app->getRecord();
     if (!$record) {
         return PEAR::raiseError("No record found.", DATAFACE_E_NOTICE);
     }
     if (!isset($query['-relationship'])) {
         return PEAR::raiseError("No relationship specified.");
     }
     $table =& Dataface_Table::loadTable($query['-table']);
     $action = $table->getRelationshipsAsActions(array(), $query['-relationship']);
     if (@$action['permission'] and !$record->checkPermission($action['permission'])) {
         return Dataface_Error::permissionDenied();
     }
     ob_start();
     import('Dataface/RelationshipCheckboxForm.php');
     $form = new Dataface_RelationshipCheckboxForm($record, $query['-relationship']);
     $out = ob_get_contents();
     ob_end_clean();
     if (isset($query['-template'])) {
         df_display(array('form' => $out), $query['-template']);
     } else {
         if (isset($action['template'])) {
             df_display(array('form' => $out), $action['template']);
         } else {
             df_display(array('form' => $out), 'Dataface_related_records_checkboxes.html');
         }
     }
 }
Exemple #4
0
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     $website = df_get_record('websites', array('website_id' => '=' . $query['website_id']));
     if (!$website) {
         throw new Exception("Website could not be found.");
     }
     if (!$website->checkPermission('capture strings')) {
         return Dataface_Error::permissionDenied("You don't have permission to perform this action.");
     }
     Dataface_JavascriptTool::getInstance()->import('swete/actions/swete_tool_bar.js');
     import('inc/SweteSite.class.php');
     df_display(array('website' => $website, 'websiteWrapper' => new SweteSite($website)), 'swete/actions/toolbar_wrapper.html');
 }
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $related_record = df_get_record_by_id($query['-related-record-id']);
     if (!$related_record || PEAR::isError($related_record)) {
         $this->out_404();
     }
     $app->_conf['orig_permissions'] = $related_record->_record->getPermissions();
     Dataface_PermissionsTool::addContextMask($related_record);
     $perms = $related_record->getPermissions();
     //print_r($perms);exit;
     if (!@$perms['view']) {
         return Dataface_Error::permissionDenied('You don\'t have permission to view this record.');
     }
     $query['-relationship'] = $related_record->_relationship->getName();
     Dataface_JavascriptTool::getInstance()->import('xataface/actions/view_related_record.js');
     df_display(array('related_record' => $related_record), 'xataface/actions/view_related_record.html');
 }
Exemple #6
0
    function handle($params)
    {
        $app = Dataface_Application::getInstance();
        $auth = Dataface_AuthenticationTool::getInstance();
        $user = $auth->getLoggedInUser();
        $username = $auth->getLoggedInUsername();
        if (!$user or !$username) {
            return Dataface_Error::permissionDenied('You must be logged in to change your password');
        }
        if ($_POST) {
            try {
                if (!@$_POST['--password1'] || !@$_POST['--password2']) {
                    throw new Exception("Please enter your new password in both fields provided.");
                }
                if (!@$_POST['--current-password']) {
                    throw new Exception("Please enter your current password in the field provided.");
                }
                $_REQUEST['UserName'] = $username;
                $_REQUEST['Password'] = $_POST['--current-password'];
                if (!$auth->checkCredentials()) {
                    throw new Exception("The password you entered is incorrect.  Please try again.");
                }
                if (strcmp($_POST['--password1'], $_POST['--password2']) !== 0) {
                    throw new Exception("Your new passwords don't match.  Please ensure that you retype your new password correctly.");
                }
                $res = $auth->setPassword($_POST['--password1']);
                $this->out(array('code' => 200, 'message' => 'Your password has been successfully changed'));
                exit;
            } catch (Exception $ex) {
                $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage()));
                exit;
            }
        } else {
            $app->addHeadContent(sprintf('<link rel="stylesheet" type="text/css" href="%s"/>
				<script src="%s"></script>
				<script src="%s"></script>', htmlspecialchars(DATAFACE_URL . '/css/change_password.css'), htmlspecialchars(DATAFACE_URL . '/js/jquery.packed.js'), htmlspecialchars(DATAFACE_URL . '/js/change_password.js')));
            df_display(array(), 'change_password.html');
        }
    }
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $auth = Dataface_AuthenticationTool::getInstance();
     $user = $auth->getLoggedInUser();
     $username = $auth->getLoggedInUsername();
     if (!$user or !$username) {
         return Dataface_Error::permissionDenied('You must be logged in to change your password');
     }
     if ($_POST) {
         try {
             if (!@$_POST['--password1'] || !@$_POST['--password2']) {
                 throw new Exception("Please enter your new password in both fields provided.");
             }
             if (!@$_POST['--current-password']) {
                 throw new Exception("Please enter your current password in the field provided.");
             }
             $_REQUEST['UserName'] = $username;
             $_REQUEST['Password'] = $_POST['--current-password'];
             if (!$auth->checkCredentials()) {
                 throw new Exception("The password you entered is incorrect.  Please try again.");
             }
             if (strcmp($_POST['--password1'], $_POST['--password2']) !== 0) {
                 throw new Exception("Your new passwords don't match.  Please ensure that you retype your new password correctly.");
             }
             $res = $auth->setPassword($_POST['--password1']);
             $this->out(array('code' => 200, 'message' => 'Your password has been successfully changed'));
             exit;
         } catch (Exception $ex) {
             $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage()));
             exit;
         }
     } else {
         $jt = Dataface_JavascriptTool::getInstance();
         $jt->import('change_password.js');
         df_display(array(), 'change_password.html');
     }
 }
Exemple #8
0
 /**
  * @ingroup actions
  */
 function handle(&$params)
 {
     import('Dataface/FeedTool.php');
     $app =& Dataface_Application::getInstance();
     $ft = new Dataface_FeedTool();
     $query = $app->getQuery();
     if (@$query['-relationship']) {
         $record =& $app->getRecord();
         $perms = $record->getPermissions(array('relationship' => $query['-relationship']));
         if (!@$perms['related records feed']) {
             return Dataface_Error::permissionDenied('You don\'t have permission to view this relationship.');
         }
     }
     header("Content-Type: application/xml; charset=" . $app->_conf['oe']);
     $conf = $ft->getConfig();
     $query['-skip'] = 0;
     if (!isset($query['-sort']) and !@$query['-relationship']) {
         $table =& Dataface_Table::loadTable($query['-table']);
         $modifiedField = $table->getLastUpdatedField(true);
         if ($modifiedField) {
             $query['-sort'] = $modifiedField . ' desc';
         }
     }
     if (!isset($query['-limit']) and !@$query['-relationship']) {
         $default_limit = $conf['default_limit'];
         if (!$default_limit) {
             $default_limit = 60;
         }
         $query['-limit'] = $default_limit;
     }
     if (isset($query['--format'])) {
         $format = $query['--format'];
     } else {
         $format = 'RSS1.0';
     }
     echo $ft->getFeedXML($query, $format);
     exit;
 }
Exemple #9
0
 function handle(&$params)
 {
     if (!$_POST) {
         return PEAR::raiseError("This method is only available via POST");
     }
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $records = df_get_selected_records($query);
     //print_r(array_keys($records));exit;
     $updated = 0;
     $errs = array();
     foreach ($records as $rec) {
         if (!$rec->checkPermission('delete')) {
             $errs[] = Dataface_Error::permissionDenied("You do not have permission to delete '" . $rec->getTitle() . "' because you do not have the 'delete' permission.");
             continue;
         }
         $res = $rec->delete(true);
         if (PEAR::isError($res)) {
             $errs[] = $res->getMessage();
         } else {
             $updated++;
         }
     }
     if ($errs) {
         $_SESSION['--msg'] = 'Errors Occurred:<br/> ' . implode('<br/> ', $errs);
     } else {
         $_SESSION['--msg'] = "No errors occurred";
     }
     $url = $app->url('-action=list');
     if (@$_POST['--redirect']) {
         $url = base64_decode($_POST['--redirect']);
     }
     $url .= '&--msg=' . urlencode($updated . ' records were deleted.');
     header('Location: ' . $url);
     exit;
 }
Exemple #10
0
 function handlePost(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (!@$_POST['--field']) {
         return PEAR::raiseError('No field specified');
     }
     $record =& $app->getRecord();
     if (!$record) {
         return PEAR::raiseError('No record found');
     }
     $fieldDef =& $record->_table->getField($_POST['--field']);
     if (PEAR::isError($fieldDef)) {
         return $fieldDef;
     }
     if (!$record->checkPermission('edit', array('field' => $fieldDef['Field']))) {
         return Dataface_Error::permissionDenied('You don\'t have permission to edit this field.');
     }
     if ($fieldDef['Type'] == 'container') {
         $fileName = $record->val($fieldDef['Field']);
         if (!$fileName) {
             return PEAR::raiseError("This record does not contain a file in the {$fieldDef['Field']} field.");
         }
         // We need to delete the file from the file system.
         $path = $fieldDef['savepath'];
         $filePath = $path . '/' . basename($fileName);
         @unlink($filePath);
         $record->setValue($fieldDef['Field'], null);
         if (@$fieldDef['mimetype']) {
             $mimeTypeField =& $record->_table->getField($fieldDef['mimetype']);
             if (!PEAR::isError($mimeTypeField)) {
                 $record->setValue($fieldDef['mimetype'], null);
             }
         }
         $res = $record->save();
         if (PEAR::isError($res)) {
             return $res;
         }
     } else {
         if ($record->_table->isBlob($fieldDef['Field'])) {
             $record->setValue($fieldDef['Field'], null);
             if (@$fieldDef['mimetype']) {
                 $mimetypeField =& $record->_table->getField($fieldDef['mimetype']);
                 if (!PEAR::isError($mimetypeField)) {
                     $record->setValue($fieldDef['mimetype'], null);
                 }
             }
             if (@$fieldDef['filename']) {
                 $filenameField =& $record->_table->getField($fieldDef['filename']);
                 if (!PEAR::isError($filenameField)) {
                     $record->setValue($fieldDef['filename'], null);
                 }
             }
             $res = $record->save();
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
     }
     // Now that we have been successful, let's return a success reply.
     if (@$query['--format'] == 'json') {
         import('Services/JSON.php');
         $json = new Services_JSON();
         header('Content-type: text/json; charset=' . $app->_conf['oe']);
         echo $json->encode(array('success' => 1, '--msg' => 'Successfully deleted file'));
         exit;
     } else {
         $redirect = '';
         if (!$redirect) {
             $redirect = @$query['-redirect'];
         }
         if (!$redirect) {
             $redirect = @$_SERVER['HTTP_REFERER'];
         }
         if (!$redirect) {
             $redirect = $record->getURL('-action=edit');
         }
         if (!$redirect or PEAR::isError($redirect)) {
             $redirect = DATAFACE_SITE_HREF;
         }
         if (strpos($redirect, '?') === false) {
             $redirect .= '?';
         }
         $redirect .= '&--msg=' . urlencode("File successfully deleted.");
         header("Location: {$redirect}");
         exit;
     }
 }
Exemple #11
0
 /**
  * Adds a value to a valuelist.  This only works for valuelists
  * that are pulled from the database.
  * @param Dataface_Table The table to add the valuelist to.
  * @param string $valuelistName The name of the valuelist.
  * @param string $value The value to add.
  * @param string $key The key to add.
  * @param boolean $checkPerms If true, this will first check permissions
  *		  before adding the value.
  * @returns mixed May return a permission denied error if there is insufficient
  *			permissions.
  */
 function addValueToValuelist(&$table, $valuelistName, $value, $key = null, $checkPerms = false)
 {
     import('Dataface/ConfigTool.php');
     $configTool =& Dataface_ConfigTool::getInstance();
     $conf = $configTool->loadConfig('valuelists', $table->tablename);
     $relname = $valuelistName . '__valuelist';
     //$conf = array($relname=>$conf);
     $table->addRelationship($relname, $conf[$valuelistName]);
     $rel =& $table->getRelationship($relname);
     $fields =& $rel->fields();
     if (count($fields) > 1) {
         $valfield = $fields[1];
         $keyfield = $fields[0];
     } else {
         $valfield = $fields[0];
         $keyfield = $fields[0];
     }
     $record = new Dataface_Record($table->tablename);
     $rrecord = new Dataface_RelatedRecord($record, $relname);
     if ($checkPerms and !$rrecord->checkPermission('edit', array('field' => $valfield))) {
         return Dataface_Error::permissionDenied();
     }
     $rrecord->setValue($valfield, $value);
     if (isset($key) and isset($keyfield)) {
         if ($checkPerms and !$rrecord->checkPermission('edit', array('field' => $keyfield))) {
             return Dataface_Error::permissionDenied();
         }
         $rrecord->setValue($keyfield, $key);
     }
     import('Dataface/IO.php');
     $io = new Dataface_IO($table->tablename);
     $res = $io->addRelatedRecord($rrecord);
     if (PEAR::isError($res)) {
         return $res;
     }
     return array('key' => $rrecord->val($keyfield), 'value' => $rrecord->val($valfield));
 }
Exemple #12
0
 /**
  * @brief Pushes data from a form widget into a Dataface_Record object.  This will
  * try to delegate to the following mechanisms if found:
  *
  * -# WidgetHandler::pushField() if it exists for the current widget type.
  * -# WidgetHandler::pushValue() if it exists for the current widget type.
  *
  * @param Dataface_Record &$record The record into which the data is being pushed.
  * @param array &$field The field configuration array as loaded from the fields.ini
  *				file.
  * @param HTML_QuickForm &$form The form from which the data is being taken.
  * @param string $formFieldName The name of the field in the form.
  * @param boolean $new Whether this is a new record form.
  * @returns mixed PEAR_Error if there is an error.  true on success.
  *
  * @see WidgetHandler::pushField()
  * @see pullField()
  */
 function pushField($record, &$field, $form, $formFieldName, $new = false)
 {
     if (!is_array($field)) {
         throw new Exception("No field passed to pushField");
     }
     // See if there is a widgethandler registered for this widget type
     $table =& $record->_table;
     $widget =& $field['widget'];
     $widgetHandler =& $this->getWidgetHandler($widget['type']);
     if (isset($widgetHandler) and method_exists($widgetHandler, 'pushField')) {
         return $widgetHandler->pushField($record, $field['name'], $form, $formFieldName, $new);
     }
     $metaValues = array();
     // will store any meta values that are produced by pushValue
     // a meta value is a field that exists only to support another field.
     // Currently the only examples of this are filename and mimetype fields
     // for File fields.
     /*
      *
      * First we must obtain the value from the element on the form.
      * $metaValues will hold an associative array of keys and values
      * of Meta fields for this field.  Meta fields are fields that describe
      * this field.  For example, if this field is a BLOB, then a meta field
      * might contain this field's mimetype.
      *
      */
     if (is_a($formFieldName, 'HTML_QuickForm_element')) {
         $element =& $formFieldName;
         unset($formFieldName);
         $formFieldName = $element->getName();
     } else {
         $element =& $this->getElement($form, $field, $formFieldName);
     }
     if (PEAR::isError($element) || !is_a($element, 'HTML_QuickForm_element') || $element->isFrozen() || $element->getType() == 'static') {
         return;
     }
     $value = $this->pushValue($record, $field, $form, $element, $metaValues);
     $params = array();
     if (!$record->validate($field['name'], $value, $params)) {
         return Dataface_Error::permissionDenied($params['message']);
     }
     if (PEAR::isError($value)) {
         $value->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushField.ERROR_GETTING_VALUE', "Error getting value for field '{$field['name']}' in QuickForm::pushField()", array('file' => "_", 'line' => 0, 'fieldname' => $field['name'])));
         return $value;
     }
     if (!$table->isMetaField($field['name'])) {
         /*
          *
          * A MetaField is a field that should not be updated on its own merit.
          * An example of a MetaField is a mimetype field for a BLOB field.  This
          * field will be updated as a meta value for the BLOB field when the BLOB 
          * field is updated.
          *
          */
         $res = $record->setValue($field['name'], $value);
         if (PEAR::isError($res)) {
             $value->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushField.ERROR_SETTING_VALUE', "Error setting value for field '{$field['name']}' in QuickForm::pushField()", array('file' => "_", 'line' => 0, 'fieldname' => $field['name'])));
             throw new Exception($value->toString(), E_USER_ERROR);
             return $res;
         }
     }
     /*
      *
      * If this field has any meta fields, then we will set them now.
      *
      */
     foreach ($metaValues as $key => $value) {
         $res = $record->setValue($key, $value);
         if (PEAR::isError($res)) {
             $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushField.ERROR_SETTING_METAVALUE', "Error setting value for meta field '{$key}' in QuickForm::pushField() ", array('file' => "_", 'line' => 0, 'field' => $key)));
             throw new Exception($res->toString(), E_USER_ERROR);
         }
     }
 }
Exemple #13
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);
 }
 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);
 }
Exemple #15
0
 function process($values)
 {
     $app =& Dataface_Application::getInstance();
     import('Dataface/CopyTool.php');
     $copyTool =& Dataface_CopyTool::getInstance();
     $query =& $app->getQuery();
     //if ( @$values['-copy_replace:copy'] ){
     //}
     $orig_replacements = $values['-copy_replace_form:replace'];
     $update_fields = explode('-', $values['-copy_replace:fields']);
     //print_r($update_fields);
     $replacements = array();
     foreach ($update_fields as $fld) {
         if (!$fld) {
             continue;
         }
         $replacements[$fld] = $orig_replacements[$fld];
     }
     $blanks = @$_POST['-copy_replace:blank_flag'];
     if (!$blanks) {
         $blanks = array();
     }
     foreach ($blanks as $key => $val) {
         if ($val) {
             $replacements[$key] = null;
         }
     }
     if (!is_array($replacements)) {
         return PEAR::raiseError(df_translate('actions.copy_replace.no_fields_selected_to_change', "No fields were selected to change."));
     }
     $records = df_get_selected_records($query);
     if (count($records) == 0) {
         $q = $query;
         $q['-limit'] = 99999;
         $q['-skip'] = 0;
         $records =& df_get_records_array($q['-table'], $q);
     }
     $fields = $this->getFieldsForRecord($records[0]);
     $dummyForm =& $this->getTableForm($query['-table']);
     foreach ($replacements as $key => $val) {
         $dummyForm =& $this->getTableForm($fields[$key]['tablename']);
         if (strpos($val, '=') === 0) {
             // This is a calculated change so we don't try to push the value
             // we'll let it go through
             continue;
         }
         $val = $dummyForm->pushValue($key, $metaValues, $this->form->getElement('-copy_replace_form:replace[' . $key . ']'));
         //echo $val;//));
         //
         if ($val === '' and !@$blanks[$key]) {
             unset($replacements[$key]);
         } else {
             $replacements[$key] = $val;
         }
         unset($dummyForm);
     }
     $warnings = array();
     $messages = array();
     foreach ($records as $record) {
         if (@$values['-copy_replace:copy']) {
             // We are performing a copy.
             $relatedRecord = null;
             // This is a hack fix.  It should work with 1:n relationships
             // but will probably fail for n:m relationships.
             if (is_a($record, 'Dataface_RelatedRecord')) {
                 $relatedRecord = $record;
                 $record = $record->toRecord();
             }
             $res = $copyTool->copy($record, $replacements);
             if (PEAR::isError($res)) {
                 $warnings[] = $res;
             } else {
                 $messages[] = sprintf(df_translate('actions.copy_replace.successfully_copied_record_x_as_record_y', "Successfully copied record '%s' as record '%s'"), $record->getTitle(), $res->getTitle());
             }
             $warnings = array_merge($warnings, $copyTool->warnings);
         } else {
             if (!$record->checkPermission('edit')) {
                 $warnings[] = Dataface_Error::permissionDenied(sprintf(df_translate('actions.copy_replace.could_not_update_record_x_insufficient_permissions', "Could not update record '%s' because of insufficient permissions."), $record->getTitle()));
                 continue;
             }
             $failed = false;
             foreach ($replacements as $key => $val) {
                 if (!$record->checkPermission('edit', array('field' => $key))) {
                     $warnings[] = Dataface_Error::permissionDenied(sprintf(df_translate('actions.copy_replace.could_not_update_record_x_insufficient_permissions_on_field_y', "Could not update record '%s' because of insufficient permissions on field '%s'."), $record->getTitle(), $key));
                     $failed = true;
                 }
             }
             if ($failed) {
                 continue;
             }
             foreach ($replacements as $k => $v) {
                 if (strpos($v, '=') === 0) {
                     $replacements[$k] = $copyTool->evaluate($v, $k, $record);
                 }
             }
             $record->setValues($replacements);
             $res = $record->save();
             if (PEAR::isError($res)) {
                 $warnings[] = $res;
             } else {
                 $messages[] = sprintf(df_translate('actions.copy_replace.successfully_updated_title', "Successfully updated '%s'"), $record->getTitle());
             }
         }
         unset($record);
     }
     if (@$values['-copy_replace:copy']) {
         $action = 'copied';
     } else {
         $action = 'updated';
     }
     $this->message = sprintf(df_translate('actions.copy_replace.x_records_y_successfully_count_warnings', '%d records %s successfully. %d warnings.'), count($messages), df_translate($action, $action), count($warnings));
     //$this->message = count($messages).' records '.$action.' successfully. '.count($warnings).' warnings.';
     if (count($warnings)) {
         $warning_msgs = array();
         foreach ($warnings as $warning) {
             $warning_msgs[] = $warning->getMessage();
         }
     } else {
         $warning_msgs = array();
     }
     //print_r($warning_msgs);
     $this->message .= '<br>' . implode('<br>', $warning_msgs);
     return true;
 }
Exemple #16
0
 /**
  * Removes the given related record from its relationship.
  *
  * @param Dataface_RelatedRecord &$related_record The related record to be removed.
  * @param boolean $delete If true then the record will also be deleted from 
  * 	the database.
  * @since 0.6.1
  */
 function removeRelatedRecord(&$related_record, $delete = false, $secure = false)
 {
     if ($secure && !$related_record->_record->checkPermission('remove related record', array('relationship' => $related_record->_relationshipName))) {
         // Use security to check to see if we are allowed to delete this
         // record.
         //echo $related_record->_record->_table->getDelegate()->getRoles(array('relationship'=>$related_record->_relationshipName));exit;
         return Dataface_Error::permissionDenied(df_translate('scripts.Dataface.IO.removeRelatedRecord.PERMISSION_DENIED', 'Could not remove record "' . $related_record->getTitle() . '" from relationship "' . $related_record->_relationshipName . '" of record "' . $related_record->_record->getTitle() . '" because you have insufficient permissions.', array('title' => $related_record->getTitle(), 'relationship' => $related_record->_relationshipName, 'parent' => $related_record->_record->getTitle())));
     }
     $res = $this->fireEvent('beforeRemoveRelatedRecord', $related_record);
     if (PEAR::isError($res)) {
         return $res;
     }
     /*
      * First we need to find out which table is the domain table.  The domain table
      * is the table that actually contains the records of interest.  The rest of
      * the tables are referred to as 'join' tables.
      */
     $domainTable = $related_record->_relationship->getDomainTable();
     if (PEAR::isError($domainTable)) {
         /*
          * Dataface_Relationship::getDomainTable() throws an error if there are 
          * no join tables.  We account for that by explicitly setting the domain
          * table to the first table in the list.
          */
         $domainTable = $related_record->_relationship->_schema['selected_tables'][0];
     }
     /*
      * Next we construct an IO object to write to the domain table.
      */
     $domainIO = new Dataface_IO($domainTable);
     $domainTable =& Dataface_Table::loadTable($domainTable);
     // reference to the Domain table Dataface_Table object.
     /*
      * Begin building queries.
      */
     $query = array();
     // query array to build the query to delete the record.
     $absVals = array();
     // same as query array except the keys are absolute field names (ie: Tablename.Fieldname)
     $currKeyNames = array_keys($domainTable->keys());
     // Names of key fields in the domain table
     foreach ($currKeyNames as $keyName) {
         $query[$keyName] = $related_record->val($keyName);
         $absVals[$domainTable->tablename . '.' . $keyName] = $query[$keyName];
     }
     $fkeys = $related_record->_relationship->getForeignKeyValues($absVals, null, $related_record->_record);
     $warnings = array();
     $confirmations = array();
     foreach (array_keys($fkeys) as $currTable) {
         // For each table in the relationship we go through and delete its record.
         $io = new Dataface_IO($currTable);
         $record = new Dataface_Record($currTable, array());
         $res = $io->read($fkeys[$currTable], $record);
         //patch for Innodb foreign keys with ON DELELE CASCADE
         // Contributed by Optik
         if (!$io->recordExists($record, null, $currTable)) {
             $warnings[] = df_translate('scripts.Dataface.IO.removeRelatedRecord.ERROR_RECORD_DOESNT_EXIST', "Failed to delete entry for record '" . $record->getTitle() . "' in table '{$currTable}' because record doesn't exist.", array('title' => $record->getTitle(), 'currTable' => $currTable));
             unset($record);
             unset($io);
             continue;
         }
         // -- end patch for Innodb foreign keys
         if ($currTable == $domainTable->tablename and !$delete) {
             // Unless we have specified that we want the domain table record
             // deleted, we leave it alone!
             unset($record);
             unset($io);
             continue;
         }
         // Let's figure out whether we need to use security for deleting this
         // record.
         // If security is on, and it is the domain table, and the user doesn't
         // have the 'delete related record' permission  then we need to use
         // security
         if ($currTable == $domainTable->tablename and $secure and !$related_record->_record->checkPermission('delete related record', array('relationship' => $related_record->_relationshipName))) {
             $useSecurity = true;
         } else {
             $useSecurity = false;
         }
         $res = $io->delete($record, $useSecurity);
         if (PEAR::isError($res) && Dataface_Error::isError($res)) {
             //$this->logError($res);
             return $res;
         } else {
             if (PEAR::isError($res)) {
                 $warnings[] = $res;
             } else {
                 $confirmations[] = df_translate('Successfully deleted record', "Successfully deleted entry for record '" . $record->getTitle() . "' in table '{$currTable}'", array('title' => $record->getTitle(), 'table' => $currTable));
             }
         }
         $record->__destruct();
         unset($record);
         unset($b);
         unset($io);
     }
     $res = $this->fireEvent('afterRemoveRelatedRecord', $related_record);
     if (PEAR::isError($res)) {
         return $res;
     }
     if (count($warnings) > 0) {
         return PEAR::raiseError(@implode("\n", $warnings), DATAFACE_E_WARNING);
     }
     if (count($confirmations) == 0) {
         return false;
     }
     return true;
 }
Exemple #17
0
 function handle(&$params)
 {
     $this->params =& $params['action'];
     unset($params);
     $params =& $this->params;
     Dataface_PermissionsTool::getInstance()->setDelegate(new dataface_actions_register_permissions_delegate());
     $app =& Dataface_Application::getInstance();
     $auth =& Dataface_AuthenticationTool::getInstance();
     import('Dataface/Ontology.php');
     Dataface_Ontology::registerType('Person', 'Dataface/Ontology/Person.php', 'Dataface_Ontology_Person');
     $this->ontology =& Dataface_Ontology::newOntology('Person', $app->_conf['_auth']['users_table']);
     $atts =& $this->ontology->getAttributes();
     $query =& $app->getQuery();
     if (!is_array(@$app->_conf['_auth'])) {
         return PEAR::raiseError("Cannot register when authentication is not enabled.", DATAFACE_E_ERROR);
     }
     if (isset($app->_conf['_auth']['email_column'])) {
         $atts['email'] =& $this->ontology->table->getField($app->_conf['_auth']['email_column']);
         $this->fieldnames['email'] = $app->_conf['_auth']['email_column'];
     }
     if ($auth->isLoggedIn()) {
         return Dataface_Error::permissionDenied("Sorry you cannot register once you are logged in.  If you want to register, you must first log out.");
     }
     if (!@$app->_conf['_auth']['allow_register']) {
         return PEAR::raiseError("Sorry, registration is not allowed.  Please contact the administrator for an account.", DATAFACE_E_ERROR);
     }
     $pt =& Dataface_PermissionsTool::getInstance();
     // Create a new record form on the users table
     $this->form =& df_create_new_record_form($app->_conf['_auth']['users_table']);
     // add the -action element so that the form will direct us back here.
     $this->form->addElement('hidden', '-action');
     $this->form->setDefaults(array('-action' => $query['-action']));
     // Check to make sure that there isn't another user with the same
     // username already.
     $validationResults = $this->validateRegistrationForm($_POST);
     if (count($_POST) > 0 and PEAR::isError($validationResults)) {
         $app->addMessage($validationResults->getMessage());
         $this->form->_errors[$app->_conf['_auth']['username_column']] = $validationResults->getMessage();
     }
     if (!PEAR::isError($validationResults) and $this->form->validate()) {
         // The form input seems OK.  Let's process the form
         // Since we will be using our own form processing for this action,
         // we need to manually push the field inputs into the Dataface_Record
         // object.
         $this->form->push();
         // Now we obtain the Dataface_Record object that is to be added.
         $rec =& $this->form->_record;
         $delegate =& $rec->_table->getDelegate();
         // Give the delegate classes an opportunity to have some fun
         if (isset($delegate) and method_exists($delegate, 'beforeRegister')) {
             $res = $delegate->beforeRegister($rec);
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
         $appdel =& $app->getDelegate();
         if (isset($appdel) and method_exists($appdel, 'beforeRegister')) {
             $res = $appdel->beforeRegister($rec);
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
         // This is where we actually do the processing.  This passes control
         // to the processRegistrationForm method in this class.
         $res = $this->form->process(array(&$this, 'processRegistrationForm'), true);
         // If there was an error in processing mark the error, and show the
         // form again.  Otherwise we just redirect to the next page and
         // let the user know that he was successful.
         if (PEAR::isError($res)) {
             $app->addError($res);
         } else {
             // Let the delegate classes perform their victory lap..
             if (isset($delegate) and method_exists($delegate, 'afterRegister')) {
                 $res = $delegate->afterRegister($rec);
                 if (PEAR::isError($res)) {
                     return $res;
                 }
             }
             if (isset($appdel) and method_exists($appdel, 'afterRegister')) {
                 $res = $appdel->afterRegister($rec);
                 if (PEAR::isError($res)) {
                     return $res;
                 }
             }
             // 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 (@$params['email_validation']) {
                 $individual = $this->ontology->newIndividual($this->form->_record);
                 $msg = df_translate('actions.register.MESSAGE_THANKYOU_PLEASE_VALIDATE', 'Thank you. An email has been sent to ' . $individual->strval('email') . ' with instructions on how to complete the registration process.', array('email' => $individual->strval('email')));
             } else {
                 // To save the user from having to log in after he has just filled
                 // in the registration form, we will just log him in right here.
                 $_SESSION['UserName'] = $this->form->exportValue($app->_conf['_auth']['username_column']);
                 $msg = df_translate('actions.register.MESSAGE_REGISTRATION_SUCCESSFUL', "Registration successful.  You are now logged in.");
             }
             // Now we actually forward to the success page along with a success message
             if (strpos($url, '?') === false) {
                 $url .= '?';
             }
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     }
     // We want to display the form, but not yet so we will use an output buffer
     // to store the form HTML in a variable and pass it to our template.
     ob_start();
     $this->form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('registration_form' => $out);
     // We don't want to keep the registration page in history, because we want to
     // be able to redirect the user back to where he came from before registering.
     $app->prefs['no_history'] = true;
     df_display($context, 'Dataface_Registration.html');
 }
 function handle(&$params)
 {
     if (!isset($_POST['-redirect']) and !isset($_POST['relatedList-body'])) {
         return PEAR::raiseError('Cannot reorder related records because no redirect url was specified in the POST parameters.' . Dataface_Error::printStackTrace());
     }
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (!($record = df_get_selected_records($query))) {
         $record =& $app->getRecord();
     } else {
         $record = $record[0];
     }
     if (PEAR::isError($record)) {
         return $record;
     }
     if (!$record) {
         return PEAR::raiseError('The specified record could not be found.');
     }
     if (!@$query['-relationship']) {
         return PEAR::raiseError("No relationship specified.");
     }
     $relationship =& $record->_table->getRelationship($query['-relationship']);
     if (PEAR::isError($relationship)) {
         return $relationship;
     }
     $orderColumn = $relationship->getOrderColumn();
     if (!$orderColumn) {
         return PEAR::raiseError('Could not reorder records of this relationship because it does not have any order column specified.');
     }
     if (!Dataface_PermissionsTool::checkPermission('reorder_related_records', $record, array('relationship' => $query['-relationship']))) {
         return Dataface_Error::permissionDenied('You do not have permission to reorder the records in this relationship.');
     }
     if (isset($_POST['relatedList-body'])) {
         $relatedIds = array_map('urldecode', $_POST['relatedList-body']);
         // In this case we are not just moving a record up or down the list,
         // we may be reordering the list altogether.
         // We may also just be ordering a subset of the list.
         // so we will want to be reordering the given set of records
         // with respect to each other.
         // First let's see if the ordering has been initialized yet.
         $records = array();
         //print_r($relatedIds);exit;
         foreach ($relatedIds as $recid) {
             //$recid = urldecode($recid);
             $records[] = df_get_record_by_id($recid);
         }
         $start = isset($query['-related:start']) ? $query['-related:start'] : 0;
         $record->sortRelationship($query['-relationship'], $start, $records);
         echo 'Sorted Successfully';
         exit;
     }
     if (!isset($_POST['-reorder:direction'])) {
         return PEAR::raiseError('Cannot reorder related records because no direction was specified.');
     }
     if (!isset($_POST['-reorder:index'])) {
         return PEAR::raiseError('Cannot reorder related records because no index was specified.');
     }
     $index = intval($_POST['-reorder:index']);
     switch ($_POST['-reorder:direction']) {
         case 'up':
             //echo "Moving up";exit;
             $res = $record->moveUp($query['-relationship'], $index);
             break;
         case 'down':
             $res = $record->moveDown($query['-relationship'], $index);
             break;
         default:
             return PEAR::raiseError('Invalid input for direction of reordering.  Must be up or down but received "' . $_POST['-reorder:direction'] . '"');
     }
     if (PEAR::isError($res)) {
         return $res;
     }
     header('Location: ' . $_POST['-redirect']);
     exit;
 }
Exemple #19
0
 function handle($params)
 {
     import('Dataface/ImportForm.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $form = new Dataface_ImportForm($query['-table']);
     $record =& $form->_record;
     if (is_object($record)) {
         if (!$record->checkPermission('import')) {
             return Dataface_Error::permissionDenied();
         }
     } else {
         if (!Dataface_PermissionsTool::checkPermission('import', Dataface_Table::loadTable($query['-table']))) {
             return Dataface_Error::permissionDenied();
         }
     }
     $form->_build();
     if ($form->validate()) {
         //echo "validated";
         $querystr = $form->exportValue('-query');
         $returnPage = $form->exportValue('--redirect');
         if (intval($form->_step) === 1) {
             if (preg_match('/--step=1/', $querystr)) {
                 $querystr = preg_replace('/--step=1/', '--step=2', $querystr);
             } else {
                 $querystr .= '&--step=2';
             }
             $importTablename = $form->process(array(&$form, 'import'));
             //echo "Table: $importTablename";
             //exit;
             //$link = 'Location: '.$_SERVER['PHP_SELF'].'?'.$querystr.'&--importTablename='.$importTablename;
             //echo $link;
             //exit;
             header('Location: ' . $_SERVER['PHP_SELF'] . '?' . $querystr . '&--importTablename=' . $importTablename . '&--redirect=' . urlencode($returnPage));
             exit;
         } else {
             $records = $form->process(array(&$form, 'import'));
             $returnPage = $form->exportValue('--redirect');
             //$keys  = $form->exportValue('__keys__');
             //$keys['-action'] = 'browse';
             //$keys['-step'] = null;
             //$keys['-query'] = null;
             //$link = Dataface_LinkTool::buildLink($keys);
             $link = $returnPage;
             $response =& Dataface_Application::getResponse();
             $msg = urlencode(trim("Records imported successfully.\n" . @$response['--msg']));
             if (strpos($link, '?') === false) {
                 $link .= '?';
             }
             header('Location: ' . $link . '&--msg=' . $msg);
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context['form'] = $out;
     $context['filters'] = $form->_filterNames;
     $context['step'] = $form->_step;
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             if (isset($query['-relationship'])) {
                 $template = 'Dataface_Import_RelatedRecords.html';
             } else {
                 $template = 'Dataface_Import_RelatedRecords.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);
 }
    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);
    }
Exemple #22
0
 /**
  * Builds an SQL query to copy the given record.  This honours permissions
  * and will only copy columns for which 'view' access is available in the
  * source record and 'edit' access is available in the destination record.
  *
  * Individual column failures (due to permissions) are recorded in the 
  * $warnings variable of this class.  It will be an array of Dataface_Error
  * objects.
  *
  * @param Dataface_Record $record The record being copied.
  * @param array $valls Values that should be placed in the copied version.
  * @param boolean $force If true this will perform the copy despite individual
  *			column warnings.
  * @returns string The SQL query to copy the record.
  */
 function buildCopyQuery($record, $vals = array(), $force = true)
 {
     $dummy = new Dataface_Record($record->_table->tablename, $vals);
     if (!$record->checkPermission('view') || !$dummy->checkPermission('edit')) {
         return Dataface_Error::permissionDenied("Failed to copy record '" . $record->getTitle() . "' because of insufficient permissions.");
     }
     $copy_fields = array_keys($record->_table->fields());
     // Go through each field and see if we have copy permission.
     // Copy permission is two-fold: 1- make sure the source is viewable
     //								2- make sure the destination is editable.
     $failed = false;
     foreach ($copy_fields as $key => $fieldname) {
         if (!$record->checkPermission('view', array('field' => $fieldname)) || !$dummy->checkPermission('edit', array('field' => $fieldname))) {
             $this->warnings[] = Dataface_Error::permissionDenied("The field '{$fieldname}' could not be copied for record '" . $record->getTitle() . "' because of insufficient permissions.");
             unset($copy_fields[$key]);
             $failed = true;
         }
     }
     // If we are not forcing completion, any failures will result in cancellation
     // of the copy.
     if (!$force and $failed) {
         return Dataface_Error::permissionDenied("Failed to copy the record '" . $record->getTitle() . "' due to insufficient permissions on one or more of the columns.");
     }
     // We don't copy auto increment fields.
     $auto_inc_field = $record->_table->getAutoIncrementField();
     if ($auto_inc_field) {
         $key = array_search($auto_inc_field, $copy_fields);
         if ($key !== false) {
             unset($copy_fields[$key]);
         }
     }
     // Now we can build the query.
     $sql = array();
     $sql[] = "insert into `" . $record->_table->tablename . "`";
     $sql[] = "(`" . implode('`,`', $copy_fields) . "`)";
     $copy_values = array();
     foreach ($copy_fields as $key => $val) {
         if (isset($vals[$val])) {
             $copy_values[$key] = "'" . addslashes($dummy->getSerializedValue($val)) . "' as `{$val}`";
         } else {
             $copy_values[$key] = "`" . $val . "`";
         }
     }
     $sql[] = "select " . implode(', ', $copy_values) . " from `" . $record->_table->tablename . "`";
     $qb = new Dataface_QueryBuilder($record->_table->tablename);
     $keys = array_keys($record->_table->keys());
     $q = array();
     foreach ($keys as $key_fieldname) {
         $q[$key_fieldname] = $record->strval($key_fieldname);
     }
     $where = $qb->_where($q);
     $where = $qb->_secure($where);
     $sql[] = $where;
     return implode(' ', $sql);
 }
Exemple #23
0
 function handle($params)
 {
     if (!SweteTools::getUser()) {
         return Dataface_Error::permissionDenied("You must log into access the dashboard");
     }
     $app = Dataface_Application::getInstance();
     // Get sites summary
     import('Dataface/ResultReader.php');
     /*
     $reader = new Dataface_ResultReader("select
     	ws.source_language,
     	ws.target_language,
     	ws.log_translation_misses,
     	ws.website_id, 
     	ws.website_name,
     	ws.website_url,
     	ws.translation_memory_id,
     	concat('http://',ws.host,ws.base_path) as proxy_url,
     	ws.source_language,
     	ws.target_language,
     	(
     		select count(*) from webpages w where w.website_id=ws.website_id
     	) as numpages,
     	(
     		select count(*) from swete_strings tml where tml.website_id=ws.website_id
     	) as numphrases,
     	ifnull((
     		select sum(tml.num_words) from xf_tm_strings xts 
     			inner join swete_strings tml on tml.string_id=xts.string_id
     		where tml.website_id=ws.website_id
     	), 0) as numwords,
     	(
     		select count(*) from swete_strings tml
     			inner join websites ws2 on ws2.website_id=tml.website_id
     			inner join xf_tm_translation_memory_strings xttms on xttms.translation_memory_id=ws2.translation_memory_id and xttms.string_id=tml.string_id
     		where xttms.current_translation_id is not null
     		 	and tml.website_id=ws.website_id
     		
     	) as translated_phrases,
     	
     	ifnull((
     		select sum(tml.num_words) from swete_strings tml
     			inner join websites ws2 on ws2.website_id=tml.website_id
     			inner join xf_tm_translation_memory_strings xttms on xttms.translation_memory_id=ws2.translation_memory_id and xttms.string_id=tml.string_id
     			inner join xf_tm_strings xts on xttms.string_id=xts.string_id
     		where xttms.current_translation_id is not null
     			and tml.website_id=ws.website_id
     			
     	), 0) as translated_words
     	
     		
     	from websites ws
     	", df_db());
     */
     $reader = new Dataface_ResultReader("select\n\t\t\tws.source_language,\n\t\t\tws.target_language,\n\t\t\tws.log_translation_misses,\n\t\t\tws.website_id, \n\t\t\tws.website_name,\n\t\t\tws.website_url,\n\t\t\tws.translation_memory_id,\n\t\t\tconcat('http://',ws.host,ws.base_path) as proxy_url,\n\t\t\tws.source_language,\n\t\t\tws.target_language\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\tfrom websites ws\n\t\t\t", df_db());
     $results = array();
     $languages = Dataface_Table::loadTable('websites')->getValuelist('languages');
     foreach ($reader as $row) {
         $results[] = $row;
         $row->untranslated_words = $row->numwords - $row->translated_words;
         $row->untranslated_phrases = $row->numphrases - $row->translated_phrases;
         $row->source_label = @$languages[$row->source_language] ? $languages[$row->source_language] : $row->source_language;
         $row->target_label = @$languages[$row->target_language] ? $languages[$row->target_language] : $row->target_language;
     }
     Dataface_JavascriptTool::getInstance()->import('swete/actions/dashboard.js');
     $res = df_q("select count(*) from webpages");
     list($numPages) = mysql_fetch_row($res);
     @mysql_free_result($res);
     $res = df_q("select count(*) num_phrases, sum(xts.num_words) as num_words from swete_strings tml \n\t\t\tleft join xf_tm_strings xts on tml.string_id=xts.string_id");
     list($numPhrases, $numWords) = mysql_fetch_row($res);
     @mysql_free_result($res);
     $res = df_q("select count(*) from websites");
     list($numSites) = mysql_fetch_row($res);
     @mysql_free_result($res);
     $res = df_q("select count(*) as numphrases, ifnull(sum(xts.num_words),0) as num_words from swete_strings tml \n\t\t\tinner join websites w on w.website_id=tml.website_id\n\t\t\tinner join xf_tm_translation_memory_strings xttms on w.translation_memory_id=xttms.translation_memory_id and xttms.string_id=tml.string_id\n\t\t\tinner join xf_tm_strings xts on xts.string_id=tml.string_id\n\t\t\twhere xttms.current_translation_id is not null");
     list($translatedPhrases, $translatedWords) = mysql_fetch_row($res);
     @mysql_free_result($res);
     df_display(array('results' => $results, 'systemStats' => array('numWords' => $numWords, 'numPhrases' => $numPhrases, 'numSites' => $numSites, 'numPages' => $numPages, 'translatedPhrases' => $translatedPhrases, 'translatedWords' => $translatedWords, 'untranslatedWords' => $numWords - $translatedWords, 'untranslatedPhrases' => $numPhrases - $translatedPhrases), 'swete_version' => file_get_contents('version.txt')), 'swete/actions/dashboard.html');
 }
 function handle(&$params)
 {
     session_write_close();
     header('Connection: close');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $table = $query['-table'];
     $ids = $query['-id'];
     $rec = null;
     if (!is_array($ids)) {
         $ids = array($ids);
     }
     $out = array();
     foreach ($ids as $id) {
         if (preg_match('/^' . preg_quote($table, '/') . '\\?/', $id)) {
             // This is a record id
             $rec = df_get_record_by_id($id);
         } else {
             if (strpos($id, '=') !== false) {
                 parse_str($id, $q);
                 $rec = df_get_record($table, $q);
             } else {
                 $keys = array_keys(Dataface_Table::loadTable($table)->keys());
                 $q = array($keys[0] => '=' . $id);
                 $rec = df_get_record($table, $q);
             }
         }
         if ($rec) {
             header('Content-type: text/html; charset=' . $app->_conf['oe']);
             if ($rec->checkPermission('view')) {
                 switch (strval(@$query['-text'])) {
                     case '':
                     case '__title__':
                         $out[] = $rec->getTitle();
                         break;
                     case '__json__':
                         //header('Content-type: text/json; charset='.$app->_conf['oe']);
                         $out[] = array_merge($rec->strvals(), array('__id__' => $rec->getId()));
                         break;
                     default:
                         $out[] = $rec->display($query['-text']);
                         break;
                 }
             } else {
                 return Dataface_Error::permissionDenied('You require view permission to access this record');
             }
         }
     }
     if (count($out) == 0) {
         $out[] = "";
     }
     if (count($out) < 2 and !is_array($query['-id']) and @$query['-return-type'] != 'array') {
         if (@$query['-text'] == '__json__') {
             header("Content-type: application/json; charset=" . $app->_conf['oe']);
             echo json_encode($out[0]);
         } else {
             echo $out[0];
         }
     } else {
         header("Content-type: application/json; charset=" . $app->_conf['oe']);
         echo json_encode($out);
     }
     exit;
 }
Exemple #25
0
 function process($values)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (@$values['-copy_replace:copy']) {
         import('Dataface/CopyTool.php');
         $copyTool =& Dataface_CopyTool::getInstance();
     }
     $orig_replacements = $values['-copy_replace_form:replace'];
     $update_fields = explode('-', $values['-copy_replace:fields']);
     //print_r($update_fields);
     $replacements = array();
     foreach ($update_fields as $fld) {
         if (!$fld) {
             continue;
         }
         $replacements[$fld] = $orig_replacements[$fld];
     }
     $blanks = @$_POST['-copy_replace:blank_flag'];
     if (!$blanks) {
         $blanks = array();
     }
     foreach ($blanks as $key => $val) {
         if ($val) {
             $replacements[$key] = null;
         }
     }
     if (!is_array($replacements)) {
         return PEAR::raiseError("No fields were selected to change.");
     }
     $records = df_get_selected_records($query);
     if (count($records) == 0) {
         $q = $query;
         $q['-limit'] = 99999;
         $q['-skip'] = 0;
         $records =& df_get_records_array($q['-table'], $q);
     }
     $fields = $this->getFieldsForRecord($records[0]);
     $dummyForm =& $this->getTableForm($query['-table']);
     foreach ($replacements as $key => $val) {
         $dummyForm =& $this->getTableForm($fields[$key]['tablename']);
         $val = $dummyForm->pushValue($key, $metaValues, $this->form->getElement('-copy_replace_form:replace[' . $key . ']'));
         //echo $val;//));
         //
         if ($val === '' and !@$blanks[$key]) {
             unset($replacements[$key]);
         } else {
             $replacements[$key] = $val;
         }
         unset($dummyForm);
     }
     $warnings = array();
     $messages = array();
     foreach ($records as $record) {
         if (@$values['-copy_replace:copy']) {
             // We are performing a copy.
             $res = $copyTool->copy($record, $replacements);
             if (PEAR::isError($res)) {
                 $warnings[] = $res;
             } else {
                 $messages[] = "Successfully copied record '" . $record->getTitle() . "' as record '" . $res->getTitle() . "'";
             }
             $warnings = array_merge($warnings, $copyTool->warnings);
         } else {
             if (!$record->checkPermission('edit')) {
                 $warnings[] = Dataface_Error::permissionDenied("Could not update record '" . $record->getTitle() . "' because of insufficient permissions.");
                 continue;
             }
             $failed = false;
             foreach ($replacements as $key => $val) {
                 if (!$record->checkPermission('edit', array('field' => $key))) {
                     $warnings[] = Dataface_Error::permissionDenied("Could not update record '" . $record->getTitle() . "' because of insufficient permissions on field '{$key}'.");
                     $failed = true;
                 }
             }
             if ($failed) {
                 continue;
             }
             $record->setValues($replacements);
             $res = $record->save();
             if (PEAR::isError($res)) {
                 $warnings[] = $res;
             } else {
                 $messages[] = "Successfully updated '" . $record->getTitle() . "'";
             }
         }
         unset($record);
     }
     if (@$values['-copy_replace:copy']) {
         $action = 'copied';
     } else {
         $action = 'updated';
     }
     $this->message = count($messages) . ' records ' . $action . ' successfully. ' . count($warnings) . ' warnings.';
     if (count($warnings)) {
         $warning_msgs = array();
         foreach ($warnings as $warning) {
             $warning_msgs[] = $warning->getMessage();
         }
     } else {
         $warning_msgs = array();
     }
     //print_r($warning_msgs);
     $this->message .= '<br>' . implode('<br>', $warning_msgs);
     return true;
 }