Example #1
0
 /**
  * @testdox Import rows that specify an existing PK will update existing records.
  * @test
  */
 public function primaryKey()
 {
     $testtable = $this->db->getTable('test_table');
     $rec1 = $testtable->saveRecord(array('title' => 'PK Test'));
     $this->assertEquals(1, $testtable->getRecordCount());
     $this->assertNull($rec1->description());
     // Add a field's value.
     $csv = '"ID","Title","Description"' . "\r\n" . '"1","One","A description"' . "\r\n";
     $uploaded = $this->saveDataFile($csv);
     $csv = new \Tabulate\CSV(null, $uploaded);
     $csv->loadData();
     $column_map = array('id' => 'ID', 'title' => 'Title', 'description' => 'Description');
     $csv->importData($testtable, $column_map);
     // Make sure there's still only one record, and that it's been updated.
     $this->assertEquals(1, $testtable->getRecordCount());
     $rec2 = $testtable->getRecord(1);
     $this->assertEquals('One', $rec2->title());
     $this->assertEquals('A description', $rec2->description());
     // Leave out a required field.
     $csv = '"ID","Description"' . "\r\n" . '"1","New description"' . "\r\n";
     $uploaded2 = $this->saveDataFile($csv);
     $csv2 = new \Tabulate\CSV(null, $uploaded2);
     $csv2->loadData();
     $column_map2 = array('id' => 'ID', 'description' => 'Description');
     $csv2->importData($testtable, $column_map2);
     // Make sure there's still only one record, and that it's been updated.
     $this->assertEquals(1, $testtable->getRecordCount());
     $rec3 = $testtable->getRecord(1);
     $this->assertEquals('One', $rec3->title());
     $this->assertEquals('New description', $rec3->description());
 }
Example #2
0
 /**
  * This action is for importing a single CSV file into a single database table.
  * It guides the user through the four stages of importing:
  * uploading, field matching, previewing, and doing the actual import.
  * All of the actual work is done in the CSV class.
  *
  * 1. In the first stage, a CSV file is **uploaded**, validated, and moved to a temporary directory.
  *    The file is then accessed from this location in the subsequent stages of importing,
  *    and only deleted upon either successful import or the user cancelling the process.
  *    (The 'id' parameter of this action is the identifier for the uploaded file.)
  * 2. Once a valid CSV file has been uploaded,
  *    its colums are presented to the user to be **matched** to those in the database table.
  *    The columns from the database are presented first and the CSV columns are matched to these,
  *    rather than vice versa,
  *    because this way the user sees immediately what columns are available to be imported into.
  * 3. The column matches are then used to produce a **preview** of what will be added to and/or changed in the database.
  *    All columns from the database are shown (regardless of whether they were in the import) and all rows of the import.
  *    If a column is not present in the import the database will (obviously) use the default value if there is one;
  *    this will be shown in the preview.
  * 4. When the user accepts the preview, the actual **import** of data is carried out.
  *    Rows are saved to the database using the usual `Table::save()` method
  *    and a message presented to the user to indicate successful completion.
  *
  * @return void
  */
 public function import($args)
 {
     $template = new Template('import.html');
     // Set up the progress bar.
     $template->stages = array('choose_file', 'match_fields', 'preview', 'complete_import');
     $template->stage = 'choose_file';
     // First make sure the user is allowed to import data into this table.
     $table = $this->getTable($args['table']);
     $template->record = $table->getDefaultRecord();
     $template->action = 'import';
     $template->table = $table;
     $template->maxsize = \Tabulate\File::maxUploadSize();
     if (!$table->getDatabase()->checkGrant(Grants::IMPORT, $table->getName())) {
         $template->addNotice('error', 'You do not have permission to import data into this table.');
         return $template->render();
     }
     /*
      * Stage 1 of 4: Uploading.
      */
     $template->form_action = $table->getUrl('import');
     try {
         $hash = isset($_GET['hash']) ? $_GET['hash'] : false;
         $uploaded = isset($_FILES['file']) ? $_FILES['file'] : false;
         $csvFile = new \Tabulate\CSV($hash, $uploaded);
     } catch (\Exception $e) {
         $template->addNotice('error', $e->getMessage());
         return $template->render();
     }
     /*
      * Stage 2 of 4: Matching fields
      */
     if ($csvFile->loaded()) {
         $template->file = $csvFile;
         $template->stage = $template->stages[1];
         $template->form_action .= "&hash=" . $csvFile->hash;
     }
     /*
      * Stage 3 of 4: Previewing
      */
     if ($csvFile->loaded() and isset($_POST['preview'])) {
         $template->stage = $template->stages[2];
         $template->columns = serialize($_POST['columns']);
         $errors = array();
         // Make sure all required columns are selected
         foreach ($table->getColumns() as $col) {
             // Handle missing columns separately; other column errors are
             // done in the CSV class. Missing columns don't matter if importing
             // existing records.
             $missing = empty($_POST['columns'][$col->getName()]);
             $pkPresent = isset($_POST['columns'][$table->getPkColumn()->getName()]);
             if (!$pkPresent && $col->isRequired() && $missing) {
                 $errors[] = array('column_name' => '', 'column_number' => '', 'field_name' => $col->getName(), 'row_number' => 'N/A', 'messages' => array('Column required, but not found in CSV'));
             }
         }
         $template->errors = empty($errors) ? $csvFile->matchFields($table, wp_unslash($_POST['columns'])) : $errors;
     }
     /*
      * Stage 4 of 4: Import
      */
     if ($csvFile->loaded() && isset($_POST['import'])) {
         $template->stage = $template->stages[3];
         $this->wpdb->query('BEGIN');
         $result = $csvFile->importData($table, unserialize($_POST['columns']));
         $this->wpdb->query('COMMIT');
         $template->addNotice('updated', 'Import complete; ' . $result . ' rows imported.');
     }
     return $template->render();
 }