Exemplo n.º 1
0
 function handle($params)
 {
     import('Dataface/SearchForm.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $new = true;
     $form = new Dataface_SearchForm($query['-table'], $app->db(), $query);
     $res = $form->_build();
     if (PEAR::isError($res)) {
         trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     /*
      *
      * We need to add the current GET parameter flags (the GET vars starting with '-') so
      * that the controller knows to pass control to this method again upon form submission.
      *
      */
     $form->setDefaults(array('-action' => $query['-action']));
     if ($form->validate()) {
         $res = $form->process(array(&$form, 'performFind'));
     }
     $jt = Dataface_JavascriptTool::getInstance();
     $jt->import('find.js');
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('form' => &$out);
     df_display($context, 'Dataface_Find_View.html', true);
 }
Exemplo n.º 2
0
 function lname__link(&$record)
 {
     if (!is_a($record, "Dataface_Record")) {
         trigger_error("in tables_Profiles::lname__link() expecting 'Dataface_Record' as first argument but received '" . get_class($record) . "'.\n<br>" . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     return "http://www.google.ca?fname=" . $record->strval('fname') . "&lname=" . $record->strval('lname');
 }
Exemplo n.º 3
0
 function Dataface_RelatedList(&$record, $relname, $db = '')
 {
     if (!is_a($record, 'Dataface_Record')) {
         trigger_error("In Dataface_RelatedList constructor, the first argument is expected to be an object of type 'Dataface_Record' but received '" . get_class($record) . "'.\n<br>" . Dataface_Error::printStackTrace());
     }
     $this->_record =& $record;
     $this->_tablename = $this->_record->_table->tablename;
     $this->_db = $db;
     $this->_relationship_name = $relname;
     $this->_table =& $this->_record->_table;
     $this->_relationship =& $this->_table->getRelationship($relname);
     $this->_start = isset($_REQUEST['-related:start']) ? $_REQUEST['-related:start'] : 0;
     $this->_limit = isset($_REQUEST['-related:limit']) ? $_REQUEST['-related:limit'] : 30;
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (isset($query['-related:search'])) {
         $rwhere = array();
         foreach ($this->_relationship->fields() as $rfield) {
             //list($garbage,$rfield) = explode('.', $rfield);
             $rwhere[] = '`' . str_replace('.', '`.`', $rfield) . '` LIKE \'%' . addslashes($query['-related:search']) . '%\'';
         }
         $rwhere = implode(' OR ', $rwhere);
     } else {
         $rwhere = 0;
     }
     $this->_where = $rwhere;
 }
Exemplo n.º 4
0
 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;
             }
         }
     }
 }
Exemplo n.º 5
0
 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');
         }
     }
 }
Exemplo n.º 7
0
 function Dataface_RecordGrid(&$records, $columns = null, $labels = null)
 {
     $this->records =& $records;
     if (!is_array($this->records)) {
         trigger_error('In Dataface_RecordGrid the first parameter is expected to be an array but received "' . get_class($records) . '"' . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     $this->columns = $columns;
     $this->labels = $labels;
 }
Exemplo n.º 8
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('hidden', $field['name']);
     if (PEAR::isError($el)) {
         echo "Failed to get element for field {$field['name']} of table " . $record->_table->tablename;
         echo "The error returned was " . $el->getMessage();
         echo Dataface_Error::printStackTrace();
     }
     $el->setFieldDef($field);
     return $el;
 }
Exemplo n.º 9
0
 function save($keys = null)
 {
     foreach (array_keys($this->records) as $key) {
         $res = $this->records[$key]->save($this->view->mapValuesToTable($keys));
         if (PEAR::isError($res)) {
             return $res;
         } else {
             if (!$res) {
                 return PEAR::raiseError('Error saving view record.' . Dataface_Error::printStackTrace(), E_USER_ERROR);
             }
         }
     }
     return true;
 }
Exemplo n.º 10
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');
 }
Exemplo n.º 11
0
 function Dataface_PageCache($tables = array())
 {
     $this->tables =& $tables;
     $app =& Dataface_Application::getInstance();
     $params = array('cacheDir' => $app->_conf['cache_dir'] . '/dataface_page_cache', 'lifeTime' => 3600);
     if (!file_exists($params['cacheDir'])) {
         mkdir($params['cacheDir'], true);
     }
     if (!file_exists($params['cacheDir'])) {
         trigger_error("Cannot create directory '" . $params['cacheDir'] . "'" . Dataface_Error::printStackTrace(), E_USER_ERROR);
     } else {
         //echo $params['cacheDir'];
     }
     $this->Cache_Lite($params);
 }
Exemplo n.º 12
0
 /**
  * If there is a link associated with a field of the table, this method
  * returns a full and proper url for the link.
  * @param fieldname The name of the field in the table.
  * @param $values 
  */
 function resolveLink($fieldname, &$record)
 {
     if (!is_a($record, 'Dataface_Record')) {
         trigger_error("Dataface_TableTool::resolveLink() expects an object of type 'Dataface_Record' as the second argument, but received '" . get_class($record) . "'\n<br>" . Dataface_Error::printStackTrace());
     }
     $link = $record->getLink($fieldname);
     if (is_array($link)) {
         return Dataface_LinkTool::buildLink($link);
     } else {
         if ($link) {
             return $this->_app->filterUrl($link);
         } else {
             return null;
         }
     }
 }
Exemplo n.º 13
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     if (is_string($field)) {
         echo Dataface_Error::printStackTrace();
     }
     $table =& $record->_table;
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('htmlarea', $formFieldName, $widget['label'], array('class' => $widget['class'], 'id' => $field['name']));
     if (method_exists($el, 'setWysiwygOptions')) {
         $el->setWysiwygOptions($widget);
         if (isset($widget['editor'])) {
             $el->editorName = $widget['editor'];
         }
     }
     return $el;
 }
Exemplo n.º 14
0
 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');
 }
Exemplo n.º 15
0
 function handle($params)
 {
     if (!isset($params['action']['page'])) {
         trigger_error(df_translate('Page not specified', 'No page specified at ' . Dataface_Error::printStackTrace(), array('stack_trace' => Dataface_Error::printStackTrace())), E_USER_ERROR);
     } else {
         $page = $params['action']['page'];
     }
     $app =& Dataface_Application::getInstance();
     $pages = $app->getCustomPages();
     if (!isset($pages[$page])) {
         trigger_error(df_translate('Custom page not found', "Request for custom page '{$page}' failed because page does not exist in pages directory." . Dataface_Error::printStackTrace(), array('page' => $page, 'stack_trace' => Dataface_Error::printStackTrace())), E_USER_ERROR);
     }
     ob_start();
     include $pages[$page];
     $out = ob_get_contents();
     ob_end_clean();
     df_display(array('content' => $out), 'Dataface_Custom_Template.html');
     return true;
 }
Exemplo n.º 16
0
 function handle(&$params)
 {
     import('dataface-public-api.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $action =& $params['action'];
     if (isset($action['mode'])) {
         $query['-mode'] = $action['mode'];
     }
     $context = array();
     if (@$query['-template']) {
         $template = $query['-template'];
     } else {
         if (@$action['template']) {
             $template = $action['template'];
         } else {
             trigger_error("No template found for action '" . @$action['name'] . "'." . Dataface_Error::printStackTrace(), E_USER_ERROR);
         }
     }
     $context = array();
     df_display($context, $template);
 }
Exemplo n.º 17
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');
        }
    }
Exemplo n.º 18
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 {
         $jt = Dataface_JavascriptTool::getInstance();
         $jt->import('change_password.js');
         df_display(array(), 'change_password.html');
     }
 }
Exemplo n.º 19
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;
 }
Exemplo n.º 20
0
    function handle($params)
    {
        import('Dataface/SearchForm.php');
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        $new = true;
        $form = new Dataface_SearchForm($query['-table'], $app->db(), $query);
        $res = $form->_build();
        if (PEAR::isError($res)) {
            trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        /*
         *
         * We need to add the current GET parameter flags (the GET vars starting with '-') so
         * that the controller knows to pass control to this method again upon form submission.
         *
         */
        $form->setDefaults(array('-action' => $query['-action']));
        if ($form->validate()) {
            $res = $form->process(array(&$form, 'performFind'));
        }
        $app->addHeadContent(sprintf(<<<END
\t\t\t<link rel="stylesheet" type="text/css" href="%s"/>
\t\t\t<link rel="stylesheet" type="text/css" href="%s"/>
\t\t\t<script>if ( typeof(jQuery) == 'undefined' ){document.writeln('<'+'script src="%s"><'+'/script>');}</script>
\t\t\t<script src="%s"></script>
\t\t\t<script src="%s"></script>
\t\t\t
END
, htmlspecialchars(DATAFACE_URL . '/css/smoothness/jquery-ui-1.7.2.custom.css'), htmlspecialchars(DATAFACE_URL . '/css/find.css'), htmlspecialchars(DATAFACE_URL . '/js/jquery.packed.js'), htmlspecialchars(DATAFACE_URL . '/js/jquery-ui-1.7.2.custom.min.js'), htmlspecialchars(DATAFACE_URL . '/js/find.js')));
        ob_start();
        $form->display();
        $out = ob_get_contents();
        ob_end_clean();
        $context = array('form' => &$out);
        df_display($context, 'Dataface_Find_View.html', true);
    }
Exemplo n.º 21
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;
 }
 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;
 }
Exemplo n.º 23
0
 /**
  *
  * Prepares data to be imported into the table.  It takes raw data and produces an array of
  * Dataface_Record objects that can be imported into the table.
  *
  * @param	$data			Raw data that is to be imported.
  *		@type raw
  *
  * @param	$importFilter	The name of the import filter that is used to import the data.
  *							If this is null then every import filter is attempted until one is 
  *							found that works.
  *		@type string | null
  *
  * @return	An array of Dataface_Record objects encapsulating the imported data.  These objects
  *			must be records of the current table.
  *
  * @throws PEAR_Error if the importing fails for some reason.
  *
  * Usage:
  * -------
  *
  * $data = '<phonelist>
  *				<listentry>
  *					<name>John Smith</name><number>555-555-5555</number>
  *				</listentry>
  *				<listentry>
  *					<name>Susan Moore</name><number>444-444-4444</number>
  *				</listentry>
  *			</phonelist>';
  * 
  * 		// assume that we have an import filter called 'XML_Filter' that can import the above data.
  *
  * $table =& Dataface_Table::loadTable('ListEntry');
  * $records = $table->parseImportData(	$data,			// The raw data to import
  *										'XML_Filter'	// The name of the filter to handle the import
  *										);
  *
  * echo get_class($records[0]);		// outputs 'Dataface_Record'
  * echo $records[0]->val('name');	//outputs 'John Smith'
  * echo $records[0]->val('number'); // outputs '555-555-5555'
  * echo $records[1]->val('name');	// outputs 'Susan Moore'
  * echo $records[1]->val('number');	// outputs '444-444-4444'
  *
  * // Note that the records in the $records array are NOT persisted in the database.
  * 
  * @see Dataface_Table.loadTable()
  * @see Dataface_Table.getImportFilters()
  * @see Dataface_Record.val()
  *
  */
 function parseImportData($data, $importFilter = null, $defaultValues = array())
 {
     $filters =& $this->getImportFilters();
     $delegate =& $this->getDelegate();
     if ($delegate === null) {
         /*
          * Currently the only place that Import filters can be defined is in the
          * delegate file.  If there is no delegate file, then there are no filters.
          * if there are no filters, then we can't possibly do any importing so we
          * return an error.
          */
         return Dataface_Error::noImportFiltersFound();
     }
     $errors = array();
     if ($importFilter === null) {
         /*
          * The filter is not specified so we will try every filter until we find one
          * that works.
          */
         foreach (array_keys($filters) as $filtername) {
             $parsed =& $filters[$filtername]->import($data, $defaultValues);
             if (PEAR::isError($parsed)) {
                 /*
                  * This filter encountered an error.
                  * Record the error, and unset the $parsed variable.
                  */
                 $errors[$filtername] =& $parsed;
                 unset($parsed);
                 continue;
             }
             break;
         }
         if (isset($parsed)) {
             /*
              * The only way that the $parsed variable should be 'set' is if 
              * one of the filters successfully parsed the data.
              */
             return $parsed;
         } else {
             return Dataface_Error::noImportFiltersFound("No suitable import filter was found to import data into table '" . $this->tablename . "'.  The following filters were attempted: {" . implode(',', array_keys($errors)) . "}.");
         }
     } else {
         /*
          * A particular import filter was specified so we will try with that one.
          */
         if (!isset($filters[$importFilter])) {
             return Dataface_Error::noImportFiltersFound("The import filter '" . $importFilter . "' was not found while attempting to import data into the table '" . $this->tablename . "'.  The following import filters are available: {" . implode(',', array_keys($errors)) . "}.");
         }
         return $filters[$importFilter]->import($data, $defaultValues);
     }
 }
Exemplo n.º 24
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));
 }
Exemplo n.º 25
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);
 }
Exemplo n.º 26
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);
         }
     }
 }
Exemplo n.º 27
0
 function handle(&$params)
 {
     import('Dataface/TranslationForm.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     $source = isset($_REQUEST['-sourceLanguage']) ? $_REQUEST['-sourceLanguage'] : $app->_conf['default_language'];
     $dest = isset($_REQUEST['-destinationLanguage']) ? $_REQUEST['-destinationLanguage'] : null;
     if ($resultSet->found() > 0) {
         $form = new Dataface_TranslationForm($query['-table'], $source, $dest);
         /*
          * There is either a result to edit, or we are creating a new record.
          *
          */
         $res = $form->_build();
         if (PEAR::isError($res)) {
             throw new Exception($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
         }
         /*
          *
          * We need to add the current GET parameter flags (the GET vars starting with '-') so
          * that the controller knows to pass control to this method again upon form submission.
          *
          */
         foreach ($query as $key => $value) {
             if (strpos($key, '-') === 0) {
                 $form->addElement('hidden', $key);
                 $form->setDefaults(array($key => $value));
             }
         }
         /*
          * Store the current query string (the portion after the '?') in the form, so we 
          * can retrieve it after and redirect back to our original location.
          */
         $form->addElement('hidden', '-query');
         $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING']));
         /*
          * 
          * We have to deal with 3 cases.
          * 	1) The form has not been submitted.
          *	2) The form was submitted but didn't validate (ie: it had some bad input)
          * 	3) The form was submitted and was validated.
          *
          * We deal with Case 3 first...
          *
          */
         if ($form->validate()) {
             /*
              *
              * The form was submitted and it validated ok.  We now process it (ie: save its contents).
              *
              */
             $app->clearMessages();
             $result = $form->process(array(&$form, 'save'));
             $success = true;
             $response =& Dataface_Application::getResponse();
             if (!$result) {
                 error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace());
                 throw new Exception("Error occurred in save.  See error log for details.");
             } else {
                 if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) {
                     //echo "Error..";
                     if (Dataface_Error::isDuplicateEntry($result)) {
                         return $result;
                     } else {
                         //echo "not dup entry"; exit;
                         throw new Exception($result->toString(), E_USER_ERROR);
                     }
                 } else {
                     if (Dataface_Error::isNotice($result)) {
                         $app->addError($result);
                         //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage();
                         $success = false;
                     }
                 }
             }
             if ($success) {
                 /*
                  *
                  * The original query string will have the -new flag set.  We need to remove this 
                  * flag so that we don't redirect the user to create another new record.
                  *
                  */
                 $vals = $form->exportValues();
                 $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']);
                 $msg = implode("\n", $app->getMessages());
                 //$msg =@$response['--msg'];
                 $msg = urlencode(Dataface_LanguageTool::translate('Record successfully translated', "Record successfully translated.<br>") . $msg);
                 $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--msg=' . $msg;
                 /*
                  *
                  * Redirect the user to the appropriate record.
                  *
                  */
                 $app->redirect($link);
             }
         }
         ob_start();
         $form->display();
         $out = ob_get_contents();
         ob_end_clean();
         $context = array('form' => $out, 'formObj' => $form);
     } else {
         // no records were found
         $context = array('form' => '', 'formObj' => $form);
         $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request'));
     }
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             $template = 'Dataface_Translate_Record.html';
         }
     }
     df_display($context, $template, true);
 }
Exemplo n.º 28
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);
 }
Exemplo n.º 29
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);
 }
Exemplo n.º 30
0
 /**
  * Returns an array of all actions as specified by $params.
  * $params must be an array.  It may contain the following options:
  *		record => A reference to a record for which the actions apply (This may be a related record)
  *		table => The name of a table on which the actions apply.
  *		relationship => The name of a relationship on which the action is applied. (requires that table also be set - or may use dotted name)
  *						to include the table name and the relationship name in one string.
  *		category => The name of the category of actions to be retrieved.
  */
 function getActions($params = array(), $actions = null)
 {
     if (!is_array($params)) {
         trigger_error("In Dataface_ActionTool::getActions(), expected parameter to be an array but received a scalar: " . $params . "." . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     $app =& Dataface_Application::getInstance();
     $out = array();
     $tablename = null;
     if (isset($params['table'])) {
         $tablename = $params['table'];
     }
     if (isset($params['record']) and is_a($params['record'], 'Dataface_Record')) {
         $tablename = $params['record']->_table->tablename;
     } else {
         if (isset($params['record']) and is_a($params['record'], 'Dataface_RelatedRecord')) {
             $tablename = $params['record']->_record->_table->tablename;
         }
     }
     if (isset($params['record']) && is_a($params['record'], 'Dataface_Record')) {
         // we have received a record as a parameter... we can infer the table information
         $params['table'] = $params['record']->_table->tablename;
     } else {
         if (isset($params['record']) && is_a($params['record'], 'Dataface_RelatedRecord')) {
             // we have recieved a related record object... we can infer both the table and relationship information.
             $temp =& $params['record']->getParent();
             $params['table'] = $temp->_table->tablename;
             unset($temp);
             $params['relationship'] = $params['record']->_relationshipName;
         }
     }
     if (@$params['relationship']) {
         if (strpos($params['relationship'], '.') !== false) {
             // if the relationship is specified in the form 'Tablename.RElationshipname' parse it.
             list($params['table'], $params['relationship']) = explode('.', $params['relationship']);
         }
     }
     if ($tablename !== null) {
         // Some actions are loaded from the table's actions.ini file and must be loaded before we return the actions.
         $table =& Dataface_Table::loadTable($tablename);
         if (!$table->_actionsLoaded) {
             $tparams = array();
             $table->getActions($tparams, true);
         }
         unset($table);
     }
     if ($actions === null) {
         $actions = $this->actions;
     }
     foreach (array_keys($actions) as $key) {
         if (isset($action)) {
             unset($action);
         }
         $action =& $actions[$key];
         if (@$params['name'] and @$params['name'] !== @$action['name']) {
             continue;
         }
         if (@$params['id'] and @$params['id'] !== @$action['id']) {
             continue;
         }
         if (isset($params['category']) and $params['category'] !== @$action['category']) {
             continue;
         }
         // make sure that the category matches
         if (@$params['table'] && !(@$action['table'] == @$params['table'] or @in_array(@$params['table'], @$action['table']))) {
             continue;
         }
         // Filter actions by table
         if (@$params['relationship'] && @$action['relationship'] && @$action['relationship'] != @$params['relationship']) {
             continue;
         }
         // Filter actions by relationship.
         if (@$action['condition'] and !$app->testCondition($action['condition'], $params)) {
             continue;
         }
         if (isset($params['record'])) {
             if (isset($action['permission']) and !$params['record']->checkPermission($action['permission'])) {
                 continue;
             }
         } else {
             if (isset($action['permission']) and !$app->checkPermission($action['permission'])) {
                 continue;
             }
         }
         if (@$action['selected_condition']) {
             $action['selected'] = $app->testCondition($action['selected_condition'], $params);
         }
         if (isset($action['visible']) and !$action['visible']) {
             continue;
         }
         // Filter based on a condition
         foreach (array_keys($action) as $attribute) {
             // Some entries may have variables that need to be evaluated.  We use Dataface_Application::eval()
             // to evaluate these entries. The eval method will replace variables such as $site_url, $site_href
             // $dataface_url with the appropriate real values.  Also if $params['record'] contains a
             // Record object or a related record object its values are treated as php variables that can be
             // replaced.  For example if a Profile record has fields 'ProfileID' and 'ProfileName' with
             // ProfileID=10 and ProfileName = 'John Smith', then:
             // $app->parseString('ID is ${ProfileID} and Name is ${ProfileName}') === 'ID is 10 and Name is John Smith'
             //if ( strpos($attribute, 'condition') !== false) continue;
             if (preg_match('/condition/i', $attribute)) {
                 continue;
             }
             if (isset($action[$attribute . '_condition']) and !$app->testCondition($action[$attribute . '_condition'], $params)) {
                 $action[$attribute] = null;
             } else {
                 $action[$attribute] = $app->parseString($action[$attribute], $params);
             }
         }
         $out[$key] =& $action;
         unset($action);
     }
     uasort($out, array(&$this, '_compareActions'));
     return $out;
 }