Skip to content

Commit

Permalink
work for the #41
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitry-kurmanov committed Feb 1, 2024
1 parent 60d5202 commit 237430d
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 28 deletions.
28 changes: 28 additions & 0 deletions src/trunk/ajax_handlers/delete_file.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

include_once("ajax_handler.php");
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

class SurveyJS_DeleteFile extends SurveyJS_AJAX_Handler {

function __construct() {
parent::__construct("SurveyJS_DeleteFile", false);
}

function callback() {
if($_SERVER['REQUEST_METHOD'] === 'GET') {
$filename = $_GET["name"];

if (str_contains($filename, "/uploads/surveyjs")) {
$uploadpath = substr($filename, strpos($filename, "/surveyjs"));
$upload_dir=wp_upload_dir();
$fullname = $upload_dir['basedir'] . $uploadpath;
wp_delete_file($fullname);
}
}
}
}

?>
44 changes: 40 additions & 4 deletions src/trunk/ajax_handlers/upload_files.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,63 @@
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

function get_file_url( $file = __FILE__ ) {
$file_path = str_replace( "\\", "/", str_replace( str_replace( "/", "\\", WP_CONTENT_DIR ), "", $file ) );
if ( $file_path )
return content_url( $file_path );
return false;
}

function upload_user_file( $file = array(),$path) {
$result = [];
if(!empty($file))
{
$uploaded=move_uploaded_file($file['tmp_name'],$path.$file['name']);
if($uploaded)
{
$relativePath = substr($path, strlen($_SERVER['DOCUMENT_ROOT'] . "/wp-content"));
$result["url"] = get_file_url($relativePath.$file['name']);
} else {
$result["error"] = $file['error'];
}
}
return $result;
}

class SurveyJS_UploadFiles extends SurveyJS_AJAX_Handler {

function __construct() {
parent::__construct("SurveyJS_UploadFiles", false);
}



function callback() {
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$result = [];
$upload_dir=wp_upload_dir();
$path=$upload_dir['basedir'].'/surveyjs/'; //upload dir.
if(!is_dir($path)) { mkdir($path); }

foreach ($_FILES as $key=>$value) {
$uploadedfile = $value;
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
$path_info = pathinfo($uploadedfile["name"]);
$originalname = $uploadedfile["name"];
$filename = uniqid(rand(), true) . "." . $path_info['extension'];


$uploadedfile["name"] = $filename;

$movefile = upload_user_file( $uploadedfile, $path);

// $upload_overrides = array( 'test_form' => false );
//$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

if ( !$movefile || isset( $movefile['error'] ) ) {
wp_send_json( array('error' => $movefile['error']) );
return;
}

$result[$key] = $movefile['url'];
$result[$originalname] = $movefile['url'];
}

wp_send_json( $result );
Expand Down
82 changes: 58 additions & 24 deletions src/trunk/initializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ function wps_process_shortcode($attrs) {
$getSurveyJsonUri = add_query_arg(array('action' => 'SurveyJS_GetSurveyJson'), admin_url('admin-ajax.php'));
$saveResultUri = add_query_arg(array('action' => 'SurveyJS_SaveResult'), admin_url('admin-ajax.php'));
$uploadFileUri = add_query_arg(array('action' => 'SurveyJS_UploadFiles'), admin_url('admin-ajax.php'));
$deleteFileUri = add_query_arg(array('action' => 'SurveyJS_DeleteFile'), admin_url('admin-ajax.php'));
?>
<div class="wp-sjs-plugin" id="surveyContainer-<?php echo $id ?>">
<div id="surveyElement-<?php echo $id ?>">Survey is loading...</div>
Expand Down Expand Up @@ -221,32 +222,65 @@ function initSurvey<?php echo $id ?>(json, theme) {
// .innerHTML = "result: " + JSON.stringify(result.data);
});

survey<?php echo $id ?>.onUploadFiles.add((_, options) => {
const formData = new FormData();
options.files.forEach((file) => {
formData.append(file.name, file);
});
survey<?php echo $id ?>.onUploadFiles.add((_, options) => {
const formData = new FormData();
options.files.forEach((file) => {
formData.append(file.name, file);
});

fetch("<?php echo esc_url($uploadFileUri) ?>", {
method: "POST",
body: formData
fetch("<?php echo esc_url($uploadFileUri) ?>", {
method: "POST",
body: formData
})
.then((response) => response.json())
.then((data) => {
options.callback(
options.files.map((file) => {
return {
file: file,
content: data[file.name]
};
})
);
})
.then((response) => response.json())
.then((data) => {
options.callback(
options.files.map((file) => {
return {
file: file,
content: data[file.name]
};
})
);
})
.catch((error) => {
console.error("Error: ", error);
options.callback([], [ 'An error occurred during file upload.' ]);
});
});
.catch((error) => {
console.error("Error: ", error);
options.callback([], [ 'An error occurred during file upload.' ]);
});
});

function deleteFile(fileURL, options) {
try {
const apiUrl = `<?php echo esc_url($deleteFileUri) ?>&name=${fileURL}`;
fetch(apiUrl);
} catch (error) {
options.callback("error");
}
}

survey<?php echo $id ?>.onClearFiles.add((_, options) => {
if (!options.value || options.value.length === 0) {
options.callback("success");
return;
}

if (!options.fileName && !!options.value) {
for (const item of options.value) {
deleteFile(item.content, options);
}
} else {
const fileToRemove = options.value.find(
(item) => item.name === options.fileName
);
if (fileToRemove) {
deleteFile(fileToRemove.content, options);
} else {
console.error(`File with name ${options.fileName} is not found`);
}
}
options.callback("success");
});

jQuery("#surveyElement-<?php echo $id ?>").Survey({model: survey<?php echo $id ?>/*, css: customCss*/});
}
</script>
Expand Down
3 changes: 3 additions & 0 deletions src/trunk/surveyjs.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ function wps_uninstall() {
include("ajax_handlers/upload_files.php");
new SurveyJS_UploadFiles();

include("ajax_handlers/delete_file.php");
new SurveyJS_DeleteFile();

include("initializer.php");
new SurveyJS_SurveyJS();
?>

0 comments on commit 237430d

Please sign in to comment.