/** * Indexes a record so that it is searchable in the index. * If the index table does not exist yet, this will create it. * @param Dataface_Record &$record The record to be indexed. * @param string $lang The 2-digit language code representing the language * that this record is stored in. */ function indexRecord(&$record, $lang = '*') { $app =& Dataface_Application::getInstance(); if ($lang == '*') { // If the language specified is '*', that means we will // be indexing all languages. $this->indexRecord($record, $app->_conf['lang']); if (is_array($app->_conf['languages'])) { import('Dataface/IO.php'); $io = new Dataface_IO($record->_table->tablename); foreach (array_keys($app->_conf['languages']) as $lang) { if ($lang == $app->_conf['lang']) { continue; } $io->lang = $lang; $io->read($record->getId(), $record); $this->indexRecord($record, $lang); } } return true; } if (!isset($lang)) { $lang = $app->_conf['lang']; } $del =& $record->_table->getDelegate(); if (isset($del) and method_exists($del, 'getSearchableText')) { $searchable_text = $del->getSearchableText($record); if (!is_string($searchable_text)) { // If this method returns anything other than a string, // then we do not index the record... we just return false. return false; } } else { // The getSearchableText() method is not defined, so we will // just produce a concatenation of all text fields in the // record and index those. $fields = $record->_table->getCharFields(true); $searchable_text = implode(', ', $record->strvals($fields)); } // Add soundex information //$words = explode(' ', $searchable_text); //echo $searchable_text; $searchable_text = preg_replace('/<[^>]*?>/', ' ', $searchable_text); $words = preg_split('/((^\\p{P}+)|(\\p{P}*\\s+\\p{P}*)|(\\p{P}+$))/', $searchable_text, -1, PREG_SPLIT_NO_EMPTY); $soundexAddons = array(); foreach ($words as $word) { //echo htmlspecialchars("[Word $word] -> [".soundex(trim($word))."]"); $soundexAddons[] = soundex(trim($word)); } $searchable_text .= '[/////]: ' . implode(' ', $soundexAddons); $searchable_text = strip_tags($searchable_text); $sql = "\n\t\t\treplace into dataface__index \n\t\t\t(`record_id`,`table`,`record_url`,`record_title`,`record_description`,`lang`,`searchable_text`)\n\t\t\tvalues\n\t\t\t(\n\t\t\t'" . addslashes($record->getId()) . "',\n\t\t\t'" . addslashes($record->_table->tablename) . "',\n\t\t\t'" . addslashes($record->getPublicLink()) . "',\n\t\t\t'" . addslashes($record->getTitle()) . "',\n\t\t\t'" . addslashes(strip_tags($record->getDescription())) . "',\n\t\t\t'" . addslashes($lang) . "',\n\t\t\t'" . addslashes($searchable_text) . "'\n\t\t\t)"; if (!@xf_db_query($sql, df_db())) { $this->createIndexTable(); if (!xf_db_query($sql, df_db())) { trigger_error(xf_db_error(df_db()), E_USER_ERROR); } } return true; }
function test_values() { $record = new Dataface_Record('Profiles', array()); $io = new Dataface_IO('Profiles'); $io->read(array('id' => 10), $record); $this->assertEquals('10', $record->val('id')); $rr = new Dataface_RelatedRecord($record, 'appointments'); $this->assertEquals(10, $rr->val('profileid')); $this->assertEquals(10, $rr->getValue('profileid')); }
/** * Indexes a record so that it is searchable in the index. * If the index table does not exist yet, this will create it. * @param Dataface_Record &$record The record to be indexed. * @param string $lang The 2-digit language code representing the language * that this record is stored in. */ function indexRecord(&$record, $lang = '*') { $app =& Dataface_Application::getInstance(); if ($lang == '*') { // If the language specified is '*', that means we will // be indexing all languages. $this->indexRecord($record, $app->_conf['lang']); if (is_array($app->_conf['languages'])) { import('Dataface/IO.php'); $io = new Dataface_IO($record->_table->tablename); foreach (array_keys($app->_conf['languages']) as $lang) { if ($lang == $app->_conf['lang']) { continue; } $io->lang = $lang; $io->read($record->getId(), $record); $this->indexRecord($record, $lang); } } return true; } if (!isset($lang)) { $lang = $app->_conf['lang']; } $del =& $record->_table->getDelegate(); if (isset($del) and method_exists($del, 'getSearchableText')) { $searchable_text = $del->getSearchableText($record); if (!is_string($searchable_text)) { // If this method returns anything other than a string, // then we do not index the record... we just return false. return false; } } else { // The getSearchableText() method is not defined, so we will // just produce a concatenation of all text fields in the // record and index those. $fields = $record->_table->getCharFields(true); $searchable_text = implode(', ', $record->strvals($fields)); } $sql = "\n\t\t\treplace into dataface__index \n\t\t\t(`record_id`,`table`,`record_url`,`record_title`,`record_description`,`lang`,`searchable_text`)\n\t\t\tvalues\n\t\t\t(\n\t\t\t'" . addslashes($record->getId()) . "',\n\t\t\t'" . addslashes($record->_table->tablename) . "',\n\t\t\t'" . addslashes($record->getPublicLink()) . "',\n\t\t\t'" . addslashes($record->getTitle()) . "',\n\t\t\t'" . addslashes(strip_tags($record->getDescription())) . "',\n\t\t\t'" . addslashes($lang) . "',\n\t\t\t'" . addslashes($searchable_text) . "'\n\t\t\t)"; if (!@mysql_query($sql, df_db())) { $this->createIndexTable(); if (!mysql_query($sql, df_db())) { trigger_error(mysql_error(df_db()), E_USER_ERROR); } } return true; }
/** * Checks to see if any of the dependent tables have been modified since this table * was last modified. If so, it will drop the table and regenerate it. */ public function update() { $mod_times = \Dataface_Table::getTableModificationTimes(); if (!isset($mod_times[$this->tableName])) { $me = 0; } else { $me = $mod_times[$this->tableName]; } $outOfDate = false; foreach ($this->dependencies as $dep) { if (@$mod_times[$dep] > $me) { $outOfDate = true; break; } } if ($outOfDate) { \df_q("DROP TABLE IF EXISTS `" . str_replace('`', '', $this->tableName) . "`"); \df_q($this->sql); import('Dataface/IO.php'); \Dataface_IO::touchTable($this->tableName); } }
function save($values) { // First let's find out if we should SAVE the data or if we should just be // storing it in the session or if we are saving the data to the database if (!$this->_new) { // Make sure that the correct form is being submitted. if (!isset($values['__keys__'])) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } if (array_keys($values['__keys__']) != array_keys($this->_table->keys())) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } } if ($this->_new) { $this->_record->clearValues(); } $res = $this->push(); if (!$this->_new) { if ($this->_record->snapshotExists()) { $tempRecord = new Dataface_Record($this->_record->_table->tablename, $this->_record->getSnapshot()); } else { $tempRecord =& $this->_record; } if ($values['__keys__'] != $tempRecord->strvals(array_keys($this->_record->_table->keys()))) { throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR); } } if (PEAR::isError($res)) { $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_PUSHING_DATA', "Error pushing data from form onto table in QuickForm::save() ", array('line' => 0, 'file' => "_"))); return $res; } // Let's take an inventory of which fields were changed.. because // we are going to make their values available in the htmlValues() // method which is used by the ajax form to gather updates. foreach ($this->_fields as $changedfield) { if ($this->_record->valueChanged($changedfield['name'])) { $this->_changed_fields[] = $changedfield['name']; } } $io = new Dataface_IO($this->tablename, $this->db); $io->lang = $this->_lang; if ($this->_new) { $keys = null; } else { $keys = $values['__keys__']; } $res = $io->write($this->_record, $keys, null, true, $this->_new); if (PEAR::isError($res)) { if (Dataface_Error::isDuplicateEntry($res)) { /* * If this is a duplicate entry (or just a notice - not fatal), we will propogate the exception up to let the application * decide what to do with it. */ return $res; } if (Dataface_Error::isNotice($res)) { return $res; } $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving form in QuickForm::save()", array('line' => 0, 'file' => "_"))); throw new Exception($res->toString(), E_USER_ERROR); } if (isset($io->insertIds[$this->tablename]) and $this->_table->getAutoIncrementField()) { $this->_record->setValue($this->_table->getAutoIncrementField(), $io->insertIds[$this->tablename]); $this->_record->setSnapshot(); } return true; }
/** * @brief Deletes the record from the database. * * @param boolean $secure Whether to check permissions before saving. * * @return mixed True on success. PEAR_Error object on fail. */ function delete($secure = false) { import('Dataface/IO.php'); $io = new Dataface_IO($this->_table->tablename); return $io->delete($this, $secure); }
/** * * Saves the related record. * * @param values Associative array of values received from the submitted form. * */ function save($values) { import('Dataface/LinkTool.php'); $colVals = array(); /* * In case some values were not submitted, we will use the defaults (as specified in the relationships.ini * file for this relationship to fill in the blanks. */ if (isset($this->_relationship->_schema['new'])) { foreach ($this->_relationship->_schema['new'] as $key => $value) { if (!isset($values[$key])) { $values[$key] = $value; } } } $io = new Dataface_IO($values['-table']); // for writing the related record $record = new Dataface_Record($values['-table'], array()); // The parent record... not the record being inserted. $io->read($values['__keys__'], $record); // We submitted the keys to the parent record in the form // so that we can load the parent record of this related record. // convert groups foreach (array_keys($values) as $key) { if (isset($this->_groups[$key])) { foreach ($values[$key] as $fieldkey => $fieldval) { $values[$fieldkey] = $fieldval; } unset($values[$key]); } } foreach ($values as $key => $value) { // We will go through each submitted value from the form and try // to figure out how it should be stored. if (strpos($key, '-') === 0) { continue; } if ($key == "-Save") { continue; } // We don't parse the "Save" button $fullPath = $this->_relationshipName . '.' . $key; // The full path to the field can be used to obtain information // about the field from the parent table, since most methods // in the table class will take field names of the form // <relationship name>.<fieldname> if (!$this->_parentTable->exists($fullPath)) { /* * If the field in question does not exist then we just skip it. * Perhaps we should throw an error?!! * */ //echo $fullPath.' does not exist in table '.$this->_parentTable->tablename; continue; } // At this point we know that the field exists so lets obtain references // to the useful components for us to work with this field. if (isset($field)) { unset($field); } $field =& $this->_parentTable->getField($fullPath); // Field array with data about the field. if (PEAR::isError($field)) { throw new Exception("Error obtaining field '{$fullPath}' while saving related record.", E_USER_ERROR); } $abs_fieldName = $this->_parentTable->absoluteFieldName($key, $this->_relationship->_schema['selected_tables']); // The absolute fieldname of this field. e.g., of the form <Tablename>.<Fieldname> if (PEAR::isError($abs_fieldName)) { throw new Exception("Error trying to obtain absolute field name for the related field: '{$fullPath}'", E_USER_ERROR); } list($tablename, $fieldname) = explode('.', $abs_fieldName); if (isset($table)) { unset($table); } $table =& Dataface_Table::loadTable($tablename); // Reference to the table object where this field resides if (isset($quickForm)) { unset($quickForm); } $quickForm =& $this->_quickForms[$tablename]; // QuickForm object for this field's table. $el = $this->getElement($key); $metaValues = array(); // The $metaValues array will store the meta values associated with // the current field. A meta value is an associated value that // should be stored in another field. For example the mimetype // is a metavalue for a file upload field. The $metaValues array // be of the form [Column Name] -> [Column Value]. // Get the absolute field name of the field. An absolute field name is // of the form <Tablename>.<Fieldname> $tempVal = $quickForm->pushValue($fieldname, $metaValues, $el); //$serializedValue; // $tempVal will contain the value as submitted by the form.. ready // to be added to a record. // The QuickForm element. // !!! Just changed arg from $abs_fieldName to $fullPath to fix errors... but still don't // !!! fully understand what was going on - or why it was working before!?!?! if ($this->_parentTable->isMetaField($fullPath)) { // If this is a meta field, we don't insert it on its own... // we will wait until its value is supplied by its described // field. unset($tempVal); unset($el); continue; } foreach ($metaValues as $metaKey => $metaValue) { // Set the meta values $colVals[$tablename . '.' . $metaKey] = $metaValue; } $colVals[$abs_fieldName] = $tempVal; // Add the value to the array to be saved in the RelatedRecord // object. // Note that right now, Dataface_RelatedRecord will just ignore // the part of the field name before the period, but in the future, // this extra information may be used to allow multiple fields // with the same name from different tables in a single relationship. unset($tempVal); } //$queryBuilder = new Dataface_QueryBuilder($this->_parentTable->tablename); $relatedRecord = new Dataface_RelatedRecord($record, $this->_relationshipName, array()); $relatedRecord->setValues($colVals); $res = $io->addRelatedRecord($relatedRecord, true); if (PEAR::isError($res)) { return $res; } //$res = $io->performSQL($sql); return $res; }
/** * @brief Returns an associative array mapping table names to * their associated modification as a unix timestamp. * * Note that these values may not be accurate for views and innodb tables. Not * sure if this is a MySQL bug or a feature. * * @param boolean $refresh Whether to refresh the stats or use cached version. * Generally leave this false as it updates once per request anyways. * * @return array(string=>timestamp) Associative array of table names and their associated * modification timestamps. * */ public static function &getTableModificationTimes($refresh = false) { static $mod_times = 0; if ($mod_times === 0 or $refresh) { $mod_times = array(); $app = Dataface_Application::getInstance(); $dbname = $app->_conf['_database']['name']; //if ( $app->getMySQLMajorVersion() < 5 ){ // $res = xf_db_query("show table status", df_db()); //} else { // $res = xf_db_query("select TABLE_NAME as Name, UPDATE_TIME as Update_time from information_schema.tables where TABLE_SCHEMA='".addslashes($dbname)."'", df_db()); //} $res = xf_db_query("show tables", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $backup_times = null; //while ( $row = xf_db_fetch_assoc($res) ){ while ($row = xf_db_fetch_row($res)) { $row['Name'] = $row[0]; if (@$row['Update_time']) { $mod_times[$row['Name']] = @strtotime($row['Update_time']); } else { if (!$backup_times) { $backup_times =& self::getBackupModificationTimes($refresh); } if (isset($backup_times[$row['Name']]) and $backup_times[$row['Name']]) { $mod_times[$row['Name']] = $backup_times[$row['Name']]; } else { $mod_times[$row['Name']] = time(); import('Dataface/IO.php'); Dataface_IO::touchTable($row['Name']); } } } } return $mod_times; }
/** * Saves the record. Ie: creates the necessary join table records to add the * desired record to the relationship. */ function save($values) { //print_r($values);exit; $colVals = array(); /* * In case some values were not submitted, we will use the defaults (as specified in the relationships.ini * file for this relationship to fill in the blanks. */ if (isset($this->_relationship->_schema['existing'])) { foreach ($this->_relationship->_schema['existing'] as $key => $value) { if (!isset($values[$key])) { $values[$key] = $value; } } } $io = new Dataface_IO($values['-table']); $record = new Dataface_Record($values['-table'], array()); $io->read($values['__keys__'], $record); $idstring = $values['select']; $pairs = explode('&', $idstring); foreach ($pairs as $pair) { list($attname, $attval) = explode('=', $pair); $attname = urldecode($attname); $attval = urldecode($attval); $colVals[$attname] = $attval; } foreach ($values as $key => $value) { if (strpos($key, '-') === 0) { continue; } if ($key == "Save") { continue; } if ($key == "select") { continue; } $fullPath = $values['-relationship'] . '.' . $key; if (!$this->_parentTable->exists($fullPath)) { //echo "Field $fullPath does not exist"; continue; } $metaValues = array(); $abs_fieldName = $this->_parentTable->absoluteFieldName($key, array_merge(array($this->_relationship->getDomainTable()), $this->_relationship->_schema['selected_tables'])); if (PEAR::isError($abs_fieldName)) { continue; } $serializer = new Dataface_Serializer($this->_parentTable->tablename); //echo "Serializing $fullPath\n"; $serializedValue = $serializer->serialize($fullPath, $this->_quickForm->pushValue($fullPath, $metaValues, $this->getElement($key))); $colVals[$abs_fieldName] = $serializedValue; } //print_r($colVals);exit; $relatedRecord = new Dataface_RelatedRecord($record, $values['-relationship'], $colVals); $res = $io->addExistingRelatedRecord($relatedRecord, true); return $res; }
function delete($values) { require_once 'Dataface/IO.php'; $query = $this->_buildDeleteQuery($values); if (PEAR::isError($query)) { return $query; } $io = new Dataface_IO($this->_tablename); $it =& df_get_records($this->_tablename, $query); $warnings = array(); while ($it->hasNext()) { $record =& $it->next(); $res = $io->delete($record); if (PEAR::isError($res) && Dataface_Error::isError($res)) { // this is a serious error... kill it return $res; } else { if (PEAR::isError($res)) { // this is a warning or a notice $warnings[] = $res; } } unset($record); } if (count($warnings) > 0) { return $warnings; } return true; }
/** * Deletes the record from the database. */ function delete($secure = false) { import('Dataface/IO.php'); $io = new Dataface_IO($this->_table->tablename); return $io->delete($this, $secure); //trigger_error('Not implemented yet: '.Dataface_Error::printStackTrace(), E_USER_ERROR); }
/** * Gets an HTML diff output between the records at $id1 and $id2 * respectively, where $id1 and $id2 are history ids from the history__id * column of the history table. * @param string $tablename The name of the base table. * @param integer $id1 The id number of the first record (from the history__id column) * @param integer $id2 The id of the second record (from the history__id column) * @param string $fieldname Optional name of a field to return. * @returns mixed Either the value of the specified field name if $fieldname is specified, * or a Dataface_Record object whose field values are formatted diffs. */ function getDiffs($tablename, $id1, $id2 = null, $fieldname = null) { import('Text/Diff.php'); import('Text/Diff/Renderer/inline.php'); $htablename = $tablename . '__history'; if (!Dataface_Table::tableExists($htablename)) { return PEAR::raiseError(df_translate('scripts.Dataface.HistoryTool.getDiffs.ERROR_HISTORY_TABLE_DOES_NOT_EXIST', "History table for '{$tablename}' does not exist, so we cannot obtain changes for records of that table.", array('tablename' => $tablename)), DATAFACE_E_ERROR); } $rec1 = df_get_record($htablename, array('history__id' => $id1)); if (!isset($id2)) { // The 2nd id wasn't provided so we assume we want to know the diffs // against the current state of the record. $table =& Dataface_Table::loadTable($tablename); $query = $rec1->strvals(array_keys($table->keys())); $io = new Dataface_IO($tablename); $io->lang = $rec1->val('history__language'); $rec2 = new Dataface_Record($tablename, array()); $io->read($query, $rec2); } else { $rec2 = df_get_record($htablename, array('history__id' => $id2)); } $vals1 = $rec1->strvals(); $vals2 = $rec2->strvals(); $vals_diff = array(); $renderer = new Text_Diff_Renderer_inline(); foreach ($vals2 as $key => $val) { $diff = new Text_Diff(explode("\n", @$vals1[$key]), explode("\n", $val)); $vals_diff[$key] = $renderer->render($diff); } $diff_rec = new Dataface_Record($htablename, $vals_diff); if (isset($fieldname)) { return $diff_rec->val($fieldname); } return $diff_rec; }
/** * Sets a value by ID. */ static function setByID($uri, $value) { @(list($uri, $fieldname) = explode('#', $uri)); $record =& Dataface_IO::getByID($uri); if (PEAR::isError($record)) { return $record; } if (!is_object($record)) { return PEAR::raiseError("Could not find record matching '{$uri}'."); } if (isset($fieldname)) { $res = $record->setValue($fieldname, $value); } else { $res = $record->setValues($value); } if (PEAR::isError($res)) { return $res; } $res = $record->save(); return $res; }
function save($values) { $app = Dataface_Application::getInstance(); // Which ones were checked $checked = array(); foreach ($values['--related-checkboxes'] as $k => $v) { if ($v) { $checked[] = $k; } } // Which ones are currently part of the relationship $default = array_keys($this->getCheckedRecordsDefaults()); // Which ones need to be added? $toAdd = array_diff($checked, $default); // Which ones need to be removed? $toRemove = array_diff($default, $checked); // Now we go through and remove the ones that need to be removed. $io = new Dataface_IO($this->record->_table->tablename); $messages = array(); $successfulRemovals = 0; $successfulAdditions = 0; foreach ($toRemove as $id) { $res = $io->removeRelatedRecord($this->id2record($id), false, true); if (PEAR::isError($res)) { $messages[] = $res->getMessage(); } else { $successfulRemovals++; } } // Now we go through and add the ones that need to be added. foreach ($toAdd as $id) { $res = $io->addExistingRelatedRecord($this->id2record($id), true); if (PEAR::isError($res)) { $messages[] = $res->getMessage(); } else { $successfulAdditions++; } } array_unshift($messages, df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_ADDED', $successfulAdditions . ' records were successfully added to the relationship.', array('num_added' => $successfulAdditions)), df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_REMOVED', $successfulRemovals . ' records were successfully removed from the relationship.', array('num_removed' => $successfulRemovals))); $_SESSION['--msg'] = '<ul><li>' . implode('</li><li>', $messages) . '</li></ul>'; $url = $values['--query']; $urlparts = parse_url($url); if ($urlparts and $urlparts['host'] and $urlparts['host'] != $_SERVER['HTTP_HOST']) { throw new Exception('Failed to redirect after action due to an invalid query parameter.', E_USER_ERROR); } $app->redirect($values['--query']); }
function processForm($values) { ini_set('max_execution_time', 900); import('Dataface/IO.php'); import('Dataface/TranslationTool.php'); $tt = new Dataface_TranslationTool(); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); if (strlen($values['-sourceLanguage']) != 2 || strlen($values['-destinationLanguage']) != 2) { trigger_error('Invalid input for languages. Expected a 2 digit language code.', E_USER_ERROR); } $values['-limit'] = 500; //$qt = new Dataface_QueryTool($this->table->tablename, $app->db(), $values); //$qt->loadSet(); //$it =& $qt->iterator(); $q = $query; $q['-limit'] = 9999; if (@$q['--limit']) { $q['-limit'] = $q['--limit']; } $it =& df_get_records($this->table->tablename, $q); $keycols = array_keys($this->table->keys()); $cols = $this->table->getTranslation($values['-destinationLanguage']); if (!is_array($cols)) { trigger_error('Could not find any columns to be translated in table ' . $values['-destinationLanguage'] . Dataface_Error::printStackTrace(), E_USER_ERROR); } $babelfish = $this->getTranslator(); //new babelfish(); if (isset($app->_conf['google_translate_url'])) { $babelfish->google_url_webpage = $app->_conf['google_translate_url']; } $ioSrc = new Dataface_IO($this->table->tablename); $ioSrc->lang = $values['-sourceLanguage']; $languageCodes = new I18Nv2_Language('en'); $ioDest = new Dataface_IO($this->table->tablename); $ioDest->lang = $values['-destinationLanguage']; $count = 0; $to_be_translated = array(); $destObjects = array(); while ($it->hasNext()) { $curr =& $it->next(); $translationInfo =& $tt->getTranslationRecord($curr, $values['-destinationLanguage']); if ($translationInfo and $translationInfo->val('translation_status') == TRANSLATION_STATUS_NEEDS_UPDATE_MACHINE) { $t_needsUpdate = true; } else { $t_needsUpdate = false; } $translation_text = array(); $keyvals = $curr->vals($keycols); $srcObject = new Dataface_Record($this->table->tablename, array()); $destObject = new Dataface_Record($this->table->tablename, array()); $ioSrc->read($keyvals, $srcObject); $ioDest->read($keyvals, $destObject); $keyvalsQuery = $keyvals; foreach ($keyvals as $key => $val) { $keyvalsQuery[$key] = '=' . $keyvals[$key]; } $qb = new Dataface_QueryBuilder($this->table->tablename, $keyvalsQuery); $sql = "select * from `" . $this->table->tablename . "_" . $values['-destinationLanguage'] . "` " . $qb->_where(); $res = mysql_query($sql, $app->db()); if (!$res) { trigger_error(mysql_error($app->db()) . 'SQL : ' . $sql . " Stacktrace:" . Dataface_Error::printStackTrace(), E_USER_ERROR); } $queryResult = mysql_fetch_array($res); if (!$queryResult) { $queryResult = array(); } foreach ($cols as $col) { if (in_array($col, $keycols)) { continue; } if (!$this->table->isText($col) and !$this->table->isChar($col)) { continue; } if (!isset($queryResult[$col]) || $t_needsUpdate) { //$updateRequired = true; } else { continue; } $translation_text[$col] = $srcObject->getValue($col); } if (count($translation_text) > 0) { $to_be_translated[] =& $translation_text; $destObjects[] =& $destObject; } unset($curr); unset($srcObject); unset($destObject); unset($qb); unset($translatedRecord); unset($translation_text); unset($translationInfo); } $translated = $this->translate($to_be_translated, $values['-sourceLanguage'], $values['-destinationLanguage'], $babelfish); if (PEAR::isError($translated)) { return $translated; } foreach ($translated as $rowid => $row) { if ($translated[$rowid] == $to_be_translated[$rowid]) { continue; } $update = false; foreach ($row as $col => $val) { if (strlen(trim($val)) === 0) { continue; } $destObjects[$rowid]->setValue($col, $val); $update = true; } if ($update) { $res = $ioDest->write($destObjects[$rowid]); if (PEAR::isError($res)) { trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } $tt->setTranslationStatus($destObjects[$rowid], $ioDest->lang, TRANSLATION_STATUS_MACHINE); } } }
function commit(&$grid) { $columnnames = array_keys($grid->columns); if ($this->recordid == '__new__') { // this is a new record - so we must create a new one. $parentObj =& $grid->getParentObject(); if (is_a($parentObj, 'Dataface_Table')) { $record = new Dataface_Record($parentObj->tablename, array()); } else { $record = new Dataface_RelatedRecord($parentObj, $grid->relationship, array()); } } else { $record =& df_get_record_by_id($this->recordid); } $rowdata =& $grid->data[$this->rowid]; $savedata = array(); foreach ($this->params['cells'] as $key) { $savedata[$key] = $rowdata[$key]; } $record->setValues($savedata); if ($this->recordid == '__new__' and is_a($record, 'Dataface_RelatedRecord')) { import('Dataface/IO.php'); $io = new Dataface_IO($parentObj->_table->tablename); $io->addRelatedRecord($record); } else { $record->save(); } }
function import($values) { if (intval($this->_step) === 1) { $upload =& $this->getElement('upload'); if ($upload->isUploadedFile()) { /* * A file was uploaded. */ $val =& $upload->getValue(); $data = file_get_contents($val['tmp_name']); } else { /* * No file was uploaded so we will get data from the paste field. */ $data = $values['content']; } $io = new Dataface_IO($this->_table->tablename); $relname = $this->_relationship === null ? null : $this->_relationship->getName(); $importTablename = $io->importData($this->_record, $data, $values['filter'], $relname, false, @$values['__default_values__']); return $importTablename; } else { if ($this->_step == 2) { $io = new Dataface_IO($this->_table->tablename); $relname = $this->_relationship === null ? null : $this->_relationship->getName(); $records = $io->importData($this->_record, $values['--importTablename'], @$values['filter'], $relname, true); return $records; } } }
function writeConfigToDB() { import('Dataface/Table.php'); import('Dataface/Record.php'); import('Dataface/IO.php'); if (!is_a($this, 'Dataface_ConfigTool')) { throw new Exception('ConfigWriter methods are only to be used via the Dataface_ConfigTool class.', E_USER_ERROR); } $this->loadAllConfig(); $app =& Dataface_Application::getInstance(); // first let's make copies of the current configuration. $timestamp = time(); foreach ($this->configTypes as $type) { $res = xf_db_query("CREATE TABLE `__" . addslashes($type) . "__" . $timestamp . "` SELECT * FROM `__" . addslashes($type) . "__`", $app->db()); if (!$res) { throw new Exception("Failed to make backup of table '__" . $type . "__'." . xf_db_error($app->db()), E_USER_ERROR); } } $res = xf_db_query("CREATE TABLE `__properties__" . $timestamp . "` SELECT * FROM `__properties__`", $app->db()); if (!$res) { throw new Exception("Failed to make backup of table '__properties__'.", $app->db()); } // Now that we have made our backups, we can continue to write the configuration to the database. //print_r($this->config); foreach ($this->configTypes as $type) { $res = xf_db_query("DELETE FROM `__" . addslashes($type) . "__`", $app->db()); if (!$res) { throw new Exception("Failed to delete all records from table '__" . $type . "__'", $app->db()); } foreach ($this->config[$type] as $tablename => $tableConfig) { foreach ($tableConfig as $sectionname => $section) { $tableObj =& Dataface_Table::loadTable('__' . $type . '__'); $record = new Dataface_Record('__' . $type . '__', array()); $record->useMetaData = false; // some of the field names begin with '__' which would conflict with dataface's handling of MetaData fields. foreach (array_keys($tableObj->fields()) as $fieldname) { $record->setValue($fieldname, @$section[$fieldname]); unset($section[$fieldname]); } $record->setValue('name', $sectionname); $record->setValue('table', $tablename); //echo nl2br("Section name: $sectionname\nTable: $tablename\n"); //print_r($record->strvals()); echo nl2br("\nWriting section: {$sectionname} : "); print_r($record->strvals()); // now that we have created the record, we write the record $io = new Dataface_IO('__' . $type . '__'); $res = $io->write($record); if (PEAR::isError($res)) { throw new Exception($res->toString(), E_USER_ERROR); } else { if (!$res) { throw new Exception("Failure to write to database for unknown reason.", E_USER_ERROR); } } // now for the rest of the properties. foreach ($section as $propertyName => $propertyValue) { $res = xf_db_query("\n\t\t\t\t\t\t\tINSERT INTO \n\t\t\t\t\t\t\t `__properties__` \n\t\t\t\t\t\t\t (`parent_id`,`parent_type`,`property_name`,`property_value`)\n\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t ('" . $record->val($type . '_id') . "', \n\t\t\t\t\t\t\t '" . addslashes($type) . "',\n\t\t\t\t\t\t\t '" . addslashes($propertyName) . "',\n\t\t\t\t\t\t\t '" . addslashes($propertyValue) . "')", $app->db()); if (!$res) { throw new Exception("Failed to add property '{$propertyName}' to table '__properties__' with value '{$propertyValue}'" . xf_db_error($app->db()), E_USER_ERROR); } } unset($tableObj); unset($record); unset($io); } } } }
/** * 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)); }
/** * @see Dataface_IO::setByID() */ function df_set($uri, $value) { $res = Dataface_IO::setByID($uri, $value); return $res; }
function testAddRelatedRecord() { $fragrance = df_get_record('fragrances', array('fragrance_id' => '=1')); $this->assertTrue($fragrance instanceof Dataface_Record, 'Loaded fragrance should be a Dataface_Record object.'); $formulasRelationship = $fragrance->table()->getRelationship('formulas'); $this->assertTrue($formulasRelationship instanceof Dataface_Relationship, 'The formulas relationship does not exist or could not be loaded.'); $relatedRecord = new Dataface_RelatedRecord($fragrance, 'formulas'); $this->assertTrue(!$relatedRecord->isDirty('formula_name'), 'Record should not be dirty when it is first created.'); $formula = $relatedRecord->toRecord('formulas'); $this->assertTrue($formula instanceof Dataface_Record, 'Formula should be a Dataface_Record'); $records = $relatedRecord->toRecords(); $this->assertTrue($records[0] instanceof Dataface_Record, 'Formulas record from toRecords() should be of type Dataface_Record.'); $relatedRecord->setValues(array('formula_name' => 'Test formula', 'formula_description' => 'This is just a test formula', 'ingredients' => array(0 => array('ingredient_id' => 3, 'concentration' => 10, 'concentration_units' => 1, 'amount' => 10, 'amount_units' => 2, '__id__' => 'new', '__order__' => 0), '__loaded__' => 1))); $this->assertTrue($relatedRecord->isDirty('formula_name'), 'The formula name should be dirty before it is saved.'); $this->assertTrue($relatedRecord->isDirty('ingredients'), 'The ingredients should be dirty befor it is saved.'); $io = new Dataface_IO('fragrances'); $res = $io->addRelatedRecord($relatedRecord); $this->assertTrue(!PEAR::isError($res), 'The result of saving a related formula should not be an error.'); }
function save($values) { // Which ones were checked $checked = array_keys($values['--related-checkboxes']); // Which ones are currently part of the relationship $default = array_keys($this->getCheckedRecordsDefaults()); // Which ones need to be added? $toAdd = array_diff($checked, $default); // Which ones need to be removed? $toRemove = array_diff($default, $checked); // Now we go through and remove the ones that need to be removed. $io = new Dataface_IO($this->record->_table->tablename); $messages = array(); $successfulRemovals = 0; foreach ($toRemove as $id) { $res = $io->removeRelatedRecord($this->id2record($id)); if (PEAR::isError($res)) { $messages[] = $res->getMessage(); } else { $sucessfulRemovals++; } } // Now we go through and add the ones that need to be added. foreach ($toAdd as $id) { $res = $io->addExistingRelatedRecord($this->id2record($id)); if (PEAR::isError($res)) { $messages[] = $res->getMessage(); } else { $successfulAdditions++; } } array_unshift($messages, df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_ADDED', $successfulAdditions . ' records were successfully added to the relationship.', array('num_added' => $successfulAdditions)), df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_REMOVED', $successfulRemovals . ' records were successfully removed from the relationship.', array('num_removed' => $successfulRemovals))); $_SESSION['msg'] = '<ul><li>' . implode('</li><li>', $messages) . '</li></ul>'; header('Location: ' . $values['--query']); exit; }
function test_destination_tables() { $record = new Dataface_Record('Profiles', array()); $io = new Dataface_IO('Profiles'); $io->read(array('id' => 10), $record); $relationship =& $record->_table->getRelationship('appointments'); $destinationTables =& $relationship->getDestinationTables(); $this->assertEquals(1, count($destinationTables)); $this->assertEquals('Appointments', $destinationTables[0]->tablename); //$this->assertEquals(array('Appointments'), $destinationTables); require_once 'dataface-public-api.php'; $registration =& df_get_record('Registrations', array('RegistrationID' => 1)); $products =& $registration->getRelationshipIterator('Products'); $product =& $products->next(); $destTables =& $product->_relationship->getDestinationTables(); $this->assertEquals(2, count($destTables)); }
/** * Deletes the appropriate records from the join table and the domain table (if requested). */ function delete($values) { /* * Next we construct an IO object to write to the domain table. */ $domainTable =& $this->getDomainTable(); $domainIO = new Dataface_IO($domainTable->tablename); $records =& $this->getSelectedRecords(); $messages = array(); $confirmations = array(); $warnings = array(); $table =& $this->_record->_table; // This is the table of the parent record. $io = new Dataface_IO($table->tablename); $removePermission = $this->_record->checkPermission('remove related record', array('relationship' => $this->_relationshipName)); //if ($removePermission ){ // $mask = array('delete'=>1); //} else { // $mask = array(); //} $deleteRequired = $this->deleteRequired(); // Do we have to delete the domain record // to make the removal effective foreach ($records as $record) { // If deletion is required, we will do ou $res = $io->removeRelatedRecord($record, @$values['delete'], true); if (PEAR::isError($res)) { $warnings[] = $res->getMessage(); } else { $confirmations[] = $confirmations[] = df_translate('Successfully deleted record', "Successfully deleted entry for record '" . $record->getTitle() . "' in table '" . $table->tablename . "'", array('title' => $record->getTitle(), 'table' => $table->tablename)); } } return array('confirmations' => $confirmations, "warnings" => $warnings); }
function test_setByID() { $this->assertEquals('John', Dataface_IO::getByID('Profiles?id=10#fname')); Dataface_IO::setByID('Profiles?id=10#fname', 'Jimmy'); $this->assertEquals('Jimmy', Dataface_IO::getByID('Profiles?id=10#fname')); $this->assertEquals('Teacher', Dataface_IO::getById('Profiles/appointments?id=10&appointments::id=2#position')); Dataface_IO::setByID('Profiles/appointments?id=10&appointments::id=2#position', 'firefighter'); $this->assertEquals('firefighter', Dataface_IO::getById('Profiles/appointments?id=10&appointments::id=2#position')); Dataface_IO::setByID('Profiles?id=10', array('fname' => 'Bobby', 'lname' => 'Brown')); $r =& Dataface_IO::getByID('Profiles?id=10'); $this->assertEquals(array('fname' => 'Bobby', 'lname' => 'Brown'), $r->vals(array('fname', 'lname'))); }
/** * Neither INNODB tables nor views store the last updated time * inside of MySQL. This wreaks havoc on caching, so we create * our own backup table called dataface__mtimes as a fallback * mechanism to track uptime times of tables. The down side * is that it only updates the timestamp when a change is made * via Xataface. Outside changes aren't tracked. * * @see Dataface_IO::createModificationTimesTable() * @see Dataface_IO::touchTable($tablename) */ public static function &getBackupModificationTimes($refresh = false) { $backup_times = 0; if ($backup_times === 0 or $refresh) { $res = mysql_query("select * from dataface__mtimes", df_db()); if (!$res) { import('Dataface/IO.php'); Dataface_IO::createModificationTimesTable(); $res = mysql_query("select * from dataface__mtimes", df_db()); if (!$res) { throw new Exception(mysql_error(df_db())); } } $backup_times = array(); while ($row = mysql_fetch_assoc($res)) { $backup_times[$row['name']] = $row['mtime']; } @mysql_free_result($res); } return $backup_times; }
function loadRecords() { $keyMissing = true; if (isset($this->_record)) { $keyMissing = false; foreach (array_keys($this->_table->keys()) as $key) { if (!$this->_record->val($key)) { // the current record is missing a primary key. // we need to reload the record. $keyMissing = true; break; } } } if ($keyMissing) { return PEAR::raiseError(df_translate('scripts.Dataface.TranslationForm.ERROR_NO_RECORD_FOUND', "No record was found to be translated."), E_USER_ERROR); } // Now we want to load all of the translations for the current record for use on this // translation form. $query = array(); foreach (array_keys($this->_table->keys()) as $key) { $query[$key] = '=' . $this->_record->strval($key); } $io = new Dataface_IO($this->_table->tablename); foreach ($this->translatableLanguages as $lang) { $io->lang = $lang; $record = new Dataface_Record($this->_table->tablename, array()); $io->read($query, $record); $this->records[$lang] =& $record; unset($record); } unset($this->_record); $this->_record =& $this->records[$this->destinationLanguage]; }