function handle($params) { $app = Dataface_Application::getInstance(); $query = $app->getQuery(); try { if (!@$_POST['-table']) { throw new Exception("No table was specified"); } $vals = array(); foreach ($query as $k => $v) { if ($k and $k[0] != '-') { $vals[$k] = $v; } } $record = new Dataface_Record($_POST['-table'], array()); $record->setValues($vals); if (!$record->checkPermission('ajax_save')) { throw new Exception("Permission Denied", 502); } $res = $record->save(null, true); if (PEAR::isError($res)) { error_log($res->getMessage(), $res->getCode()); throw new Exception("Failed to save record due to a server error. See log for details."); } $this->out(array('code' => 200, 'message' => 'Successfully inserted record.', 'recordId' => $record->getId())); } catch (Exception $ex) { $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage())); } }
/** * Defines how a geopicker widget should be built. * * @param Dataface_Record $record The Dataface_Record that is being edited. * @param array &$field The field configuration data structure that the widget is being generated for. * @param HTML_QuickForm The form to which the field is to be added. * @param string $formFieldName The name of the field in the form. * @param boolean $new Whether this widget is being built for a new record form. * @return HTML_QuickForm_element The element that can be added to a form. * */ function &buildWidget($record, &$field, $form, $formFieldName, $new = false) { $factory = Dataface_FormTool::factory(); $mt = Dataface_ModuleTool::getInstance(); $mod = $mt->loadModule('modules_geopicker'); $widget =& $field['widget']; $atts = array(); if (!@$atts['class']) { $atts['class'] = ''; } $atts['class'] .= ' xf-geopicker'; $atts['df:cloneable'] = 1; $perms = $record->getPermissions(array('field' => $field['name'])); $noEdit = ($new and !@$perms['new']) or !$new and !@$perms['edit']; if ($noEdit) { $atts['data-geopicker-read-only'] = "1"; } $mod->registerPaths(); // Add our javascript Dataface_JavascriptTool::getInstance()->import('xataface/modules/geopicker/widgets/geopicker.js'); $el = $factory->addElement('text', $formFieldName, $widget['label'], $atts); if (PEAR::isError($el)) { throw new Exception($el->getMessage(), $el->getCode()); } return $el; }
function handle(&$params) { $app =& Dataface_Application::getInstance(); $tt = new Dataface_TranslationTool(); if (!Dataface_Table::tableExists('dataface__translation_submissions', false)) { $tt->createTranslationSubmissionsTable(); header('Location: ' . $app->url('')); exit; } if (!@$_POST['--submit']) { df_display(array('query' => $app->getQuery(), 'success' => @$_REQUEST['--success']), 'Dataface_submit_translation.html'); exit; } else { if (@$_POST['subject']) { // This is a dummy field - possible hacking attempt header('Location: ' . $app->url('-action=list')); exit; } if (@$_POST['--recordid']) { $record = df_get_record_by_id($_POST['--recordid']); $values = array('record_id' => @$_POST['--recordid'], 'language' => @$_POST['--language'], 'url' => @$_POST['--url'], 'original_text' => @$_POST['--original_text'], 'translated_text' => @$_POST['--translated_text'], 'translated_by' => @$_POST['--translated_by']); $trec = new Dataface_Record('dataface__translation_submissions', array()); $trec->setValues($values); $trec->save(); $email = <<<END The following translation was submitted to the web site {$app->url('')}: Translation for record {$record->getTitle()} which can be viewed at {$record->getURL('-action=view')}. This translation was submitted by {$_POST['--translated_by']} after viewing the content at {$_POST['--url']}. The original text that was being translated is as follows: {$_POST['--original_text']} The translation proposed by this person is as follows: {$_POST['--translated_text']} For more details about this translation, please visit {$trec->getURL('-action=view')}. END; if (@$app->_conf['admin_email']) { mail($app->_conf['admin_email'], 'New translation submitted', $email); } if (@$_POST['--redirect'] || @$_POST['--url']) { $url = @$_POST['--redirect'] ? $_POST['--redirect'] : $_POST['--url']; header('Location: ' . $url . '&--msg=' . urlencode('Thank you for your submission.')); exit; } else { header('Location: ' . $app->url('') . '&--success=1&--msg=' . urlencode('Thank you for your submission.')); exit; } } else { trigger_error("No record id was provided", E_USER_ERROR); } } }
function handle($params) { if (!defined('DISABLE_reCAPTCHA')) { define('DISABLE_reCAPTCHA', 1); } import('Dataface/QuickForm.php'); Dataface_QuickForm::$TRACK_SUBMIT = false; $app = Dataface_Application::getInstance(); $query = $app->getQuery(); $errors = null; try { if (!@$_POST['-table']) { throw new Exception("No table specified"); } $table = $_POST['-table']; $rec = new Dataface_Record($table, array()); $tableObj = $rec->_table; $fields = array(); if (!$rec->checkPermission('new')) { throw new Exception("Failed to insert record. Permission denied"); } foreach ($_POST as $k => $v) { if ($k[0] == '-') { continue; } $fields[] = $k; $rec->setValue($k, $v); if (!$rec->checkPermission('new', array('field' => $k))) { throw new Exception(sprintf("Failed to insert record because you do not have permission to insert data into the %s column", $k)); } } $form = df_create_new_record_form($table, $fields); $form->_flagSubmitted = true; $res = $form->validate(); if (!$res) { $errors = $form->_errors; throw new Exception('Validation error', REST_INSERT_VALIDATION_ERROR); } $res = $rec->save(null, true); if (PEAR::isError($res)) { throw new Exception("Failed to insert record due to a server error: " . $res->getMessage(), 500); } $out = array(); $vals = $rec->strvals(); foreach ($vals as $k => $v) { if ($rec->checkPermission('view')) { $out[$k] = $v; } } $this->out(array('code' => 200, 'message' => 'Record successfully inserted', 'record' => $out)); exit; } catch (Exception $ex) { $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage(), 'errors' => $errors)); exit; } }
/** * Builds an SQL query to copy the given record. This honours permissions * and will only copy columns for which 'view' access is available in the * source record and 'edit' access is available in the destination record. * * Individual column failures (due to permissions) are recorded in the * $warnings variable of this class. It will be an array of Dataface_Error * objects. * * @param Dataface_Record $record The record being copied. * @param array $valls Values that should be placed in the copied version. * @param boolean $force If true this will perform the copy despite individual * column warnings. * @returns string The SQL query to copy the record. */ function buildCopyQuery($record, $vals = array(), $force = true) { $dummy = new Dataface_Record($record->_table->tablename, $vals); if (!$record->checkPermission('view') || !$dummy->checkPermission('edit')) { return Dataface_Error::permissionDenied("Failed to copy record '" . $record->getTitle() . "' because of insufficient permissions."); } $copy_fields = array_keys($record->_table->fields()); // Go through each field and see if we have copy permission. // Copy permission is two-fold: 1- make sure the source is viewable // 2- make sure the destination is editable. $failed = false; foreach ($copy_fields as $key => $fieldname) { if (!$record->checkPermission('view', array('field' => $fieldname)) || !$dummy->checkPermission('edit', array('field' => $fieldname))) { $this->warnings[] = Dataface_Error::permissionDenied("The field '{$fieldname}' could not be copied for record '" . $record->getTitle() . "' because of insufficient permissions."); unset($copy_fields[$key]); $failed = true; } } // If we are not forcing completion, any failures will result in cancellation // of the copy. if (!$force and $failed) { return Dataface_Error::permissionDenied("Failed to copy the record '" . $record->getTitle() . "' due to insufficient permissions on one or more of the columns."); } // We don't copy auto increment fields. $auto_inc_field = $record->_table->getAutoIncrementField(); if ($auto_inc_field) { $key = array_search($auto_inc_field, $copy_fields); if ($key !== false) { unset($copy_fields[$key]); } } // Now we can build the query. $sql = array(); $sql[] = "insert into `" . $record->_table->tablename . "`"; $sql[] = "(`" . implode('`,`', $copy_fields) . "`)"; $copy_values = array(); foreach ($copy_fields as $key => $val) { if (isset($vals[$val])) { $copy_values[$key] = "'" . addslashes($dummy->getSerializedValue($val)) . "' as `{$val}`"; } else { $copy_values[$key] = "`" . $val . "`"; } } $sql[] = "select " . implode(', ', $copy_values) . " from `" . $record->_table->tablename . "`"; $qb = new Dataface_QueryBuilder($record->_table->tablename); $keys = array_keys($record->_table->keys()); $q = array(); foreach ($keys as $key_fieldname) { $q[$key_fieldname] = $record->strval($key_fieldname); } $where = $qb->_where($q); $where = $qb->_secure($where); $sql[] = $where; return implode(' ', $sql); }
function testCrawlSite() { $s = new Dataface_Record('websites', array()); $s->setValues(array('website_url' => 'http://solutions.weblite.ca/', 'source_language' => 'en', 'target_language' => 'fr', 'website_name' => 'Site 1 french', 'active' => 1, 'base_path' => '/fr/', 'host' => 'localhost')); $s->save(); $site = SweteSite::loadSiteById($s->val('website_id')); $crawler = new SiteCrawler(); $crawler->site = $site; $crawler->startingPoint = 'http://solutions.weblite.ca/'; $crawler->depth = 3; $crawler->crawl(); //print_r($crawler->root); }
public function saveResource($url, $content, $contentType) { $app = Dataface_Application::getInstance(); $res = new Dataface_Record('job_content', array()); $res->setValues(array('job_id' => $this->job->getRecord()->val('job_id'), 'url' => $url, 'url_hash' => md5($url), 'content_type' => $contentType, 'content' => $content)); $old = $app->_conf['multilingual_content']; $app->_conf['multilingual_content'] = 0; $result = $res->save(); $app->_conf['multilingual_content'] = $old; if (PEAR::isError($res)) { throw new Exception($res->getMessage()); } }
public function __construct($rows, $cols = null, $opts = array()) { // Make sure rows are all arrays foreach ($rows as $k => $row) { if (!is_array($row)) { $rows[$k] = (array) $rows[$k]; } } if (!isset($cols)) { $cols = array(); if (count($rows) > 0) { $row = $rows[0]; foreach ($row as $k => $v) { if ($k === '__meta__') { continue; } $cols[] = array('label' => $k, 'name' => $k); } } } $flds = array('table', 'cssClass', 'canEdit', 'canAdd', 'canDelete', 'rowActions', 'newParams', 'params', 'addButtonLabel'); foreach ($flds as $fld) { if (isset($opts[$fld])) { $this->{$fld} = $opts[$fld]; } } $this->cssClass .= ' xf-portlet'; $decorateRow = null; if (isset($opts['decorateRow']) and is_callable($opts['decorateRow'])) { $decorateRow = $opts['decorateRow']; } foreach ($rows as $k => $row) { if (!isset($rows[$k]['__meta__'])) { $rows[$k]['__meta__'] = array(); } $dfRec = new \Dataface_Record($this->table, array()); if (!@$rows[$k]['__meta__']['recordId']) { $dfRec->setValues($row); $rows[$k]['__meta__']['recordId'] = $dfRec - getId(); } $rows[$k]['__meta__']['record'] = $dfRec; if (isset($decorateRow)) { $decorateRow($rows[$k]); } } $this->cols = $cols; $this->rows = $rows; $this->opts = $opts; }
function test_insert() { $io = new Dataface_IO('Profiles', $this->db); $s = new Dataface_Record('Profiles', array()); $s->setValues(array("fname" => "Thomas", "lname" => "Hutchinson", "title" => "Mr.")); ob_start(); $res = $io->write($s); $buffer = ob_get_contents(); ob_end_clean(); $this->assertEquals(" beforeSave beforeInsert afterInsert afterSave", $buffer); if (PEAR::isError($res)) { echo $res->toString(); } $s2 = new Dataface_Record('Profiles', array()); $io->read(array("fname" => "Thomas"), $s2); $this->assertEquals($s2->getValue("lname"), "Hutchinson"); }
function afterCopy(Dataface_Record $orig, Dataface_Record $copy) { $rand = md5(rand(0, 1000000)); $copytable = 'copy_' . $rand; $res = xf_db_query("create temporary table `{$copytable}` select * from formula_ingredients where formula_id='" . addslashes($orig->val('formula_id')) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("update `{$copytable}` set formula_id='" . addslashes($copy->val('formula_id')) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("insert into formula_ingredients select * from `{$copytable}`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("drop table `{$copytable}`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } }
function testPage() { $url = DATAFACE_SITE_URL . '/tests/testsites/site1/index.html'; $site = new Dataface_Record('websites', array()); $site->setValues(array('website_url' => df_absolute_url(DATAFACE_SITE_URL . '/tests/testsites/site1/'), 'source_language' => 'en', 'target_language' => 'fr', 'website_name' => 'Site 1 French', 'active' => 1, 'base_path' => DATAFACE_SITE_URL . '/proxies/site1/', 'host' => $_SERVER['HTTP_HOST'])); $site->save(); df_q("delete from site_text_filters where website_id='" . addslashes($site->val('website_id')) . "'"); $server = new ProxyServer(); $server->site = SweteSite::loadSiteById($site->val('website_id')); $server->SERVER = array('REQUEST_METHOD' => 'get'); $server->URL = df_absolute_url(DATAFACE_SITE_URL . '/proxies/site1/index.html'); $server->buffer = true; $server->handleRequest(); $doc = new DOMDocument(); $doc->loadHtml(file_get_contents('tests/testsites/site1_output/index.out.html')); $expected = $doc->saveHtml(); //echo $server->contentBuffer; $doc2 = new DOMDocument(); $doc2->loadHtml($server->contentBuffer); $actual = $doc2->saveHtml(); //$this->assertEquals(trim($expected), trim($actual)); // Cancelled this test because WTF!!!! Even if I print the actual output, copy it to the file // and compare it to itself, it still fails!!!! WTF!!!! }
/** * Handles the insertion of a new imported record. This should parse the * input file and place the strings appropriately into the translation_miss_log * table and the translation memory. * @param Dataface_Record $record */ public function afterInsert(Dataface_Record $record) { $filePath = $record->getContainerSource('file'); if (!file_exists($filePath)) { throw new Exception("Source file doesn't exist"); } switch ($record->val('file_format')) { case 'CSV': case 'XLS': $translationMemory = null; if ($record->val('target_translation_memory_uuid')) { $translationMemory = XFTranslationMemory::loadTranslationMemoryByUuid($record->val('target_translation_memory_uuid')); } if ($record->val('file_format') === 'XLS') { import('inc/ExcelStringImporter.php'); $importer = new ExcelStringImporter($filePath, $translationMemory); } else { $importer = new CSVStringImporter($filePath, $translationMemory); } $importer->fixEncoding(); $message = 'Import succeeded'; $status = 'COMPLETE'; try { $importer->import(); } catch (Exception $ex) { $message = 'Import failed: ' . $ex->getMessage(); $status = 'FAILED'; } $log = $message . "\r\n" . "Succeeded: " . $importer->succeeded . ", " . "Failed: " . $importer->failed . "\r\n" . "Error Log:\r\n===========\r\n"; foreach ($importer->errors as $row) { $log .= "Import Row: " . implode(",", $row['row']) . "\r\n" . "Error Message: " . $row['message']; } df_q(sprintf("update string_imports \n set \n log='%s', \n status='%s', \n succeeded=%d, \n failed=%d\n where\n string_import_id=%d", addslashes($log), addslashes($status), $importer->succeeded, $importer->failed, $record->val('string_import_id'))); break; default: throw new Exception(sprintf("Unrecognized file format: %s", $record->val('file_format'))); } }
public function process() { $this->translationStats = null; $this->translationMissLogRecord = null; $this->translatedPage = null; $proxyWriter = $this->site->getProxyWriter(); $pageWrapper = $this->page; $page = $pageWrapper->getRecord(); $tmid = null; if (!isset($this->translationMemory)) { $tmid = $pageWrapper->getTranslationMemoryId(true); } else { $tmid = $this->translationMemory->getRecord()->val('translation_memory_id'); } $translatedContent = null; $untranslatedContent = $page->val('webpage_content'); if (!trim($untranslatedContent)) { // There is nothing to process on this page. return; } if ($tmid or $this->translationMemory) { if ($this->translationMemory) { $tm = $this->translationMemory; } else { $tm = $this->getTranslationMemory($tmid); } if ($tm) { if ($tm->getSourceLanguage() != $pageWrapper->getLanguage()) { throw new Exception("Translation memory language does not match the record language. Translation memory source language is " . $tm->getSourceLanguage() . " but the page language is " . $pageWrapper->getLanguage() . '.'); } $proxyWriter->setTranslationMemory($tm); $proxyWriter->setMinTranslationStatus($this->translateMinStatus); $translatedContent = $proxyWriter->translateHtml($untranslatedContent, $translationStats, $this->logTranslationMisses); $this->translationStats = $translationStats; $page->setValues(array('last_translation_memory_applied' => date('Y-m-d H:i:s'), 'last_translation_memory_misses' => $translationStats['misses'], 'last_translation_memory_hits' => $translationStats['matches'])); // Let's record the strings in this page. $res = df_q("delete from webpage_strings where webpage_id='" . addslashes($page->val('webpage_id')) . "'"); if ($proxyWriter->lastStrings) { //print_r($proxyWriter->lastStrings);exit; $sqlpre = "insert into webpage_strings (webpage_id,string_id) values "; $sql = array(); $wpid = $page->val('webpage_id'); foreach ($proxyWriter->lastStrings as $str) { if (!trim($str)) { continue; } if (preg_match('/^[^\\w]+$/', trim($str))) { // This is to skip any strings that contain only // non-word characters(e.g. numbers) continue; } $encStr = TMTools::encode($str, $params); $strRec = XFTranslationMemory::addString($encStr, $tm->getSourceLanguage()); $sql[] = '(' . $wpid . ',' . $strRec->val('string_id') . ')'; } $sql = $sqlpre . implode(',', $sql); df_q($sql); } $translatedPage = SweteWebpage::loadById($page->val('webpage_id'), $this->site->getDestinationLanguage()); $translatedPage->getRecord()->setValue('webpage_content', $translatedContent); $res = $translatedPage->getRecord()->save(); if (PEAR::isError($res)) { throw new Exception(mysql_error(df_db())); } $lastApproved = $translatedPage->getLastVersionWithStatus(SweteWebpage::STATUS_APPROVED); if ($lastApproved and $lastApproved->val('webpage_content') == $translatedContent) { $page->setValue('webpage_status', SweteWebpage::STATUS_APPROVED); } else { if ($translationStats['matches'] > 0 and $translationStats['misses'] == 0) { // We have perfect matches in what we are supposed to be translating // We are either approving this page or we are marking it pending approval if ($translatedPage->getAutoApprove(true)) { $page->setValue('webpage_status', SweteWebpage::STATUS_APPROVED); $lastApproved = $translatedPage->setStatus(SweteWebpage::STATUS_APPROVED); } else { $page->setValue('webpage_status', SweteWebpage::STATUS_PENDING_APPROVAL); } } else { if ($translationStats['misses'] > 0) { $page->setValue('webpage_status', SweteWebpage::STATUS_CHANGED); } else { $page->setValue('webpage_status', null); } } } if ($this->logTranslationMisses and @$translationStats['log']) { //print_r($translationStats);exit; foreach ($translationStats['log'] as $str) { $tlogEntry = new Dataface_Record('translation_miss_log', array()); $nstr = TMTools::normalize($str); $estr = TMTools::encode($str, $junk); $hstr = md5($estr); $strRec = XFTranslationMemory::findString($estr, $this->site->getSourceLanguage()); if (!$strRec) { $strRec = XFTranslationMemory::addString($estr, $this->site->getSourceLanguage()); } $tlogEntry->setValues(array('string' => $str, 'normalized_string' => $nstr, 'encoded_string' => $estr, 'string_hash' => $hstr, 'date_inserted' => date('Y-m-d H:i:s'), 'webpage_id' => $page->val('webpage_id'), 'website_id' => $page->val('website_id'), 'source_language' => $this->site->getSourceLanguage(), 'destination_language' => $this->site->getDestinationLanguage(), 'translation_memory_id' => $tmid, 'string_id' => $strRec->val("string_id"))); if (isset($this->webpageRefreshLogId)) { $tlogEntry->setValue('webpage_refresh_log_id', $this->webpageRefreshLogId); } if ($this->saveTranslationLogRecord) { $res = $tlogEntry->save(); if (PEAR::isError($res)) { //throw new Exception($res->getMessage()); // This will throw an error if there is a duplicate... we don't care... we're not interested in duplicates } } $this->translationMissLogRecord = $tlogEntry; } } if ($this->savePage) { $res = $page->save(); if (PEAR::isError($res)) { throw new Exception($res->getMessage()); } } } } }
function field__properties($record) { $p = df_get_record('webpage_properties', array('webpage_id' => '=' . $record->val('webpage_id'))); if (!$p) { $p = new Dataface_Record('webpage_properties', array()); $p->setValue('webpage_id', $record->val('webpage_id')); $p->pouch['webpage'] = $record; $p->save(); } return $p; }
/** * Sends the reset email to a particular user. * * @param Dataface_Record $user The user record. * @return true on success * * @throws Exception code: self::$EX_NO_USERNAME_FOR_USER If username is blank * @throws Exception code: self::$EX_NO_EMAIL_COLUMN_FOUND No email column was found in the users table. * @throws Exception code: self::$EX_NO_USERS_FOUND_WITH_EMAIL If the user record doesn't have an email address. */ public function send_reset_email_for_user(Dataface_Record $user) { $app = Dataface_Application::getInstance(); $auth = Dataface_AuthenticationTool::getInstance(); $emailCol = $auth->getEmailColumn(); $usernameCol = $auth->usernameColumn; if (!$emailCol) { throw new Exception(df_translate('actions.forgot_password.no_email_column_found', "No Email Column found in the users table. Please specify one using the email_column directive in the [_auth] section of the conf.ini file."), self::$EX_NO_EMAIL_COLUMN_FOUND); } if (!$usernameCol) { throw new Exception(df_translate('actions.forgot_password.no_username_column_found', "No username column found in the users table. Please specify one using the username_column directive in the [_auth] section of the conf.ini file."), self::$EX_NO_USERNAME_COLUMN_FOUND); } if (!$user) { throw new Exception(df_translate('actions.forgot_password.null_user', "Cannot send email for null user"), self::$EX_NO_USERS_FOUND_WITH_EMAIL); } $username = $user->val($usernameCol); if (!$username) { throw new Exception(df_translate('actions.forgot_password.user_without_name', "Cannot reset password for user without a username"), self::$EX_NO_USERNAME_FOR_USER); } $email = $user->val($emailCol); if (!$email) { throw new Exception(df_translate('actions.forgot_password.user_without_email', "User has not email address on file"), $EX_NO_EMAIL_FOR_USER); } $ip = null; $val = ip2long($_SERVER['REMOTE_ADDR']); if ($val !== false) { $ip = sprintf('%u', $val); } else { $ip = 0; //If IP is empty MySQL throws Incorrect Integer value on insert } $expire_seconds = 600; if (@$app->_conf['reset_password_expiry']) { $expire_seconds = intval($app->_conf['reset_password_expiry']); } // Insert the entry $this->create_reset_password_table(); $table = self::$TABLE_RESET_PASSWORD; $sql = "insert into `{$table}`\n\t\t\t(`request_uuid`, `username`, `request_ip`, `date_created`, `expires`)\n\t\t\tvalues\n\t\t\t(UUID(),'" . addslashes($username) . "','" . addslashes($ip) . "', NOW(), " . (time() + $expire_seconds) . ")"; $res = xf_db_query($sql, df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $id = xf_db_insert_id(df_db()); $res = xf_db_query("select * from `{$table}` where request_id='" . addslashes($id) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $row = xf_db_fetch_assoc($res); if (!$row) { throw new Exception(df_translate('actions.forgot_password.failed_fetch_password_row', "Failed to fetch reset password request row from database after it has been inserted. This should never happen ... must be a bug")); } $uuid = $row['request_uuid']; if (!$uuid) { throw new Exception(df_translate('actions.forgot_password.blank_uuid_for_reset_request', "Blank uuid for the reset request. This should never happen. Must be a bug.")); } $url = df_absolute_url(DATAFACE_SITE_HREF . '?-action=forgot_password&--uuid=' . $uuid); $site_url = df_absolute_url(DATAFACE_SITE_URL); $msg = df_translate('actions.forgot_password.reset_password_request_email_body', <<<END You have requested to reset the password for the user '{$username}'. Please go to the URL below in order to proceed with resetting your password: <{$url}> If you did not make this request, please disregard this email. END , array('username' => $username, 'url' => $url)); $subject = df_translate('actions.forgot_password.password_reset', "Password Reset"); $del = $app->getDelegate(); $info = array(); if (isset($del) and method_exists($del, 'getResetPasswordEmailInfo')) { $info = $del->getResetPasswordEmailInfo($user, $url); } if (isset($info['subject'])) { $subject = $info['subject']; } if (isset($info['message'])) { $msg = $info['message']; } $parameters = null; if (isset($info['parameters'])) { $parameters = $info['parameters']; } $site_title = $app->getSiteTitle(); $support_email = $_SERVER['SERVER_ADMIN']; if (isset($app->_conf['admin_email'])) { $support_email = $app->_conf['admin_email']; } if (isset($app->_conf['support_email'])) { $support_email = $app->_conf['support_email']; } $from_email = $support_email; if (strpos($support_email, '>') === false) { $from_email = $site_title . ' <' . $support_email . '>'; } $headers = 'From: ' . $from_email . "\r\nReply-to: " . $from_email . "\r\nContent-type: text/plain; charset=" . $app->_conf['oe']; if (isset($info['headers'])) { $headers = $info['headers']; } //echo "Subject: $subject \nEmail: $email \n$msg \nHeaders: $headers";exit; if (@$app->_conf['_mail']['func']) { $func = $app->_conf['_mail']['func']; } else { $func = 'mail'; } $res = $func($email, $subject, $msg, $headers, $parameters); if (!$res) { throw new Exception(df_translate('actions.forgot_password.failed_send_activation', "Failed to send activation email. Please try again later."), DATAFACE_E_ERROR); } else { //echo "Successfully sent mail to $email";exit; return true; } }
/** * 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; }
function addExistingRelatedRecord(&$relatedRecord) { $record =& $relatedRecord->_record; $relationshipName =& $relatedRecord->_relationshipName; $values = $relatedRecord->getAbsoluteValues(true); if (!is_a($record, 'Dataface_Record')) { throw new Exception("In Dataface_QueryBuilder::addExistingRelatedRecord() expected first argument to be of type 'Dataface_Record' but received '" . get_class($record) . "'.\n<br>", E_USER_ERROR); } if (!is_array($values)) { throw new Exception("In Dataface_QueryBuilder::addExistingRelatedRecord() expected third argument to be an array but received a scalar.", E_USER_ERROR); } $relationship =& $record->_table->getRelationship($relationshipName); $foreignKeys = $relationship->getForeignKeyValues(); $foreignKeys_withValues = $relatedRecord->getForeignKeyValues(); if (count($this->errors) > 0) { $error = array_pop($this->errors); $error->addUserInfo("Error getting foreign key values for relationship '{$relationship_name}'"); throw new Exception($error->toString()); } $sql = array(); foreach ($foreignKeys as $table => $cols) { $skip = true; foreach ($cols as $field_name => $field_value) { if ($field_value != "__" . $table . "__auto_increment__") { $skip = false; break; } } if ($skip) { continue; } $cols = $foreignKeys_withValues[$table]; if (isset($recordObj)) { unset($recordObj); } $recordObj = new Dataface_Record($table, $cols); $recordVals =& $recordObj->vals(); if (isset($recordVals[$recordObj->_table->getAutoIncrementField()])) { // We don't want the auto-increment field to be inserted - though it may // have a placeholder value. $recordObj->setValue($recordObj->_table->getAutoIncrementField(), null); } $qb = new Dataface_QueryBuilder($table); $sql[$table] = $qb->insert($recordObj); /* $skip = true; // indicator to say whether or not to skip this table // we skip the table if it contains an unresolved autoincrement value foreach ($cols as $field_name=>$field_value){ if ( $field_value != "__".$table."__auto_increment__" ) { $skip = false; break; } } if ( $skip == true ) continue; $cols = $foreignKeys_withValues[$table]; $query = "INSERT INTO `$table`"; $colnames = ""; $colvals = ""; foreach ( $cols as $colname=>$colval){ $colnames .= $colname.','; $colvals .= "'".addslashes($colval)."',"; } $colnames = substr($colnames, 0, strlen($colnames)-1); $colvals = substr($colvals, 0, strlen($colvals)-1); $query .= " ($colnames) VALUES ($colvals)"; $sql[$table] = $query; */ } return $sql; }
function normalized_translation_value__csvValue(Dataface_Record $record) { return $record->val('normalized_translation_value'); }
function handle(&$params) { $app = Dataface_Application::getInstance(); if (!isset($_GET['code'])) { // We need this parameter or we can do nothing. return PEAR::raiseError(df_translate('actions.activate.MESSAGE_MISSING_CODE_PARAMETER', 'The code parameter is missing from your request. Validation cannot take place. Please check your url and try again.'), DATAFACE_E_ERROR); } // Step 0: Find out what the redirect URL will be // We accept --redirect markers to specify which page to redirect // to after we're done. This will usually be the page that the // user was on before they went to the login page. if (isset($_SESSION['--redirect'])) { $url = $_SESSION['--redirect']; } else { if (isset($_SESSION['-redirect'])) { $url = $_SESSION['-redirect']; } else { if (isset($_REQUEST['--redirect'])) { $url = $_REQUEST['--redirect']; } else { if (isset($_REQUEST['-redirect'])) { $url = $_REQUEST['-redirect']; } else { $url = $app->url('-action=' . $app->_conf['default_action']); } } } } if (strpos($url, '?') === false) { $url .= '?'; } // Step 1: Delete all registrations older than time limit $time_limit = 24 * 60 * 60; // 1 day if (isset($params['time_limit'])) { $time_limit = intval($params['time_limit']); } $res = xf_db_query("delete from dataface__registrations \n\t\t\t\twhere registration_date < '" . addslashes(date('Y-m-d H:i:s', time() - $time_limit)) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to delete registrations due to an SQL error. See error log for details.", E_USER_ERROR); } // Step 2: Load the specified registration information $res = xf_db_query("select registration_data from dataface__registrations\n\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to load registration information due to an SQL error. See error log for details.", E_USER_ERROR); } if (xf_db_num_rows($res) == 0) { // We didn't find any records matching the prescribed code, so // we redirect the user to their desired page and inform them // that the registration didn't work. $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_NOT_FOUND', 'No registration information could be found to match this code. Please try registering again.'); $app->redirect($url . '&--msg=' . urlencode($msg)); } // Step 3: Check to make sure that there are no other users with the // same name. list($raw_data) = xf_db_fetch_row($res); $values = unserialize($raw_data); $appdel = $app->getDelegate(); if (isset($appdel) and method_exists($appdel, 'validateRegistrationForm')) { $res = $appdel->validateRegistrationForm($values); if (PEAR::isError($res)) { $msg = $res->getMessage(); $app->redirect($url . '&--msg=' . urlencode($msg)); } } else { $res = xf_db_query("select count(*) from \n\t\t\t\t`" . str_replace('`', '', $app->_conf['_auth']['users_table']) . "` \n\t\t\t\twhere `" . str_replace('`', '', $app->_conf['_auth']['username_column']) . "` = '" . addslashes($values[$app->_conf['_auth']['username_column']]) . "'\n\t\t\t\t", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to find user records due to an SQL error. See error log for details.", E_USER_ERROR); } list($num) = xf_db_fetch_row($res); if ($num > 0) { $msg = df_translate('actions.activate.MESSAGE_DUPLICATE_USER', 'Registration failed because a user already exists by that name. Try registering again with a different name.'); $app->redirect($url . '&--msg=' . urlencode($msg)); } } // Step 4: Save the registration data and log the user in. $record = new Dataface_Record($app->_conf['_auth']['users_table'], array()); $record->setValues($values); $res = $record->save(); if (PEAR::isError($res)) { $app->redirect($url . '&--msg=' . urlencode($res->getMessage())); } else { $res = xf_db_query("delete from dataface__registrations\n\t\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to clean up old registrations due to an SQL error. See error log for details.", E_USER_ERROR); } $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_COMPLETE', 'Registration complete. You are now logged in.'); $_SESSION['UserName'] = $record->strval($app->_conf['_auth']['username_column']); import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_activate', array('record' => $record)); $app->redirect($url . '&--msg=' . urlencode($msg)); } }
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); } } } }
/** * Returns a join record for the give table. A join record is one that contains * auxiliary data for the current record. It is specified by the [__join__] * section of the fields.ini file or the __join__() method of the delegate * class. It is much like a one-to-one relationship. The key difference * between a join record and a related record is that a join record * is assumed to be one-to-one, and an extra tab is added to the edit form * to edit a join record. * * @param string $tablename The name of the table from which the join record * should be drawn. * @param boolean $nullIfNotFound If set, then this will return null if no join * record yet exists in the database. Added in Xataface 2.0 * * @returns Dataface_Record Join record from the specified join table or * a new record with the correct primary key values if none exists. * * @returns PEAR_Error If the specified table in incompatible. * */ function getJoinRecord($tablename, $nullIfNotFound = false) { $table =& Dataface_Table::loadTable($tablename); $query = $this->getJoinKeys($tablename); foreach ($query as $key => $val) { $query[$key] = '=' . $val; } $record = df_get_record($tablename, $query); if (!$record) { if ($nullIfNotFound) { return null; } // No record was found, so we create a new one. $record = new Dataface_Record($tablename, array()); foreach ($query as $key => $value) { $record->setValue($key, substr($value, 1)); } } return $record; }
/** * The early versions of the Dataface QueryTranslation extension stored even the default language * translations in a translation table. This is not necessary, and even undesired when you consider * that the default language should be a fall-back point for records that do not contain the proper * translation. This method copies the translation data from the translation table of a particular * language into the main table. Use this with caution as it will overwrite data from the underlying * table. * @param string $newDefault The 2-digit language code for the new default language. */ function migrateDefaultLanguage($newDefault, $tables = null) { import('Dataface/Utilities.php'); import('Dataface/IO.php'); $app = Dataface_Application::getInstance(); $no_fallback = @$app->_conf['default_language_no_fallback']; // Whether or not the application is currently set to disable fallback // to default language. $tables = $this->getMigratableTables(); $log = array(); foreach ($tables as $tablename) { $table = Dataface_Table::loadTable($tablename); $t_tablename = $tablename . '_' . $app->_conf['default_language']; if (!$table || PEAR::isError($table)) { continue; } $res = xf_db_query("create table `{$tablename}_bu_" . time() . "` select * from `{$tablename}`", $app->db()); $sql = "select `" . join('`,`', array_keys($table->keys())) . "` from `" . $tablename . "`"; $res2 = xf_db_query($sql, $app->db()); $io = new Dataface_IO($tablename); $io->lang = $newDefault; while ($rec = xf_db_fetch_assoc($res2)) { //foreach (array_keys($rec) as $colkey){ // $rec[$colkey] = '='.$rec[$colkey]; //} $app->_conf['default_language_no_fallback'] = 1; $record = df_get_record($tablename, $rec, $io); //print_r($record->strvals()); $app->_conf['default_language_no_fallback'] = 0; $record2 = new Dataface_Record($tablename, array()); $record2->setValues($record->vals()); $r = $io->write($record2); if (PEAR::isError($r)) { $log[$tablename] = "Failed to migrate data from table '{$t_tablename}' to '{$tablename}': " . $r->getMessage() . "'"; } else { $log[$tablename] = "Successfully migrated data from table '{$t_tablename}' to '{$tablename}'."; } unset($record); } xf_db_free_result($res2); $res = xf_db_query("create table `{$t_tablename}_bu_" . time() . "` select * from `{$t_tablename}`", $app->db()); $res = xf_db_query("truncate `{$t_tablename}`", $app->db()); unset($io); unset($table); } return $log; $app->_conf['default_language_no_fallback'] = $no_fallback; }
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; }
/** * Returns a record or record value given it's unique URI. * @param string $uri The URI of the data we wish to retrieve. * The URI must be of one of the following forms: * tablename?key1=val1&keyn=valn#fieldname * tablename?key1=val1&keyn=valn * tablename/relationshipname?key1=val1&keyn=valn&relationshipname::relatedkey=relatedval#fieldname * tablename/relationshipname?key1=val1&keyn=valn&relationshipname::relatedkey=relatedval * * Where url encoding is used as in normal HTTP urls. If a field is specified (after the '#') * * @param string $filter The name of a filter to pass the data through. This * is only applicable when a field name is specified. Possible filters * include: * strval - Returns the string value of the field. (aka stringValue, getValueAsString) * display - Returns the display value of the field. (This substitutes valuelist values) * htmlValue - Returns the html value of the field. * preview - Returns the preview value of the field (usually this limits * the length of the output and strips any HTML. * * @returns mixed Either a Dataface_Record object, a Dataface_RelatedRecord object * of a value as stored in the object. The output depends on * the input. If it receives invalid input, it will return a PEAR_Error * object. * * Example usage: * * <code> * // Get record from Users table with UserID=10 * $user =& Dataface_IO::getByID('Users?UserID=10'); * // Dataface_Record object * * // get birthdate of user with UserID=10 * $birthdate =& Dataface_IO::getByID('Users?UserID=10#birthdate'); * // array('year'=>'1978','month'=>'12','day'=>'27', ...) * * // get related record from jobs relationship of user with UserID=10 * // where the jobtitle is "cook" * $job =& Dataface_IO::getByID('Users?UserID=10&jobs::jobtitle=cook"); * // Dataface_RelatedRecord object * * // Get the employers name of the cook job * $employername = Dataface_IO::getByID('Users?UserID=10&jobs::jobtitle=cook#employername'); * // String * * // Add filter, so we get the HTML value of the bio field rather than just * // the raw value. * $bio = Dataface_IO::getByID('Users?UserID=10#bio', 'htmlValue'); * * </code> */ static function &getByID($uri, $filter = null) { if (strpos($uri, '?') === false) { return PEAR::raiseError("Invalid record id: " . $uri); } $uri_parts = df_parse_uri($uri); if (PEAR::isError($uri_parts)) { return $uri_parts; } if (!isset($uri_parts['relationship'])) { // This is just requesting a normal record. // Check to see if this is to be a new record or an existing record if (@$uri_parts['action'] and $uri_parts['action'] == 'new') { $record = new Dataface_Record($uri_parts['table'], array()); $record->setValues($uri_parts['query']); return $record; } foreach ($uri_parts['query'] as $ukey => $uval) { if ($uval and $uval[0] != '=') { $uval = '=' . $uval; } $uri_parts['query'][$ukey] = $uval; } // At this point we are sure that this is requesting an existing record $record =& df_get_record($uri_parts['table'], $uri_parts['query']); if (isset($uri_parts['field'])) { if (isset($filter) and method_exists($record, $filter)) { $val =& $record->{$filter}($uri_parts['field']); return $val; } else { $val =& $record->val($uri_parts['field']); return $val; } } else { return $record; } } else { // This is requesting a related record. $record =& df_get_record($uri_parts['table'], $uri_parts['query']); if (!$record) { return PEAR::raiseError("Could not find any records matching the query"); } // Check to see if we are creating a new record if (@$uri_parts['action'] and $uri_parts['action'] == 'new') { $related_record = new Dataface_RelatedRecord($record, $uri_parts['relationship']); $related_record->setValues($uri_parts['query']); return $related_record; } // At this point we can be sure that we are requesting an existing record. $related_records =& $record->getRelatedRecordObjects($uri_parts['relationship'], 0, 1, $uri_parts['related_where']); if (count($related_records) == 0) { return PEAR::raiseError("Could not find any related records matching the query: " . $uri_parts['related_where']); } if (isset($uri_parts['field'])) { if (isset($filter) and method_exists($related_records[0], $filter)) { $val =& $related_records[0]->{$filter}($uri_parts['field']); return $val; } else { $val =& $related_records[0]->val($uri_parts['field']); return $val; } } else { return $related_records[0]; } } }
function test_num_related_records() { $record = new Dataface_Record('Profiles', array('id' => 10)); $this->assertEquals(2, $record->numRelatedRecords('addresses')); }
/** * Builds the form. */ function _build() { $app =& Dataface_Application::getInstance(); $mainQuery =& $app->getQuery(); if ($this->_built) { return true; } $r =& $this->_relationship->_schema; $t =& $this->_parentTable; $fkCols =& $this->_relatedRecord->getForeignKeyValues(); if (PEAR::isError($fkCols)) { $fkCols->addUserInfo(df_translate('scripts.Dataface.ExistingRelatedRecordForm._build.ERROR_GETTING_FOREIGN_KEY_COLS', "Error getting foreign key columns while building Related Record Form on line " . __LINE__ . " of file " . __FILE__, array('line' => __LINE__, 'file' => __FILE__))); echo $fkCols->toString(); return $fkCols; } $factory = new HTML_QuickForm('factory'); $fkeys = $this->_relationship->getForeignKeyValues(); // Values of foreign keys (fields involved in where and join clauses) $table = $this->_relationship->getDomainTable(); // The name of the table holding related records. if (!isset($table) || PEAR::isError($table)) { $table = $r['selected_tables'][0]; } // It is possible for getDomainTable() to return an error if no foreign // keys are specified. In this case, we will just use the table associated // with the first selected column. $relatedTableObject =& Dataface_Table::loadTable($table); // The Dataface_Table object for the related records. $tkey_names = array_keys($relatedTableObject->keys()); // The names of the key fields for the related record. // The main table that holds the related records $options = $this->_relationship->getAddableValues($this->_record); if (!$options) { return PEAR::raiseError('There are no records that can be added to this relationship.', DATAFACE_E_NOTICE); } $select =& $this->addElement('select', 'select', df_translate('scripts.Dataface.ExistingRelatedRecordForm._build.LABEL_SELECT', 'Select'), $options, array('class' => 'record_selector')); $permissions = $this->_record->getPermissions(array('relationship' => $this->_relationshipName)); if (isset($permissions['add existing related record']) and $permissions['add existing related record']) { // We are allowed to add a new related record, so we will create a mask to allow this. $mask = array('edit' => 1); } // Now we still need to add fields so that the user can specify information about the relationship. // ie: some fields of the join table may be descriptive. foreach (array_keys($fkCols) as $fkTable) { if ($fkTable == $table) { // This table is the main domain table... we don't want to input any data for this table. continue; } $qfFactory = new Dataface_QuickForm($fkTable, $this->_parentTable->db); $tableRef =& Dataface_Table::loadTable($fkTable); $recordRef = new Dataface_Record($fkTable, array()); $recordRef->setValues($fkCols[$fkTable]); $currFieldnames = array_keys($tableRef->fields()); foreach ($currFieldnames as $currFieldname) { if (isset($fkCols[$fkTable][$currFieldname])) { // this value is bound, and should not be changed. continue; } $field =& $tableRef->getField($currFieldname); //$el = $qfFactory->_buildWidget($field, array_merge($mask, $this->_record->getPermissions(array('field'=>$this->_relationshipName.'.'.$currFieldname)))); $el = $qfFactory->_buildWidget($field, $recordRef->getPermissions(array('field' => $currFieldname, 'recordmask' => $mask))); // To Do: Make it work with groups $this->addElement($el); /* * * If there are any validation options set for the field, we must add these rules to the quickform * element. * */ $validators = $field['validators']; foreach ($validators as $vname => $validator) { /* * * $validator['arg'] would be specified in the INI file. * Example ini file listing: * ------------------------- * [FirstName] * widget:label = First name * widget:description = Enter your first name * validators:regex = "/[0-9a-zA-Z/" * * This would result in $validator['arg'] = "/[0-9a-zA-Z/" in this section * and $vname == "regex". Hence it would mean that a regular expression validator * is being placed on this field so that only Alphanumeric characters are accepted. * Please see documentation for HTML_QuickForm PEAR class for more information * about QuickForm validators. * */ $this->addRule($field['name'], $validator['message'], $vname, $validator['arg'], 'client'); } unset($field); } unset($tableRef); unset($qfFactory); } $keyEls = array(); $keyDefaults = array(); foreach (array_keys($this->_parentTable->keys()) as $key) { $keyEls[] = $factory->addElement('hidden', $key); } $this->addGroup($keyEls, '__keys__'); $keyvals = array(); foreach (array_keys($this->_parentTable->keys()) as $key) { $keyvals[$key] = $this->_record->getValueAsString($key); } $this->setDefaults(array('__keys__' => $keyvals)); $this->addElement('hidden', '-table'); $this->addElement('hidden', '-relationship'); $this->addElement('hidden', '-action'); $this->addElement('submit', 'Save', 'Save'); $this->setDefaults(array('-table' => $this->_parentTable->tablename, '-relationship' => $this->_relationshipName, '-action' => "existing_related_record")); // Set the return page $returnPage = @$_SERVER['HTTP_REFERER']; if (isset($mainQuery['-redirect'])) { $returnPage = $mainQuery['-redirect']; } else { if (isset($mainQuery['--redirect'])) { $returnPage = $mainQuery['--redirect']; } } if (!$returnPage) { $returnPage = $app->url('-action=related_records_list&-relationship=' . $this->_relationshipname); } $this->addElement('hidden', '--redirect'); $this->setDefaults(array('--redirect' => $returnPage)); /* * There may be some default values specified in the relationship schema. */ if (isset($r['existing'])) { $this->setDefaults($r['existing']); } $this->_built = true; }
/** * @brief Wrapper around getContextMask() to get the permissions * for a record through the context of a portal. * @returns array($perm:string => $val:boolean) * @since 2.0 */ function getPortalFieldPermissions(Dataface_Record $record, $params = array()) { return $this->getContextMask($record->getId(), @$params['field']); }
function handle($params) { $app = Dataface_Application::getInstance(); if (!$_POST) { throw new Exception("Commit requires post"); } $data = @$_POST['--data']; if (!$data) { throw new Exception("No data provided"); } $data = json_decode($data, true); $updates = array(); $inserts = array(); $deletes = array(); if (isset($data['inserts'])) { $inserts =& $data['inserts']; } if (isset($data['updates'])) { $updates =& $data['updates']; } if (isset($data['deletes'])) { $deletes =& $data['deletes']; } $numFailures = 0; $numSuccesses = 0; $deleteResponses = array(); // Let's do the deletes first foreach ($deletes as $deleteInfo) { $response = array(); $deleteResponses[] =& $response; $record = df_get_record_by_id($deleteInfo['id']); if (!$record) { $response['message'] = 'Record ' . $deleteInfo['id'] . ' could not be found.'; $response['code'] = 404; $numFailures++; } else { $res = $response->delete(true); if (PEAR::isError($res)) { $response['message'] = $res->getMessage(); $response['code'] = $res->getCode(); $numFailures++; } else { $response['message'] = 'Deleted record ' . $deleteInfo['id'] . '.'; $response['code'] = 200; $response['recordId'] = $deleteInfo['id']; $numSuccesses++; } } } $insertResponses = array(); foreach ($inserts as $insertInfo) { $response = array(); $insertResponses[] =& $response; $record = new Dataface_Record($insertInfo['table'], array()); $record->setValues($insertInfo['data']); $res = $record->save(null, true); if (PEAR::isError($res)) { $response['message'] = $res->getMessage(); $response['code'] = $res->getCode(); $numFailures++; } else { $response['message'] = 'Inserted record'; $response['code'] = $res->getCode(); $response['recordId'] = $record->getId(); $response['version'] = $record->getVersion(); $numSuccesses++; } } $updateResponses = array(); foreach ($updates as $updateInfo) { $response = array(); $insertResponses[] =& $response; $record = df_get_record_by_id($updateInfo['id']); if (!$record) { $response['message'] = 'Record ' . $updateInfo['id'] . ' could not be found.'; $response['code'] = 404; $numFailures++; } else { $record->setValues($updateInfo['data']); $res = $record->save(null, true); if (PEAR::isError($res)) { $response['message'] = $res->getMessage(); $response['code'] = $res->getCode(); $numFailures++; } else { $response['message'] = 'Updated record'; $response['code'] = 200; $response['recordId'] = $record->getId(); $response['version'] = $record->getVersion(); $numSuccesses++; } } } header('Content-type: text/json; charset="' . $app->_conf['oe'] . '"'); $out = array('code' => ($numFailures == 0 and $numSuccesses > 0) ? 200 : $numSuccesses > 0 ? 201 : 202, 'message' => $numSuccesses . ' successes. ' . $numFailures . ' failures.', 'numSuccesses' => $numSuccesses, 'numFailures' => $numFailures, 'responses' => array('updates' => $updateResponses, 'inserts' => $insertResponses, 'deletes' => $deleteResponses)); echo json_encode($out); }
function getGroupRecordRoles(Dataface_Record $record = null) { if (!isset($record)) { return null; } return $record->getGroupRoles(); }
public function addMessage($content) { $note = new Dataface_Record('job_notes', array()); $note->setValues(array('job_id' => $this->getJob()->getRecord()->val('job_id'), 'note_content' => $content, 'date_posted' => date('Y-m-d H:i:s'), 'posted_by' => $this->getUsername())); $res = $note->save(); if (PEAR::isError($res)) { throw new Exception($res->getMessage(), $res->getCode()); } return $note; }