示例#1
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');
 }
示例#2
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);
 }
示例#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;
 }
示例#4
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;
 }
示例#5
0
文件: hidden.php 项目: promoso/HVAC
 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;
 }
示例#6
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;
 }
示例#7
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);
 }
示例#8
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;
         }
     }
 }
示例#9
0
文件: htmlarea.php 项目: promoso/HVAC
 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;
 }
示例#10
0
文件: custom.php 项目: promoso/HVAC
 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;
 }
示例#11
0
文件: default.php 项目: promoso/HVAC
 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);
 }
示例#12
0
文件: find.php 项目: promoso/HVAC
    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);
    }
示例#13
0
 /**
  * Returns true if element is in the form
  *
  * @param     string   $element         form name of element to check
  * @since     1.0
  * @access    public
  * @return    boolean
  */
 function elementExists($element = null)
 {
     if (!is_string($element)) {
         echo Dataface_Error::printStackTrace();
     }
     return isset($this->_elementIndex[$element]);
 }
示例#14
0
文件: Record.php 项目: promoso/HVAC
 /**
  * <p>Gets the value of a field in this record.</p>
  * @param $fieldname The name of the field whose value we wish to obtain.   Could be simple name (eg: 'id') or related name (eg: 'addresses.city').
  * @param $index The index of the value.  This is primarily used when retrieving the value of a related field that has more than one record.
  */
 function &getValue($fieldname, $index = 0, $where = 0, $sort = 0, $debug = false)
 {
     static $callcount = 0;
     $callcount++;
     if ($debug) {
         echo "Num calls to getValue(): {$callcount}";
     }
     if (isset($this->cache[__FUNCTION__][$fieldname][$index][$where][$sort])) {
         return $this->cache[__FUNCTION__][$fieldname][$index][$where][$sort];
     }
     if (is_array($index)) {
         trigger_error(df_translate('scripts.Dataface.Record.getValue.ERROR_PARAMETER_2', "In Dataface_Record.getValue() expected 2nd parameter to be integer but received array.") . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     if (is_array($where)) {
         trigger_error(df_translate('scripts.Dataface.Record.getValue.ERROR_PARAMETER_3', "In Dataface_Record.getValue() expected 3rd parameter to be a string, but received array.") . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     if (is_array($sort)) {
         trigger_error(df_translate('scripts.Dataface.Record.getValue.ERROR_PARAMETER_4', "In Dataface_Record.getValue() expected 4th parameter to be a string but received array.") . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     $out = null;
     if (strpos($fieldname, '.') === false) {
         $delegate =& $this->_delegate;
         if (!isset($this->_values[$fieldname])) {
             // The field is not set... check if there is a calculated field we can use.
             if ($delegate !== null and method_exists($delegate, "field__{$fieldname}")) {
                 $methodname = "field__{$fieldname}";
                 $out =& $delegate->{$methodname}($this, $index);
                 //$out =& call_user_func( array(&$delegate, "field__$fieldname"), $this, $index);
                 //} else if ( array_key_exists($fieldname, $this->_transientValues) ){
             } else {
                 if (array_key_exists($fieldname, $this->_table->transientFields())) {
                     $transientFields =& $this->_table->transientFields();
                     if (array_key_exists($fieldname, $this->_transientValues)) {
                         $out = $this->_transientValues[$fieldname];
                     } else {
                         if (isset($transientFields[$fieldname]['relationship']) and $transientFields[$fieldname]['widget']['type'] == 'grid') {
                             $out = array();
                             $rrecords =& $this->getRelatedRecordObjects($transientFields[$fieldname]['relationship'], 'all');
                             $currRelationship =& $this->_table->getRelationship($transientFields[$fieldname]['relationship']);
                             $relKeys =& $currRelationship->keys();
                             //print_r(array_keys($currRelationship->keys()));
                             foreach ($rrecords as $rrecord) {
                                 $row = $rrecord->strvals();
                                 foreach (array_keys($row) as $row_field) {
                                     $ptable =& $rrecord->_relationship->getTable($row_field);
                                     $precord =& $rrecord->toRecord($ptable->tablename);
                                     if (!$precord or PEAR::isError($precord)) {
                                         continue;
                                     }
                                     $row['__permissions__'][$row_field] = $precord->getPermissions(array('field' => $row_field));
                                     if (isset($relKeys[$row_field])) {
                                         unset($row['__permissions__'][$row_field]['edit']);
                                     }
                                     unset($precord);
                                     unset($ptable);
                                 }
                                 $row['__id__'] = $rrecord->getId();
                                 $out[] = $row;
                                 unset($rrecord);
                                 unset($row);
                             }
                             unset($relKeys);
                             unset($currRelationship);
                             unset($rrecords);
                             $this->_transientValues[$fieldname] = $out;
                         } else {
                             if (isset($transientFields[$fieldname]['relationship']) and $transientFields[$fieldname]['widget']['type'] == 'checkbox') {
                                 $out = array();
                                 $rrecords =& $this->getRelatedRecordObjects($transientFields[$fieldname]['relationship'], 'all');
                                 $currRelationship =& $this->_table->getRelationship($transientFields[$fieldname]['relationship']);
                                 foreach ($rrecords as $rrecord) {
                                     $row = $rrecord->strvals();
                                     $domRec = $rrecord->toRecord();
                                     $rowstr = array();
                                     foreach (array_keys($domRec->_table->keys()) as $relKey) {
                                         $rowStr[] = urlencode($relKey) . '=' . urlencode($row[$relKey]);
                                     }
                                     $out[] = implode('&', $rowStr);
                                     unset($rowStr, $domRec);
                                     unset($rrecord);
                                     unset($row);
                                 }
                                 unset($relKeys);
                                 unset($currRelationship);
                                 unset($rrecords);
                                 $this->_transientValues[$fieldname] = $out;
                             } else {
                                 $out = null;
                             }
                         }
                     }
                 } else {
                     if ($parent =& $this->getParentRecord() and $parent->_table->hasField($fieldname)) {
                         return $parent->getValue($fieldname, $index, $where, $sort, $debug);
                     } else {
                         $this->_values[$fieldname] = null;
                         $out = null;
                     }
                 }
             }
         } else {
             $out = $this->_values[$fieldname];
         }
         if (isset($out)) {
             // We only store non-null values in cache.  We were having problems
             // with segfaulting in PHP5 when groups are used.
             // This seems to fix the issue, but let's revisit it later.
             $this->cache[strval(__FUNCTION__)][strval($fieldname)][$index][$where][$sort] = $out;
         }
         return $out;
     } else {
         list($relationship, $fieldname) = explode('.', $fieldname);
         $rec =& $this->getRelatedRecords($relationship, false, $index, 1, $where, $sort);
         $this->cache[__FUNCTION__][$relationship . '.' . $fieldname][$index][$where][$sort] =& $rec[$fieldname];
         return $rec[$fieldname];
     }
 }
示例#15
0
 /**
  * Returns a list of names of granted permissions in a given permissions array.
  */
 function namesAsArray($permissions)
 {
     if (!is_array($permissions)) {
         echo Dataface_Error::printStackTrace();
     }
     $names = array();
     foreach ($permissions as $key => $value) {
         if ($value) {
             $names[] = $key;
         }
     }
     return $names;
 }
示例#16
0
 function df_block($params)
 {
     $app = Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (isset($params['table'])) {
         $table = Dataface_Table::loadTable($params['table']);
     } else {
         if (isset($params['record'])) {
             $table = $params['record']->_table;
         } else {
             $table = Dataface_Table::loadTable($query['-table']);
         }
     }
     if (isset($params['name'])) {
         $name = $params['name'];
     } else {
         trigger_error('No name specified for block. ' . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     unset($params['name']);
     unset($params['table']);
     return $table->displayBlock($name, $params);
 }
示例#17
0
文件: SkinTool.php 项目: promoso/HVAC
 /**
  * Checks to see if the current user has a particular permission on a given record.
  *
  * @param array $params Associative array of parameters.
  * @param string $content Since this method acts as a block tag, the second time
  * it is called, it is passed the content of the block in this parameter.
  * @param Smarty &$smarty Reference to the SkinTool object.
  * @smarty-block boolean if_allowed
  * @smarty-param string permission The name of the permission that is being checked.  e.g. 'edit', or 'view'.
  * @smarty-param Dataface_Record record The record to check the permission against.
  */
 function if_allowed($params, $content, &$smarty)
 {
     if (isset($content)) {
         if (!isset($params['permission'])) {
             trigger_error('Missing permission parameter in if_allowed tag.' . Dataface_Error::printStackTrace(), E_USER_ERROR);
         }
         if (isset($params['record'])) {
             $allowed = $params['record']->checkPermission($params['permission'], $params);
         } else {
             if (isset($params['table'])) {
                 $table =& Dataface_Table::loadTable($params['table']);
                 $allowed = $table->checkPermission($params['permission'], $params);
             } else {
                 $allowed = false;
             }
         }
         if ($allowed) {
             return $content;
         }
         return '';
     }
 }
示例#18
0
 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;
 }
示例#19
0
    function test_import_data()
    {
        $t =& $this->_table1;
        /*
         * For our first test we will try to import data directly into a table.
         * We do not worry about relationships here.
         */
        $data = '<?xml version="1.0"?>
			<dataface>
				<Profiles>
					<fname>John</fname>
					<lname>Smith</lname>
					<title>Professor</title>
				</Profiles>
				<Profiles>
					<fname>Julia</fname>
					<lname>Vaughn</lname>
					<title>Assistant</title>
				</Profiles>
			
			
			</dataface>';
        $io = new Dataface_IO('Profiles', $this->db);
        $record = null;
        // First we try to import the data into a temporary import table.
        $importTablename = $io->importData($record, $data);
        $res = xf_db_query("SELECT * FROM `{$importTablename}`", $this->db);
        $rows = array();
        while ($row = xf_db_fetch_array($res)) {
            $rows[] = $row;
        }
        $this->assertEquals(2, count($rows), "Incorrect number of rows in import table: '{$importTablename}'");
        $this->assertEquals('John', $rows[0]['fname']);
        $this->assertEquals('Smith', $rows[0]['lname']);
        $this->assertEquals('Professor', $rows[0]['title']);
        // now we try to commit the records
        $records = $io->importData($record, $importTablename, null, null, true);
        $this->assertEquals(2, count($records));
        $this->assertEquals('John Smith', $records[0]->val('fname') . ' ' . $records[0]->val('lname'));
        $this->assertEquals('Julia Vaughn', $records[1]->val('fname') . ' ' . $records[1]->val('lname'));
        $this->assertTrue($records[0]->val('id') > 0);
        $this->assertTrue($records[1]->val('id') > 0);
        //Now let's try to imort some records into a relationship
        /*
         * Now we attempt to import data into a one-to-many relationship
         */
        $data = '
			<dataface>
				<Appointments>
					<position>Trucker</position>
					<startdate>2003-11-12</startdate>
					<enddate>2004-05-06</enddate>
					<salary>1234.56</salary>
				</Appointments>
				<Appointments>
					<position>Director</position>
					<startdate>2002-01-02</startdate>
					<enddate>2005-02-03</enddate>
					<salary>5678.57</salary>
				</Appointments>
			</dataface>';
        $record = new Dataface_Record('Profiles', array());
        $io->read(array('id' => 10), $record);
        $importTablename = $io->importData($record, $data, 'xml', 'appointments');
        $res = xf_db_query("SELECT * FROM `{$importTablename}`", $this->db);
        if (!$res) {
            trigger_error("Error selecting records from import table '{$importTablename}'.  A mysql error occurred: " . xf_db_error($this->db) . "\n" . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $this->assertEquals(2, xf_db_num_rows($res));
        $rows = array();
        while ($row = xf_db_fetch_array($res)) {
            $rows[] = $row;
        }
        $this->assertEquals('Trucker', $rows[0]['position']);
        $this->assertEquals('Director', $rows[1]['position']);
        // now to commit this import
        $records = $io->importData($record, $importTablename, 'xml', 'appointments', true);
        if (PEAR::isError($records)) {
            trigger_error($records->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $this->assertEquals(2, count($records));
        $this->assertEquals('dataface_relatedrecord', strtolower(get_class($records[0])));
        $this->assertEquals(10, $records[0]->val('profileid'));
        $this->assertEquals('Trucker', $records[0]->val('Appointments.position'));
        //print_r($records[0]->getValues());
        $res = xf_db_query("select * from `Appointments`", $this->db);
        $rows = array();
        while ($row = xf_db_fetch_array($res)) {
            $rows[] = $row;
        }
        $this->assertEquals(10, $rows[3]['profileid']);
        $this->assertEquals('Trucker', $rows[3]['position']);
        $this->assertEquals('Director', $rows[4]['position']);
        /*
         *
         * Finally we try to import data into a many-to-many relationship.
         *
         */
        $data = '
			<dataface>
				<Courses>
					<dept>Math</dept>
					<coursenumber>332</coursenumber>
				</Courses>
				<Courses>
					<dept>CMPT</dept>
					<coursenumber>475</coursenumber>
				</Courses>
			</dataface>';
        $importTablename = $io->importData($record, $data, 'xml', 'courses');
        if (PEAR::isError($importTablename)) {
            trigger_error($importTablename->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $res = xf_db_query("SELECT * FROM `{$importTablename}`", $this->db);
        if (!$res) {
            trigger_error("Error selecting records from import table '{$importTablename}'.  A mysql error occurred: " . xf_db_error($this->db) . "\n" . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $this->assertEquals(2, xf_db_num_rows($res));
        $rows = array();
        while ($row = xf_db_fetch_array($res)) {
            $rows[] = $row;
        }
        $this->assertEquals('Math', $rows[0]['dept']);
        $this->assertEquals('CMPT', $rows[1]['dept']);
        $records = $io->importData($record, $importTablename, 'xml', 'courses', true);
        if (PEAR::isError($records)) {
            trigger_error($records->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $this->assertEquals(2, count($records));
        foreach ($records as $rec) {
            $this->assertEquals('dataface_relatedrecord', strtolower(get_class($rec)));
        }
        //echo "Records: $records";
        $this->assertEquals('Math', $records[0]->val('dept'));
        $this->assertEquals('CMPT', $records[1]->val('dept'));
        $res = xf_db_query("SELECT * FROM Courses c inner join Student_Courses sc on c.id=sc.courseid inner join Profiles p on p.id=sc.studentid where p.id='10'", $this->db);
        if (!$res) {
            trigger_error(xf_db_error($this->db) . Dataface_Error::printStackTrace(), E_USER_ERROR);
        }
        $this->assertEquals(2, xf_db_num_rows($res));
        $course1 = xf_db_fetch_array($res);
        $course2 = xf_db_fetch_array($res);
        $this->assertEquals(10, $course1['studentid']);
        $this->assertTrue($course1['courseid'] > 0);
        $this->assertEquals(10, $course2['studentid']);
        $this->assertTrue($course2['courseid'] > 0);
        $this->assertEquals('Math', $course1['dept']);
        $this->assertEquals('CMPT', $course2['dept']);
        $this->assertEquals('John Smith', $course1['fname'] . ' ' . $course1['lname']);
    }
示例#20
0
    function handle(&$params)
    {
        $app = Dataface_Application::getInstance();
        header('Content-type: text/html; charset=' . $app->_conf['oe']);
        $record =& $app->getRecord();
        $query =& $app->getQuery();
        if (isset($_REQUEST['-form-id'])) {
            $formid = $_REQUEST['-form-id'];
        } else {
            $formid = 'ajax-form-' . rand();
        }
        // First let's figure out what kind of form this is
        $form_type = @$_REQUEST['-form-type'];
        $form = null;
        if (isset($_REQUEST['-fields'])) {
            $fields = explode(',', $_REQUEST['-fields']);
        } else {
            $fields = null;
        }
        switch ($form_type) {
            case 'new':
                $form = df_create_new_record_form($query['-table'], $fields);
                $form->_build();
                break;
            case 'edit':
                $form = df_create_edit_record_form($query['-table'], $fields);
                break;
            case 'new_related_record':
                $form = df_create_new_related_record_form($record, $query['-relationship'], $fields);
                break;
            case 'existing_related_record':
                $form = df_create_existing_related_record_form($record, $query['-relationship']);
                break;
            case 'composite':
                import('Dataface/CompositeForm.php');
                $form = new Dataface_CompositeForm($fields);
                $form->build();
                break;
            default:
                @(include_once 'forms/' . $form_type . '.php');
                if (!class_exists('forms_' . $form_type)) {
                    return PEAR::raiseError('Could not find form of type "' . $form_type . '".', DATAFACE_E_ERROR);
                }
                $classname = 'forms_' . $form_type;
                $form = new $classname($fields);
                break;
        }
        // We want the form to be submitted to the embedded iframe
        $form->updateAttributes(array('target' => $formid . '-target', 'accept-charset' => $app->_conf['ie']));
        $formparams = preg_grep('/^-[^\\-].*/', array_keys($query));
        foreach ($formparams as $param) {
            $form->addElement('hidden', $param);
            $form->setDefaults(array($param => $query[$param]));
        }
        $form->addElement('hidden', '-form-id');
        $form->setDefaults(array('-form-id' => $formid));
        // Now that we have our form, we can do our thing with it.
        if ($form->validate()) {
            /*
             *
             * The form was submitted and it validated ok.  We now process it (ie: save its contents).
             *
             */
            $app->clearMessages();
            $result = $form->process(array(&$form, 'save'));
            $success = true;
            $response =& Dataface_Application::getResponse();
            if (!$result) {
                trigger_error("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR);
                exit;
            } else {
                if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) {
                    if (Dataface_Error::isDuplicateEntry($result)) {
                        return $result;
                    } else {
                        trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
                        exit;
                    }
                } else {
                    if (Dataface_Error::isNotice($result)) {
                        $app->addError($result);
                        $success = false;
                    }
                }
            }
            if ($success) {
                import('Dataface/Utilities.php');
                Dataface_Utilities::fireEvent('after_action_ajax_form');
                $msg = implode("\n", $app->getMessages());
                //$msg =@$response['--msg'];
                $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg);
                // We need to output the success content.
                // This could be in any of the following formats:
                //	1. HTML --- actually not yet.. let's just do JSON
                //	2. JSON
                //	3. XML --- not yet.. just JSON for now.
                $targetid = @$_REQUEST['-target-id'];
                // This should:
                // 1. Get the target element.
                // 2. Go through the element's subtree and replace
                // 		values that have been changed.  How do we know what
                // 		values have been changed.
                //
                if (method_exists($form, 'htmlValues')) {
                    if (method_exists($form, 'changedFields')) {
                        $changed_fields = $form->changedFields();
                    } else {
                        $changed_fields = null;
                    }
                    // Convert the values to JSON
                    $changed_values = $form->htmlValues($changed_fields);
                    import('Services/JSON.php');
                    $json = new Services_JSON();
                    $changed_values_json = $json->encode($changed_values);
                } else {
                    $changed_values_json = '{}';
                }
                echo <<<END
<html><body><script language="javascript"><!--
\t
\t//self.onload =  function(){
\t\t//parent.handleEditableResponse('{$targetid}', {$changed_values_json});
\t\tvar targetel = parent.document.getElementById('{$targetid}');
\t\ttargetel.handleResponse('{$targetid}', {$changed_values_json});
\t\ttargetel.onclick=parent.makeEditable;
\t\ttargetel.onmouseover=targetel.old_onmouseover;
\t\ttargetel.edit_form.parentNode.removeChild(targetel.edit_form);
\t
\t//}
\t
\t
//--></script></body></html>
END;
                exit;
            }
        }
        import('Dataface/FormTool.php');
        $formTool = new Dataface_FormTool();
        ob_start();
        if (is_array($fields) and count($fields) == 1 and strpos($fields[0], '#') !== false) {
            $singleField = $fields[0];
        } else {
            $singleField = false;
        }
        $formTool->display($form, null, $singleField);
        $out = ob_get_contents();
        ob_end_clean();
        echo <<<END
\t\t
\t\t<div id="{$formid}-wrapper">
\t\t\t<iframe id="{$formid}-target" name="{$formid}-target" style="width:0px; height:0px; border: 0px"></iframe>
\t\t\t{$out}
\t\t</div>
END;
        if ($form->isSubmitted()) {
            // The form has already been submitted so we must be displaying some
            // errors.  We need to remove this stuff from inside the iframe
            // that we are going to be inside of, and place them on the page
            // in the correct place
            echo <<<END
<script language="javascript"><!--
var targetel = parent.document.getElementById('{$formid}-wrapper');
var sourceel = document.getElementById('{$formid}-wrapper');
targetel.innerHTML = sourceel.innerHTML;
//--></script>
END;
        }
        exit;
    }
示例#21
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);
 }
示例#22
0
文件: View.php 项目: promoso/HVAC
 /**
  * Returns an associative array of the table objects associated with this view.
  * Some of these tables may actually be Dataface_View objects (if the SQL query
  * for this view has a subselect.
  */
 function &tables()
 {
     if (isset($this->_cache[__FUNCTION__])) {
         return $this->_cache[__FUNCTION__];
     }
     // It is not in the cache yet, let's calculate it.
     $data = $this->_parseSQL();
     $out = array();
     $numTables = count($data['tables']);
     for ($i = 0; $i < $numTables; $i++) {
         $tableinfo = $data['tables'][$i];
         if ($tableinfo['alias']) {
             $out[$tableinfo['alias']] =& $this->getTableOrView($tableinfo['alias']);
         } else {
             if ($tableinfo['type'] == 'ident') {
                 $out[$tableinfo['value']] =& $this->getTableOrView($tableinfo['value']);
             } else {
                 trigger_error("Problem getting tables for view '" . $this->name . "' because one of the tables in the query does not have an appropriate value." . Dataface_Error::printStackTrace(), E_USER_ERROR);
             }
         }
     }
     $this->_cache[__FUNCTION__] =& $out;
     return $out;
 }
示例#23
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;
 }
示例#24
0
 /**
  * Wraps the value inside a mysql function to encrypt the input (if the 'crypt')
  * attribute is selected.
  */
 function encrypt($fieldname, $value = null)
 {
     if (!isset($value)) {
         echo Dataface_Error::printStackTrace();
     }
     if (strpos($fieldname, '.') !== false) {
         // This is a related field.
         $table =& $this->_table->getTableTableForField($fieldname);
         list($relname, $fieldname) = explode('.', $fieldname);
         $serializer = new Dataface_Serializer($table->tablename);
         $out = $serializer->encrypt($fieldname, $value);
         return $out;
     }
     $field = $this->_table->getField($fieldname);
     if (PEAR::isError($field)) {
         echo $field->getMessage();
         echo Dataface_Error::printStackTrace();
         exit;
     }
     if (isset($field['encryption'])) {
         switch (strtolower($field['encryption'])) {
             case 'md5':
                 return 'MD5(' . $value . ')';
             case 'password':
                 return 'PASSWORD(' . $value . ')';
             case 'sha1':
                 return 'SHA1(' . $value . ')';
             case 'encrypt':
                 return 'ENCRYPT(' . $value . ')';
             case 'aes_encrypt':
                 return 'AES_ENCRYPT(' . $value . ',\'' . addslashes($field['aes_key']) . '\')';
         }
     }
     return $value;
 }
示例#25
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);
 }
示例#26
0
文件: Error.php 项目: Zunair/xataface
 public static function duplicateEntry($msg = "This record already exists", $userInfo = '')
 {
     if (!$userInfo) {
         $userInfo = Dataface_Error::printStackTrace();
     }
     $err = PEAR::raiseError($msg, DATAFACE_E_DUPLICATE_ENTRY, E_USER_WARNING, null, $userInfo);
     return $err;
 }
示例#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);
 }
示例#28
0
文件: blob.php 项目: promoso/HVAC
 /**
  *
  * Blob requests are ones that only want the content of a blob field in the database.
  * These requests are special in that they will not generally return a content-type of
  * text/html.  These are often images.
  *
  * @param $request  A reference to the global $_REQUEST variable generally.
  *
  */
 function _handleGetBlob($request)
 {
     if (!is_a($this, 'Dataface_Application')) {
         trigger_error('Dataface_Application_blob methods can only be accessed via Dataface_Application.' . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     import('Dataface/Table.php');
     import('Dataface/QueryTool.php');
     if (strpos(@$request['-field'], '.') !== false) {
         $request = $this->_parseRelatedBlobRequest($request);
     }
     if (!isset($request['-field'])) {
         die("Could not complete request.  No field name specified.");
     }
     if (!isset($request['-table'])) {
         die("Could not complete request.  No table specified.");
     }
     $fieldname = $request['-field'];
     $tablename = $request['-table'];
     $table =& Dataface_Table::loadTable($tablename);
     $keys = array_keys($table->keys());
     $lastTableUpdate = $table->getUpdateTime();
     $lastTableUpdate = strtotime($lastTableUpdate);
     if ($table->isContainer($fieldname)) {
         $field =& $table->getField($fieldname);
         if (PEAR::isError($field)) {
             header('HTTP/1.0 500 Internal Server Error');
             echo '<h1>Internal Server Error</h1>';
             error_log($field->getMessage());
             exit;
         }
         $savepath = $field['savepath'];
         $app =& Dataface_Application::getInstance();
         $query =& $app->getQuery();
         $rec =& df_get_record($table->tablename, $query);
         if (!$rec) {
             trigger_error("No record found to match the request.", E_USER_ERROR);
         }
         if (!$rec->val($fieldname)) {
             header('HTTP/1.0 404 Not Found');
             echo '<h1>404 File Not Found</h1>';
             exit;
         }
         if (!$rec->checkPermission('view', array('field' => $fieldname))) {
             header('HTTP/1.1 403 Forbidden');
             echo '<h1>Access Forbidden</h1>';
             exit;
         }
         header('Content-type: ' . $rec->getMimetype($fieldname));
         header('Content-disposition: attachment; filename="' . basename($rec->val($fieldname)) . '"');
         echo file_get_contents($savepath . '/' . basename($rec->val($fieldname)));
         exit;
         foreach (array_keys($_REQUEST) as $rkey) {
             unset($_REQUEST[$rkey]);
             unset($_GET[$rkey]);
         }
         $_GET['phpThumbDebug'] = 7;
         $_REQUEST['src'] = $_GET['src'] = substr($field['savepath'], strlen(DATAFACE_SITE_PATH)) . '/' . $rec->val($fieldname);
         $_REQUEST['w'] = $_GET['w'] = isset($query['--width']) ? $query['--width'] : (isset($field['width']) ? $field['width'] : null);
         $_REQUEST['h'] = $_GET['h'] = isset($query['--height']) ? $query['--height'] : (isset($field['height']) ? $field['height'] : null);
         include 'phpThumb/phpThumb.php';
         exit;
     }
     if (!$table->isBlob($fieldname)) {
         die("blob.php can only be used to load BLOB or Binary columns.  The requested field '{$fieldname}' is not a blob");
     }
     $field =& $table->getField($fieldname);
     if (isset($request['-index'])) {
         $index = $request['-index'];
     } else {
         $index = 0;
     }
     $cachePath = $this->_conf['cache_dir'] . '/' . $this->_conf['_database']['name'] . '-' . $tablename . '-' . $fieldname . '-' . $index . '?';
     foreach ($keys as $key) {
         $cachePath .= urlencode($key) . '=' . urlencode($_REQUEST[$key]) . '&';
     }
     $queryTool =& Dataface_QueryTool::loadResult($tablename, null, $request);
     // No mimetype was recorded.  Use the PECL Fileinto extension if it is available.
     $files = glob($cachePath . '-*');
     $found = false;
     if (is_array($files)) {
         foreach ($files as $file) {
             $matches = array();
             if (preg_match('/.*-([^\\-]+)$/', $file, $matches)) {
                 $time = $matches[1];
                 if (intval($time) > $lastTableUpdate) {
                     $found = $file;
                     break;
                 } else {
                     @unlink($file);
                 }
             }
         }
     }
     if ($found !== false) {
         $contents = file_get_contents($found);
     } else {
         $columns = array($fieldname);
         if (isset($field['mimetype']) and $field['mimetype']) {
             $columns[] = $field['mimetype'];
         }
         if (isset($field['filename']) and $field['filename']) {
             $columns[] = $field['filename'];
         }
         $record =& $queryTool->loadCurrent($columns, true, true);
         $record->loadBlobs = true;
         $contents = $record->getValue($fieldname, $index);
         $found = $cachePath . '-' . time();
         $found = str_replace("?", "-", $found);
         if ($fh = fopen($found, "w")) {
             fwrite($fh, $contents);
             fclose($fh);
         } else {
             $found = false;
         }
     }
     if (!isset($record)) {
         $columns = array();
         if (isset($field['mimetype']) and $field['mimetype']) {
             $columns[] = $field['mimetype'];
         }
         if (isset($field['filename']) and $field['filename']) {
             $columns[] = $field['filename'];
         }
         $record =& $queryTool->loadCurrent($columns);
     }
     if (isset($field['mimetype']) and $field['mimetype']) {
         $mimetype = $record->getValue($field['mimetype'], $index);
     }
     if (isset($field['filename']) and $field['filename']) {
         $filename = $record->getValue($field['filename'], $index);
     }
     //$mimetype = $record->getValue($field['mimetype'], $index);
     //echo $mimetype; exit;
     if ((!isset($mimetype) or !$mimetype) and $found !== false) {
         if (!extension_loaded('fileinfo')) {
             @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
         }
         if (extension_loaded('fileinfo')) {
             $res = finfo_open(FILEINFO_MIME);
             /* return mime type ala mimetype extension */
             $mimetype = finfo_file($found);
         } else {
             if (function_exists('mime_content_type')) {
                 $mimetype = mime_content_type($found);
             } else {
                 trigger_error("Could not find mimetype for field '{$fieldname}'" . Dataface_Error::printStackTrace(), E_USER_ERROR);
             }
         }
     }
     if (!isset($filename)) {
         $filename = $request['-table'] . '_' . $request['-field'] . '_' . date('Y_m_d_H_i_s');
     }
     //echo "here";
     //echo "here: $mimetype";
     //echo $contents;
     //echo $mimetype; exit;
     header('Content-type: ' . $mimetype);
     header('Content-disposition: attachment; filename="' . $filename . '"');
     echo $contents;
     exit;
 }
示例#29
0
文件: Table.php 项目: promoso/HVAC
 /**
  * Cleans up old import tables.  Any import tables older (in seconds) than the
  * garbage collector threshold (as defined in $app->_conf['garbage_collector_threshold'])
  * will be dropped.
  *
  */
 function cleanImportTables()
 {
     $tables = $this->getImportTables();
     $app =& Dataface_Application::getInstance();
     $garbageLifetime = $app->_conf['garbage_collector_threshold'];
     foreach ($tables as $table) {
         $matches = array();
         if (preg_match('/^' . $this->tablename . '__import_(\\d+)_(\\d)$/', $table, $matches)) {
             if (time() - intval($matches[1]) > intval($garbageLifetime)) {
                 $res = mysql_query("DROP TABLE `{$table}`", $this->db);
                 if (!$res) {
                     trigger_error("Problem occurred attemtping to clean up old import table '{$table}'. MySQL returned an error: " . mysql_error($this->db) . "\n" . Dataface_Error::printStackTrace(), E_USER_ERROR);
                 }
             }
         }
     }
 }
示例#30
0
文件: DB.php 项目: promoso/HVAC
 function checkoutBlob($blobID)
 {
     if (!isset($this->blobs[$blobID])) {
         return PEAR::raiseError(df_translate('scripts.Dataface.DB.checkoutBlob.BLOB_DOESNT_EXIST', "Blob with ID {$blobID} doesn't exist. ", array('blobID' => $blobID)) . Dataface_Error::printStackTrace(), DATAFACE_E_ERROR);
     }
     $blob = $this->blobs[$blobID];
     unset($this->blobs[$blobID]);
     return $blob;
 }