Example #1
0
 private static function import_attachment_for_post($prim_key, $data, $post_id, $download = true)
 {
     $remotefile = $data['url'];
     $title = $data['title'];
     $localfile = isset($data['file']) ? $data['file'] : basename($remotefile);
     $post = self::get_post($prim_key);
     if ($post == null) {
         if ($download) {
             $contents = ojsaccess::get_content($remotefile);
             if ($contents == FALSE) {
                 return new WP_Error('download_failed', __("Could not get file:") . $remotefile . ' for post:' . $prim_key);
             }
             $upload = wp_upload_bits($localfile, null, $contents);
             if ($upload['error'] != false) {
                 return new WP_Error('upload_failed', __("Could not upload file:") . $remotefile . ' for post:' . $prim_key . ':' . $upload['error']);
             }
             $filename = $upload['file'];
         } else {
             $filename = $remotefile;
         }
         $wp_filetype = wp_check_filetype(basename($filename), null);
         $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => $title, 'post_excerpt' => $title, 'guid' => $remotefile, 'post_content' => '', 'post_status' => 'publish');
         $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
         $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
         wp_update_attachment_metadata($attach_id, $attach_data);
         add_post_meta($attach_id, "_prim_key", $prim_key, true);
         add_post_meta($attach_id, "_post_type", 'ojsimport', true);
     } else {
         if ($post->guid != $remotefile) {
             // filename changed, delete this attachment and create a new one
             wp_delete_post($post->ID, true);
             $attach_id = self::import_attachment_for_post($prim_key, $data, $post_id, $download);
         } else {
             //XXX: update the attachment? then we need a hash or something
             // only update title
             $post->post_title = $title;
             $post->post_excerpt = $title;
             $attach_id = wp_update_post($post);
         }
     }
     if (!is_wp_error($attach_id)) {
         // mark the attachment as imported
         unset(self::$global_imported_posts[$attach_id]);
     }
     return $attach_id;
 }