/** * * * @dataProvider provider * */ public function testImportAttachmentsFromCSVFile($test_filename, $expected_result, $update, $dry_run) { $path = dirname(__FILE__) . '/' . $test_filename; // Open the CSV file $result = AttachmentsImport::importAttachmentsFromCSVFile($path, $verify_parent = true, $update, $dry_run); if (is_numeric($expected_result) && is_numeric($result)) { $this->assertEquals((int) $expected_result, (int) $result); } elseif (is_array($result)) { $this->assertEquals((int) $expected_result, count($result)); } else { // Cut off the error number for comparison $errmsg = substr($result, 0, strpos($result, ' (ERR')); $this->assertEquals($expected_result, $errmsg); } // Delete the attachments if (!$update) { $db = JFactory::getDBO(); if (is_array($result)) { $query = $db->getQuery(true); $ids = implode(',', $result); $query->delete('#__attachments')->where("id IN ( {$ids} )"); $db->setQuery($query); if (!$db->query()) { $this->assertTrue(false, 'ERROR deleting new test attachments' . $db->getErrorMsg()); } } } }
/** * Install attachments data from CSV file */ public function installAttachmentsFromCsvFile() { // Access check. if (!JFactory::getUser()->authorise('core.admin', 'com_attachments')) { return JError::raiseError(404, JText::_('JERROR_ALERTNOAUTHOR') . ' (ERR 160)'); } require_once JPATH_ADMINISTRATOR . '/components/com_attachments/import.php'; $filename = JRequest::getString('filename', null); if ($filename == null) { $errmsg = JText::_('ATTACH_ERROR_MUST_ADD_FILENAME_TO_URL') . ' (ERR 161)'; return JError::raiseError(500, $errmsg); } $verify_parent = JRequest::getBool('verify_parent', true); $update = JRequest::getBool('update', false); $dry_run = JRequest::getBool('dry_run', false); $status = AttachmentsImport::importAttachmentsFromCSVFile($filename, $verify_parent, $update, $dry_run); // Abort if it is an error message if (is_string($status)) { return JError::raiseError(500, $status); } // Otherwise, report the results if (is_array($status)) { $msg = JText::sprintf('ATTACH_ADDED_DATA_FOR_N_ATTACHMENTS', count($status)); $this->setRedirect('index.php?option=com_attachments', $msg); } else { if ($dry_run) { $msg = JText::sprintf('ATTACH_DATA_FOR_N_ATTACHMENTS_OK', $status) . ' (ERR 162)'; return JError::raiseNotice(200, $msg); } else { $errmsg = JText::sprintf('ATTACH_ERROR_IMPORTING_ATTACHMENTS_S', $status) . ' (ERR 163)'; return JError::raiseError(500, $errmsg); } } }
/** * Import attachment data from a CSV file * * The CSV file must have the field names in the first row * * @param string $filename the filename of the CSV file * @param bool $verify_parent if true, each attachments parent must exist * @param bool $update if true, if the attachment exists, update it (or create a new one) * @param bool $dry_run do everything except actually add entries to attachment table in the database * * @return array of IDs of the imported attachemnts (if $dry_run, number that would have been imported), or error message */ public static function importAttachmentsFromCSVFile($filename, $verify_parent = true, $update = false, $dry_run = false) { $db = JFactory::getDBO(); // Open the CSV file $line_num = 0; $f = @fopen($filename, 'r'); if (!$f) { return JText::sprintf('ATTACH_ERROR_UNABLE_TO_OPEN_CSV_FILE_S', $filename) . ' (ERR 85)'; } // Parse the first row to process field names and indeces $field = AttachmentsImport::_parseFieldNames($f); $line_num += 1; if (!is_array($field)) { return $field; } // Get the default access level from the Attachments options jimport('joomla.application.component.helper'); $params = JComponentHelper::getParams('com_attachments'); $default_access_level = $params->get('default_access_level', AttachmentsDefines::$DEFAULT_ACCESS_LEVEL_ID); // Load the attachents parent manager JPluginHelper::importPlugin('attachments'); $apm = getAttachmentsPluginManager(); // Process the CSV data if ($dry_run) { $ids_ok = 0; } else { $ids_ok = array(); } iconv_set_encoding("internal_encoding", "UTF-8"); setlocale(LC_ALL, 'en_US.UTF-8'); while (!feof($f)) { // Read the next line $adata = fgetcsv($f); $line_num += 1; $line_str = ' [LINE: ' . $line_num . '] '; // Skip blank lines if (!$adata) { continue; } // get the attachment ID $attachment_id = $adata[$field['id']]; if (!is_numeric($attachment_id)) { return JText::sprintf('ATTACH_ERROR_BAD_ATTACHMENT_ID_S', $attachment_id) . $line_str . ' (ERR 86)'; } $attachment_id = (int) $attachment_id; $parent_type = $adata[$field['parent_type']]; $parent_entity = strtolower($adata[$field['parent_entity']]); $parent_id = (int) $adata[$field['parent_id']]; // Make sure it is not a 'section' attachment if ($parent_entity == 'section') { return JText::sprintf('ATTACH_ERROR_SECTION_ATTACHMENT_NOT_ALLOWED_ID', $attachment_id) . $line_str . ' (ERR 86B)'; } // Get the attachment parent object if (!$apm->attachmentsPluginInstalled($parent_type)) { return JText::sprintf('ATTACH_ERROR_UNKNOWN_PARENT_TYPE_S', $parent_type) . $line_str . ' (ERR 87)'; } $parent = $apm->getAttachmentsPlugin($parent_type); // Does the parent exist? if ($verify_parent) { // Make sure a parent with the specified ID exists if (!$parent->parentExists($parent_id, $parent_entity)) { return JText::sprintf('ATTACH_ERROR_UNKNOWN_PARENT_ID_N', $parent_id) . $line_str . ' (ERR 88)'; } // Double-check by comparing the title $attachment_parent_title = $adata[$field['parent_title']]; $parent_title = $parent->getTitle($parent_id, $parent_entity); if (!AttachmentsImport::utf8StringsEqual($parent_title, $attachment_parent_title)) { return JText::sprintf('ATTACH_ERROR_PARENT_TITLE_MISMATCH_ID_N_TITLE_S_S', $parent_id, $parent_title, $attachment_parent_title) . $line_str . ' (ERR 89)'; } } // Check the creator username $creator_id = (int) $adata[$field['created_by']]; $attachment_creator_username = $adata[$field['created_by_username']]; $query = $db->getQuery(true); $query->select('username')->from('#__users')->where('id = ' . (int) $creator_id); $db->setQuery($query, 0, 1); $creator_username = $db->loadResult(); if (empty($creator_username) || $db->getErrorNum()) { return JText::sprintf('ATTACH_ERROR_UNABLE_TO_FIND_CREATOR_ID_S', $creator_id, $attachment_creator_username) . $line_str . ' (ERR 90)'; } if (!AttachmentsImport::utf8StringsEqual($creator_username, $attachment_creator_username)) { return JText::sprintf('ATTACH_ERROR_CREATOR_USERNAME_MISMATCH_ID_S_S', $creator_id, $attachment_creator_username, $creator_username) . $line_str . ' (ERR 91)'; } // Check the modifier name $modifier_id = (int) $adata[$field['modified_by']]; $attachment_modifier_username = $adata[$field['modified_by_username']]; $query = $db->getQuery(true); $query->select('username')->from('#__users')->where('id = ' . (int) $modifier_id); $db->setQuery($query, 0, 1); $modifier_username = $db->loadResult(); if (empty($modifier_username) || $db->getErrorNum()) { return JText::sprintf('ATTACH_ERROR_UNABLE_TO_FIND_MODIFIER_ID_S', $modifier_id, $attachment_modifier_username) . $line_str . ' (ERR 92)'; } if (!AttachmentsImport::utf8StringsEqual($modifier_username, $attachment_modifier_username)) { return JText::sprintf('ATTACH_ERROR_MODIFIER_USERNAME_MISMATCH_ID_S_S', $modifier_id, $attachment_modifier_username, $modifier_username) . $line_str . ' (ERR 93)'; } // Construct an attachments entry JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_attachments/tables'); $attachment = JTable::getInstance('Attachment', 'AttachmentsTable'); if ($update) { // The attachment ID cannot be 0 for updating! if ($attachment_id == 0) { return JText::_('ATTACH_ERROR_CANNOT_MODIFY_ATTACHMENT_ZERO_ID') . $line_str . ' (ERR 94)'; } // Load the data from the attachment to be updated (or create new one) if (!$attachment->load($attachment_id)) { $attachment->reset(); } } else { // Create new attachment $attachment->reset(); } // Copy in the data from the CSV file foreach (AttachmentsImport::$field_names as $fname) { if ($fname != 'id' && !in_array($fname, AttachmentsImport::$extra_field_names)) { $attachment->{$fname} = $adata[$field[$fname]]; } } // Do any necessary overrides $attachment->parent_entity = $parent_entity; // ??? what about parent_entity_name? $attachment->access = $default_access_level; $attachment->file_size = (int) $adata[$field['file_size']]; if ($dry_run) { $ids_ok++; } else { // Store the new/updated attachment if ($attachment->store()) { $ids_ok[] = $attachment->getDbo()->insertid(); } else { return JText::sprintf('ATTACH_ERROR_STORING_ATTACHMENT_S', $attachment->getError()) . ' (ERR 95)'; } } } fclose($f); return $ids_ok; }
/** * Parse the field names from the first(next) line of the CSV file * @param file $file the opened file object * @return the associative array (fieldname => index) or error message */ public static function parseFieldNames($file) { return AttachmentsImport::_parseFieldNames($file); }