Exemplo n.º 1
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query = $app->getQuery();
     $query['-skip'] = 0;
     $query['-limit'] = 999999999;
     $at = Dataface_ActionTool::getInstance();
     $emailAction = $at->getAction(array('name' => 'email'));
     if (!isset($emailAction) or !isset($emailAction['email_column'])) {
         return PEAR::raiseError("No email column specified");
     }
     $col = $emailAction['email_column'];
     $qb = new Dataface_QueryBuilder($query['-table'], $query);
     $sql = "select `" . $col . "` " . $qb->_from() . $qb->_secure($qb->_where());
     $res = mysql_query($sql, df_db());
     if (!$res) {
         trigger_error(mysql_error(df_db()), E_USER_ERROR);
     }
     $addresses = array();
     while ($row = mysql_fetch_row($res)) {
         $addresses[] = $row[0];
     }
     @mysql_free_result($res);
     header("Content-type: text/plain");
     echo implode(', ', $addresses);
     exit;
 }
Exemplo n.º 2
0
 function block__before_result_list_content()
 {
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     $builder = new Dataface_QueryBuilder($query['-table'], $query);
     $sql = 'select sum(num_words) ' . $builder->_from() . $builder->_where();
     $res = df_q($sql);
     $row = mysql_fetch_row($res);
     @mysql_free_result($res);
     $app->addHeadContent('<style type="text/css">#total-words-found {float:right;width: 200px;}</style>');
     echo '<div id="total-words-found">Total Words: ' . $row[0] . '</div>';
     Dataface_JavascriptTool::getInstance()->import('swete/actions/batch_google_translate.js');
 }
Exemplo n.º 3
0
 /**
  * Creates an import table for this table.  An import table is an empty clone
  * of this table.  It serves as an intermediate step  towards importing data into
  * the main table.
  */
 function createImportTable()
 {
     /*
      * It is a good idea to clean the import tables before we create them.
      * That way they don't get cluttered
      */
     $this->cleanImportTables();
     $rand = rand(10000, 999999);
     $name = $this->tablename . '__import_' . strval(time()) . '_' . strval($rand);
     $qb = new Dataface_QueryBuilder($this->tablename);
     $res = mysql_query("CREATE TABLE `{$name}` SELECT * " . $qb->_from() . " LIMIT 0", $this->db);
     if (!$res) {
         trigger_error("Failed to create import table `{$name}` because a mysql error occurred: " . mysql_error($this->db) . "\n" . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     return $name;
 }
Exemplo n.º 4
0
 /**
  * Builds an SQL query to copy the given record.  This honours permissions
  * and will only copy columns for which 'view' access is available in the
  * source record and 'edit' access is available in the destination record.
  *
  * Individual column failures (due to permissions) are recorded in the 
  * $warnings variable of this class.  It will be an array of Dataface_Error
  * objects.
  *
  * @param Dataface_Record $record The record being copied.
  * @param array $valls Values that should be placed in the copied version.
  * @param boolean $force If true this will perform the copy despite individual
  *			column warnings.
  * @returns string The SQL query to copy the record.
  */
 function buildCopyQuery($record, $vals = array(), $force = true)
 {
     $dummy = new Dataface_Record($record->_table->tablename, $vals);
     if (!$record->checkPermission('view') || !$dummy->checkPermission('edit')) {
         return Dataface_Error::permissionDenied("Failed to copy record '" . $record->getTitle() . "' because of insufficient permissions.");
     }
     $copy_fields = array_keys($record->_table->fields());
     // Go through each field and see if we have copy permission.
     // Copy permission is two-fold: 1- make sure the source is viewable
     //								2- make sure the destination is editable.
     $failed = false;
     foreach ($copy_fields as $key => $fieldname) {
         if (!$record->checkPermission('view', array('field' => $fieldname)) || !$dummy->checkPermission('edit', array('field' => $fieldname))) {
             $this->warnings[] = Dataface_Error::permissionDenied("The field '{$fieldname}' could not be copied for record '" . $record->getTitle() . "' because of insufficient permissions.");
             unset($copy_fields[$key]);
             $failed = true;
         }
     }
     // If we are not forcing completion, any failures will result in cancellation
     // of the copy.
     if (!$force and $failed) {
         return Dataface_Error::permissionDenied("Failed to copy the record '" . $record->getTitle() . "' due to insufficient permissions on one or more of the columns.");
     }
     // We don't copy auto increment fields.
     $auto_inc_field = $record->_table->getAutoIncrementField();
     if ($auto_inc_field) {
         $key = array_search($auto_inc_field, $copy_fields);
         if ($key !== false) {
             unset($copy_fields[$key]);
         }
     }
     // Now we can build the query.
     $sql = array();
     $sql[] = "insert into `" . $record->_table->tablename . "`";
     $sql[] = "(`" . implode('`,`', $copy_fields) . "`)";
     $copy_values = array();
     foreach ($copy_fields as $key => $val) {
         if (isset($vals[$val])) {
             $copy_values[$key] = "'" . addslashes($dummy->getSerializedValue($val)) . "' as `{$val}`";
         } else {
             $copy_values[$key] = "`" . $val . "`";
         }
     }
     $sql[] = "select " . implode(', ', $copy_values) . " from `" . $record->_table->tablename . "`";
     $qb = new Dataface_QueryBuilder($record->_table->tablename);
     $keys = array_keys($record->_table->keys());
     $q = array();
     foreach ($keys as $key_fieldname) {
         $q[$key_fieldname] = $record->strval($key_fieldname);
     }
     $where = $qb->_where($q);
     $where = $qb->_secure($where);
     $sql[] = $where;
     return implode(' ', $sql);
 }
Exemplo n.º 5
0
    function getResultFilters()
    {
        ob_start();
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        echo '<div class="resultlist-filters">
		<h3>' . df_translate('scripts.Dataface_ResultList.MESSAGE_FILTER_RESULTS', 'Filter Results') . ':</h3>
		<script language="javascript"><!--
		
		function resultlist__updateFilters(col,select){
			var currentURL = "' . $app->url('') . '";
			var currentParts = currentURL.split("?");
			var currentQuery = "?"+currentParts[1];
			var value = select.options[select.selectedIndex].value;
			var regex = new RegExp(\'([?&])\'+col+\'={1,2}[^&]*\');
			if ( currentQuery.match(regex) ){
				if ( value ){
					prefix = "=";
				} else {
					prefix = "";
				}
				currentQuery = currentQuery.replace(regex, \'$1\'+col+\'=\'+prefix+encodeURIComponent(value));
			} else {
				currentQuery += \'&\'+col+\'==\'+encodeURIComponent(value);
			}
			window.location=currentParts[0]+currentQuery;
		}
		//--></script>
		<ul>';
        $qb = new Dataface_QueryBuilder($this->_table->tablename, $query);
        foreach ($this->_filterCols as $col) {
            $field =& $this->_table->getField($col);
            unset($vocab);
            if (isset($field['vocabulary'])) {
                $vocab =& $this->_table->getValuelist($field['vocabulary']);
            } else {
                $vocab = null;
            }
            echo '<li> ' . htmlspecialchars($field['widget']['label']) . ' <select onchange="resultlist__updateFilters(\'' . addslashes($col) . '\', this);"><option value="">' . df_translate('scripts.GLOBAL.LABEL_ALL', 'All') . '</option>';
            $res = df_query("select `{$col}`, count(*) as `num` " . $qb->_from() . " " . $qb->_secure($qb->_where(array($col => null))) . " group by `{$col}`", null, true);
            if (!$res and !is_array($res)) {
                trigger_error(mysql_error(df_db()), E_USER_ERROR);
            }
            if (@$query[$col] and $query[$col][0] == '=') {
                $queryColVal = substr($query[$col], 1);
            } else {
                $queryColVal = @$query[$col];
            }
            //while ( $row = mysql_fetch_assoc($res) ){
            foreach ($res as $row) {
                if (isset($vocab) and isset($vocab[$row[$col]])) {
                    $val = $vocab[$row[$col]];
                } else {
                    $val = $row[$col];
                }
                if ($queryColVal == $row[$col]) {
                    $selected = ' selected';
                } else {
                    $selected = '';
                }
                echo '<option value="' . htmlspecialchars($row[$col]) . '"' . $selected . '>' . htmlspecialchars($val) . ' (' . $row['num'] . ')</option>';
            }
            //@mysql_free_result($res);
            echo '</select></li>';
        }
        echo '</ul></div>';
        $out = ob_get_contents();
        ob_end_clean();
        return $out;
    }
Exemplo n.º 6
0
 function found()
 {
     if (!isset($this->_data['found'])) {
         $cache =& $this->staticCache();
         $builder = new Dataface_QueryBuilder($this->_tablename, $this->_query);
         $sql = $builder->select_num_rows();
         if (isset($cache[$sql])) {
             $this->_data['found'] = $cache[$sql];
         } else {
             $res = $this->dbObj->query($sql, $this->_db, null, true);
             $this->_data['found'] = array_shift($res[0]);
             $cache[$sql] = $this->_data['found'];
         }
     }
     return $this->_data['found'];
 }
Exemplo n.º 7
0
 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;
 }
Exemplo n.º 8
0
 /**
  * Returns an array of history ids of history records that match the 
  * given query.
  */
 function findMatchingSnapshots($record, $query, $idsOnly = true)
 {
     $app =& Dataface_Application::getInstance();
     $htablename = $record->_table->tablename . '__history';
     if (!Dataface_Table::tableExists($htablename)) {
         return array();
     }
     $keys = $record->strvals(array_keys($record->_table->keys()));
     foreach ($keys as $key => $val) {
         $query[$key] = '=' . $val;
     }
     if ($idsOnly) {
         $qbuilder = new Dataface_QueryBuilder($htablename, $query);
         $sql = $qbuilder->select(array('history__id'), $query);
         $res = xf_db_query($sql, df_db());
         $ids = array();
         while ($row = xf_db_fetch_row($res)) {
             $ids[] = $row[0];
         }
         @xf_db_free_result($res);
         return $ids;
     } else {
         return df_get_records_array($htablename, $query);
     }
 }
Exemplo n.º 9
0
 /**
  * @brief Creates an import table for this table.  An import table is an empty clone
  * of this table.  It serves as an intermediate step  towards importing data into
  * the main table.
  * @return string The name of the created table.
  * @see getImportTables()
  * 
  */
 function createImportTable()
 {
     import('Dataface/QueryBuilder.php');
     /*
      * It is a good idea to clean the import tables before we create them.
      * That way they don't get cluttered
      */
     $this->cleanImportTables();
     $rand = rand(10000, 999999);
     $name = $this->tablename . '__import_' . strval(time()) . '_' . strval($rand);
     $qb = new Dataface_QueryBuilder($this->tablename);
     $res = xf_db_query("CREATE TABLE `{$name}` SELECT * " . $qb->_from() . " LIMIT 0", $this->db);
     if (!$res) {
         throw new Exception("Failed to create import table `{$name}` because a mysql error occurred: " . xf_db_error($this->db) . "\n", E_USER_ERROR);
     }
     return $name;
 }
Exemplo n.º 10
0
 /**
  * implements action handle() method.
  */
 function handle(&$params)
 {
     $action =& $params['action'];
     //print_r($params);
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $query['-skip'] = 0;
     $query['-limit'] = 9999999;
     // Let's validate some of the parameters first
     // The actions.ini file should define an email_column and email_table parameters
     // to indicate:
     //	a. the name of the column from the current table that should be used
     //	    as the "send to" email address.
     //	b. the name of the table that should store the email messages.
     if (!@$action['email_column']) {
         return PEAR::raiseError("No email column specified in actions.ini", DATAFACE_E_WARNING);
     }
     if (!@$action['email_table']) {
         return PEAR::raiseError("No email table specified in actions.ini", DATAFACE_E_WARNING);
     }
     // Make sure the table and column names are not malicious.
     $this->emailColumn = $col = $action['email_column'];
     if (strpos($col, '`') !== false) {
         return PEAR::raiseError("Invalid email column name: '{$col}'", DATAFACE_E_WARNING);
     }
     $this->emailTable = $table = $action['email_table'];
     if (strpos($table, '`') !== false) {
         return PEAR::raiseError("Invalid email table name: '{$table}'", DATAFACE_E_WARNING);
     }
     $this->joinTable = $join_table = $query['-table'] . '__' . $table;
     $this->recipientsTable = $query['-table'];
     // The name of the table that tracks which records have had email sent.
     // Next make sure that the email table(s) exist(s)
     if (!Dataface_Table::tableExists($table, false) || !Dataface_Table::tableExists($join_table, false)) {
         $this->createEmailTables($table, $join_table);
     }
     $emailTableObj =& Dataface_Table::loadTable($this->emailTable);
     $contentField =& $emailTableObj->getField('content');
     $contentField['widget']['atts']['rows'] = 20;
     $contentField['widget']['atts']['cols'] = 60;
     $contentField['widget']['label'] = 'Message body';
     $contentField['widget']['description'] = 'Please enter your message content in plain text.';
     $contentField['widget']['type'] = 'htmlarea';
     $contentField['widget']['editor'] = 'nicEdit';
     $subjectField =& $emailTableObj->getField('subject');
     $subjectField['widget']['atts']['size'] = 60;
     $fromField =& $emailTableObj->getField('from');
     $fromField['widget']['atts']['size'] = 60;
     $fromField['widget']['description'] = 'e.g. Web Lite Solutions &lt;info@weblite.ca&gt;';
     $ccField =& $emailTableObj->getField('cc');
     $ccField['widget']['atts']['size'] = 60;
     $ignoreBlacklistField =& $emailTableObj->getField('ignore_blacklist');
     $ignoreBlacklistField['widget']['type'] = 'checkbox';
     $ignoreBlacklistField['widget']['description'] = 'The black list is a list of email addresses that have opted out of receiving email.  I.e. Users on the black list do not want to receive email.  Check this box if you want to send to blacklisted addresses despite their wish to be left alone.';
     $form = df_create_new_record_form($table);
     $form->_build();
     $form->addElement('hidden', '-action');
     $form->addElement('hidden', '-table');
     $form->setDefaults(array('-action' => $query['-action'], '-table' => $query['-table']));
     $form->insertElementBefore($form->createElement('checkbox', 'send_now', '', 'Send now (leave this box unchecked if you wish these emails to be queued for later sending by the daily cron job.  Recommended to leave this box unchecked for large found sets (&gt;100 records).)'), 'submit_new_newsletters_record');
     $form->addElement('hidden', '-query_string');
     $form->setDefaults(array('-query_string' => base64_encode(serialize($query))));
     if (@$app->_conf['from_email']) {
         $form->setDefaults(array('from' => $app->_conf['from_email']));
     }
     if ($form->validate()) {
         $res = $form->process(array(&$form, 'save'), true);
         if (PEAR::isError($res)) {
             return $res;
         }
         // The form saved ok.. so we can send the emails.
         //$resultSet = $app->getResultSet();
         //$resultSet->loadSet();
         //$it =& $resultSet->iterator();
         $vals = $form->exportValues();
         $q2 = unserialize(base64_decode($vals['-query_string']));
         //print_r($q2);
         //exit;
         $qb = new Dataface_QueryBuilder($query['-table'], $q2);
         $sql = "insert ignore into `{$join_table}` (recipient_email,messageid,date_created) select `" . $col . "`, '" . addslashes($form->_record->val('id')) . "' as messageid, now() as date_created " . $qb->_from() . " " . $qb->_secure($qb->_where());
         //echo $sql;exit;
         $sres = mysql_query($sql, df_db());
         if (!$sres) {
             trigger_error(mysql_error(df_db()), E_USER_ERROR);
         }
         //while ($row = mysql_fetch_row($sres) ){
         //	$join_rec = new Dataface_Record($join_table, array('messageid'=>$form->_record->val('id'),
         //													   'recipient_email'=>$row[0],
         //													   'date_created'=>date('Y-m-d h:i:s')));
         //	$res = $join_rec->save();
         //	if ( !$res ) return PEAR::raiseError("Failed to add entry for email '".$curr->val($col)."'", DATAFACE_E_WARNING);
         //	unset($join_rec);
         //	unset($curr);
         //}
         //$it = df_get_records($query['-table'], $q2);
         //while ( $it->hasNext() ){
         //	$curr =& $it->next();
         //	$join_rec = new Dataface_Record($join_table, array('messageid'=>$form->_record->val('id'),
         //													   'recipient_email'=>$curr->val($col),
         //													   'date_created'=>date('Y-m-d h:i:s')));
         //	$res = $join_rec->save();
         //	if ( !$res ) return PEAR::raiseError("Failed to add entry for email '".$curr->val($col)."'", DATAFACE_E_WARNING);
         //	unset($join_rec);
         //	unset($curr);
         //}
         //$this->messages = array();
         // If we're set to send the email right now
         //if ( $form->exportValue('send_now') ){
         //	$this->sendMail($form->_record->val('id'));
         //}
         $this->postJob($form->_record->val('id'), $this->emailTable, $this->joinTable, $this->recipientsTable, $this->emailColumn);
         //$this->messages[] = "Email has been queued for delivery.";
         //if ( count($this->messages) > 0 ){
         //$_SESSION['--msg'] = implode("\n",$this->messages);
         //echo $_SESSION['--msg'];
         //exit;
         //}
         $q2['-action'] = 'list';
         unset($q2['-limit']);
         header('Location: ' . $app->url($q2) . '&--msg=' . urlencode("The message has been queued for delivery"));
         exit;
     }
     $addresses = array();
     //$resultSet = $app->getResultSet();
     //$resultSet->loadSet();
     //$it =& $resultSet->iterator();
     //$it = df_get_records($query['-table'], array_merge($query, array('-limit'=>30)));
     //while ( $it->hasNext() ){
     //	$curr =& $it->next();
     //	$addresses[] = $curr->val($col);
     //
     //	unset($curr);
     //}
     ob_start();
     $form->display();
     $context = array();
     $context['email_form'] = ob_get_contents();
     $profileTable =& Dataface_Table::loadTable($query['-table']);
     $context['fields'] = array_keys($profileTable->fields(false, true, true));
     //$context['blacklist'] = $this->getBlackListed($addresses);
     //$context['addresses'] = array_diff($addresses, $context['blacklist']);
     ob_end_clean();
     df_register_skin('email', DATAFACE_PATH . '/modules/Email/templates');
     df_display($context, 'email_form.html');
 }
Exemplo n.º 11
0
Arquivo: IO.php Projeto: promoso/HVAC
 /**
  * 
  * Imports data into the supplied record's relationship.  This makes use of this table's delegate
  * file to handle the importing.
  *
  * @param 	$record 			A Dataface_Record object whose relationship is to have records added to it.
  * @type Dataface_Record | null
  *
  * @param 	$data 				Either raw data that is to be imported, or the name of an Import table from which
  * 							data is to be imported.
  * @type Raw | string
  * 
  * @param	$importFilter		The name of the import filter that should be used.
  * @type string
  * 
  * @param	$relationshipName	The name of the relationship where these records should be added.
  * @type string
  * 
  * @param $commit				A boolean value indicating whether this import should be committed to the 
  *								database.  If this is false, then the records will not actually be imported.  They
  *								will merely be stored in an import table.  This must be explicitly set to true
  *								for the import to succeed.
  * @type boolean
  *
  * @param defaultValues			Array of default values of the form [Abs fieldname] -> [field value], where 'Abs fieldname'
  *								is the absolute field name (ie: tablename.fieldname).  All imported records will attain
  *								these default values.
  * @type array([string] -> [mixed])
  *
  * @return						Case 1: The import succeeds.
  *									Case 1.1: if commit = false return Import Table name where data is stored.
  *									Case 1.2: If commit = true return array of Dataface_Record objects that were inserted.
  *								Case 2: The import failed
  *									return PEAR_Error object.
  *
  *
  * Usage:
  * -------
  * $data = '<phonelist>
  *				<listentry>
  *					<name>John Smith</name><number>555-555-5555</number>
  *				</listentry>
  *				<listentry>
  *					<name>Susan Moore</name><number>444-444-4444</number>
  *				</listentry>
  *			</phonelist>';
  * 
  * 		// assume that we have an import filter called 'XML_Filter' that can import the above data.
  * 
  * $directory = new Dataface_Record('Directory', array('Name'=>'SFU Directory'));
  * 		// assume that the Directory table has a relationship called 'phonelist' and we want to 
  *		// import the above data into this relationship.
  *
  * $io = new Dataface_IO('Directory');
  * $importTableName = $io->importData(	$directory,		// The record that owns the relationship where imported records will be added
  *										$data, 			// The raw data to import
  *										'XML_Filter', 	// The name of the impot
  *										'phonelist'
  *									);
  *		// Since we didn't set the $commit flag, the data has been imported into an import table
  *		// whose name is stored now in $importTableName.
  *
  *  //
  *  // Now suppose we have confirmed that the import is what we want to do and we are ready to import
  *	// the data into the database.
  * $records = $io->importData($directory, $importTableName, null, 'phonelist', true );
  *
  * echo $records[0]->val('name'); 	// should output 'John Smith'
  * echo $records[0]->val('number'); // should output '555-555-5555'
  * echo $records[1]->val('name'); 	// should output 'Susan Moore'
  * echo $records[1]->val('number'); // should output '444-444-4444'
  * 
  *  // note that at this point the records in $records are already persisted to the database
  *
  */
 function importData(&$record, $data, $importFilter = null, $relationshipName = null, $commit = false, $defaultValues = array())
 {
     if ($relationshipName === null) {
         /*
          * No relationship is specified so our import table is just the current table.
          */
         $table =& $this->_table;
     } else {
         /*
          * A relationship is specified so we are actually importing the records into the
          * domain table of the relationship.
          */
         $relationship =& $this->_table->getRelationship($relationshipName);
         $tablename = $relationship->getDomainTable();
         if (PEAR::isError($tablename)) {
             /*
              * This relationship does not have a domain table.. so we will just take the destination table.
              */
             $destinationTables =& $relationship->getDestinationTables();
             if (count($destinationTables) <= 0) {
                 trigger_error(df_translate('scripts.Dataface.IO.importData.ERROR_NO_DESTINATION_TABLES', "Error occurred while attempting to parse import data into a table.  The relationship '" . $relationship->getName() . "' of table '" . $this->_table->tablename . "' has not destination tables listed.  It should have at least one.\n", array('relationship' => $relationship->getName(), 'table' => $this->_table->tablename)) . Dataface_Error::printStackTrace(), E_USER_ERROR);
             }
             $tablename = $destinationTables[0]->tablename;
         }
         if (PEAR::isError($tablename)) {
             trigger_error($tablename->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
         }
         $table =& Dataface_Table::loadTable($tablename);
         $rel_io = new Dataface_IO($tablename);
         $io =& $rel_io;
     }
     if (!$commit) {
         // If data is provided, we must parse it and prepare it for
         // import
         $records = $table->parseImportData($data, $importFilter, $defaultValues);
         if (PEAR::isError($records)) {
             /*
              * The import didn't work with the specified import filter, so we will
              * try the other filters.
              */
             $records = $table->parseImportData($data, null, $defaultValues);
         }
         if (PEAR::isError($records)) {
             /*
              * Apparently we have failed to import the data, so let's just 
              * return the errors.
              */
             return $records;
         }
         // Now we will load the values of the records into an array
         // so that we can store it in the session
         $importData = array('table' => $table->tablename, 'relationship' => $relationshipName, 'defaults' => $defaultValues, 'importFilter' => $importFilter, 'record' => null, 'rows' => array());
         if (isset($record)) {
             $importData['record'] = $record->getId();
         }
         foreach ($records as $r) {
             if (is_a($r, 'Dataface_ImportRecord')) {
                 // The current record is actually an ImportRecord
                 $importData['rows'][] = $r->toArray();
             } else {
                 $importData['rows'][] = $r->vals(array_keys($r->_table->fields(false, true)));
                 unset($r);
             }
         }
         $dumpFile = tempnam(sys_get_temp_dir(), 'dataface_import');
         $handle = fopen($dumpFile, "w");
         if (!$handle) {
             trigger_error("Could not write import data to dump file {$dumpFile}", E_USER_ERROR);
         }
         fwrite($handle, serialize($importData));
         fclose($handle);
         $_SESSION['__dataface__import_data__'] = $dumpFile;
         return $dumpFile;
     }
     if (!@$_SESSION['__dataface__import_data__']) {
         trigger_error("No import data to import", E_USER_ERROR);
     }
     $dumpFile = $_SESSION['__dataface__import_data__'];
     $importData = unserialize(file_get_contents($dumpFile));
     if ($importData['table'] != $table->tablename) {
         return PEAR::raiseError("Unexpected table name in import data.  Expected " . $table->tablename . " but received " . $importData['table']);
     }
     $inserted = array();
     $i = 0;
     foreach ($importData['rows'] as $row) {
         if (isset($row['__CLASS__']) and isset($row['__CLASSPATH__'])) {
             // This row is an import record - not merely a Dataface_Record
             // object so it provides its own logic to import the records.
             import($row['__CLASSPATH__']);
             $class = $row['__CLASS__'];
             $importRecord = new $class($row);
             $res = $importRecord->commit($record, $relationshipName);
             if (PEAR::isError($res)) {
                 return $res;
             }
         } else {
             $values = array();
             foreach (array_keys($row) as $key) {
                 if (!is_int($key)) {
                     $values[$key] = $row[$key];
                 }
             }
             if ($relationshipName === null) {
                 /*
                  * These records are not being added to a relationship.  They are just being added directly
                  * into the table.
                  */
                 $defaults = array();
                 // for absolute field name keys for default values, we will strip out the table name.
                 foreach (array_keys($defaultValues) as $key) {
                     if (strpos($key, '.') !== false) {
                         list($tablename, $fieldname) = explode('.', $key);
                         if ($tablename == $this->_table->tablename) {
                             $defaults[$fieldname] = $defaultValues[$key];
                         } else {
                             continue;
                         }
                     } else {
                         $defaults[$key] = $defaultValues[$key];
                     }
                 }
                 $values = array_merge($defaults, $values);
                 $insrecord = new Dataface_Record($this->_table->tablename, $values);
                 $inserted[] =& $insrecord;
                 $this->write($insrecord);
                 $insrecord->__destruct();
                 unset($insrecord);
             } else {
                 /*
                  * The records are being added to a relationship so we need to make sure that we add the appropriate
                  * entries to the "join" tables as well.
                  */
                 foreach (array_keys($values) as $key) {
                     $values[$table->tablename . '.' . $key] = $values[$key];
                     unset($values[$key]);
                 }
                 $values = array_merge($defaultValues, $values);
                 /*
                  * Let's check if all of the keys are set.  If they are then the record already exists.. we
                  * just need to update the record.
                  *
                  */
                 $rvalues = array();
                 foreach ($values as $valkey => $valval) {
                     if (strpos($valkey, '.') !== false) {
                         list($tablename, $fieldname) = explode('.', $valkey);
                         if ($tablename == $table->tablename) {
                             $rvalues[$fieldname] = $valval;
                         }
                     }
                 }
                 $rrecord = new Dataface_Record($table->tablename, array());
                 $rrecord->setValues($rvalues);
                 // we set the values in a separate call because we want to be able to do an update
                 // and setting values in the constructer sets the snapshot (ie: it will think that
                 // no values have changed.
                 if ($io->recordExists($rrecord)) {
                     /*
                      * The record already exists, so we update it and then add it to the relationship.
                      *
                      */
                     if (Dataface_PermissionsTool::edit($rrecord)) {
                         /*
                          * We only edit the record if we have permission to do so.
                          */
                         $result = $io->write($rrecord);
                         if (PEAR::isError($result)) {
                             trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
                         }
                     }
                     $relatedRecord = new Dataface_RelatedRecord($record, $relationshipName, $values);
                     $inserted[] =& $relatedRecord;
                     $qb = new Dataface_QueryBuilder($this->_table->tablename);
                     $sql = $qb->addExistingRelatedRecord($relatedRecord);
                     $res2 = $this->performSQL($sql);
                     unset($relatedRecord);
                 } else {
                     $relatedRecord = new Dataface_RelatedRecord($record, $relationshipName, $values);
                     $inserted[] =& $relatedRecord;
                     $qb = new Dataface_QueryBuilder($this->_table->tablename);
                     $sql = $qb->addRelatedRecord($relatedRecord);
                     $res2 = $this->performSQL($sql);
                     unset($relatedRecord);
                 }
                 unset($rrecord);
             }
         }
         unset($row);
     }
     @unlink($dumpFile);
     unset($_SESSION['__dataface__import_data__']);
     return $inserted;
 }
Exemplo n.º 12
0
 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);
         }
     }
 }
Exemplo n.º 13
0
 function test_metadata_from()
 {
     $app =& Dataface_Application::getInstance();
     $original_value = @$app->_conf['metadata_enabled'];
     $app->_conf['metadata_enabled'] = 1;
     import('Dataface/MetadataTool.php');
     $mt = new Dataface_MetadataTool('Profiles');
     $mt->createMetadataTable();
     $builder = new Dataface_QueryBuilder('Profiles');
     echo $from = $builder->_from();
     $sql = "select * {$from} where id='10'";
     //$res = xf_db_query($sql, $app->db());
     //if ( !$res ) trigger_error(xf_db_error($app->db()), E_USER_ERROR);
 }
Exemplo n.º 14
0
 function display()
 {
     $this->_build();
     $showform = true;
     $b = new Dataface_QueryBuilder($this->_tablename, $this->_query);
     if (isset($this->_query['-delete-one'])) {
         $q = array('-skip' => $this->_query['-cursor'], '-limit' => 1);
         $sql = $b->select('', $q);
         $res = xf_db_query($sql, $this->_db);
         if (!$res) {
             throw new Exception(df_translate('scripts.Dataface.DeleteForm._build.ERROR_TRYING_TO_FETCH', "Error trying to fetch element to be deleted.: ") . xf_db_error($this->_db), E_USER_ERROR);
         }
         if (xf_db_num_rows($res) == 0) {
             $msg = df_translate('scripts.Dataface.DeleteForm._build.ERROR_NO_RECORD_SELECTED', "No record is currently selected so no record can be deleted.");
             $showform = false;
         } else {
             $row = xf_db_fetch_array($res);
             $rowRec = new Dataface_Record($this->_tablename, $row);
             $displayCol = $rowRec->getTitle();
             $msg = df_translate('scripts.Dataface.DeleteForm.display.ARE_YOU_SURE', "Are you sure you want to delete this record: &quot;{$displayCol}&quot;?", array('displayCol' => $displayCol));
         }
     } else {
         if (isset($this->_query['-delete-found'])) {
             $q = $b->select_num_rows();
             $res = xf_db_query($q, $this->_db);
             if (!$res) {
                 throw new Exception(df_translate('scripts.Dataface.DeleteForm.display.ERROR_ESTIMATING', "Error estimating number of rows that will be deleted: ") . xf_db_error($this->_db), E_USER_ERROR);
             }
             list($num) = xf_db_fetch_row($res);
             if ($num <= 0) {
                 $msg = df_translate('scripts.Dataface.DeleteForm.display.ERROR_NO_RECORDS_FOUND', "There are no records in the current found set so no records can be deleted.");
                 $showform = false;
             } else {
                 $msg = df_translate('scripts.Dataface.DeleteForm.display.ARE_YOU_SURE_MULTIPLE', "Are you sure you want to delete the found records.  {$num} records will be deleted.", array('num' => $num));
             }
         } else {
             $msg = df_translate('scripts.Dataface.DeleteForm.display.ERROR_GET_VARS', "Error: You must specify either '-delete-one' or '-delete-found' in GET vars.");
             $showform = false;
         }
     }
     if ($showform) {
         ob_start();
         parent::display();
         $form = ob_get_contents();
         ob_end_clean();
     } else {
         $form = '';
     }
     $context = array('msg' => $msg, 'form' => $form);
     import('Dataface/SkinTool.php');
     $skinTool =& Dataface_SkinTool::getInstance();
     //$smarty = new Smarty;
     //$smarty->template_dir = $GLOBALS['Dataface_Globals_Templates'];
     //$smarty->compile_dir = $GLOBALS['Dataface_Globals_Templates_c'];
     //$smarty->assign($context);
     //$smarty->display('Dataface_DeleteForm.html');
     $skinTool->display($context, 'Dataface_DeleteForm.html');
 }