Example #1
0
/**
 * Process the uploaded file:
 *
 * Make a usable unique filename.
 * Generate a thumb if necessary.
 * Prepare the metadata sent to Fedora and Solr.
 * Mint and reserve a DOI.
 * For this uploaded file, we will create 2 objects in Fedora and 1 document in Solr and 2 posts.
 * Get the next 2 object id values for Fedora.
 * Add solr first, if Tika errors out we'll quit before updating Fedora and WordPress.
 * Create the aggregator post so that we can reference the ID in the Solr document.
 * Set object terms for subjects.
 * Add any new keywords and set object terms for tags.
 * Add to metadata and store in post meta.
 * Index the deposit content and metadata in Solr.
 * Create the aggregator Fedora object along with the DC and RELS-EXT datastreams.
 * Upload the MODS file to the Fedora server temp file storage.
 * Create the descMetadata datastream for the aggregator object.
 * Upload the deposited file to the Fedora server temp file storage.
 * Create the CONTENT datastream for the resource object.
 * Upload the thumb to the Fedora server temp file storage if necessary.
 * Prepare an array of post data for the resource post.
 * Insert the resource post.
 * Add the activity entry for the author.
 * Publish the reserved DOI.
 * Add any group activity entries.
 */
function humcore_deposit_file()
{
    if (empty($_POST)) {
        return false;
    }
    global $fedora_api, $solr_client;
    $upload_error_message = '';
    if (empty($_POST['selected_file_name'])) {
        // Do something!
        $upload_error_message = __('No file was uploaded! Please press "Select File" and upload a file first.', 'humcore_domain');
    } elseif (0 == $_POST['selected_file_size']) {
        $upload_error_message = sprintf(__('%1$s appears to be empty, please choose another file.', 'humcore_domain'), sanitize_file_name($_POST['selected_file_name']));
    }
    if (!empty($upload_error_message)) {
        echo '<div id="message" class="info"><p>' . $upload_error_message . '</p></div>';
        // XSS OK.
        return false;
    }
    // Single file uploads at this point.
    $tempname = sanitize_file_name($_POST['selected_temp_name']);
    $fileloc = $fedora_api->tempDir . '/' . $tempname;
    $filename = strtolower(sanitize_file_name($_POST['selected_file_name']));
    $filesize = sanitize_text_field($_POST['selected_file_size']);
    $renamed_file = $fileloc . '.' . $filename;
    $MODS_file = $fileloc . '.MODS.' . $filename . '.xml';
    $datastream_id = 'CONTENT';
    $thumb_datastream_id = 'THUMB';
    $generated_thumb_name = '';
    // Make a usable unique filename.
    if (file_exists($fileloc)) {
        $file_rename_status = rename($fileloc, $renamed_file);
    }
    // TODO handle file error.
    $check_filetype = wp_check_filetype($filename, wp_get_mime_types());
    $filetype = $check_filetype['type'];
    if (preg_match('~^image/~', $check_filetype['type'])) {
        $thumb_image = wp_get_image_editor($renamed_file);
        if (!is_wp_error($thumb_image)) {
            $current_size = $thumb_image->get_size();
            $thumb_image->resize(150, 150, false);
            $thumb_filename = $thumb_image->generate_filename('thumb', $fedora_api->tempDir . '/', 'jpg');
            $generated_thumb = $thumb_image->save($thumb_filename, 'image/jpeg');
            $generated_thumb_path = $generated_thumb['path'];
            $generated_thumb_name = str_replace($tempname . '.', '', $generated_thumb['file']);
            $generated_thumb_mime = $generated_thumb['mime-type'];
        } else {
            echo 'Error - thumb_image : ' . esc_html($thumb_image->get_error_code()) . '-' . esc_html($thumb_image->get_error_message());
            error_log(sprintf('*****HumCORE Deposit Error***** - thumb_image : %1$s-%2$s', $thumb_image->get_error_code(), $thumb_image->get_error_message()));
        }
    }
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit started');
    }
    /**
     * For this uploaded file, we will create 2 objects in Fedora and 1 document in Solr.
     * Get the next 2 object id values for Fedora.
     */
    $nextPids = $fedora_api->get_next_pid(array('numPIDs' => '2', 'namespace' => $fedora_api->namespace));
    if (is_wp_error($nextPids)) {
        echo 'Error - nextPids : ' . esc_html($nextPids->get_error_code()) . '-' . esc_html($nextPids->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - nextPids : %1$s-%2$s', $nextPids->get_error_code(), $nextPids->get_error_message()));
        return false;
    }
    /* echo "<br />DEBUG  0 ", date ( 'Y-m-d H:i:s' ), var_export( $nextPids, true ); */
    $metadata = prepare_metadata($nextPids);
    $aggregatorXml = create_aggregator_xml(array('pid' => $nextPids[0], 'creator' => $metadata['creator']));
    $aggregatorRdf = create_aggregator_rdf(array('pid' => $nextPids[0], 'collectionPid' => $fedora_api->collectionPid));
    $aggregatorFoxml = create_foxml(array('pid' => $nextPids[0], 'label' => '', 'xmlContent' => $aggregatorXml, 'state' => 'Active', 'rdfContent' => $aggregatorRdf));
    /* echo "<br />DEBUG  1 ", date ( 'Y-m-d H:i:s' ), var_export( $aggregatorFoxml, true ); */
    $metadataMODS = create_mods_xml($metadata);
    $resourceXml = create_resource_xml($metadata, $filetype);
    $resourceRdf = create_resource_rdf(array('aggregatorPid' => $nextPids[0], 'resourcePid' => $nextPids[1]));
    $resourceFoxml = create_foxml(array('pid' => $nextPids[1], 'label' => $filename, 'xmlContent' => $resourceXml, 'state' => 'Active', 'rdfContent' => $resourceRdf));
    /* echo "<br />DEBUG  2 ", date ( 'Y-m-d H:i:s' ), var_export( $resourceFoxml, true ); */
    // TODO handle file write error.
    $file_write_status = file_put_contents($MODS_file, $metadataMODS);
    /* echo "<br />DEBUG  3 ", date ( 'Y-m-d H:i:s' ), var_export( $metadataMODS, true ); */
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit metadata complete');
    }
    /* echo "<br />DEBUG 10 ", date ( 'Y-m-d H:i:s' ), var_export( $metadata, true ); */
    /**
     * Create the aggregator post now so that we can reference the ID in the Solr document.
     */
    $deposit_post_data = array('post_title' => $metadata['title'], 'post_excerpt' => $metadata['abstract'], 'post_status' => 'publish', 'post_type' => 'humcore_deposit', 'post_name' => $nextPids[0], 'post_author' => bp_loggedin_user_id());
    $deposit_post_ID = wp_insert_post($deposit_post_data);
    $metadata['record_identifier'] = $deposit_post_ID;
    /**
     * Set object terms for subjects.
     */
    if (!empty($_POST['deposit-subject'])) {
        $term_ids = array();
        foreach ($_POST['deposit-subject'] as $subject) {
            $term_key = term_exists($subject, 'humcore_deposit_subject');
            if (!is_wp_error($term_key) && !empty($term_key)) {
                $term_ids[] = intval($term_key['term_id']);
            } else {
                error_log('*****HumCORE Deposit Error - bad subject*****' . var_export($term_key, true));
            }
        }
        if (!empty($term_ids)) {
            $term_taxonomy_ids = wp_set_object_terms($deposit_post_ID, $term_ids, 'humcore_deposit_subject');
            $metadata['subject_ids'] = $term_taxonomy_ids;
        }
    }
    /**
     * Add any new keywords and set object terms for tags.
     */
    if (!empty($_POST['deposit-keyword'])) {
        $term_ids = array();
        foreach ($_POST['deposit-keyword'] as $keyword) {
            $term_key = term_exists($keyword, 'humcore_deposit_tag');
            if (empty($term_key)) {
                $term_key = wp_insert_term(sanitize_text_field($keyword), 'humcore_deposit_tag');
            }
            if (!is_wp_error($term_key)) {
                $term_ids[] = intval($term_key['term_id']);
            } else {
                error_log('*****HumCORE Deposit Error - bad tag*****' . var_export($term_key, true));
            }
        }
        if (!empty($term_ids)) {
            $term_taxonomy_ids = wp_set_object_terms($deposit_post_ID, $term_ids, 'humcore_deposit_tag');
            $metadata['keyword_ids'] = $term_taxonomy_ids;
        }
    }
    $json_metadata = json_encode($metadata, JSON_HEX_APOS);
    if (json_last_error()) {
        error_log('*****HumCORE Deposit Error***** Post Meta Encoding Error - Post ID: ' . $deposit_post_ID . ' - ' . json_last_error_msg());
    }
    $post_meta_ID = update_post_meta($deposit_post_ID, '_deposit_metadata', wp_slash($json_metadata));
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit - postmeta (1)', $json_metadata);
    }
    /* echo "<br />DEBUG 12 ", date ( 'Y-m-d H:i:s' ), var_export( $json_metadata, true ); */
    /**
     * Add to metadata and store in post meta.
     */
    $post_metadata['files'][] = array('pid' => $nextPids[1], 'datastream_id' => $datastream_id, 'filename' => $filename, 'filetype' => $filetype, 'filesize' => $filesize, 'fileloc' => $renamed_file, 'thumb_datastream_id' => !empty($generated_thumb_name) ? $thumb_datastream_id : '', 'thumb_filename' => !empty($generated_thumb_name) ? $generated_thumb_name : '');
    $json_metadata = json_encode($post_metadata, JSON_HEX_APOS);
    if (json_last_error()) {
        error_log('*****HumCORE Deposit Error***** File Post Meta Encoding Error - Post ID: ' . $deposit_post_ID . ' - ' . json_last_error_msg());
    }
    $post_meta_ID = update_post_meta($deposit_post_ID, '_deposit_file_metadata', wp_slash($json_metadata));
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit - postmeta (2)', $json_metadata);
    }
    /* echo "<br />DEBUG 13 ", date ( 'Y-m-d H:i:s' ), var_export( $json_metadata, true ); */
    /**
     * Add solr first, if Tika errors out we'll quit before updating Fedora and WordPress.
     *
     * Index the deposit content and metadata in Solr.
     */
    try {
        if (preg_match('~^audio/|^image/|^video/~', $check_filetype['type'])) {
            $sResult = $solr_client->create_humcore_document('', $metadata);
            /* echo "<br />DEBUG 11.1 ", date ( 'Y-m-d H:i:s' ), var_export( $sResult, true ); */
        } else {
            $sResult = $solr_client->create_humcore_extract($renamed_file, $metadata);
            /* echo "<br />DEBUG 11.2 ", date ( 'Y-m-d H:i:s' ), var_export( $sResult, true ); */
        }
    } catch (Exception $e) {
        if ('500' == $e->getCode() && strpos($e->getMessage(), 'TikaException')) {
            try {
                $sResult = $solr_client->create_humcore_document('', $metadata);
                error_log(sprintf('*****HumCORE Deposit Error***** - A Tika error occurred extracting text from the uploaded file. This deposit, %1$s, will be indexed using only the web form metadata.', $nextPids[0]));
            } catch (Exception $e) {
                echo '<h3>', __('An error occurred while depositing your file!', 'humcore_domain'), '</h3>';
                error_log(sprintf('*****HumCORE Deposit Error***** - solr : %1$s-%2$s', $e->getCode(), $e->getMessage()));
                wp_delete_post($deposit_post_ID);
                return false;
            }
        } else {
            echo '<h3>', __('An error occurred while depositing your file!', 'humcore_domain'), '</h3>';
            error_log(sprintf('*****HumCORE Deposit Error***** - solr : %1$s-%2$s', $e->getCode(), $e->getMessage()));
            wp_delete_post($deposit_post_ID);
            return false;
        }
    }
    /**
     * Create the aggregator Fedora object along with the DC and RELS-EXT datastreams.
     */
    $aIngest = $fedora_api->ingest(array('xmlContent' => $aggregatorFoxml));
    if (is_wp_error($aIngest)) {
        echo 'Error - aIngest : ' . esc_html($aIngest->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - aIngest : %1$s-%2$s', $aIngest->get_error_code(), $aIngest->get_error_message()));
        return false;
    }
    /* echo "<br />DEBUG  4 ", date ( 'Y-m-d H:i:s' ), var_export( $aIngest, true ); */
    /**
     * Upload the MODS file to the Fedora server temp file storage.
     */
    $uploadMODS = $fedora_api->upload(array('file' => $MODS_file));
    if (is_wp_error($uploadMODS)) {
        echo 'Error - uploadMODS : ' . esc_html($uploadMODS->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - uploadMODS : %1$s-%2$s', $uploadMODS->get_error_code(), $uploadMODS->get_error_message()));
    }
    /* echo "<br />DEBUG  5 ", date ( 'Y-m-d H:i:s' ), var_export( $uploadMODS, true ); */
    /**
     * Create the descMetadata datastream for the aggregator object.
     */
    $mContent = $fedora_api->add_datastream(array('pid' => $nextPids[0], 'dsID' => 'descMetadata', 'controlGroup' => 'M', 'dsLocation' => $uploadMODS, 'dsLabel' => $metadata['title'], 'versionable' => true, 'dsState' => 'A', 'mimeType' => 'text/xml', 'content' => false));
    if (is_wp_error($mContent)) {
        echo esc_html('Error - mContent : ' . $mContent->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - mContent : %1$s-%2$s', $mContent->get_error_code(), $mContent->get_error_message()));
    }
    /* echo "<br />DEBUG 5.1 ", date ( 'Y-m-d H:i:s' ), var_export( $mContent, true ); */
    $rIngest = $fedora_api->ingest(array('xmlContent' => $resourceFoxml));
    if (is_wp_error($rIngest)) {
        echo esc_html('Error - rIngest : ' . $rIngest->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - rIngest : %1$s-%2$s', $rIngest->get_error_code(), $rIngest->get_error_message()));
    }
    /* echo "<br />DEBUG  6 ", date ( 'Y-m-d H:i:s' ), var_export( $rIngest, true ); */
    /**
     * Upload the deposit to the Fedora server temp file storage.
     */
    $uploadUrl = $fedora_api->upload(array('file' => $renamed_file, 'filename' => $filename, 'filetype' => $filetype));
    if (is_wp_error($uploadUrl)) {
        echo 'Error - uploadUrl : ' . esc_html($uploadUrl->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - uploadUrl (1) : %1$s-%2$s', $uploadUrl->get_error_code(), $uploadUrl->get_error_message()));
    }
    /* echo "<br />DEBUG  7 ", date ( 'Y-m-d H:i:s' ), var_export( $uploadUrl, true ); */
    /**
     * Create the CONTENT datastream for the resource object.
     */
    $rContent = $fedora_api->add_datastream(array('pid' => $nextPids[1], 'dsID' => $datastream_id, 'controlGroup' => 'M', 'dsLocation' => $uploadUrl, 'dsLabel' => $filename, 'versionable' => true, 'dsState' => 'A', 'mimeType' => $filetype, 'content' => false));
    if (is_wp_error($rContent)) {
        echo 'Error - rContent : ' . esc_html($rContent->get_error_message());
        error_log(sprintf('*****HumCORE Deposit Error***** - rContent : %1$s-%2$s', $rContent->get_error_code(), $rContent->get_error_message()));
    }
    /* echo "<br />DEBUG  8 ", date ( 'Y-m-d H:i:s' ), var_export( $rContent, true ); */
    /**
     * Upload the thumb to the Fedora server temp file storage if necessary.
     */
    if (preg_match('~^image/~', $check_filetype['type'])) {
        $uploadUrl = $fedora_api->upload(array('file' => $generated_thumb_path, 'filename' => $generated_thumb_name, 'filetype' => $generated_thumb_mime));
        if (is_wp_error($uploadUrl)) {
            echo 'Error - uploadUrl : ' . esc_html($uploadUrl->get_error_message());
            error_log(sprintf('*****HumCORE Deposit Error***** - uploadUrl (2) : %1$s-%2$s', $uploadUrl->get_error_code(), $uploadUrl->get_error_message()));
        }
        /* echo "<br />DEBUG  8.1 ", date ( 'Y-m-d H:i:s' ), var_export( $uploadUrl, true ); */
        /**
         * Create the THUMB datastream for the resource object if necessary.
         */
        $tContent = $fedora_api->add_datastream(array('pid' => $nextPids[1], 'dsID' => $thumb_datastream_id, 'controlGroup' => 'M', 'dsLocation' => $uploadUrl, 'dsLabel' => $generated_thumb_name, 'versionable' => true, 'dsState' => 'A', 'mimeType' => $generated_thumb_mime, 'content' => false));
        if (is_wp_error($tContent)) {
            echo 'Error - tContent : ' . esc_html($tContent->get_error_message());
            error_log(sprintf('*****HumCORE Deposit Error***** - tContent : %1$s-%2$s', $tContent->get_error_code(), $tContent->get_error_message()));
        }
        /* echo "<br />DEBUG  8.2 ", date ( 'Y-m-d H:i:s' ), var_export( $tContent, true ); */
    }
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit fedora/solr writes complete');
    }
    /**
     * Prepare an array of post data for the resource post.
     */
    $resource_post_data = array('post_title' => $filename, 'post_status' => 'publish', 'post_type' => 'humcore_deposit', 'post_name' => $nextPids[1], 'post_author' => bp_loggedin_user_id(), 'post_parent' => $deposit_post_ID);
    /**
     * Insert the resource post.
     */
    $resource_id = wp_insert_post($resource_post_data);
    $local_link = sprintf(bp_get_root_domain() . '/deposits/item/%s/', $nextPids[0]);
    /**
     * Add the activity entry for the author.
     */
    $activity_ID = humcore_new_deposit_activity($deposit_post_ID, $metadata['abstract'], $local_link);
    /**
     * Publish the reserved DOI.
     */
    if (!empty($metadata['deposit_doi'])) {
        $eStatus = humcore_publish_handle($metadata['deposit_doi']);
        if (false === $eStatus) {
            echo '<h3>', __('There was an EZID API error, the DOI was not sucessfully published.', 'humcore_domain'), '</h3><br />';
        }
        if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
            humcore_write_error_log('HumCORE deposit DOI published');
        }
    }
    /**
     * Add any group activity entries.
     */
    $group_activity_ids = array();
    // Moving here due to possible timeout issues.
    if (!empty($_POST['deposit-group'])) {
        foreach ($_POST['deposit-group'] as $group_id) {
            $group_activity_ids[] = humcore_new_group_deposit_activity($deposit_post_ID, sanitize_text_field($group_id), $metadata['abstract'], $local_link);
        }
    }
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('HumCORE deposit transaction complete');
    }
    echo '<h3>', __('Deposit complete!', 'humcore_domain'), '</h3><br />';
    return $nextPids[0];
}
Example #2
0
/**
 * Save any changes to custom metadata
 *
 * @param int $post_id The ID of the post being saved.
 */
function humcore_deposit_metabox_save($post_id)
{
    /*
     * We need to verify this came from our screen and with proper authorization,
     * because the save_post action can be triggered at other times.
     */
    // Check if our nonce is set.
    if (!isset($_POST['deposit_metabox_noncename'])) {
        return $post_id;
    }
    // Verify that the nonce is valid.
    if (!wp_verify_nonce($_POST['deposit_metabox_noncename'], 'humcore_deposit_metabox')) {
        return $post_id;
    }
    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    // Check the user's permissions.
    if (isset($_POST['post_type']) && 'page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } else {
        if (!current_user_can('edit_post', $post_id)) {
            return $post_id;
        }
    }
    // Make sure that at least the ID is set.
    if (!isset($_POST['aggregator_id'])) {
        return $post_id;
    }
    global $fedora_api, $solr_client;
    $aggregator_metadata = json_decode(get_post_meta($post_id, '_deposit_metadata', true), true);
    $current_groups = $aggregator_metadata['group'];
    $current_group_ids = $aggregator_metadata['group_ids'];
    $current_subjects = $aggregator_metadata['subject'];
    $current_subject_ids = $aggregator_metadata['subject_ids'];
    $current_keywords = $aggregator_metadata['keyword'];
    $current_keyword_ids = $aggregator_metadata['keyword_ids'];
    // No changes allowed.
    // $aggregator_metadata['id'] = sanitize_text_field( $_POST['aggregator_id'] );
    // $aggregator_metadata['pid'] = sanitize_text_field( $_POST['aggregator_pid'] );
    // $aggregator_metadata['creator'] = sanitize_text_field( $_POST['aggregator_creator'] );
    // Sanitize user input.
    $aggregator_metadata['title'] = sanitize_text_field(stripslashes($_POST['aggregator_title_unchanged']));
    $aggregator_metadata['title_unchanged'] = wp_kses(stripslashes($_POST['aggregator_title_unchanged']), array('b' => array(), 'em' => array(), 'strong' => array()));
    $aggregator_metadata['abstract'] = sanitize_text_field(stripslashes($_POST['aggregator_abstract_unchanged']));
    $aggregator_metadata['abstract_unchanged'] = wp_kses(stripslashes($_POST['aggregator_abstract_unchanged']), array('b' => array(), 'em' => array(), 'strong' => array()));
    $aggregator_metadata['genre'] = sanitize_text_field($_POST['aggregator_genre']);
    $aggregator_metadata['organization'] = sanitize_text_field(stripslashes($_POST['aggregator_organization']));
    $aggregator_metadata['institution'] = sanitize_text_field(stripslashes($_POST['aggregator_institution']));
    $aggregator_metadata['conference_title'] = sanitize_text_field(stripslashes($_POST['aggregator_conference_title']));
    $aggregator_metadata['conference_organization'] = sanitize_text_field(stripslashes($_POST['aggregator_conference_organization']));
    // No changes allowed.
    //$aggregator_metadata['committee_deposit'] = sanitize_text_field( $_POST['aggregator_committee_deposit'] );
    //$aggregator_metadata['committee_id'] = sanitize_text_field( $_POST['aggregator_committee_id'] );
    //$aggregator_metadata['submitter'] = sanitize_text_field( $_POST['aggregator_submitter'] );
    $aggregator_metadata['authors'] = array();
    $authors = array();
    $authors = array_map(function ($given, $family, $fullname, $uni, $role, $affiliation) {
        return array('given' => sanitize_text_field(stripslashes($given)), 'family' => sanitize_text_field(stripslashes($family)), 'fullname' => sanitize_text_field(stripslashes($fullname)), 'uni' => sanitize_text_field(stripslashes($uni)), 'role' => sanitize_text_field(stripslashes($role)), 'affiliation' => sanitize_text_field(stripslashes($affiliation)));
    }, $_POST['aggregator_author_given'], $_POST['aggregator_author_family'], $_POST['aggregator_author_fullname'], $_POST['aggregator_author_uni'], $_POST['aggregator_author_role'], $_POST['aggregator_author_affiliation']);
    foreach ($authors as $author) {
        if (!empty($author['given']) || !empty($author['family']) || !empty($author['fullname'])) {
            $aggregator_metadata['authors'][] = $author;
        }
    }
    $aggregator_metadata['author_info'] = humcore_deposits_format_author_info($aggregator_metadata['authors']);
    $aggregator_metadata['group'] = array();
    $aggregator_metadata['group_ids'] = array();
    if (!empty($_POST['aggregator_group'])) {
        foreach ($_POST['aggregator_group'] as $group_id) {
            $group = groups_get_group(array('group_id' => sanitize_text_field($group_id)));
            if (!empty($group)) {
                $aggregator_metadata['group'][] = $group->name;
                $aggregator_metadata['group_ids'][] = $group_id;
            }
        }
    }
    $aggregator_metadata['subject'] = array();
    if (!empty($_POST['aggregator_subject'])) {
        foreach ($_POST['aggregator_subject'] as $subject) {
            $aggregator_metadata['subject'][] = sanitize_text_field(stripslashes($subject));
        }
        if ($aggregator_metadata['subject'] != $current_subjects) {
            $term_ids = array();
            $aggregator_metadata['subject_ids'] = array();
            foreach ($_POST['aggregator_subject'] as $subject) {
                $term_key = term_exists($subject, 'humcore_deposit_subject');
                if (!is_wp_error($term_key)) {
                    $term_ids[] = intval($term_key['term_id']);
                } else {
                    error_log('*****WP Admin HumCORE Deposit Meta Update Subject Error*****' . var_export($term_key, true));
                }
            }
            // Support add and remove.
            $term_taxonomy_ids = wp_set_object_terms($post_id, $term_ids, 'humcore_deposit_subject');
            $aggregator_metadata['subject_ids'] = $term_taxonomy_ids;
        }
    }
    $aggregator_metadata['keyword'] = array();
    if (!empty($_POST['aggregator_keyword'])) {
        foreach ($_POST['aggregator_keyword'] as $keyword) {
            $aggregator_metadata['keyword'][] = sanitize_text_field(stripslashes($keyword));
        }
        if ($aggregator_metadata['keyword'] != $current_keywords) {
            $term_ids = array();
            $aggregator_metadata['keyword_ids'] = array();
            foreach ($_POST['aggregator_keyword'] as $keyword) {
                $term_key = term_exists($keyword, 'humcore_deposit_tag');
                if (empty($term_key)) {
                    $term_key = wp_insert_term(strtolower(sanitize_text_field($keyword)), 'humcore_deposit_tag');
                }
                if (!is_wp_error($term_key)) {
                    $term_ids[] = intval($term_key['term_id']);
                } else {
                    error_log('*****WP Admin HumCORE Deposit Meta Update Keyword Error*****' . var_export($term_key, true));
                }
            }
            // Support add and remove.
            $term_taxonomy_ids = wp_set_object_terms($post_id, $term_ids, 'humcore_deposit_tag');
            $aggregator_metadata['keyword_ids'] = $term_taxonomy_ids;
        }
    }
    $aggregator_metadata['type_of_resource'] = sanitize_text_field($_POST['aggregator_type_of_resource']);
    $aggregator_metadata['language'] = sanitize_text_field($_POST['aggregator_language']);
    $aggregator_metadata['notes'] = sanitize_text_field(stripslashes($_POST['aggregator_notes']));
    $aggregator_metadata['notes_unchanged'] = sanitize_text_field(stripslashes($_POST['aggregator_notes_unchanged']));
    $aggregator_metadata['notes_unchanged'] = wp_kses(stripslashes($_POST['aggregator_notes_unchanged']), array('b' => array(), 'em' => array(), 'strong' => array()));
    $aggregator_metadata['type_of_license'] = sanitize_text_field($_POST['aggregator_type_of_license']);
    // No changes allowed.
    // $aggregator_metadata['record_content_source'] = sanitize_text_field( $_POST['aggregator_record_content_source'] );
    // $aggregator_metadata['record_creation_date'] = sanitize_text_field( $_POST['aggregator_record_creation_date'] );
    // $aggregator_metadata['member_of'] = sanitize_text_field( $_POST['aggregator_member_of'] );
    $aggregator_metadata['publication-type'] = sanitize_text_field($_POST['aggregator_publication-type']);
    $aggregator_metadata['publisher'] = sanitize_text_field(stripslashes($_POST['aggregator_publisher']));
    $aggregator_metadata['date'] = sanitize_text_field($_POST['aggregator_date']);
    $aggregator_metadata['date_issued'] = sanitize_text_field($_POST['aggregator_date_issued']);
    $aggregator_metadata['doi'] = sanitize_text_field($_POST['aggregator_doi']);
    $aggregator_metadata['book_journal_title'] = sanitize_text_field(stripslashes($_POST['aggregator_book_journal_title']));
    $aggregator_metadata['book_author'] = sanitize_text_field(stripslashes($_POST['aggregator_book_author']));
    $aggregator_metadata['chapter'] = sanitize_text_field($_POST['aggregator_chapter']);
    $aggregator_metadata['volume'] = sanitize_text_field($_POST['aggregator_volume']);
    $aggregator_metadata['issue'] = sanitize_text_field($_POST['aggregator_issue']);
    $aggregator_metadata['start_page'] = sanitize_text_field($_POST['aggregator_start_page']);
    $aggregator_metadata['end_page'] = sanitize_text_field($_POST['aggregator_end_page']);
    $aggregator_metadata['isbn'] = sanitize_text_field($_POST['aggregator_isbn']);
    $aggregator_metadata['issn'] = sanitize_text_field($_POST['aggregator_issn']);
    $aggregator_metadata['handle'] = sanitize_text_field($_POST['aggregator_handle']);
    $aggregator_metadata['deposit_doi'] = sanitize_text_field($_POST['aggregator_deposit_doi']);
    // No changes allowed.
    // $aggregator_metadata['record_identifier'] = sanitize_text_field( $_POST['aggregator_record_identifier'] );
    $json_aggregator_metadata = json_encode($aggregator_metadata, JSON_HEX_APOS);
    // Update the meta field in the database.
    $post_meta_ID = update_post_meta($post_id, '_deposit_metadata', wp_slash($json_aggregator_metadata));
    if (defined('CORE_ERROR_LOG') && '' != CORE_ERROR_LOG) {
        humcore_write_error_log('WP Admin HumCORE Deposit Meta Update', $json_aggregator_metadata);
    }
    // Reindex solr doc.
    $resource_file_metadata = json_decode(get_post_meta($post_id, '_deposit_file_metadata', true), true);
    if (!empty($resource_file_metadata)) {
        $resource_pid = $resource_file_metadata['files'][0]['pid'];
        $resource_datastream_id = $resource_file_metadata['files'][0]['datastream_id'];
        $resource_filename = $resource_file_metadata['files'][0]['filename'];
        $resource_filetype = $resource_file_metadata['files'][0]['filetype'];
        $resource_filesize = $resource_file_metadata['files'][0]['filesize'];
        $resource_fileloc = $resource_file_metadata['files'][0]['fileloc'];
        $check_resource_filetype = wp_check_filetype($resource_filename, wp_get_mime_types());
        $resource_file_prefix = str_replace($resource_filename, '', $resource_fileloc);
        $resource_MODS_file = $resource_file_prefix . 'MODS.' . $resource_filename . '.xml';
        $thesePids = array($aggregator_metadata['pid'], $resource_pid);
        $metadata_MODS = create_mods_xml($aggregator_metadata);
        $file_write_status = file_put_contents($resource_MODS_file, $metadata_MODS);
        $upload_MODS = $fedora_api->upload(array('file' => $resource_MODS_file));
        if (is_wp_error($upload_MODS)) {
            echo 'Error - uploadMODS : ' . esc_html($upload_MODS->get_error_message());
            error_log(sprintf('*****WP Admin HumCORE Deposit Error***** - uploadMODS : %1$s-%2$s', $upload_MODS->get_error_code(), $upload_MODS->get_error_message()));
        }
        $mContent = $fedora_api->modify_datastream(array('pid' => $thesePids[0], 'dsID' => 'descMetadata', 'dsLocation' => $upload_MODS, 'dsLabel' => $aggregator_metadata['title'], 'mimeType' => 'text/xml', 'content' => false));
        if (is_wp_error($mContent)) {
            echo esc_html('Error - mContent : ' . $mContent->get_error_message());
            error_log(sprintf('*****WP Admin HumCORE Deposit Error***** - mContent : %1$s-%2$s', $mContent->get_error_code(), $mContent->get_error_message()));
        }
        $resource_Xml = create_resource_xml($aggregator_metadata, $resource_filetype);
        $rContent = $fedora_api->modify_datastream(array('pid' => $thesePids[1], 'dsID' => 'DC', 'mimeType' => 'text/xml', 'content' => $resource_Xml));
        if (is_wp_error($rContent)) {
            echo 'Error - rContent : ' . esc_html($rContent->get_error_message());
            error_log(sprintf('*****WP Admin HumCORE Deposit Error***** - rContent : %1$s-%2$s', $rContent->get_error_code(), $rContent->get_error_message()));
        }
        try {
            if (preg_match('~^audio/|^image/|^video/~', $check_resource_filetype['type'])) {
                $sResult = $solr_client->create_humcore_document('', $aggregator_metadata);
            } else {
                $sResult = $solr_client->create_humcore_extract($resource_fileloc, $aggregator_metadata);
            }
        } catch (Exception $e) {
            echo '<h3>', __('An error occurred while depositing your file!', 'humcore_domain'), '</h3>';
            error_log(sprintf('*****WP Admin HumCORE Deposit Error***** - solr : %1$s-%2$s', $e->getCode(), $e->getMessage()));
            return $post_id;
        }
        // Handle doi metadata changes.
        if (!empty($aggregator_metadata['deposit_doi'])) {
            $creators = array();
            foreach ($aggregator_metadata['authors'] as $author) {
                if ('author' === $author['role'] && !empty($author['fullname'])) {
                    $creators[] = $author['fullname'];
                }
            }
            $creator_list = implode(',', $creators);
            $eStatus = humcore_modify_handle($aggregator_metadata['deposit_doi'], $aggregator_metadata['title'], $creator_list, $aggregator_metadata['genre'], $aggregator_metadata['date_issued'], $aggregator_metadata['publisher']);
            if (false === $eStatus) {
                echo '<h3>', __('There was an EZID API error, the DOI was not sucessfully published.', 'humcore_domain'), '</h3><br />';
            }
        }
    }
    return $post_id;
}