/**
 * Saves the entity URL for the specified post ID (set via the *save_post* hook).
 *
 * @param int $post_id The post ID.
 *
 * @return int|null
 */
function wl_entity_type_save_custom_fields($post_id)
{
    // Check if our nonce is set.
    if (!isset($_POST['wordlift_entity_box_nonce'])) {
        return $post_id;
    }
    $nonce = $_POST['wordlift_entity_box_nonce'];
    // Verify that the nonce is valid.
    if (!wp_verify_nonce($nonce, 'wordlift_entity_box')) {
        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 ('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;
        }
    }
    // save the entity URL.
    wl_set_entity_uri($post_id, $_POST['entity_url']);
    /*
    	// save the rdf:type values.
    	wl_set_entity_rdf_types(
    		$post_id,
    		explode( "\r\n", $_POST['entity_types'] )
    	);
    */
}
 /**
  * Only accept URIs or local entity IDs.
  * Build new entity if the user inputted a name that is not present in DB.
  */
 public function sanitize_data_filter($value)
 {
     if (empty($value)) {
         return null;
     }
     // Check that the inserted URI, ID or name does not point to a saved entity.
     if (is_numeric($value)) {
         $absent_from_db = is_null(get_post($value));
         // search by ID
     } else {
         $absent_from_db = is_null(wl_get_entity_post_by_uri($value)) && is_null(get_page_by_title($value, OBJECT, Wordlift_Entity_Service::TYPE_NAME));
         // search by name
     }
     // Is it an URI?
     $name_is_uri = strpos($value, 'http') === 0;
     // We create a new entity only if the entity is not present in the DB.
     // In the case of an external uri, we just save the uri.
     if ($absent_from_db && !$name_is_uri) {
         // ...we create a new entity!
         $new_entity_id = wp_insert_post(array('post_status' => 'publish', 'post_type' => Wordlift_Entity_Service::TYPE_NAME, 'post_title' => $value));
         $new_entity = get_post($new_entity_id);
         $type = 'http://schema.org/' . (isset($this->expected_uri_type) ? $this->expected_uri_type[0] : 'Thing');
         wl_set_entity_main_type($new_entity_id, $type);
         // Build uri for this entity
         $new_uri = wl_build_entity_uri($new_entity_id);
         wl_set_entity_uri($new_entity_id, $new_uri);
         wl_push_entity_post_to_redlink($new_entity);
         // Update the value that will be saved as meta
         $value = $new_entity_id;
     }
     return $value;
 }
/**
 * Save the specified data as an entity in WordPress. This method only create new entities. When an existing entity is
 * found (by its URI), then the original post is returned.
 *
 * @param array $entity_properties, associative array containing: 
 * string 'uri' The entity URI.
 * string 'label' The entity label.
 * string 'main_type_uri' The entity type URI.
 * string 'description' The entity description.
 * array 'type_uris' An array of entity type URIs.
 * array 'images' An array of image URLs.
 * int 'related_post_id' A related post ID.
 * array 'same_as' An array of sameAs URLs.
 *
 * @return null|WP_Post A post instance or null in case of failure.
 */
function wl_save_entity($entity_properties)
{
    $uri = $entity_properties['uri'];
    $label = $entity_properties['label'];
    $type_uri = $entity_properties['main_type_uri'];
    $description = $entity_properties['description'];
    $entity_types = $entity_properties['type_uris'];
    $images = $entity_properties['images'];
    $related_post_id = $entity_properties['related_post_id'];
    $same_as = $entity_properties['same_as'];
    // Avoid errors due to null.
    if (is_null($entity_types)) {
        $entity_types = array();
    }
    wl_write_log("[ uri :: {$uri} ][ label :: {$label} ][ type uri :: {$type_uri} ]");
    // Prepare properties of the new entity.
    $params = array('post_status' => is_numeric($related_post_id) ? get_post_status($related_post_id) : 'draft', 'post_type' => WL_ENTITY_TYPE_NAME, 'post_title' => $label, 'post_content' => $description, 'post_excerpt' => '');
    // Check whether an entity already exists with the provided URI.
    $post = wl_get_entity_post_by_uri($uri);
    if (null !== $post) {
        // We insert into the params the entity ID, so it will be updated and not inserted.
        $params['ID'] = $post->ID;
    }
    // create or update the post.
    $post_id = wp_insert_post($params, true);
    // TODO: handle errors.
    if (is_wp_error($post_id)) {
        wl_write_log(': error occurred');
        // inform an error occurred.
        return null;
    }
    wl_set_entity_main_type($post_id, $type_uri);
    // Save the entity types.
    wl_set_entity_rdf_types($post_id, $entity_types);
    // Get a dataset URI for the entity.
    $wl_uri = wl_build_entity_uri($post_id);
    // Save the entity URI.
    wl_set_entity_uri($post_id, $wl_uri);
    // Add the uri to the sameAs data if it's not a local URI.
    if ($wl_uri !== $uri) {
        array_push($same_as, $uri);
    }
    $new_uri = wl_get_entity_uri($post_id);
    // Save the sameAs data for the entity.
    wl_schema_set_value($post_id, 'sameAs', $same_as);
    // Call hooks.
    do_action('wl_save_entity', $post_id);
    wl_write_log("[ post id :: {$post_id} ][ uri :: {$uri} ][ label :: {$label} ][ wl uri :: {$wl_uri} ][ types :: " . implode(',', $entity_types) . " ][ images count :: " . count($images) . " ][ same_as count :: " . count($same_as) . " ]");
    foreach ($images as $image_remote_url) {
        // Check if image is already present in local DB
        if (strpos($image_remote_url, site_url()) !== false) {
            // Do nothing.
            continue;
        }
        // Check if there is an existing attachment for this post ID and source URL.
        $existing_image = wl_get_attachment_for_source_url($post_id, $image_remote_url);
        // Skip if an existing image is found.
        if (null !== $existing_image) {
            continue;
        }
        // Save the image and get the local path.
        $image = wl_save_image($image_remote_url);
        // Get the local URL.
        $filename = $image['path'];
        $url = $image['url'];
        $content_type = $image['content_type'];
        $attachment = array('guid' => $url, 'post_title' => $label, 'post_content' => '', 'post_status' => 'inherit', 'post_mime_type' => $content_type);
        // Create the attachment in WordPress and generate the related metadata.
        $attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
        // Set the source URL for the image.
        wl_set_source_url($attachment_id, $image_remote_url);
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        // Set it as the featured image.
        set_post_thumbnail($post_id, $attachment_id);
    }
    // The entity is pushed to Redlink on save by the function hooked to save_post.
    // save the entity in the triple store.
    wl_linked_data_push_to_redlink($post_id);
    // finally return the entity post.
    return get_post($post_id);
}
/**
 * Get the entity URI of the provided post.
 *
 * @uses wl_build_entity_uri() to create a new URI if the entity doesn't have an URI yet.
 * @uses wl_set_entity_uri() to set a newly create URI.
 *
 * @param int $post_id The post ID.
 *
 * @return string|null The URI of the entity or null if not configured.
 */
function wl_get_entity_uri($post_id)
{
    $uri = get_post_meta($post_id, WL_ENTITY_URL_META_NAME, true);
    // If the dataset uri is not properly configured, null is returned
    if ('' === wl_configuration_get_redlink_dataset_uri()) {
        return null;
    }
    // Set the URI if it isn't set yet.
    $post_status = get_post_status($post_id);
    if (empty($uri) && 'auto-draft' !== $post_status && 'revision' !== $post_status) {
        $uri = wl_build_entity_uri($post_id);
        //  "http://data.redlink.io/$user_id/$dataset_id/post/$post->ID";
        wl_set_entity_uri($post_id, $uri);
    }
    return $uri;
}
/**
 * Save the specified data as an entity in WordPress. This method only create new entities. When an existing entity is
 * found (by its URI), then the original post is returned.
 *
 * @param array $entity_data, associative array containing: 
 * string 'uri'             The entity URI.
 * string 'label'           The entity label.
 * string 'main_type'       The entity type URI.
 * array  'type'            An array of entity type URIs.
 * string 'description'     The entity description.
 * array  'images'          An array of image URLs.
 * int    'related_post_id' A related post ID.
 * array  'same_as'         An array of sameAs URLs.
 *
 * @return null|WP_Post A post instance or null in case of failure.
 */
function wl_save_entity($entity_data)
{
    $uri = $entity_data['uri'];
    $label = $entity_data['label'];
    $type_uri = $entity_data['main_type'];
    $entity_types = isset($entity_data['type']) ? $entity_data['type'] : array();
    $description = $entity_data['description'];
    $images = isset($entity_data['image']) ? wl_force_to_array($entity_data['image']) : array();
    $same_as = isset($entity_data['sameas']) ? wl_force_to_array($entity_data['sameas']) : array();
    $related_post_id = isset($entity_data['related_post_id']) ? $entity_data['related_post_id'] : null;
    $other_properties = isset($entity_data['properties']) ? $entity_data['properties'] : array();
    // wl_write_log( "[ uri :: $uri ][ label :: $label ][ type uri :: $type_uri ]" );
    // Prepare properties of the new entity.
    $params = array('post_status' => is_numeric($related_post_id) ? get_post_status($related_post_id) : 'draft', 'post_type' => Wordlift_Entity_Service::TYPE_NAME, 'post_title' => $label, 'post_content' => $description, 'post_excerpt' => '');
    // Check whether an entity already exists with the provided URI.
    $post = wl_get_entity_post_by_uri($uri);
    if (null !== $post) {
        // We insert into the params the entity ID, so it will be updated and not inserted.
        $params['ID'] = $post->ID;
        // Preserve the current entity status
        if ('public' === $post->post_status) {
            $params['post_status'] = $post->post_status;
        }
        // Preserve the current entity post_content.
        $params['post_content'] = $post->post_content;
        // Preserve the entity post_title to avoid de-synch between WP and RL
        // See: https://github.com/insideout10/wordlift-plugin/issues/221
        $params['post_title'] = $post->post_title;
    }
    // If Yoast is installed and active, we temporary remove the save_postdata hook which causes Yoast to "pass over"
    // the local SEO form values to the created entity (https://github.com/insideout10/wordlift-plugin/issues/156)
    // Same thing applies to SEO Ultimate (https://github.com/insideout10/wordlift-plugin/issues/148)
    // This does NOT affect saving an entity from the entity admin page since this function is called when an entity
    // is created when saving a post.
    global $wpseo_metabox, $seo_ultimate;
    if (isset($wpseo_metabox)) {
        remove_action('wp_insert_post', array($wpseo_metabox, 'save_postdata'));
    }
    if (isset($seo_ultimate)) {
        remove_action('save_post', array($seo_ultimate, 'save_postmeta_box'));
    }
    // The fact that we're calling here wp_insert_post is causing issues with plugins (and ourselves too) that hook to
    // save_post in order to save additional inputs from the edit page. In order to avoid issues, we pop all the hooks
    // to the save_post and restore them after we saved the entity.
    // see https://github.com/insideout10/wordlift-plugin/issues/203
    // see https://github.com/insideout10/wordlift-plugin/issues/156
    // see https://github.com/insideout10/wordlift-plugin/issues/148
    global $wp_filter;
    $save_post_filters = $wp_filter['save_post'];
    $wp_filter['save_post'] = array();
    // create or update the post.
    $post_id = wp_insert_post($params, true);
    // Restore all the existing filters.
    $wp_filter['save_post'] = $save_post_filters;
    // If Yoast is installed and active, we restore the Yoast save_postdata hook (https://github.com/insideout10/wordlift-plugin/issues/156)
    if (isset($wpseo_metabox)) {
        add_action('wp_insert_post', array($wpseo_metabox, 'save_postdata'));
    }
    // If SEO Ultimate is installed, add back the hook we removed a few lines above.
    if (isset($seo_ultimate)) {
        add_action('save_post', array($seo_ultimate, 'save_postmeta_box'), 10, 2);
    }
    // TODO: handle errors.
    if (is_wp_error($post_id)) {
        wl_write_log(': error occurred');
        // inform an error occurred.
        return null;
    }
    wl_set_entity_main_type($post_id, $type_uri);
    // Save the entity types.
    wl_set_entity_rdf_types($post_id, $entity_types);
    // Get a dataset URI for the entity.
    $wl_uri = wl_build_entity_uri($post_id);
    // Save the entity URI.
    wl_set_entity_uri($post_id, $wl_uri);
    // Add the uri to the sameAs data if it's not a local URI.
    if ($wl_uri !== $uri) {
        array_push($same_as, $uri);
    }
    $new_uri = wl_get_entity_uri($post_id);
    // Save the sameAs data for the entity.
    wl_schema_set_value($post_id, 'sameAs', $same_as);
    // Save the other properties (latitude, langitude, startDate, endDate, etc.)
    foreach ($other_properties as $property_name => $property_value) {
        wl_schema_set_value($post_id, $property_name, $property_value);
    }
    // Call hooks.
    do_action('wl_save_entity', $post_id);
    wl_write_log("[ post id :: {$post_id} ][ uri :: {$uri} ][ label :: {$label} ][ wl uri :: {$wl_uri} ][ types :: " . implode(',', $entity_types) . " ][ images count :: " . count($images) . " ][ same_as count :: " . count($same_as) . " ]");
    foreach ($images as $image_remote_url) {
        // Check if image is already present in local DB
        if (strpos($image_remote_url, site_url()) !== false) {
            // Do nothing.
            continue;
        }
        // Check if there is an existing attachment for this post ID and source URL.
        $existing_image = wl_get_attachment_for_source_url($post_id, $image_remote_url);
        // Skip if an existing image is found.
        if (null !== $existing_image) {
            continue;
        }
        // Save the image and get the local path.
        $image = wl_save_image($image_remote_url);
        // Get the local URL.
        $filename = $image['path'];
        $url = $image['url'];
        $content_type = $image['content_type'];
        $attachment = array('guid' => $url, 'post_title' => $label, 'post_content' => '', 'post_status' => 'inherit', 'post_mime_type' => $content_type);
        // Create the attachment in WordPress and generate the related metadata.
        $attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
        // Set the source URL for the image.
        wl_set_source_url($attachment_id, $image_remote_url);
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        // Set it as the featured image.
        set_post_thumbnail($post_id, $attachment_id);
    }
    // The entity is pushed to Redlink on save by the function hooked to save_post.
    // save the entity in the triple store.
    wl_linked_data_push_to_redlink($post_id);
    // finally return the entity post.
    return get_post($post_id);
}