/* metaweblog.newMediaObject uploads a file, following your settings */
function mw_newMediaObject
($args) {
// adapted from a patch by Johann Richard
// http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
global $wpdb;
$blog_ID = (int) $args[0];
$user_login = $wpdb->escape($args[1]);
$user_pass = $wpdb->escape($args[2]);
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
logIO
('O',
'(MW) Received '.
strlen($bits).
' bytes');
if ( !$this->login_pass_ok($user_login, $user_pass) )
return $this->error;
set_current_user(0, $user_login);
if ( !current_user_can('upload_files') ) {
logIO('O', '(MW) User does not have upload_files capability');
$this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
return $this->error;
}
if ( $upload_err = apply_filters( "pre_upload_error", false ) )
return new IXR_Error(500, $upload_err);
if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
// Get postmeta info on the object.
$old_file = $wpdb->get_row("
SELECT ID
FROM {$wpdb->posts}
WHERE post_title = '{$name}'
AND post_type = 'attachment'
");
// Delete previous file.
wp_delete_attachment($old_file->ID);
// Make sure the new name is different by pre-pending the
// previous post id.
$filename = preg_replace("/^wpid\d+-/", "", $name);
$name = "wpid{$old_file->ID}-{$filename}";
}
$upload = wp_upload_bits($name, $type, $bits, $overwrite);
if ( ! empty($upload['error']) ) {
$errorString = 'Could not write file ' . $name . ' (' . $upload['error'] . ')';
logIO('O', '(MW) ' . $errorString);
return new IXR_Error(500, $errorString);
}
// Construct the attachment array
// attach to post_id -1
$post_id = -1;
$attachment = array(
'post_title' => $name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $upload[ 'url' ]
);
// Save the data
$id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
}