Skip to content

Commit

Permalink
#2766 work on uploading files with correc thashes
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Pollock committed Oct 25, 2018
1 parent 791beab commit 937886d
Show file tree
Hide file tree
Showing 12 changed files with 97 additions and 62 deletions.
3 changes: 3 additions & 0 deletions caldera-core.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
die;
}


global $wp_version;
if (!version_compare(PHP_VERSION, '5.6.0', '>=')) {
function caldera_forms_php_version_nag()
Expand Down Expand Up @@ -119,6 +120,8 @@ function caldera_forms_load()
* @since 1.3.5.3
*/
do_action('caldera_forms_includes_complete');


}

add_action('plugins_loaded', array('Caldera_Forms', 'get_instance'));
Expand Down
6 changes: 3 additions & 3 deletions cf2/Fields/Handlers/FileUpload.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ public function __construct(array $field, array $form, UploaderContract $uploade
* @throws \Exception
*/
public function processFiles(array $files,array $hashes ){

$i = 0;
foreach ($files as $file) {
$isPrivate = \Caldera_Forms_Files::is_private($this->field);
Expand All @@ -47,10 +46,9 @@ public function processFiles(array $files,array $hashes ){
$actual = md5_file( $file['tmp_name'] );

if ( $expected !== $actual ) {
throw new Exception(__( 'Content hash did not match expected.' ), 412 );
//throw new Exception(__( 'Content hash did not match expected.' ), 412 );
}


$this->uploader
->addFilter(
$this->field[ 'ID' ],
Expand All @@ -61,6 +59,8 @@ public function processFiles(array $files,array $hashes ){
if( ! $this->isAllowedType( $file ) ){
throw new Exception( __('This file type is not allowed. Please try another.', 'caldera-forms'), 415 );
}

require_once( ABSPATH . 'wp-admin/includes/file.php' );
$upload = wp_handle_upload($file, array( 'test_form' => false, 'action' => 'foo' ) );
$this->uploader->removeFilter();
if( !empty( $field['config']['media_lib'] ) ){
Expand Down
11 changes: 9 additions & 2 deletions cf2/Fields/RenderField.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,21 @@ class RenderField implements RenderFieldContract
*/
protected $formIdAttr;

/**
* @var array
*/
protected $domArgs;

/**
* RenderField constructor.
* @param string $formIdAttr Id attribute for form
* @param array $field Field configuration (MAKE THIS AN OBJECT!)
*/
public function __construct($formIdAttr, array $field)
public function __construct($formIdAttr, array $field, array $domArgs = [] )
{
$this->formIdAttr = $formIdAttr;
$this->field = $field;
$this->domArgs = $domArgs;
}

/** @inheritdoc */
Expand Down Expand Up @@ -108,9 +114,10 @@ public function data()
'multiple'=> ! empty($this->field[ 'config' ]['multi_upload' ]) ? $this->field[ 'config' ]['multi_upload' ] : false,
'multiUploadText' => ! empty($this->field[ 'config' ]['multi_upload_text' ]) ? $this->field[ 'config' ]['multi_upload_text' ] : false,
'allowedTypes' => ! empty($this->field[ 'config' ]['allowed' ]) ? $this->field[ 'config' ]['allowed' ] : false,
'control' => uniqid($this->getOuterIdAttr() ),
];
}
return $data;
return array_merge( $data, $this->domArgs) ;
}

/** @inheritdoc */
Expand Down
10 changes: 8 additions & 2 deletions cf2/RestApi/File/CreateFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,10 @@ protected function getArgs()
* @return bool
*/
public function permissionsCallback(\WP_REST_Request $request ){
$form = \Caldera_Forms_Forms::get_form($request->get_param( 'formId' ) );
$form = \Caldera_Forms_Forms::get_form( $request->get_param( 'formId' ) );
if( FileFieldType::getCf1Identifier() !== \Caldera_Forms_Field_Util::get_type( $request->get_param( 'fieldId' ), $form ) ){
return false;
}

return \Caldera_Forms_Render_Nonce::verify_nonce(
$request->get_param( 'verify'),
$request->get_param( 'formId' )
Expand All @@ -89,6 +88,9 @@ public function createItem(\WP_REST_Request $request)
{

$files = $request->get_file_params();
if( isset( $files[ 'file'] ) ){
$files = [$files['file']];
}
$formId = $request->get_param('formId');
$this->setFormById($formId);
$fieldId = $request->get_param('fieldId');
Expand All @@ -108,6 +110,10 @@ public function createItem(\WP_REST_Request $request)
new Cf1FileUploader()
);
try{
if( is_string($hashes ) ){
$hashes = [$hashes];
}

$uploads = $handler->processFiles($files,$hashes);
$transdata = is_array( $transientApi->getTransient( $controlCode ) )
? $transientApi->getTransient( $controlCode )
Expand Down
8 changes: 7 additions & 1 deletion classes/core.php
Original file line number Diff line number Diff line change
Expand Up @@ -3944,7 +3944,13 @@ static public function render_field($field, $form = null, $entry_data = array(),
array_merge( $field, [
'fieldIdAttr' => $field_id_attr,
'formIdAttr' => $form_id_attribute,
]));
]),
[
'formId' => $form['ID'],
'control' => uniqid( $type )

]
);
return $renderer->render();
}
$field_classes = Caldera_Forms_Field_Util::prepare_field_classes($field, $form);
Expand Down
2 changes: 2 additions & 0 deletions classes/render/assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,8 @@ public static function enqueue_form_assets(){
wp_localize_script( $field_script_to_localize, 'CF_API_DATA', array(
'rest' => array(
'root' => esc_url_raw(Caldera_Forms_API_Util::url()),
'rootV3' => esc_url_raw(Caldera_Forms_API_Util::url('', false, 'v3') ),
'fileUpload' => esc_url_raw(Caldera_Forms_API_Util::url('file', false, 'v3') ),
'tokens' => array(
'nonce' => esc_url_raw(Caldera_Forms_API_Util::url('tokens/form'))
),
Expand Down
2 changes: 1 addition & 1 deletion clients/blocks/build/index.min.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/privacy/build/index.min.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/pro/build/index.min.js.map

Large diffs are not rendered by default.

58 changes: 31 additions & 27 deletions clients/render/build/index.min.js
Original file line number Diff line number Diff line change
Expand Up @@ -23156,6 +23156,7 @@ Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_react_dom___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_react_dom__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__wordpress_dom_ready__ = __webpack_require__(720);

/** globals CF_API_DATA **/



Expand All @@ -23169,6 +23170,8 @@ Object.defineProperty(global.wp, 'element', {
});

Object(__WEBPACK_IMPORTED_MODULE_4__wordpress_dom_ready__["a" /* default */])(function () {
var _this = this;

jQuery(document).on('cf.form.init', function (e, obj) {
var state = obj.state,
formId = obj.formId,
Expand Down Expand Up @@ -23206,21 +23209,24 @@ Object(__WEBPACK_IMPORTED_MODULE_4__wordpress_dom_ready__["a" /* default */])(fu
*/
var shouldBeValidating = false;

var API_FOR_FILES_URL = CF_API_DATA.rest.fileUpload;
var _wp_nonce = CF_API_DATA.rest.nonce;
function createMediaFromFile(file, additionalData) {
// Create upload payload
var data = new window.FormData();
data.append('file', file, file.name || file.type.replace('/', '.'));
data.append('title', file.name ? file.name.replace(/\.[^.]+$/, '') : file.type.replace('/', '.'));
forEach(additionalData, function (value, key) {
return data.append(key, value);
__WEBPACK_IMPORTED_MODULE_0_babel_runtime_core_js_object_keys___default()(additionalData).forEach(function (key) {
return data.append(key, additionalData[key]);
});

return fetch(API_FOR_FILES_URL, {
body: data,
method: 'POST',
headers: {
'X-WP-Nonce': _wp_nonce
}
});
/**
return apiFetch( {
path: '/cf-api/v3/file',
body: data,
method: 'POST',
} );
**/
}

//When form submits, push values onto form object before it is serialized
Expand All @@ -23234,33 +23240,31 @@ Object(__WEBPACK_IMPORTED_MODULE_4__wordpress_dom_ready__["a" /* default */])(fu
if (field) {
if ('file' === field.type) {
var verify = jQuery("#_cf_verify_" + field.formId).val();
var hashes = [];

var binaries = [];
var files = [values[fieldId]];

files.forEach(function (file) {
var readerForHashes = new FileReader();
readerForHashes.addEventListener('load', function () {
hashes.push(CryptoJS.MD5(CryptoJS.lib.WordArray.create(this.result)).toString());
var hash = CryptoJS.MD5(CryptoJS.lib.WordArray.create(_this.result)).toString();
createMediaFromFile(file, {
hashes: [hash],
verify: verify,
formId: field.formId,
fieldId: field.fieldId,
control: field.control,
_wp_nonce: _wp_nonce
}).then(function (response) {
return response.json();
}).then(function (success) {
return console.log(success);
}).catch(function (error) {
return console.log(error);
});
});
readerForHashes.readAsArrayBuffer(file);
var readerForBianary = new FileReader();
readerForBianary.onload = function () {
binaries.push(readerForHashes.result);
};

readerForBianary.readAsBinaryString(file);
});

var data = {
files: binaries,
hashes: hashes,
verify: verify,
formId: field.formId,
fieldId: field.fieldId,
control: field.control
};
console.log(data);
}
} else {
obj.$form.data(fieldId, values[fieldId]);
Expand Down
2 changes: 1 addition & 1 deletion clients/render/build/index.min.js.map

Large diffs are not rendered by default.

53 changes: 30 additions & 23 deletions clients/render/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/** globals CF_API_DATA **/
import {CalderaFormsRender} from "./components/CalderaFormsRender";

import React from 'react';
Expand All @@ -19,6 +20,7 @@ domReady(function () {
} = obj;
const fieldsToControl = [];


//Build configurations
document.querySelectorAll('.cf2-field-wrapper').forEach(function (fieldElement) {
const fieldIdAttr = fieldElement.getAttribute('data-field-id');
Expand Down Expand Up @@ -53,20 +55,25 @@ domReady(function () {
let shouldBeValidating = false;


const API_FOR_FILES_URL = CF_API_DATA.rest.fileUpload;
const _wp_nonce = CF_API_DATA.rest.nonce;
function createMediaFromFile(file, additionalData) {
// Create upload payload
const data = new window.FormData();
data.append('file', file, file.name || file.type.replace('/', '.'));
data.append('title', file.name ? file.name.replace(/\.[^.]+$/, '') : file.type.replace('/', '.'));
forEach(additionalData, ((value, key) => data.append(key, value)));
/**
return apiFetch( {
path: '/cf-api/v3/file',
Object.keys(additionalData)
.forEach( key => data.append(key, additionalData[key]));

return fetch(API_FOR_FILES_URL,{
body: data,
method: 'POST',
headers: {
'X-WP-Nonce' : _wp_nonce
}
} );

**/

}


Expand All @@ -79,37 +86,37 @@ domReady(function () {
if (field) {
if ('file' === field.type) {
const verify = jQuery(`#_cf_verify_${field.formId}`).val();
const hashes = [];

const binaries = [];
const files = [values[fieldId]];

files.forEach(file => {
var readerForHashes = new FileReader();
readerForHashes.addEventListener(
'load',
function () {
hashes.push(CryptoJS.MD5(CryptoJS.lib.WordArray.create(this.result)).toString());
() => {
const hash = CryptoJS.MD5(CryptoJS.lib.WordArray.create(this.result)).toString();
createMediaFromFile(file,{
hashes: [hash],
verify,
formId: field.formId,
fieldId: field.fieldId,
control: field.control,
_wp_nonce
}).then(
response => response.json()
).then(
success => console.log(success)
).catch(
error => console.log(error)
);
}
);
readerForHashes.readAsArrayBuffer(file);
var readerForBianary = new FileReader();
readerForBianary.onload = () => {
binaries.push( readerForHashes.result );
};

readerForBianary.readAsBinaryString(file);

});

const data = {
files: binaries,
hashes,
verify,
formId: field.formId,
fieldId: field.fieldId,
control: field.control
};
console.log(data);

}
} else {
obj.$form.data(fieldId, values[fieldId]);
Expand Down

0 comments on commit 937886d

Please sign in to comment.