b3bffd0f by Jeff Balicki

ninja forms

Signed-off-by: Jeff <jeff@gotenzing.com>
1 parent ee3abc03
Showing 1000 changed files with 4873 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

.nf-fu-progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.nf-fu-progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #428bca;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.nf-fu-fileinput-button {
position: relative;
overflow: hidden;
display: inline-block;
margin-bottom: 10px;
}
.nf-fu-button-cancel {
float: right;
display: none;
}
.nf-fu-fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
opacity: 0;
-ms-filter: 'alpha(opacity=0)';
font-size: 200px !important;
direction: ltr;
cursor: pointer;
}
/* Fixes for IE < 8 */
@media screen\9 {
.nf-fu-fileinput-button input {
filter: alpha(opacity=0);
font-size: 100%;
height: 100%;
}
}
var fileUploadsFieldController = Marionette.Object.extend( {
initialize: function() {
Backbone.Radio.channel( 'conditions-key-select-field-file_upload' ).reply( 'hide', function( modelType ){ if ( 'when' == modelType ) { return true; } else { return false; } } );
Backbone.Radio.channel( 'conditions-file_upload' ).reply( 'get:triggers', this.getTriggers );
},
getTriggers: function() {
return {
show_field: {
label: nfcli18n.templateHelperShowField,
value: 'show_field'
},
hide_field: {
label: nfcli18n.templateHelperHideField,
value: 'hide_field'
}
};
}
});
jQuery( document ).ready( function( $ ) {
new fileUploadsFieldController();
});
\ No newline at end of file
var fileUploadsMergeTagsController = Marionette.Object.extend( {
initialize: function() {
this.listenTo( Backbone.Radio.channel( 'app' ), 'after:appStart', this.afterNFLoad );
},
afterNFLoad: function() {
this.listenTo( Backbone.Radio.channel( 'fields' ), 'add:field', this.addFieldTags );
this.listenTo( Backbone.Radio.channel( 'fields' ), 'delete:field', this.deleteFieldTags );
this.listenTo( Backbone.Radio.channel( 'actions' ), 'update:setting', this.maybeAlterExternalFieldTags );
this.listenTo( Backbone.Radio.channel( 'fields' ), 'update:setting', this.maybeAlterAttachmentFieldTags );
this.listenTo( Backbone.Radio.channel( 'fieldSetting-key' ), 'update:setting', this.maybeAlterFieldTags );
this.listenTo( Backbone.Radio.channel( 'fieldSetting-label' ), 'update:setting', this.maybeAlterFieldTags );
var fieldCollection = Backbone.Radio.channel( 'fields' ).request( 'get:collection' );
var that = this;
var fileUploadTags = this.getFileUploadTags();
_.each( fieldCollection.models, function( field ) {
if ( 'file_upload' !== field.get( 'type' ) ) {
return;
}
var variants = that.getMergeTagVariants( field );
that.addField( field, fileUploadTags, variants );
} );
},
getFieldwithExternalService: function() {
var actionCollection = Backbone.Radio.channel( 'actions' ).request( 'get:collection' );
var externalActions = _.filter( actionCollection.models, function( model ) {
return model.get( 'type' ) === 'file-upload-external';
} );
var fieldsWithExternalServices = {};
_.each( externalActions, function( action ) {
_.each( action.attributes, function( value, key ) {
if ( value == "1" && key.indexOf( 'field_list_' ) === 0 ) {
key = key.replace( 'field_list_', '' );
var keyParts = key.split( '-' );
var service = keyParts.shift();
var field = keyParts.join('-');
if ( !fieldsWithExternalServices.hasOwnProperty( field ) ) {
fieldsWithExternalServices[ field ] = [];
}
if ( !fieldsWithExternalServices[ field ].includes( service ) ) {
fieldsWithExternalServices[ field ].push( service );
}
}
} );
} );
return fieldsWithExternalServices;
},
getFileUploadTags: function() {
var mergeTagCollection = Backbone.Radio.channel( 'mergeTags' ).request( 'get:collection' );
return mergeTagCollection.get( 'file_uploads' ).get( 'tags' );
},
getMergeTagVariants: function( field, withAttachmentVariants ) {
var variants = nfFileUploadsAdmin.mergeTagVariants;
if ( (typeof withAttachmentVariants !== 'undefined' && !withAttachmentVariants) || 'false' == field.get( 'media_library' ) ) {
variants = variants.filter( function( variant ) {
return variant.indexOf( 'attachment_' ) < 0;
} );
}
var externalVariants = this.addExternalMergeTagVariants( field.get( 'key' ) );
variants = _.union( variants, externalVariants );
return variants;
},
addExternalMergeTagVariants: function( fieldKey ) {
var fieldsWithExternalServices = this.getFieldwithExternalService();
var externalServices = fieldsWithExternalServices[ fieldKey ];
var variants = [];
if ( externalServices !== undefined ) {
_.each( externalServices, function( externalService ) {
variants.push( externalService );
variants.push( externalService + '_plain' );
} );
}
return variants;
},
addField: function( field, fileUploadTags, variants ) {
if ( 'file_upload' !== field.get( 'type' ) ) {
return;
}
var that = this;
_.each( variants, function( variant ) {
fileUploadTags.add( {
id: field.get( 'id' ) + '_' + variant,
label: field.get( 'label' ) + ' ' + variant,
tag: that.getFieldKeyFormat( field.get( 'key' ), variant )
} );
} );
},
addFieldTags: function( fieldModel, withAttachmentVariants ) {
var fileUploadTags = this.getFileUploadTags();
var variants = this.getMergeTagVariants( fieldModel, withAttachmentVariants );
this.addField( fieldModel, fileUploadTags, variants );
},
deleteFieldTags: function( fieldModel ) {
var fieldID = fieldModel.get( 'id' );
var fileUploadTags = this.getFileUploadTags();
var variants = this.getMergeTagVariants( fieldModel, true );
_.each( variants, function( variant ) {
var ID = fieldID + '_' + variant;
var tagModel = fileUploadTags.get( ID );
fileUploadTags.remove( tagModel );
} );
},
maybeAlterFieldTags: function( field, settingModel ) {
if ( typeof settingModel === 'undefined' ) {
return;
}
if ( field.get( 'type' ) !== 'file_upload' ) {
return;
}
this.deleteFieldTags( field );
this.addFieldTags( field );
},
maybeAlterAttachmentFieldTags: function( field, settingModel ) {
if ( typeof settingModel === 'undefined' ) {
return;
}
if ( field.get( 'type' ) !== 'file_upload' ) {
return;
}
if ( settingModel.get( 'name' ) !== 'media_library' ) {
return;
}
var isChecked = jQuery( '#' + settingModel.get( 'name' ) ).is( ':checked' );
this.deleteFieldTags( field );
this.addFieldTags( field, isChecked );
},
maybeAlterExternalFieldTags: function( action, settingModel ) {
if ( typeof settingModel === 'undefined' ) {
return;
}
if ( action.get( 'type' ) !== 'file-upload-external' ) {
return;
}
if ( settingModel.get( 'type' ) !== 'toggle' ) {
return;
}
var isChecked = jQuery( '#' + settingModel.get( 'name' ) ).is( ':checked' );
this.alterExternalFieldTags( settingModel.get( 'name' ), isChecked );
},
alterExternalFieldTags: function( settingKey, enabled ) {
var fieldCollection = Backbone.Radio.channel( 'fields' ).request( 'get:collection' );
settingKey = settingKey.replace( 'field_list_', '' );
var keyParts = settingKey.split( '-' );
var externalService = keyParts[ 0 ];
var fieldKey = keyParts[ 1 ];
var fieldModel = _.find( fieldCollection.models, function( field ) {
if ( field.get( 'key' ) === fieldKey ) {
return field;
}
} );
var that = this;
var variants = [];
variants.push( externalService );
variants.push( externalService + '_plain' );
var fieldID = fieldModel.get( 'id' );
var fileUploadTags = this.getFileUploadTags();
_.each( variants, function( variant ) {
var ID = fieldID + '_' + variant;
var tagModel = fileUploadTags.get( ID );
fileUploadTags.remove( tagModel );
if ( enabled ) {
that.addField( fieldModel, fileUploadTags, variants );
}
} );
},
getFieldKeyFormat: function( key, variant ) {
return '{field:' + key + ':' + variant + '}';
}
} );
jQuery( document ).ready( function( $ ) {
new fileUploadsMergeTagsController();
} );
\ No newline at end of file
/*
* jQuery File Upload Processing Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2012, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery', './jquery.fileupload'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(require('jquery'), require('./jquery.fileupload'));
} else {
// Browser globals:
factory(window.jQuery);
}
})(function ($) {
'use strict';
var originalAdd = $.blueimp.fileupload.prototype.options.add;
// The File Upload Processing plugin extends the fileupload widget
// with file processing functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The list of processing actions:
processQueue: [
/*
{
action: 'log',
type: 'debug'
}
*/
],
add: function (e, data) {
var $this = $(this);
data.process(function () {
return $this.fileupload('process', data);
});
originalAdd.call(this, e, data);
}
},
processActions: {
/*
log: function (data, options) {
console[options.type](
'Processing "' + data.files[data.index].name + '"'
);
}
*/
},
_processFile: function (data, originalData) {
var that = this,
// eslint-disable-next-line new-cap
dfd = $.Deferred().resolveWith(that, [data]),
chain = dfd.promise();
this._trigger('process', null, data);
$.each(data.processQueue, function (i, settings) {
var func = function (data) {
if (originalData.errorThrown) {
// eslint-disable-next-line new-cap
return $.Deferred().rejectWith(that, [originalData]).promise();
}
return that.processActions[settings.action].call(
that,
data,
settings
);
};
chain = chain[that._promisePipe](func, settings.always && func);
});
chain
.done(function () {
that._trigger('processdone', null, data);
that._trigger('processalways', null, data);
})
.fail(function () {
that._trigger('processfail', null, data);
that._trigger('processalways', null, data);
});
return chain;
},
// Replaces the settings of each processQueue item that
// are strings starting with an "@", using the remaining
// substring as key for the option map,
// e.g. "@autoUpload" is replaced with options.autoUpload:
_transformProcessQueue: function (options) {
var processQueue = [];
$.each(options.processQueue, function () {
var settings = {},
action = this.action,
prefix = this.prefix === true ? action : this.prefix;
$.each(this, function (key, value) {
if ($.type(value) === 'string' && value.charAt(0) === '@') {
settings[key] =
options[
value.slice(1) ||
(prefix
? prefix + key.charAt(0).toUpperCase() + key.slice(1)
: key)
];
} else {
settings[key] = value;
}
});
processQueue.push(settings);
});
options.processQueue = processQueue;
},
// Returns the number of files currently in the processsing queue:
processing: function () {
return this._processing;
},
// Processes the files given as files property of the data parameter,
// returns a Promise object that allows to bind callbacks:
process: function (data) {
var that = this,
options = $.extend({}, this.options, data);
if (options.processQueue && options.processQueue.length) {
this._transformProcessQueue(options);
if (this._processing === 0) {
this._trigger('processstart');
}
$.each(data.files, function (index) {
var opts = index ? $.extend({}, options) : options,
func = function () {
if (data.errorThrown) {
// eslint-disable-next-line new-cap
return $.Deferred().rejectWith(that, [data]).promise();
}
return that._processFile(opts, data);
};
opts.index = index;
that._processing += 1;
that._processingQueue = that._processingQueue[that._promisePipe](
func,
func
).always(function () {
that._processing -= 1;
if (that._processing === 0) {
that._trigger('processstop');
}
});
});
}
return this._processingQueue;
},
_create: function () {
this._super();
this._processing = 0;
// eslint-disable-next-line new-cap
this._processingQueue = $.Deferred().resolveWith(this).promise();
}
});
});
/*
* jQuery File Upload Validation Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery', './jquery.fileupload-process'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(require('jquery'), require('./jquery.fileupload-process'));
} else {
// Browser globals:
factory(window.jQuery);
}
})(function ($) {
'use strict';
// Append to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.push({
action: 'validate',
// Always trigger this action,
// even if the previous action was rejected:
always: true,
// Options taken from the global options map:
acceptFileTypes: '@',
maxFileSize: '@',
minFileSize: '@',
maxNumberOfFiles: '@',
disabled: '@disableValidation'
});
// The File Upload Validation plugin extends the fileupload widget
// with file validation functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
/*
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// The maximum allowed file size in bytes:
maxFileSize: 10000000, // 10 MB
// The minimum allowed file size in bytes:
minFileSize: undefined, // No minimal file size
// The limit of files to be uploaded:
maxNumberOfFiles: 10,
*/
// Function returning the current number of files,
// has to be overriden for maxNumberOfFiles validation:
getNumberOfFiles: $.noop,
// Error and info messages:
messages: {
maxNumberOfFiles: 'Maximum number of files exceeded',
acceptFileTypes: 'File type not allowed',
maxFileSize: 'File is too large',
minFileSize: 'File is too small'
}
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
// eslint-disable-next-line new-cap
var dfd = $.Deferred(),
settings = this.options,
file = data.files[data.index],
fileSize;
if (options.minFileSize || options.maxFileSize) {
fileSize = file.size;
}
if (
$.type(options.maxNumberOfFiles) === 'number' &&
(settings.getNumberOfFiles() || 0) + data.files.length >
options.maxNumberOfFiles
) {
file.error = settings.i18n('maxNumberOfFiles');
} else if (
options.acceptFileTypes &&
!(
options.acceptFileTypes.test(file.type) ||
options.acceptFileTypes.test(file.name)
)
) {
file.error = settings.i18n('acceptFileTypes');
} else if (fileSize > options.maxFileSize) {
file.error = settings.i18n('maxFileSize');
} else if (
$.type(fileSize) === 'number' &&
fileSize < options.minFileSize
) {
file.error = settings.i18n('minFileSize');
} else {
delete file.error;
}
if (file.error || data.files.error) {
data.files.error = true;
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
});
});
/*
* jQuery Iframe Transport Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(require('jquery'));
} else {
// Browser globals:
factory(window.jQuery);
}
})(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0,
jsonAPI = $,
jsonParse = 'parseJSON';
if ('JSON' in window && 'parse' in JSON) {
jsonAPI = JSON;
jsonParse = 'parse';
}
// The iframe transport accepts four additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
// options.initialIframeSrc: the URL of the initial iframe src,
// by default set to "javascript:false;"
$.ajaxTransport('iframe', function (options) {
if (options.async) {
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6:
// eslint-disable-next-line no-script-url
var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
'<iframe src="' +
initialIframeSrc +
'" name="iframe-transport-' +
counter +
'"></iframe>'
).on('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName)
? options.paramName
: [options.paramName];
iframe.off('load').on('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(200, 'success', { iframe: response });
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="' + initialIframeSrc + '"></iframe>').appendTo(
form
);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (
options.fileInput &&
options.fileInput.length &&
options.type === 'POST'
) {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop('name', paramNames[index] || options.paramName);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
// Remove the HTML5 form attribute from the input(s):
options.fileInput.removeAttr('form');
}
window.setTimeout(function () {
// Submitting the form in a setTimeout call fixes an issue with
// Safari 13 not triggering the iframe load event after resetting
// the load event handler, see also:
// https://github.com/blueimp/jQuery-File-Upload/issues/3633
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
// Restore the original name and form properties:
$(input)
.prop('name', clone.prop('name'))
.attr('form', clone.attr('form'));
clone.replaceWith(input);
});
}
}, 0);
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
iframe.off('load').prop('src', initialIframeSrc);
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && jsonAPI[jsonParse]($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc)
? xmlDoc
: $.parseXML(
(xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html()
);
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
});
<?php
global $wpdb;
define("NINJA_FORMS_UPLOADS_DIR", dirname( __FILE__ ) );
define("NINJA_FORMS_UPLOADS_URL", plugins_url()."/".basename( dirname( NF_File_Uploads()->plugin_file_path ) ) . '/deprecated' );
define("NINJA_FORMS_UPLOADS_TABLE_NAME", $wpdb->prefix . "ninja_forms_uploads");
define("NINJA_FORMS_UPLOADS_VERSION", NF_File_Uploads()->plugin_version );
define("NINJA_FORMS_UPLOADS_DEFAULT_LOCATION", 'server' );
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/pages/ninja-forms-uploads/tabs/browse-uploads/browse-uploads.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/pages/ninja-forms-uploads/tabs/browse-uploads/sidebars/select-uploads.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/pages/ninja-forms-uploads/tabs/upload-settings/upload-settings.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/pages/ninja-forms-uploads/tabs/external-settings/external-settings.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/scripts.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/help.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/csv-filter.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/add-attachment-type.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/admin/upgrade-functions.php");
// External location class loader
require_once( NINJA_FORMS_UPLOADS_DIR . '/includes/external/external.php' );
$external_dir = glob( NINJA_FORMS_UPLOADS_DIR . '/includes/external/*.php' );
if ( $external_dir ) {
foreach ( $external_dir as $dir ) {
if ( basename( $dir, '.php' ) == 'external' ) {
continue;
}
$external = NF_Upload_External::instance( $dir, true );
}
}
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/pre-process.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/process.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/attach-image.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/shortcode-filter.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/post-meta-filter.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/processing/email-value-filter.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/deprecated.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/scripts.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/display/mp-confirm-filter.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/fields/file-uploads.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/activation.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/ajax.php");
require_once(NINJA_FORMS_UPLOADS_DIR."/includes/functions.php");
//Add File Uploads to the admin menu
add_action('admin_menu', 'ninja_forms_add_upload_menu', 99);
function ninja_forms_add_upload_menu(){
$capabilities = 'administrator';
$capabilities = apply_filters( 'ninja_forms_admin_menu_capabilities', $capabilities );
$uploads = add_submenu_page("ninja-forms", "File Uploads", "File Uploads", $capabilities, "ninja-forms-uploads", "ninja_forms_admin");
add_action('admin_print_styles-' . $uploads, 'ninja_forms_admin_js');
add_action('admin_print_styles-' . $uploads, 'ninja_forms_uploads_admin_js');
add_action('admin_print_styles-' . $uploads, 'ninja_forms_admin_css');
}
register_activation_hook( NF_File_Uploads()->plugin_file_path, 'ninja_forms_uploads_activation' );
$plugin_settings = get_option( 'ninja_forms_settings' );
if( isset( $plugin_settings['uploads_version'] ) ){
$current_version = $plugin_settings['uploads_version'];
}else{
$current_version = 0.4;
}
if( version_compare( $current_version, '0.5', '<' ) ){
ninja_forms_uploads_activation();
}
/**
* Load translations for add-on.
* First, look in WP_LANG_DIR subfolder, then fallback to add-on plugin folder.
*/
function ninja_forms_uploads_load_translations() {
/** Set our unique textdomain string */
$textdomain = 'ninja-forms-uploads';
/** The 'plugin_locale' filter is also used by default in load_plugin_textdomain() */
$locale = apply_filters( 'plugin_locale', get_locale(), $textdomain );
/** Set filter for WordPress languages directory */
$wp_lang_dir = apply_filters(
'ninja_forms_uploads_wp_lang_dir',
trailingslashit( WP_LANG_DIR ) . 'ninja-forms-uploads/' . $textdomain . '-' . $locale . '.mo'
);
/** Translations: First, look in WordPress' "languages" folder = custom & update-secure! */
load_textdomain( $textdomain, $wp_lang_dir );
/** Translations: Secondly, look in plugin's "lang" folder = default */
$plugin_dir = trailingslashit( basename( dirname( NF_File_Uploads()->plugin_file_path ) ) );
$lang_dir = apply_filters( 'ninja_forms_uploads_lang_dir', $plugin_dir . 'languages/' );
load_plugin_textdomain( $textdomain, FALSE, $lang_dir );
}
add_action( 'init', 'ninja_forms_uploads_load_translations' );
function nf_fu_load_externals() {
// External location class loader
require_once( NINJA_FORMS_UPLOADS_DIR . '/includes/external/external.php' );
$external_dir = glob( NINJA_FORMS_UPLOADS_DIR . '/includes/external/*.php' );
if ( $external_dir ) {
foreach ( $external_dir as $dir ) {
if ( basename( $dir, '.php' ) == 'external' ) {
continue;
}
$external = NF_Upload_External::instance( $dir, true );
}
$external = NF_Upload_External::instance( $dir, true );
}
}
function nf_fu_pre_27() {
if ( defined( 'NINJA_FORMS_VERSION' ) ) {
if ( version_compare( NINJA_FORMS_VERSION, '2.7' ) == -1 ) {
return true;
} else {
return false;
}
} else {
return null;
}
}
//Save User Progress Table Column
add_filter( 'nf_sp_user_sub_table' , 'nf_fu_sp_user_sub_table', 10, 2 );
function nf_fu_sp_user_sub_table( $user_value, $field_id ) {
$field = ninja_forms_get_field_by_id( $field_id );
if ( isset( $field['type'] ) AND '_upload' == $field['type'] ) {
$file_names = array();
foreach ( $user_value as $value ) {
$file_names[] = $value['file_name'];
}
return implode( ', ', $file_names );
}
return $user_value;
}
\ No newline at end of file
<?php
function ninja_forms_uploads_activation(){
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$sql = "CREATE TABLE IF NOT EXISTS ".NINJA_FORMS_UPLOADS_TABLE_NAME." (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`form_id` int(11) NOT NULL,
`field_id` int(11) NOT NULL,
`data` longtext CHARACTER SET utf8 NOT NULL,
`date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;";
dbDelta($sql);
$opt = get_option( 'ninja_forms_settings' );
if( isset( $opt['version'] ) ){
$current_version = $opt['version'];
}else{
$current_version = '';
}
$base_upload_url = wp_upload_dir();
$base_upload_url = $base_upload_url['baseurl'].'/ninja-forms';
$opt['base_upload_url'] = $base_upload_url;
$base_upload_dir = wp_upload_dir();
$base_upload_dir = $base_upload_dir['basedir'].'/ninja-forms';
$opt['base_upload_dir'] = $base_upload_dir;
if( !is_dir( $base_upload_dir ) ){
mkdir( $base_upload_dir );
}
if( !is_dir( $base_upload_dir."/tmp/" ) ){
mkdir( $base_upload_dir."/tmp/" );
}
if( !isset( $opt['upload_error'] ) ){
$opt['upload_error'] = __( 'There was an error uploading your file.', 'ninja-forms-uploads' );
}
if( !isset( $opt['max_filesize'] ) ){
$opt['max_filesize'] = 2;
}
$opt['uploads_version'] = NINJA_FORMS_UPLOADS_VERSION;
update_option( 'ninja_forms_settings', $opt );
}
\ No newline at end of file
<?php
// Adds an attachment type to the email notification dropdown
function nf_fu_add_attachment_type( $types ) {
// Bail if we don't have a form id set.
if ( ! isset ( $_REQUEST['form_id'] ) )
return $types;
foreach( Ninja_Forms()->form( $_REQUEST['form_id'] )->fields as $field_id => $field ) {
if ( '_upload' == $field['type'] ) {
$label = nf_get_field_admin_label( $field_id );
$types[ 'file_upload_' . $field_id ] = $label . ' - ID: ' . $field_id;
}
}
return $types;
}
add_filter( 'nf_email_notification_attachment_types', 'nf_fu_add_attachment_type' );
// Add our attachment to the email notification if the box was checked.
function nf_fu_attach_files( $files, $id ) {
global $ninja_forms_processing;
foreach ( $ninja_forms_processing->get_all_fields() as $field_id => $user_value ) {
$type = $ninja_forms_processing->get_field_setting( $field_id, 'type' );
if ( '_upload' == $type && 1 == Ninja_Forms()->notification( $id )->get_setting( 'file_upload_' . $field_id ) ) {
if ( is_array( $user_value ) ) {
$file_urls = array();
foreach ( $user_value as $key => $file ) {
if ( ! isset ( $file['file_path'] ) )
continue;
$files[] = $file['file_path'] . $file['file_name'];
}
}
}
}
return $files;
}
add_filter( 'nf_email_notification_attachments', 'nf_fu_attach_files', 10, 2 );
\ No newline at end of file
<?php
function nf_fu_export_filter( $user_value, $field_id ) {
$field = ninja_forms_get_field_by_id( $field_id );
if ( $field['type'] == '_upload' ) {
if ( is_array( $user_value ) ) {
$user_value = NF_File_Uploads()->normalize_submission_value( $user_value );
$file_urls = array();
foreach ( $user_value as $key => $file ) {
if ( ! isset ( $file['file_url'] ) )
continue;
$file_url = ninja_forms_upload_file_url( $file );
$file_urls[] = apply_filters( 'nf_fu_export_file_url', $file_url );
}
$user_value = apply_filters( 'nf_fu_export_files', $file_urls );
}
}
return $user_value;
}
function nf_fu_add_export_filter() {
if ( ! nf_fu_pre_27() ) {
add_filter( 'nf_subs_export_pre_value', 'nf_fu_export_filter', 10, 2 );
}
}
add_action( 'init', 'nf_fu_add_export_filter' );
\ No newline at end of file
<?php
add_action( 'init', 'ninja_forms_register_uploads_help' );
function ninja_forms_register_uploads_help(){
$args = array(
'page' => 'ninja-forms',
'tab' => 'builder',
'title' => 'File Renaming',
'display_function' => 'ninja_forms_help_uploads',
);
if( function_exists( 'ninja_forms_register_help_screen_tab' ) ){
ninja_forms_register_help_screen_tab('upload_help', $args);
}
}
function ninja_forms_help_uploads(){
?>
<p><?php _e('If you leave the advanced rename box empty, the uploaded file will retain the original user\'s filename. (With any special characters removed.)', 'ninja-forms-uploads');?></p>
</p><?php _e('If you want to rename the file, however, you can. These are the conventions that Ninja Forms understands, and their effect.', 'ninja-forms-uploads');?>
<ul>
<li><span class="code">%filename%</span> - <?php _e('The file\'s original filename, with any special characters removed.', 'ninja-forms-uploads');?></li>
<li><span class="code">%formtitle%</span> - <?php _e('The title of the current form, with any special characters removed.', 'ninja-forms-uploads');?></li>
<li><span class="code">%username%</span> - <?php _e('The WordPress username for the user, if they are logged in.', 'ninja-forms-uploads');?></li>
<li><span class="code">%userid%</span> - <?php _e('The WordPress ID (int) for the user, if they are logged in.', 'ninja-forms-uploads');?></li>
<li><span class="code">%displayname%</span> - <?php _e('The WordPress displayname for the user, if they are logged in.', 'ninja-forms-uploads');?></li>
<li><span class="code">%lastname%</span> - <?php _e('The WordPress lastname for the user, if they are logged in.', 'ninja-forms-uploads');?></li>
<li><span class="code">%firstname%</span> - <?php _e('The WordPress firstname for the user, if they are logged in.', 'ninja-forms-uploads');?></li>
<li><span class="code">%date%</span> - <?php _e('Today\'s date in yyyy-mm-dd format.', 'ninja-forms-uploads');?></li>
<li><span class="code">%month%</span> - <?php _e('Today\'s month in mm format.', 'ninja-forms-uploads');?></li>
<li><span class="code">%day%</span> - <?php _e('Today\'s day in dd format.', 'ninja-forms-uploads');?></li>
<li><span class="code">%year%</span> - <?php _e('Today\'s year in yyyy format.', 'ninja-forms-uploads');?></li>
<li><span class="code">%field_x%</span> - <?php _e('Another field in your form, where x is the field id.', 'ninja-forms-uploads');?></li>
</ul>
</p>
<p>
<?php _e('Any characters other than letters, numbers, dashes (-) and those on the list above will be removed. This includes spaces.', 'ninja-forms-uploads');?>
</p>
<p>
<?php _e('An Example', 'ninja-forms-uploads');?>: <span class="code">%date%-%filename%</span>
</p>
<p>
<?php _e('Would Yield', 'ninja-forms-uploads');?>: <span class="code">2011-07-09-myflowers.jpg</span>
<p>
<?php
}
\ No newline at end of file
<?php
/* *
* Browse Uploads Sidebar Functions
*/
add_action('admin_init', 'ninja_forms_register_sidebar_select_uploads');
function ninja_forms_register_sidebar_select_uploads(){
$args = array(
'name' => __( 'Find File Uploads', 'ninja-forms-uploads' ),
'page' => 'ninja-forms-uploads',
'tab' => 'browse_uploads',
'display_function' => 'ninja_forms_sidebar_select_uploads',
'save_function' => 'ninja_forms_save_sidebar_select_uploads',
);
if( function_exists( 'ninja_forms_register_sidebar' ) ){
ninja_forms_register_sidebar('select_uploads', $args);
}
if( is_admin() AND isset( $_REQUEST['page'] ) AND $_REQUEST['page'] == 'ninja-forms-uploads' ){
if( !isset( $_REQUEST['paged'] ) AND !isset( $_REQUEST['form_id'] ) ){
if( !session_id() ) {
session_start();
}
unset( $_SESSION['ninja_forms_form_id'] );
unset( $_SESSION['ninja_forms_begin_date'] );
unset( $_SESSION['ninja_forms_end_date'] );
unset( $_SESSION['ninja_forms_upload_types'] );
unset( $_SESSION['ninja_forms_upload_name'] );
unset( $_SESSION['ninja_forms_upload_user'] );
}
}
}
function ninja_forms_sidebar_select_uploads(){
$plugin_settings = get_option( 'ninja_forms_settings' );
if ( isset ( $plugin_settings['date_format'] ) ) {
$date_format = $plugin_settings['date_format'];
} else {
$date_format = 'mm/dd/yyyy';
}
$form_results = ninja_forms_get_all_forms();
if(isset($_REQUEST['form_id']) AND !empty($_REQUEST['form_id'])){
$form_id = $_REQUEST['form_id'];
}else if(isset($_SESSION['ninja_forms_form_id']) AND !empty($_SESSION['ninja_forms_form_id'])){
$form_id = $_SESSION['ninja_forms_form_id'];
}else{
$form_id = '';
}
if(isset($_REQUEST['upload_types']) AND !empty($_REQUEST['upload_types'])){
$upload_types = $_REQUEST['upload_types'];
}else if(isset($_SESSION['ninja_forms_upload_types']) AND !empty($_SESSION['ninja_forms_upload_types'])){
$upload_types = $_SESSION['ninja_forms_upload_types'];
}else{
$upload_types = '';
}
if(isset($_REQUEST['upload_name']) AND !empty($_REQUEST['upload_name'])){
$upload_name = $_REQUEST['upload_name'];
}else if(isset($_SESSION['ninja_forms_upload_name']) AND !empty($_SESSION['ninja_forms_upload_name'])){
$upload_name = $_SESSION['ninja_forms_upload_name'];
}else{
$upload_name = '';
}
if(isset($_REQUEST['upload_user']) AND !empty($_REQUEST['upload_user'])){
$upload_user = $_REQUEST['upload_user'];
}else if(isset($_SESSION['ninja_forms_upload_user']) AND !empty($_SESSION['ninja_forms_upload_user'])){
$upload_user = $_SESSION['ninja_forms_upload_user'];
}else{
$upload_user = '';
}
if(isset($_REQUEST['begin_date']) AND !empty($_REQUEST['begin_date'])){
$begin_date = $_REQUEST['begin_date'];
}else if(isset($_SESSION['ninja_forms_begin_date']) AND !empty($_SESSION['ninja_forms_begin_date'])){
$begin_date = $_SESSION['ninja_forms_begin_date'];
}else{
$begin_date = '';
}
if(isset($_REQUEST['end_date']) AND !empty($_REQUEST['end_date'])){
$end_date = $_REQUEST['end_date'];
}else if(isset($_SESSION['ninja_forms_end_date']) AND !empty($_SESSION['ninja_forms_end_date'])){
$end_date = $_SESSION['ninja_forms_end_date'];
}else{
$end_date = '';
}
?>
<label><strong><?php _e('Select A Form', 'ninja-forms-uploads');?>:</strong></label>
<p>
<select name="form_id" id="" class="">
<option value="all">- <?php _e ( 'All Forms', 'ninja-forms-uploads' ); ?></option>
<?php
if(is_array($form_results)){
foreach($form_results as $form){
$data = $form['data'];
$form_title = $data['form_title'];
?>
<option value="<?php echo $form['id'];?>" <?php if($form_id == $form['id']){ echo 'selected';}?>><?php echo $form_title;?></option>
<?php
}
}
?>
</select>
</p>
<label><strong><?php _e( 'User', 'ninja-forms-uploads' ); ?> - <span>(<?php _e( 'Optional', 'ninja-forms-uploads' );?>)</span>:</strong></label>
<p>
<input type="text" id="" name="upload_user" class="code" value="<?php echo $upload_user; ?>">
<br />
<?php _e( 'login, email, user ID', 'ninja-forms-uploads' );?>
</p>
<label><strong><?php _e( 'File Name', 'ninja-forms-uploads' ); ?> - <span>(<?php _e( 'Optional', 'ninja-forms-uploads' );?>)</span>:</strong></label>
<p>
<input type="text" id="" name="upload_name" class="code" value="<?php echo $upload_name; ?>">
</p>
<label><strong><?php _e( 'File Type', 'ninja-forms-uploads' ); ?> - <span>(<?php _e( 'Optional', 'ninja-forms-uploads' ); ?>)</span></strong></label>
<p>
<input type="text" id="" name="upload_types" class="code" value="<?php echo $upload_types; ?>">
<br />
.jpg,.pdf.docx
</p>
<h4><?php _e('Date Range', 'ninja-forms-uploads');?> - <span>(<?php _e( 'Optional', 'ninja-forms-uploads' ); ?>)</span></h4>
<p>
<?php _e('Begin Date', 'ninja-forms-uploads');?>: <input type="text" id="" name="begin_date" class="ninja-forms-admin-date" value="<?php echo $begin_date;?>">
<br />
<?php echo $date_format;?>
</p>
<p>
<?php _e('End Date', 'ninja-forms-uploads');?>: <input type="text" id="" name="end_date" class="ninja-forms-admin-date" value="<?php echo $end_date;?>">
<br />
<?php echo $date_format;?>
</p>
<p class="description">
<?php //_e('If both Begin Date and End Date are left blank, all file uploads will be displayed.', 'ninja-forms-uploads');?>
</p>
<p class="description description-wide">
<input type="submit" name="submit" id="" class="button-primary" value="<?php _e('Filter File Uploads', 'ninja-forms-uploads');?>">
</p>
</form>
<?php
}
function ninja_forms_save_sidebar_select_uploads(){
}
\ No newline at end of file
<?php
add_action('init', 'ninja_forms_external_settings', 1);
function ninja_forms_external_settings() {
$load = false;
if ( isset( $_GET['page'] ) && 'ninja-forms-uploads' == $_GET['page'] && isset( $_GET['tab'] ) && 'external_settings' == $_GET['tab'] ) {
$load = true;
}
if ( isset( $_GET['page'] ) && 'ninja-forms' == $_GET['page'] && isset( $_GET['tab'] ) && 'field_settings' == $_GET['tab'] ) {
$load = true;
}
if ( $load ) {
nf_fu_load_externals();
}
}
add_action( 'ninja_forms_pre_process', 'ninja_forms_pre_process_load_externals', 1 );
function ninja_forms_pre_process_load_externals() {
global $ninja_forms_processing;
if ( $ninja_forms_processing->get_form_setting( 'create_post' ) != 1 ) {
if ( $ninja_forms_processing->get_extra_value( 'uploads' ) ) {
foreach ( $ninja_forms_processing->get_extra_value( 'uploads' ) as $field_id ) {
$field_row = $ninja_forms_processing->get_field_settings( $field_id );
if ( isset( $field_row['data']['upload_location'] ) AND ninja_forms_upload_is_location_external( $field_row['data']['upload_location'] ) ) {
nf_fu_load_externals();
}
}
}
}
}
add_action('admin_init', 'ninja_forms_register_tab_external_settings');
function ninja_forms_register_tab_external_settings(){
$args = array(
'name' => __( 'External Settings', 'ninja-forms-uploads' ),
'page' => 'ninja-forms-uploads',
'display_function' => '',
'save_function' => 'ninja_forms_save_upload_settings',
'tab_reload' => true,
);
if( function_exists( 'ninja_forms_register_tab' ) ){
ninja_forms_register_tab('external_settings', $args);
}
}
add_action( 'admin_init', 'ninja_forms_external_url' );
if ( defined( 'NINJA_FORMS_UPLOADS_USE_PUBLIC_URL') && NINJA_FORMS_UPLOADS_USE_PUBLIC_URL ) {
add_action('template_redirect', 'ninja_forms_external_url');
}
function ninja_forms_external_url() {
if ( isset( $_GET['nf-upload'] ) ) {
$args = array(
'id' => $_GET['nf-upload']
);
$upload = ninja_forms_get_uploads( $args );
$external = NF_Upload_External::instance( $upload['data']['upload_location'] );
if ( $external ) {
$path = ( isset( $upload['data']['external_path'] ) ) ? $upload['data']['external_path'] : '';
$filename = ( isset( $upload['data']['external_filename'] ) ) ? $upload['data']['external_filename'] : $upload['data']['file_name'];
$file_url = $external->file_url( $filename, $path, $upload['data'] );
}
wp_redirect( $file_url );
die();
}
}
function ninja_forms_upload_file_url( $data ) {
nf_fu_load_externals();
$file_url = isset ( $data['file_url'] ) ? $data['file_url'] : '';
if ( isset( $data['upload_location'] ) && ( isset( $data['upload_id'] ) ) && ninja_forms_upload_is_location_external( $data['upload_location'] ) ) {
$external = NF_Upload_External::instance( $data['upload_location'] );
if ( $external && $external->is_connected() ) {
$url_path = '?nf-upload='. $data['upload_id'];
if ( defined( 'NINJA_FORMS_UPLOADS_USE_PUBLIC_URL') && NINJA_FORMS_UPLOADS_USE_PUBLIC_URL ) {
$file_url = home_url( $url_path );
} else {
$file_url = admin_url( $url_path );
}
}
}
return $file_url;
}
function ninja_forms_upload_is_location_external( $location ) {
return ! in_array( $location, array( NINJA_FORMS_UPLOADS_DEFAULT_LOCATION, 'none' ) );
}
\ No newline at end of file
<?php
add_action('admin_init', 'ninja_forms_register_tab_upload_settings');
function ninja_forms_register_tab_upload_settings(){
$args = array(
'name' => 'Upload Settings',
'page' => 'ninja-forms-uploads',
'display_function' => '',
'save_function' => 'ninja_forms_save_upload_settings',
'tab_reload' => true,
);
if( function_exists( 'ninja_forms_register_tab' ) ){
ninja_forms_register_tab('upload_settings', $args);
}
}
function nf_return_mb($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'k':
$val /= 1024;
}
return $val;
}
add_action( 'admin_init', 'ninja_forms_register_upload_settings_metabox');
function ninja_forms_register_upload_settings_metabox(){
$max_filesize = nf_return_mb( ini_get( 'upload_max_filesize' ) );
$args = array(
'page' => 'ninja-forms-uploads',
'tab' => 'upload_settings',
'slug' => 'upload_settings',
'title' => __('Upload Settings', 'ninja-forms-uploads'),
'settings' => array(
array(
'name' => 'max_filesize',
'type' => 'text',
'label' => __( 'Max File Size (in MB)', 'ninja-forms-uploads' ),
'desc' => sprintf( __( 'Your server\'s maximum file size is set to %s. This setting cannot be increased beyond this value. To increase your server file size limit, please contact your host.', 'ninja-forms-uploads' ), $max_filesize ),
),
array(
'name' => 'upload_error',
'type' => 'text',
'label' => __('File upload error message', 'ninja-forms-uploads'),
'desc' => '',
),
array(
'name' => 'adv_settings',
'type' => '',
'display_function' => 'ninja_forms_upload_settings_adv',
),
),
);
if( function_exists( 'ninja_forms_register_tab_metabox' ) ){
ninja_forms_register_tab_metabox($args);
}
}
function ninja_forms_upload_settings_adv(){
$plugin_settings = nf_get_settings();
if(isset($plugin_settings['base_upload_dir'])){
$base_upload_dir = stripslashes($plugin_settings['base_upload_dir']);
}else{
$base_upload_dir = wp_upload_dir();
$base_upload_dir = $base_upload_dir['basedir'];
$plugin_settings['base_upload_dir'] = $base_upload_dir;
update_option( 'ninja_forms_settings', $plugin_settings );
}
if(isset($plugin_settings['base_upload_url'])){
$base_upload_url = stripslashes($plugin_settings['base_upload_url']);
}else{
$base_upload_url = wp_upload_dir();
$base_upload_url = $base_upload_url['baseurl'];
$plugin_settings['base_upload_url'] = $base_upload_url;
update_option( 'ninja_forms_settings', 'ninja-forms-uploads' );
}
if(isset($plugin_settings['custom_upload_dir'])){
$custom_upload_dir = stripslashes($plugin_settings['custom_upload_dir']);
}else{
$custom_upload_dir = '';
}
if(isset($plugin_settings['max_filesize'])){
$max_filesize = $plugin_settings['max_filesize'];
}else{
$max_filesize = '';
}
?>
<div class="">
<?php /*
<h4><?php _e('Base Directory', 'ninja-forms-uploads');?> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""></h4>
<label for="">
<input type="text" class="widefat code" name="base_upload_dir" id="base_upload_dir" value="<?php echo $base_upload_dir;?>" />
</label>
<span class="howto">Where should Ninja Forms place uploaded files? This should be the "first part" of the directory, including trailing slash. i.e. /var/html/wp-content/plugins/ninja-forms/uploads/</span>
<h4><?php _e('Base URL', 'ninja-forms-uploads');?> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""></h4>
<label for="">
<input type="text" class="widefat code" name="base_upload_url" id="base_upload_url" value="<?php echo $base_upload_url;?>" />
</label>
<span class="howto">What is the URL to the base directory given above? This will be used on the backend to link to the files that have been uploaded.</span>
<br />
<span class="howto"><b>Please note that Ninja Forms will attempt to determine this directory, but you may need to overwrite it based on your server settings.</b></span>
<input type="hidden" id="ninja_forms_default_base_upload_dir" value="<?php echo $default_base_upload_dir;?>">
<input type="hidden" id="ninja_forms_default_base_upload_url" value="<?php echo $default_base_upload_url;?>">
<input type="button" id="ninja_forms_reset_base_upload_dir" value="Reset Upload Directory">
<br />
*/ ?>
<h4><?php _e('Custom Directory', 'ninja-forms-uploads');?> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""></h4>
<label for="">
<input type="text" class="widefat code" name="custom_upload_dir" id="" value="<?php echo $custom_upload_dir;?>" />
</label>
<span class="howto">
<?php _e( 'If you want to create dynamic directories, you can put folder names in this box. You can use the following shortcodes, please include a slash at the beginning and a trailing slash', 'ninja-forms-uploads' );?>:<br /><br />
<?php _e( 'For example: /custom/director/structure/', 'ninja-forms-uploads' );?><br><br>
<li>%formtitle% - <?php _e('Puts in the title of the current form without any spaces', 'ninja-forms-uploads');?></li>
<li>%username% - <?php _e('Puts in the user\'s username if they are logged in', 'ninja-forms-uploads');?>.</li>
<li>%date% - <?php _e('Puts in the date in yyyy-mm-dd (1998-05-23) format', 'ninja-forms-uploads');?>.</li>
<li>%month% - <?php _e('Puts in the month in mm (04) format', 'ninja-forms-uploads');?>.</li>
<li>%day% - <?php _e('Puts in the day in dd (20) format', 'ninja-forms-uploads');?>.</li>
<li>%year% - <?php _e('Puts in the year in yyyy (2011) format', 'ninja-forms-uploads');?>.</li>
<li>For Example: /%formtitle%/%month%/%year%/ &nbsp;&nbsp;&nbsp; would be &nbsp;&nbsp;&nbsp; /MyFormTitle/04/2012/</li>
</span>
<h4><?php _e('Full Directory', 'ninja-forms-uploads');?> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""></h4>
<span class="code"><?php echo $base_upload_dir;?><b><?php echo $custom_upload_dir;?></b></span>
<br />
</div>
<?php
}
function ninja_forms_save_upload_settings( $data ){
$plugin_settings = nf_get_settings();
foreach( $data as $key => $val ){
if ( 'max_filesize' == $key ) {
if ( $val > preg_replace( "/[^0-9]/", "", nf_return_mb( ini_get( 'upload_max_filesize' ) ) ) ) {
$val = preg_replace( "/[^0-9]/", "", nf_return_mb( ini_get( 'upload_max_filesize' ) ) );
}
$val = preg_replace( "/[^0-9]/", "", $val );
}
$plugin_settings[$key] = $val;
}
update_option( 'ninja_forms_settings', $plugin_settings );
$update_msg = __( 'Settings Saved', 'ninja-forms-uploads' );
return $update_msg;
}
\ No newline at end of file
<?php
add_action( 'admin_init', 'ninja_forms_uploads_admin_js' );
function ninja_forms_uploads_admin_js(){
wp_enqueue_script( 'ninja-forms-uploads-admin',
NINJA_FORMS_UPLOADS_URL .'/js/min/ninja-forms-uploads-admin.min.js',
array( 'jquery', 'ninja-forms-admin' ) );
}
\ No newline at end of file
<?php
/**
* Update the "attach file to this email" settings on any "Admin" email notifications we may have.
*
* @since 1.3.8
* @return void
*/
function nf_fu_upgrade_settings() {
// Check to see if we've already done this.
$updated = get_option( 'nf_convert_upload_settings_complete', false );
if( ! defined( 'NINJA_FORMS_VERSION' ) ) return;
if ( $updated || version_compare( NINJA_FORMS_VERSION, '2.8', '<' ) )
return;
$notifications = nf_get_all_notifications();
// Make sure that there are some notifications.
if ( ! is_array ( $notifications ) )
return;
// Loop through our notifications and see if any of them were "admin emails"
foreach ( $notifications as $n ) {
if ( Ninja_Forms()->notification( $n['id'] )->get_setting( 'admin_email' ) ) {
// Grab our form id so that we can loop over our fields.
$form_id = Ninja_Forms()->notification( $n['id'] )->form_id;
// Loop over our form fields. If we find an upload field, see if the option is checked.
foreach ( Ninja_Forms()->form( $form_id )->fields as $field_id => $field ) {
if ( '_upload' == $field['type'] && isset ( $field['data']['email_attachment'] ) && $field['data']['email_attachment'] == 1 ) {
Ninja_Forms()->notification( $n['id'] )->update_setting( 'file_upload_' . $field_id, 1 );
}
}
}
}
update_option( 'nf_convert_upload_settings_complete', true );
}
add_action( 'admin_init', 'nf_fu_upgrade_settings' );
<?php
//Add the ajax listener for deleting the upload
add_action('wp_ajax_ninja_forms_delete_upload', 'ninja_forms_delete_upload');
function ninja_forms_delete_upload($upload_id = ''){
global $wpdb;
if(isset($_REQUEST['upload_id']) AND $upload_id == ''){
$upload_id = $_REQUEST['upload_id'];
}
$args = array('id' => $upload_id);
$upload_row = ninja_forms_get_uploads($args);
$upload_data = $upload_row['data'];
if(is_array($upload_data) AND isset($upload_data['file_path'])){
$file = $upload_data['file_path'].$upload_data['file_name'];
if(file_exists($file)){
unlink($file);
}
}
$wpdb->query($wpdb->prepare("DELETE FROM ".NINJA_FORMS_UPLOADS_TABLE_NAME." WHERE id = %d", $upload_id));
if(isset($_REQUEST['upload_id'])){
die();
}
}
\ No newline at end of file
<?php
/*
*
* Function that sets admin email attachment for this file if it is enabled.
*
* @since 1.0.7
* @returns void
*/
function ninja_forms_upload_email_attachment( $field_id ){
global $ninja_forms_processing;
$field = ninja_forms_get_field_by_id( $field_id );
$field_data = $field['data'];
if ( isset ( $field_data['email_attachment'] ) AND $field_data['email_attachment'] == 1 ){
$files = $ninja_forms_processing->get_field_value( $field_id );
if ( is_array ( $files ) ) {
foreach ( $files as $key => $val ) {
if ( isset ( $val['file_path'] ) ) {
$upload_path = $val['file_path'];
$file_name = $val['file_name'];
$attach_files = $ninja_forms_processing->get_form_setting( 'admin_attachments' );
array_push( $attach_files, $upload_path.'/'.$file_name );
$ninja_forms_processing->update_form_setting( 'admin_attachments', $attach_files );
}
}
}
}
}
add_action( 'ninja_forms_upload_process', 'ninja_forms_upload_email_attachment' );
\ No newline at end of file
<?php
/*
*
* Function that filters the confirmation page in multi-part forms so that the filename is displayed properly.
*
* @since 1.0.4
* @returns $user_value
*/
function ninja_forms_uploads_filter_mp_confirm_value( $user_value, $field_id ){
$field_row = ninja_forms_get_field_by_id( $field_id );
$field_type = $field_row['type'];
if ( $field_type == '_upload' ) {
if ( is_array( $user_value ) ) {
foreach( $user_value as $key => $file ){
$user_value = $file['user_file_name'];
}
}
}
return $user_value;
}
add_filter( 'ninja_forms_mp_confirm_user_value', 'ninja_forms_uploads_filter_mp_confirm_value', 10, 2 );
\ No newline at end of file
<?php
function ninja_forms_attach_files_to_post( $post_id ){
global $ninja_forms_processing;
if( $ninja_forms_processing->get_extra_value( 'uploads' ) ){
foreach( $ninja_forms_processing->get_extra_value( 'uploads' ) as $field_id ){
$field_row = $ninja_forms_processing->get_field_settings( $field_id );
$user_value = $ninja_forms_processing->get_field_value( $field_id );
if( is_array( $user_value ) AND !empty( $user_value ) ){
$tmp_array = array();
$args = array(
'post_parent' => $post_id,
'post_status' => 'null',
'post_type'=> 'attachment',
'posts_per_page' => -1,
);
$attachments = get_posts( $args );
if( !empty( $attachments ) ){
$x = 0;
foreach( $attachments as $attachment ){
$attach_field = get_post_meta( $attachment->ID, 'ninja_forms_field_id', true );
$file_key = get_post_meta( $attachment->ID, 'ninja_forms_file_key', true );
$upload_id = get_post_meta( $attachment->ID, 'ninja_forms_upload_id', true );
if( $attach_field == $field_id ){
if( !array_key_exists( $file_key, $user_value ) ){
if( $upload_id != '' ){
ninja_forms_delete_upload( $upload_id );
}
wp_delete_attachment( $attachment->ID );
}else{
$tmp_array[$x]['id'] = $attachment->ID;
$tmp_array[$x]['field_id'] = $attach_field;
$tmp_array[$x]['file_key'] = $file_key;
}
}else if( $attach_field == '' ){
wp_update_post( array( 'ID' => $attachment->ID, 'post_parent' => 0 ) );
}
$x++;
}
}
$attachments = $tmp_array;
foreach( $user_value as $key => $file ){
// Check to see if we are changing files that already exist.
if( !isset( $file['changed'] ) OR $file['changed'] == 1 ){
foreach( $attachments as $attachment ){
if( $attachment['file_key'] == $key ){
$upload_id = get_post_meta( $attachment['id'], 'ninja_forms_upload_id', true );
if( $upload_id != '' ){
ninja_forms_delete_upload( $upload_id );
}
wp_delete_attachment( $attachment['id'] );
}
}
}
if( isset( $file['complete'] ) AND $file['complete'] == 1 && ( ! isset ( $file['changed'] ) || $file['changed'] == 1 ) ){
$filename = $file['file_path'].$file['file_name'];
$attach_array = ninja_forms_generate_metadata( $post_id, $filename );
$attach_id = $attach_array['attach_id'];
$attach_data = $attach_array['attach_data'];
if( !empty( $attach_array ) AND isset( $field_row['data']['featured_image'] ) AND $field_row['data']['featured_image'] == 1 ){
ninja_forms_set_featured_image( $post_id, $attach_id );
}
update_post_meta( $attach_id, 'ninja_forms_field_id', $field_id );
update_post_meta( $attach_id, 'ninja_forms_file_key', $key );
update_post_meta( $attach_id, 'ninja_forms_upload_id', $file['upload_id'] );
$file['attachment_id'] = $attach_id;
$user_value[ $key ] = $file;
}
}
$ninja_forms_processing->update_field_value( $field_id, $user_value );
} else {
$args = array(
'post_parent' => $post_id,
'post_status' => 'null',
'post_type'=> 'attachment',
'posts_per_page' => -1,
);
$attachments = get_posts( $args );
// Loop through our attachments and make sure that we don't have any empty fields.
foreach ( $ninja_forms_processing->get_all_fields() as $field_id => $user_value ) {
if ( $ninja_forms_processing->get_field_setting( $field_id, 'type') == '_upload' ) {
if( !empty( $attachments ) ){
foreach( $attachments as $attachment ){
$attach_field = get_post_meta( $attachment->ID, 'ninja_forms_field_id', true );
if( $attach_field == $field_id && empty ( $user_value ) ){
wp_delete_attachment( $attachment->ID );
}
}
}
}
}
}
}
}
}
add_action( 'ninja_forms_create_post', 'ninja_forms_attach_files_to_post' );
add_action( 'ninja_forms_update_post', 'ninja_forms_attach_files_to_post' );
/*
*
* Function to check whether or not a file should be added to the media library. If it is, call the attachment function.
*
* @since 1.0.3
* @return void
*/
function ninja_forms_check_add_to_media_library( $form_id ){
global $ninja_forms_processing;
if ( $ninja_forms_processing->get_form_setting( 'create_post' ) != 1 ) {
if( $ninja_forms_processing->get_extra_value( 'uploads' ) ){
foreach( $ninja_forms_processing->get_extra_value( 'uploads' ) as $field_id ){
$field_row = $ninja_forms_processing->get_field_settings( $field_id );
$user_value = $ninja_forms_processing->get_field_value( $field_id );
if( isset( $field_row['data']['media_library'] ) AND $field_row['data']['media_library'] == 1 ){
if( is_array( $user_value ) ){
foreach( $user_value as $key => $file ){
$filename = $file['file_path'].$file['file_name'];
$attach_array = ninja_forms_generate_metadata( '', $filename );
$user_value[$key]['attachment_id'] = $attach_array['attach_id'];
}
// $ninja_forms_processing->update_field_value( $field_id, $user_value );
}
}
}
}
}
}
add_action( 'ninja_forms_post_process', 'ninja_forms_check_add_to_media_library' );
function ninja_forms_generate_metadata( $post_id, $filename ){
$wp_filetype = wp_check_filetype( basename( $filename ), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'null'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
$attach_data['ninja_forms_upload_field'] = true;
wp_update_attachment_metadata( $attach_id, $attach_data );
return array( 'attach_id' => $attach_id, 'attach_data' => $attach_data );
}
function ninja_forms_set_featured_image( $post_id, $attach_id ) {
// set as featured image
return update_post_meta( $post_id, '_thumbnail_id', $attach_id );
}
function ninja_forms_post_edit_file_attachment_filter( $data, $field_id ){
global $post;
$field_row = ninja_forms_get_field_by_id( $field_id );
$field_type = $field_row['type'];
if( $field_type == '_upload' AND is_object( $post ) ){
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post->ID,
'posts_per_page' => -1,
);
$attachments = get_posts($args);
if( $attachments ){
foreach ($attachments as $attachment) {
$attach_field = get_post_meta( $attachment->ID, 'ninja_forms_field_id', true );
$file_key = get_post_meta( $attachment->ID, 'ninja_forms_file_key', true );
$upload_id = get_post_meta( $attachment->ID, 'ninja_forms_upload_id', true );
if( $attach_field == $field_id ){
$filename = basename ( get_attached_file( $attachment->ID ) );
$filepath = str_replace( $filename, '', get_attached_file( $attachment->ID ) );
if ( ! is_array( $data['default_value'] ) ) {
$data['default_value'] = array();
}
$data['default_value'][$file_key] = array(
'user_file_name' => $filename,
'file_name' => $filename,
'file_path' => $filepath,
'file_url' => wp_get_attachment_url( $attachment->ID ),
'complete' => 1,
'upload_id' => $upload_id
);
}
}
}
if( isset( $field_row['data']['featured_image'] ) AND $field_row['data']['featured_image'] == 1 ){
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
if ( $post_thumbnail_id != '' ) {
$attach_field = get_post_meta( $post_thumbnail_id, 'ninja_forms_field_id', true );
if( $attach_field == '' ){
$file_key = ninja_forms_field_uploads_create_key( array() );
$upload_id = '';
$filename = basename ( get_attached_file( $post_thumbnail_id ) );
$filepath = str_replace( $filename, '', get_attached_file( $post_thumbnail_id ) );
$data['default_value'][$file_key] = array(
'user_file_name' => $filename,
'file_name' => $filename,
'file_path' => $filepath,
'file_url' => wp_get_attachment_url( $post_thumbnail_id ),
'complete' => 1,
'upload_id' => $upload_id
);
}
}
}
if( isset( $data['default_value'] ) AND is_array( $data['default_value'] ) ){
uasort($data['default_value'], 'ninja_forms_compare_file_name');
}
}
return $data;
}
add_filter( 'ninja_forms_field', 'ninja_forms_post_edit_file_attachment_filter', 25, 2 );
function ninja_forms_compare_file_name( $a, $b ){
if ( !isset ( $a['file_name'] ) or !isset ( $b['file_name'] ) )
return false;
if( $a['file_name'] == $b['file_name'] ){
return 0;
}
return ($a['file_name'] < $b['file_name']) ? -1 : 1;
}
\ No newline at end of file
<?php
/*
*
* Function that filters the email value so that only the file name is sent in the email list.
*
* @since 1.0.11
* @return $user_value string
*/
function ninja_forms_upload_email_value_filter( $user_value, $field_id ) {
global $ninja_forms_processing;
$field = $ninja_forms_processing->get_field_settings( $field_id );
if ( $field['type'] == '_upload' ) {
if ( is_array ( $user_value ) ) {
$tmp_array = array();
foreach ( $user_value as $key => $data ) {
if ( isset ( $data['user_file_name'] ) ) {
$tmp_array[] = $data['user_file_name'];
}
}
if ( empty( $tmp_array ) ) {
$tmp_array = '';
}
$user_value = $tmp_array;
}
}
return $user_value;
}
add_filter( 'ninja_forms_email_user_value', 'ninja_forms_upload_email_value_filter', 10, 2 );
\ No newline at end of file
<?php
/*
*
* Function that filters the post meta values if the field is an upload field.
*
* @since 1.0.11
* @return $value
*/
function ninja_forms_upload_post_meta_filter( $user_value, $meta_key, $field_id ){
global $ninja_forms_processing;
$field = $ninja_forms_processing->get_field_settings( $field_id );
if ( $field['type'] == '_upload' ) {
if ( is_array ( $user_value ) ) {
foreach ( $user_value as $key => $data ) {
if ( isset ( $data['file_url'] ) ) {
$user_value = $data['file_url'];
}
break;
}
}
}
return $user_value;
}
add_filter( 'ninja_forms_add_post_meta_value', 'ninja_forms_upload_post_meta_filter', 10, 3 );
\ No newline at end of file
<?php
/**
* This function will be ran during the processing (process) of a form.
* The goals here are to:
* Move the temporary file to its permanent location.
*
* @param int $field_id - ID number of the field that is currently being displayed.
* @param array/string $user_value - the value of the field within the user-submitted form.
*/
function ninja_forms_field_upload_process($field_id, $user_value){
global $ninja_forms_processing;
$field_data = $ninja_forms_processing->get_all_submitted_fields();
$plugin_settings = get_option('ninja_forms_settings');
$field_row = ninja_forms_get_field_by_id($field_id);
$field_data = $field_row['data'];
$base_upload_dir = $plugin_settings['base_upload_dir'];
if(isset($plugin_settings['custom_upload_dir'])){
$custom_upload_dir = $plugin_settings['custom_upload_dir'];
}else{
$custom_upload_dir = '';
}
$tmp_upload_file = $ninja_forms_processing->get_field_value( $field_id );
if( is_array( $tmp_upload_file ) ){
foreach( $tmp_upload_file as $key => $file ){
if( ( isset( $file['complete'] ) AND $file['complete'] == 0 ) OR !isset( $file['complete'] ) ){
if( isset( $file['file_path'] ) ){
$file_path = $file['file_path'];
}else{
$file_path = '';
}
if($file_path != ''){
$file_name = $file['file_name'];
$user_file_name = $file['user_file_name'];
$form_title = strtolower( stripslashes( trim( $ninja_forms_processing->get_form_setting('form_title') ) ) );
$form_title = preg_replace("/[\/\&%#\$]/", "", $form_title);
$form_title = preg_replace("/[\"\']/", "", $form_title);
$form_title = preg_replace('/\s+/', '', $form_title);
if(is_user_logged_in()){
$current_user = wp_get_current_user();
$user_name = $current_user->user_nicename;
$user_id = $current_user->ID;
$display_name = $current_user->display_name;
$first_name = $current_user->user_firstname;
$last_name = $current_user->user_lastname;
}else{
$user_name = '';
$user_id = '';
$display_name ='';
$first_name = '';
$last_name = '';
}
if($custom_upload_dir != ''){
$custom_upload_dir = stripslashes(trim($custom_upload_dir));
$custom_upload_dir = str_replace("%filename%", $user_file_name, $custom_upload_dir);
$custom_upload_dir = str_replace("%formtitle%", $form_title, $custom_upload_dir);
$custom_upload_dir = str_replace("%date%", date('Y-m-d'), $custom_upload_dir);
$custom_upload_dir = str_replace("%month%", date('m'), $custom_upload_dir);
$custom_upload_dir = str_replace("%day%", date('d'), $custom_upload_dir);
$custom_upload_dir = str_replace("%year%", date('Y'), $custom_upload_dir);
$custom_upload_dir = str_replace("%username%", $user_name, $custom_upload_dir);
$custom_upload_dir = str_replace("%userid%", $user_id, $custom_upload_dir);
$custom_upload_dir = str_replace("%displayname%", $display_name, $custom_upload_dir);
$custom_upload_dir = str_replace("%firstname%", $first_name, $custom_upload_dir);
$custom_upload_dir = str_replace("%lastname%", $last_name, $custom_upload_dir);
if( strpos( $custom_upload_dir, '/' ) !== false ){
$sep = '/';
}else if( strpos( $custom_upload_dir, '\\' ) !== false ){
$sep = '\\';
} else {
$sep = '/';
}
$custom_upload_dir = untrailingslashit( $custom_upload_dir );
//Replacement for line 85->98 in ninja-forms-uploads\includes\display\processing\processing.php
$tmp_upload_dir = explode( $sep, $custom_upload_dir );
$tmp_dirs = array(); //We are going to store all dir levels in this array first
$tmp_dir = $base_upload_dir; //easier to set here directly instead of in the foreach loop
//Let’s store all dir levels
foreach( $tmp_upload_dir as $dir ){
$tmp_dir = $tmp_dir.$dir.$sep;
//Prepend to array to get the deepest dir at the beginning
array_unshift($tmp_dirs, $tmp_dir);
}
$to_create = array();
//check which dirs to create
foreach( $tmp_dirs as $dir ){
if( is_dir($dir) ) {
break;
} else {
array_unshift( $to_create, $dir ); //Prepend to array so the deepest dir will at the end.
}
}
//create dirs
foreach( $to_create as $dir ) {
mkdir($dir);
}
}
$upload_dir = $base_upload_dir.$custom_upload_dir;
$upload_dir = apply_filters( 'ninja_forms_uploads_dir', $upload_dir, $field_id );
$upload_dir = trailingslashit( $upload_dir );
if( strpos( $upload_dir, '/' ) !== false ){
$sep = '/';
}else if( strpos( $upload_dir, '\\' ) !== false ){
$sep = '\\';
}
//Replacement for line 113->124 ninja-forms-uploads\includes\display\processing\processing.php
$tmp_upload_dir = explode( $sep, $upload_dir );
$tmp_dirs = array(); //We are going to store all dir levels in this array first
$tmp_dir = '';
//Let’s store all dir levels
foreach( $tmp_upload_dir as $dir ){
$tmp_dir = $tmp_dir.$dir.$sep;
//Prepend to array to get the deepest dir at the beginning
array_unshift( $tmp_dirs, $tmp_dir );
}
$to_create = array();
//check which dirs to create
foreach( $tmp_dirs as $dir ){
if( is_dir($dir) ) {
break;
} else {
array_unshift( $to_create, $dir ); //Prepend to array so the deepest dir will at the end.
}
}
//create dirs
foreach( $to_create as $dir ) {
mkdir($dir);
}
$file_dir = $upload_dir.$file_name;
if(!$ninja_forms_processing->get_all_errors()){
if( file_exists ( $file_path ) AND !is_dir( $file_path ) AND copy( $file_path, $file_dir ) ){
$current_uploads = $ninja_forms_processing->get_field_value( $field_id );
if( is_array( $current_uploads ) AND !empty( $current_uploads ) ){
foreach( $current_uploads as $key => $file ){
if( $file['file_path'] == $file_path ){
$current_uploads[$key]['file_path'] = $upload_dir;
//$current_uploads[$key]['file_name'] = $file_name;
$current_uploads[$key]['complete'] = 1;
}
}
}
$ninja_forms_processing->update_field_value($field_id, $current_uploads);
if(file_exists($file_path)){
$dir = str_replace('ninja_forms_field_'.$field_id, '', $file_path);
unlink($file_path);
if(is_dir($dir)){
rmdir($dir);
}
}
}else{
$ninja_forms_processing->add_error('upload_'.$field_id, __( 'File Upload Error', 'ninja-forms-uploads' ), $field_id);
}
}
}
}
}
if ( !$ninja_forms_processing->get_all_errors() ) {
do_action('ninja_forms_upload_process', $field_id);
}
}
}
/**
* This section updates the upload database whenever a file is uploaded.
*
*/
function ninja_forms_upload_db_update( $field_id ){
global $wpdb, $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
$user_id = $ninja_forms_processing->get_user_ID();
$files = $ninja_forms_processing->get_field_value( $field_id );
$field_row = $ninja_forms_processing->get_field_settings( $field_id );
if( is_array( $files ) AND !empty( $files ) ){
foreach( $files as $key => $f ){
if( !isset( $f['upload_id'] ) OR $f['upload_id'] == '' ){
if( isset( $field_row['data']['upload_location'] ) ) {
$f['upload_location'] = $field_row['data']['upload_location'];
}
if ( isset ( $f['user_file_name'] ) ) {
$data = serialize( $f );
$wpdb->insert( NINJA_FORMS_UPLOADS_TABLE_NAME, array('user_id' => $user_id, 'form_id' => $form_id, 'field_id' => $field_id, 'data' => $data) );
$files[$key]['upload_id'] = $wpdb->insert_id;
}
}
}
$ninja_forms_processing->update_field_value( $field_id, $files );
}
}
add_action('ninja_forms_upload_process', 'ninja_forms_upload_db_update');
/**
* Get files uploaded to form for a specific location to save to
*
* @param $location
*
* @return array|bool
*/
function ninja_forms_upload_get_uploaded_files( $location ) {
global $ninja_forms_processing;
$files = array();
if ( $ninja_forms_processing->get_extra_value( 'uploads' ) ) {
foreach ( $ninja_forms_processing->get_extra_value( 'uploads' ) as $field_id ) {
$field_row = $ninja_forms_processing->get_field_settings( $field_id );
$user_value = $ninja_forms_processing->get_field_value( $field_id );
if ( isset( $field_row['data']['upload_location'] ) AND $field_row['data']['upload_location'] == $location ) {
if ( is_array( $user_value ) ) {
$files[] = array(
'user_value' => $user_value,
'field_row' => $field_row,
'field_id' => $field_id
);
}
}
}
}
return $files;
}
/**
* Remove uploaded files
*
* @param $files
*/
function ninja_forms_upload_remove_uploaded_files( $files ) {
if ( ! $files ) {
return;
}
foreach( $files as $data ) {
if ( ! is_array( $data['user_value'] ) ) {
return;
}
foreach ( $data['user_value'] as $key => $file ) {
if ( ! isset( $file['file_path'] ) ) {
continue;
}
$filename = $file['file_path'] . $file['file_name'];
if ( file_exists( $filename ) ) {
// Delete local file
unlink( $filename );
}
}
}
}
/**
* Remove uploaded files for when a file upload field has no location set
* Eg. when an admin only wants uploads to be sent on email attachments and not saved anywhere
*/
function ninja_forms_upload_remove_files_no_location() {
$files_data = ninja_forms_upload_get_uploaded_files( 'none' );
ninja_forms_upload_remove_uploaded_files( $files_data );
}
add_action( 'ninja_forms_post_process', 'ninja_forms_upload_remove_files_no_location', 1001 );
\ No newline at end of file
<?php
add_action( 'init', 'ninja_forms_register_uploads_shortcode' );
function ninja_forms_register_uploads_shortcode(){
add_filter( 'ninja_forms_field_shortcode', 'ninja_forms_uploads_shortcode', 10, 2 );
}
function ninja_forms_uploads_shortcode( $value, $atts ){
global $ninja_forms_processing;
if( isset( $atts['method'] ) ){
$method = $atts['method'];
}else{
$method = 'link';
}
$field_settings = $ninja_forms_processing->get_field_settings( $atts['id'] );
if( $field_settings['type'] == '_upload' ){
$tmp_value = '';
if( is_array( $value ) AND !empty( $value ) ){
$x = 0;
foreach( $value as $val ){
if ( ! isset ( $val['file_url'] ) )
continue;
// Make sure we get link to external file if necessary
$url = ninja_forms_upload_file_url( $val );
$filename = $val['user_file_name'];
switch( $method ){
case 'embed':
$tmp_value .= "<img src='".$url."'>";
break;
case 'link':
if( $x > 0 ){
$tmp_value .= ", ";
}
$tmp_value .= "<a href='".$url."'>".$filename."</a>";
break;
case 'url':
$tmp_value .= $url;
break;
}
$x++;
}
}
}else{
$tmp_value = $value;
}
return $tmp_value;
}
\ No newline at end of file
<?php
add_action( 'init', 'ninja_forms_register_uploads_display_js_css' );
function ninja_forms_register_uploads_display_js_css(){
add_action( 'ninja_forms_display_js', 'ninja_forms_upload_display_js', 10, 2 );
}
function ninja_forms_upload_display_js( $form_id ){
if( !is_admin() ){
$fields = ninja_forms_get_fields_by_form_id( $form_id );
$output = false;
$multi = false;
foreach( $fields as $field ){
if( $field['type'] == '_upload' ){
if( !$output ){
$output = true;
}
if( !$multi && isset($field['data']['upload_multi']) && $field['data']['upload_multi'] == 1 ){
$multi = true;
}
}
}
if( $output ){
if ( defined( 'NINJA_FORMS_JS_DEBUG' ) && NINJA_FORMS_JS_DEBUG ) {
$suffix = '';
$src = 'dev';
} else {
$suffix = '.min';
$src = 'min';
}
wp_enqueue_script( 'ninja-forms-uploads-display',
NINJA_FORMS_UPLOADS_URL .'/js/' . $src . '/ninja-forms-uploads-display' .$suffix .'.js',
array( 'jquery', 'ninja-forms-display' ) );
if( $multi ){
wp_enqueue_script( 'jquery-multi-file',
NINJA_FORMS_UPLOADS_URL .'/js/min/jquery.MultiFile.pack.js',
array( 'jquery' ) );
wp_localize_script( 'ninja-forms-uploads-display', 'ninja_forms_uploads_settings', array( 'delete' => __( 'Really delete this item?', 'ninja-forms-uploads' ) ) );
}
}
}
}
\ No newline at end of file
<?php
require_once( NINJA_FORMS_UPLOADS_DIR . '/includes/lib/s3/s3.php' );
/**
* Class External_Amazon
*/
class External_Amazon extends NF_Upload_External {
private $title = 'Amazon S3';
private $slug = 'amazon';
private $settings;
private $connected_settings = false;
private $file_path = false;
function __construct() {
$this->set_settings();
parent::__construct( $this->title, $this->slug, $this->settings );
}
private function set_settings() {
$this->settings = array(
array(
'name' => 'amazon_s3_access_key',
'type' => 'text',
'label' => __( 'Access Key', 'ninja-forms-uploads' ),
'desc' => '',
),
array(
'name' => 'amazon_s3_secret_key',
'type' => 'text',
'label' => __( 'Secret Key', 'ninja-forms-uploads' ),
'desc' => '',
),
array(
'name' => 'amazon_s3_bucket_name',
'type' => 'text',
'label' => __( 'Bucket Name', 'ninja-forms-uploads' ),
'desc' => '',
),
array(
'name' => 'amazon_s3_file_path',
'type' => 'text',
'label' => __( 'File Path', 'ninja-forms-uploads' ),
'desc' => __( 'The default file path in the bucket where the file will be uploaded to', 'ninja-forms-uploads' ),
'default_value' => 'ninja-forms/'
),
);
}
public function is_connected() {
$data = get_option( 'ninja_forms_settings' );
if ( ( isset( $data['amazon_s3_access_key'] ) && $data['amazon_s3_access_key'] != '' ) &&
( isset( $data['amazon_s3_secret_key'] ) && $data['amazon_s3_secret_key'] != '' ) &&
( isset( $data['amazon_s3_bucket_name'] ) && $data['amazon_s3_bucket_name'] != '' ) &&
( isset( $data['amazon_s3_file_path'] ) && $data['amazon_s3_file_path'] != '' )
) {
return true;
}
return false;
}
private function load_settings() {
if ( ! $this->connected_settings ) {
$data = get_option( 'ninja_forms_settings' );
$settings = array();
$settings['access_key'] = $data['amazon_s3_access_key'];
$settings['secret_key'] = $data['amazon_s3_secret_key'];
$settings['bucket_name'] = $data['amazon_s3_bucket_name'];
$bucket = $settings['bucket_name'];
if ( ( ! isset( $data['amazon_s3_bucket_region'][ $bucket ] ) || empty( $data['amazon_s3_bucket_region'][ $bucket ] ) ) && isset( $settings['bucket_name'] ) ) {
// Retrieve the bucket region if we don't have it
// Or the bucket has changed since we last retrieved it
$s3 = new S3( $settings['access_key'], $settings['secret_key'] );
$region = $s3->getBucketLocation( $settings['bucket_name'] );
$data['amazon_s3_bucket_region'] = array( $settings['bucket_name'] => $region );
update_option( 'ninja_forms_settings', $data );
} else {
$region = $data['amazon_s3_bucket_region'][ $bucket ];
}
$settings['bucket_region'] = $region;
$settings['file_path'] = $data['amazon_s3_file_path'];
$this->connected_settings = $settings;
}
}
private function prepare( $path = false, $region = null ) {
$this->load_settings();
if ( ! $path ) {
$path = apply_filters( 'ninja_forms_uploads_' . $this->slug . '_path', $this->connected_settings['file_path'] );
} else if ( $path == '' ) {
$path = $this->connected_settings['file_path'];
}
$this->file_path = $this->sanitize_path( $path );
$s3 = new S3( $this->connected_settings['access_key'], $this->connected_settings['secret_key'] );
if ( is_null( $region ) ) {
$region = $this->connected_settings['bucket_region'];
}
if ( '' !== $region && 'US' !== $region ) {
// Use the correct API endpoint for non US standard bucket regions
$s3->setEndpoint( 's3-' . $this->connected_settings['bucket_region'] . '.amazonaws.com' );
}
return $s3;
}
public function upload_file( $file, $path = false ) {
$s3 = $this->prepare( $path );
$filename = $this->get_filename_external( $file );
$s3->putObjectFile( $file, $this->connected_settings['bucket_name'], $this->file_path . $filename, S3::ACL_PUBLIC_READ );
return array( 'path' => $this->file_path, 'filename' => $filename );
}
/**
* Get the Amazon S3 URL using bucket and region for the file, falling
* back to the settings bucket and region
*
* @param string $filename
* @param string $path
* @param array $data
*
* @return string
*/
public function file_url( $filename, $path = '', $data = array() ) {
$bucket = ( isset( $data['bucket'] ) ) ? $data['bucket'] : $this->connected_settings['bucket_name'];
$region = ( isset( $data['region'] ) ) ? $data['region'] : $this->connected_settings['bucket_region'];
$s3 = $this->prepare( $path, $region );
return $s3->getAuthenticatedURL( $bucket, $this->file_path . $filename, 3600 );
}
/**
* Save the bucket and region to the file data
* in case it is changed in settings.
*
* @param array $data
*
* @return array
*/
public function enrich_file_data( $data ) {
$data['bucket'] = $this->connected_settings['bucket_name'];
$data['region'] = $this->connected_settings['bucket_region'];
return $data;
}
}
<?php
require_once( NINJA_FORMS_UPLOADS_DIR . '/includes/lib/dropbox/dropbox.php' );
class External_Dropbox extends NF_Upload_External {
private $title = 'Dropbox';
private $slug = 'dropbox';
private $path;
private $settings;
function __construct() {
$this->set_settings();
parent::__construct( $this->title, $this->slug, $this->settings );
add_action( 'admin_init', array( $this, 'disconnect' ) );
add_action( 'admin_notices', array( $this, 'connect_notice' ) );
add_action( 'admin_notices', array( $this, 'disconnect_notice' ) );
}
private function set_settings() {
$this->settings = array(
array(
'name' => 'dropbox_connect',
'type' => '',
'label' => sprintf( __( 'Connect to %s', 'ninja-forms-uploads' ), $this->title ),
'desc' => '',
'display_function' => array( $this, 'connect_url' )
),
array(
'name' => 'dropbox_file_path',
'type' => 'text',
'label' => __( 'File Path', 'ninja-forms-uploads' ),
'desc' => __( 'Custom directory for the files to be uploaded to in your Dropbox:<br> /Apps/Ninja Forms Uploads/'. $this->get_path() , 'ninja-forms-uploads' ),
'default_value' => ''
),
array(
'name' => 'dropbox_token',
'type' => 'hidden'
)
);
}
private function get_path() {
if ( is_null( $this->path ) ) {
$plugin_settings = get_option( 'ninja_forms_settings' );
$this->path = isset( $plugin_settings['dropbox_file_path'] ) ? $plugin_settings['dropbox_file_path'] : '';
$this->path = trim( $this->path );
$this->path = apply_filters( 'ninja_forms_uploads_' . $this->slug . '_path', $this->path );
if ( '/' == $this->path ) {
$this->path = '';
}
if ( '' != $this->path ) {
$this->path = $this->sanitize_path( $this->path );
}
}
return $this->path;
}
public function is_connected() {
$data = get_option( 'ninja_forms_settings' );
if ( ( isset( $data['dropbox_access_token'] ) && $data['dropbox_access_token'] != '' ) &&
( isset( $data['dropbox_access_token_secret'] ) && $data['dropbox_access_token_secret'] != '' )
) {
if ( false === ( $authorised = get_transient( 'nf_fu_dropbox_authorised' ) ) ) {
$dropbox = new nf_dropbox();
$authorised = $dropbox->is_authorized();
set_transient( 'nf_fu_dropbox_authorised', $authorised, 60 * 60 * 5 );
}
return $authorised;
}
return false;
}
public function upload_file( $file, $path = '' ) {
$dropbox = new nf_dropbox();
$path = $this->get_path();
$filename = $this->get_filename_external( $file );
$dropbox->upload_file( $file, $filename, $path );
return array( 'path' => $path, 'filename' => $filename );
}
public function file_url( $filename, $path = '', $data = array() ) {
$dropbox = new nf_dropbox();
$url = $dropbox->get_link( $path . $filename );
if ( $url ) {
return $url;
}
return admin_url();
}
public function connect_url( $form_id, $data ) {
$dropbox = new nf_dropbox();
$callback_url = admin_url( '/admin.php?page=ninja-forms-uploads&tab=external_settings' );
$disconnect_url = admin_url( '/admin.php?page=ninja-forms-uploads&tab=external_settings&action=disconnect_' . $this->slug );
if ( $dropbox->is_authorized() ) {
?>
<a id="dropbox-disconnect" href="<?php echo $disconnect_url; ?>" class="button-secondary"><?php _e( 'Disconnect', 'ninja-forms-uploads' ); ?></a>
<?php } else { ?>
<a id="dropbox-connect" href="<?php echo $dropbox->get_authorize_url( $callback_url ); ?>" class="button-secondary"><?php _e( 'Connect', 'ninja-forms-uploads' ); ?></a>
<?php
}
}
public function disconnect() {
if ( isset( $_GET['page'] ) && $_GET['page'] == 'ninja-forms-uploads' &&
isset( $_GET['tab'] ) && $_GET['tab'] == 'external_settings' &&
isset( $_GET['action'] ) && $_GET['action'] == 'disconnect_' . $this->slug
) {
$dropbox = new nf_dropbox();
$dropbox->unlink_account();
}
}
public function connect_notice() {
if ( isset( $_GET['page'] ) && $_GET['page'] == 'ninja-forms-uploads' &&
isset( $_GET['tab'] ) && $_GET['tab'] == 'external_settings' &&
isset( $_GET['oauth_token'] ) && isset( $_GET['uid'] )
) {
echo '<div class="updated"><p>' . sprintf( __( 'Connected to %s', 'ninja-forms-uploads' ), $this->title ) . '</p></div>';
}
}
public function disconnect_notice() {
if ( isset( $_GET['page'] ) && $_GET['page'] == 'ninja-forms-uploads' &&
isset( $_GET['tab'] ) && $_GET['tab'] == 'external_settings' &&
isset( $_GET['action'] ) && $_GET['action'] == 'disconnect_' . $this->slug
) {
echo '<div class="updated"><p>' . sprintf( __( 'Disconnected from %s', 'ninja-forms-uploads' ), $this->title ) . '</p></div>';
}
}
}
\ No newline at end of file
<?php
abstract class NF_Upload_External {
private $slug;
private $title;
private $settings;
function __construct( $title, $slug, $settings ) {
$this->title = $title;
$this->slug = $slug;
$this->settings = $settings;
$this->init();
}
public function init( ){
add_action( 'admin_init', array( $this, 'register_settings' ) );
add_filter( 'ninja_forms_upload_locations', array( $this, 'register_location' ) );
add_action( 'ninja_forms_post_process', array( $this, 'upload_to_external' ) );
add_action( 'ninja_forms_post_process', array( $this, 'remove_server_upload' ), 1001 );
}
public static function instance( $external, $require = false ) {
if ( $require ) {
require_once( $external );
$external = basename( $external, '.php' );
}
$external_class = 'External_' . ucfirst( $external );
if ( class_exists( $external_class ) ) {
return new $external_class();
}
return false;
}
public function register_location( $locations ) {
if ( $this->is_connected() && ! $this->already_registered( $locations, $this->slug ) ) {
$locations[] = array(
'value' => $this->slug,
'name' => $this->title
);
}
return $locations;
}
private function already_registered( $locations, $slug ) {
foreach ( $locations as $location ) {
if ( isset( $location[ 'value' ] ) && $location[ 'value' ] == $slug ) {
return true;
}
}
return false;
}
public function register_settings() {
$args = array(
'page' => 'ninja-forms-uploads',
'tab' => 'external_settings',
'slug' => $this->slug . '_settings',
'title' => sprintf( __( '%s Settings', 'ninja-forms-uploads' ), $this->title ),
'settings' => $this->settings
);
if ( function_exists( 'ninja_forms_register_tab_metabox' ) ) {
ninja_forms_register_tab_metabox( $args );
}
}
public function is_connected() {
return false;
}
private function post_process( $form_id ) {
if ( ! $this->is_connected() ) {
return false;
}
return ninja_forms_upload_get_uploaded_files( $this->slug );
}
public function upload_to_external( $form_id ) {
$files = $this->post_process( $form_id );
if ( ! is_array( $files ) || empty( $files ) ) {
return;
}
global $ninja_forms_processing, $wpdb;
foreach ( $files as $data ) {
if ( ! $data['user_value'] ) {
continue;
}
foreach ( $data['user_value'] as $key => $file ) {
if ( ! isset( $file['file_path'] ) ) {
continue;
}
$filename = $file['file_path'] . $file['file_name'];
if ( file_exists( $filename ) ) {
$args = $this->upload_file( $filename );
if ( $args['path'] != '' ) {
$path = trailingslashit( $args['path'] );
}
if ( isset( $data['field_row']['data']['upload_location'] ) ) {
$data['user_value'][ $key ]['upload_location'] = $data['field_row']['data']['upload_location'];
}
$data['user_value'][ $key ]['external_path'] = $path;
$data['user_value'][ $key ]['external_filename'] = $args['filename'];
// Allow the external service classes to alter the file data
$file_data = $this->enrich_file_data( $data['user_value'][ $key ] );
$wpdb->update( NINJA_FORMS_UPLOADS_TABLE_NAME, array( 'data' => serialize( $file_data) ), array( 'id' => $data['user_value'][ $key ]['upload_id'] ) );
}
}
$ninja_forms_processing->update_field_value( $data['field_id'], $data['user_value'] );
}
}
public function remove_server_upload( $form_id ) {
$files = $this->post_process( $form_id );
if ( ! is_array( $files ) || empty( $files ) ) {
return;
}
ninja_forms_upload_remove_uploaded_files( $files );
}
public function upload_file( $filename, $path = '' ) {
return '';
}
public function file_url( $filename, $path = '', $data = array() ) {
return '';
}
public function sanitize_path( $path, $suffix = '/' ) {
$path = ltrim( $path, '/' );
$path = rtrim( $path, '/' );
return $path . $suffix;
}
public function get_filename_external( $file ) {
$filename = basename( $file );
$filename = time() . '-'. $filename;
return apply_filters( 'ninja_forms_uploads_' . $this->slug . '_filename', $filename );
}
public function enrich_file_data( $data ){
return $data;
}
}
\ No newline at end of file
<?php
/*
* Function that checks to see if a mutlidimensional array is empty.
*
* @since 1.2
* @return bool
*/
function ninja_forms_is_array_empty( $array ) {
if ( is_array ( $array ) ) {
foreach ( $array as $value ) {
if ( !ninja_forms_is_array_empty ( $value ) ) {
return false;
}
}
} elseif ( !empty ( $array ) ) {
return false;
}
return true;
}
/*
* Normally, Ninja Forms checks for an empty input to determine whether or not a field has been left blank.
* This function will be called to provide custom 'required field' validation.
*
* If both the $_FILES[] and $_POST['_upload_ID_user_file_name'] are empty, then the upload field has not been submitted.
*
* @param int $field_id - ID number of the field that is currently being displayed.
* @param array/string $user_value - the value of the field within the user-submitted form.
*/
function ninja_forms_field_upload_req_validation($field_id, $user_value){
global $ninja_forms_processing;
if( isset( $_FILES['ninja_forms_field_'.$field_id] ) ){
$files = array();
$fdata = $_FILES['ninja_forms_field_'.$field_id];
if( is_array( $fdata['name'] ) ){
foreach( $fdata['name'] as $key => $val ){
if( $key == 'new' ){
for ($x=0; $x < count( $fdata['name']['new'] ); $x++) {
if( $fdata['error']['new'][$x] != 4 ){
$files[$x] = array(
'name' => $fdata['name']['new'][$x],
'type' => $fdata['type']['new'][$x],
'tmp_name'=> $fdata['tmp_name']['new'][$x],
'error' => $fdata['error']['new'][$x],
'size' => $fdata['size']['new'][$x],
);
}
}
}else{
$files[$key]=array(
'name' => $fdata['name'][$key],
'type' => $fdata['type'][$key],
'tmp_name'=> $fdata['tmp_name'][$key],
'error' => $fdata['error'][$key],
'size' => $fdata['size'][$key],
'key' => $key
);
}
}
$multi = true;
}else{
$files[0] = $fdata;
$multi = false;
}
$file_error = false;
if ( empty( $files ) ) {
$file_error = true;
}
if(!isset($_POST['_upload_'.$field_id])){
$name = false;
}else{
$name = true;
}
if($file_error AND !$name){
return false;
}else{
return true;
}
}else{
if( $ninja_forms_processing->get_field_value( $field_id ) ){
$user_value = $ninja_forms_processing->get_field_value( $field_id );
if ( ninja_forms_is_array_empty( $user_value ) ) {
return false;
} else {
return true;
}
}else{
return false;
}
}
}
/**
* This function will filter the values output into the submissions table for uploads.
* Instead of outputting what is actually in the submission database, which is an array of values (file_name, file_path, file_url),
* this filter will output a link to where the file is stored.
*
* @param array/string $user_value - the value of the field within the user-submitted form.
* @param int $field_id - ID number of the field that is currently being displayed.
*/
function ninja_forms_field_upload_sub_td($user_value, $field_id){
$field_row = ninja_forms_get_field_by_id($field_id);
$field_type = $field_row['type'];
if($field_type == '_upload'){
if ( is_array( $user_value ) ) {
$user_value = NF_File_Uploads()->normalize_submission_value( $user_value );
$new_value = '';
$x = 0;
foreach($user_value as $value){
if($x > 0){
$new_value .= ' , ';
}
$new_value .= '<a href="'.$value['file_url'].'" target="_blank">'.$value['file_name'].'</a>';
$x++;
}
$user_value = $new_value;
}
}
return $user_value;
}
/**
* This function will filter the values that are saved within the submission database.
* It allows those editing the submission to replace files submitted by uploading new ones.
*
* @param array/string $user_value - the value of the field within the user-submitted form.
* @param int $field_id - ID number of the field that is currently being displayed.
*/
function ninja_forms_field_upload_save_sub($user_value, $field_id){
global $ninja_forms_processing;
$field_row = ninja_forms_get_field_by_id($field_id);
$field_type = $field_row['type'];
$sub_id = $ninja_forms_processing->get_form_setting('sub_id');
if($field_type == '_upload'){
if($ninja_forms_processing->get_form_setting('doing_save')){
ninja_forms_field_upload_pre_process($field_id, $user_value);
$user_value = $ninja_forms_processing->get_field_value($field_id);
}else{
//Check to see if sub_id has been set. If it hasn't, then don't do any filtering.
if($sub_id != ''){
//Check to see if this is an upload field. If it is, we'll do some processing.
//If not, we'll just return the $user_value that was passed.
if(isset($_FILES['ninja_forms_field_'.$field_id]['error'][0]) AND $_FILES['ninja_forms_field_'.$field_id]['error'][0] != 4){
ninja_forms_field_upload_pre_process($field_id, $user_value);
ninja_forms_field_upload_process($field_id, $user_value);
$user_value = $ninja_forms_processing->get_field_value($field_id);
}else if(isset($_POST['_upload_'.$field_id])){
$user_value = $_POST['_upload_'.$field_id];
}
}
}
}
return $user_value;
}
function ninja_forms_field_upload_filter_data($data, $field_id){
$field_row = ninja_forms_get_field_by_id($field_id);
$field_type = $field_row['type'];
if($field_type == '_upload'){
$data['label'] = '';
}
return $data;
}
function ninja_forms_get_uploads($args = array()){
global $wpdb;
$plugin_settings = get_option( 'ninja_forms_settings' );
if ( isset ( $plugin_settings['date_format'] ) ) {
$date_format = $plugin_settings['date_format'];
} else {
$date_format = 'mm/dd/yyyy';
}
$where = '';
$limit = '';
$upload_id = '';
if(!empty($args)){
if(isset($args['form_id'])){
$where .= 'WHERE `form_id` = '.$args['form_id'];
}
if( isset( $args['upload_user'] ) ){
$user = $args['upload_user'];
if( is_numeric( $user ) ){
if($where == ''){
$where .= "WHERE ";
}else{
$where .= " AND ";
}
$where .= "`user_id` = ".$user;
}else{
$user_data = get_user_by( 'email', $user );
if( !$user_data ){
$user_data = get_user_by( 'slug', $user );
}
if( !$user_data ){
$user_data = get_user_by( 'login', $user );
}
if($where == ''){
$where .= "WHERE ";
}else{
$where .= " AND ";
}
if( $user_data ){
$user_id = $user_data->ID;
$where .= "`user_id` = ".$user_id;
}else{
$where .="`user_id` = 0";
}
}
}
if(isset($args['id'])){
if($where == ''){
$where .= "WHERE ";
}else{
$where .= " AND ";
}
$where .= "`id` = ".$args['id'];
$upload_id = $args['id'];
}
if(isset($args['begin_date'])){
$begin_date = $args['begin_date'];
if ( strtolower( substr( $date_format, 0, 1 ) ) == 'd' ) {
$begin_date = str_replace( '/', '-', $begin_date );
}
$begin_date .= ' 23:59:59';
$begin_date = strtotime($begin_date);
$begin_date = date("Y-m-d g:i:s", $begin_date);
if($where == ''){
$where .= "WHERE ";
}else{
$where .= " AND ";
}
$where .= "DATE(date_updated) > '".$begin_date."'";
}
if(isset($args['end_date'])){
$end_date = $args['end_date'];
if ( strtolower( substr( $date_format, 0, 1 ) ) == 'd' ) {
$end_date = str_replace( '/', '-', $end_date );
}
$end_date .= ' 23:59:59';
$end_date = strtotime($end_date);
$end_date = date("Y-m-d g:i:s", $end_date);
if($where == ''){
$where .= "WHERE ";
}else{
$where .= " AND ";
}
$where .= "DATE(date_updated) < '".$end_date."'";
}
}
$results = $wpdb->get_results( "SELECT * FROM ".NINJA_FORMS_UPLOADS_TABLE_NAME." ".$where." ORDER BY `date_updated` DESC", ARRAY_A );
if( isset( $args['upload_types'] ) OR isset( $args['upload_name'] ) ){
if(is_array($results) AND !empty($results)){
$tmp_results = array();
for ($x = 0; $x < count($results); $x++){
$results[$x]['data'] = unserialize($results[$x]['data']);
$data = $results[$x]['data'];
$form_id = $results[$x]['form_id'];
$form_row = ninja_forms_get_form_by_id($form_id);
$form_data = $form_row['data'];
if ( isset ( $form_data['form_title'] ) ) {
$form_title = $form_data['form_title'];
} else {
$form_title = '';
}
$results[$x]['data']['form_title'] = $form_title;
$user_file_name = $data['user_file_name'];
$user_file_array = explode(".", $user_file_name);
$user_ext = array_pop($user_file_array);
$file_name = $data['file_name'];
$file_array = explode(".", $file_name);
$ext = array_pop($file_array);
if(isset($args['upload_name'])){
if(stripos($file_name, $args['upload_name']) !== false OR stripos($user_file_name, $args['upload_name']) !== false){
$file_name_found = true;
}else{
$file_name_found = false;
}
}
if(isset($args['upload_types'])){
if( stripos( $args['upload_types'], $user_ext ) !== false OR stripos( $args['upload_types'], $ext ) !== false ){
$ext_found = true;
}else{
$ext_found = false;
}
}
if(isset($args['upload_name']) AND isset($args['upload_types'])){
if($file_name_found AND $ext_found){
array_push($tmp_results, $results[$x]);
}
}else if(isset($args['upload_name']) AND !isset($args['upload_types'])){
if($file_name_found){
array_push($tmp_results, $results[$x]);
}
}else if(isset($args['upload_types']) AND !isset($args['upload_name'])){
if($ext_found){
array_push($tmp_results, $results[$x]);
}
}
}
$results = $tmp_results;
}
}else{
if(is_array($results) AND !empty($results)){
for ($x = 0; $x < count($results); $x++){
$results[$x]['data'] = unserialize($results[$x]['data']);
}
}
}
ksort($results);
array_values($results);
if($upload_id != ''){
$results = $results[0];
}
return $results;
}
// ninja_forms_delete_upload is located in includes/ajax.php.
\ No newline at end of file
<?php
/**
* Abstract OAuth consumer
* @author Ben Tadiar <ben@handcraftedbyben.co.uk>
* @link https://github.com/benthedesigner/dropbox
* @package Dropbox\OAuth
* @subpackage Consumer
*/
abstract class Dropbox_OAuth_Consumer_ConsumerAbstract
{
// Dropbox web endpoint
const WEB_URL = 'https://www.dropbox.com/1/';
// OAuth flow methods
const REQUEST_TOKEN_METHOD = 'oauth/request_token';
const AUTHORISE_METHOD = 'oauth/authorize';
const ACCESS_TOKEN_METHOD = 'oauth/access_token';
/**
* Signature method, either PLAINTEXT or HMAC-SHA1
* @var string
*/
private $sigMethod = 'PLAINTEXT';
/**
* Output file handle
* @var null|resource
*/
protected $outFile = null;
/**
* Input file handle
* @var null|resource
*/
protected $inFile = null;
/**
* OAuth token
* @var stdclass
*/
private $token = null;
/**
* Acquire an unauthorised request token
* @link http://tools.ietf.org/html/rfc5849#section-2.1
* @return void
*/
public function getRequestToken()
{
$url = Dropbox_API::API_URL . self::REQUEST_TOKEN_METHOD;
$response = $this->fetch('POST', $url, '');
return $this->parseTokenString($response['body']);
}
/**
* Build the user authorisation URL
* @return string
*/
public function getAuthoriseUrl( $callback_url )
{
// Prepare request parameters
$params = array(
'oauth_token' => $this->token->oauth_token,
'oauth_token_secret' => $this->token->oauth_token_secret,
'oauth_callback' => $callback_url,
);
// Build the URL and redirect the user
$query = '?' . http_build_query($params, '', '&');
$url = self::WEB_URL . self::AUTHORISE_METHOD . $query;
return $url;
}
/**
* Acquire an access token
* Tokens acquired at this point should be stored to
* prevent having to request new tokens for each API call
* @link http://tools.ietf.org/html/rfc5849#section-2.3
*/
public function getAccessToken()
{
// Get the signed request URL
$response = $this->fetch('POST', Dropbox_API::API_URL, self::ACCESS_TOKEN_METHOD);
return $this->parseTokenString($response['body']);
}
/**
* Generate signed request URL
* See inline comments for description
* @link http://tools.ietf.org/html/rfc5849#section-3.4
* @param string $method HTTP request method
* @param string $url API endpoint to send the request to
* @param string $call API call to send
* @param array $additional Additional parameters as an associative array
* @return array
*/
protected function getSignedRequest($method, $url, $call, array $additional = array())
{
// Get the request/access token
$token = $this->token;
if (!$token) {
$token = new stdClass();
$token->oauth_token = null;
$token->oauth_token_secret = null;
}
// Generate a random string for the request
$nonce = md5(microtime(true) . uniqid('', true));
// Prepare the standard request parameters
$params = array(
'oauth_consumer_key' => $this->consumerKey,
'oauth_token' => $token->oauth_token,
'oauth_signature_method' => $this->sigMethod,
'oauth_version' => '1.0',
// Generate nonce and timestamp if signature method is HMAC-SHA1
'oauth_timestamp' => ($this->sigMethod == 'HMAC-SHA1') ? time() : null,
'oauth_nonce' => ($this->sigMethod == 'HMAC-SHA1') ? $nonce : null,
);
// Merge with the additional request parameters
$params = array_merge($params, $additional);
ksort($params);
// URL encode each parameter to RFC3986 for use in the base string
$encoded = array();
foreach ($params as $param => $value) {
if ($value !== null) {
// If the value is a file upload (prefixed with @), replace it with
// the destination filename, the file path will be sent in POSTFIELDS
if (isset($value[0]) && $value[0] === '@') $value = $params['filename'];
$encoded[] = $this->encode($param) . '=' . $this->encode($value);
} else {
unset($params[$param]);
}
}
// Build the first part of the string
$base = $method . '&' . $this->encode($url . $call) . '&';
// Re-encode the encoded parameter string and append to $base
$base .= $this->encode(implode('&', $encoded));
// Concatenate the secrets with an ampersand
$key = $this->consumerSecret . '&' . $token->oauth_token_secret;
// Get the signature string based on signature method
$signature = $this->getSignature($base, $key);
$params['oauth_signature'] = $signature;
// Build the signed request URL
$query = '?' . http_build_query($params, '', '&');
return array(
'url' => $url . $call . $query,
'postfields' => $params,
);
}
/**
* Generate the oauth_signature for a request
* @param string $base Signature base string, used by HMAC-SHA1
* @param string $key Concatenated consumer and token secrets
*/
private function getSignature($base, $key)
{
switch ($this->sigMethod) {
case 'PLAINTEXT':
$signature = $key;
break;
case 'HMAC-SHA1':
$signature = base64_encode(hash_hmac('sha1', $base, $key, true));
break;
}
return $signature;
}
/**
* Set the token to use for OAuth requests
* @param stdtclass $token A key secret pair
*/
public function setToken($token)
{
if (!is_object($token))
throw new Exception('Token is invalid.');
$this->token = $token;
return $this;
}
public function resetToken()
{
$token = new stdClass;
$token->oauth_token = false;
$token->oauth_token_secret = false;
$this->setToken($token);
return $this;
}
/**
* Set the OAuth signature method
* @param string $method Either PLAINTEXT or HMAC-SHA1
* @return void
*/
public function setSignatureMethod($method)
{
$method = strtoupper($method);
switch ($method) {
case 'PLAINTEXT':
case 'HMAC-SHA1':
$this->sigMethod = $method;
break;
default:
throw new Exception('Unsupported signature method ' . $method);
}
}
/**
* Set the output file
* @param resource Resource to stream response data to
* @return void
*/
public function setOutFile($handle)
{
if (!is_resource($handle) || get_resource_type($handle) != 'stream') {
throw new Exception('Outfile must be a stream resource');
}
$this->outFile = $handle;
}
/**
* Set the input file
* @param resource Resource to read data from
* @return void
*/
public function setInFile($handle)
{
if (!is_resource($handle) || get_resource_type($handle) != 'stream') {
throw new Exception('Infile must be a stream resource');
}
fseek($handle, 0);
$this->inFile = $handle;
}
/**
* Parse response parameters for a token into an object
* Dropbox returns tokens in the response parameters, and
* not a JSON encoded object as per other API requests
* @link http://oauth.net/core/1.0/#response_parameters
* @param string $response
* @return object stdClass
*/
private function parseTokenString($response)
{
if (!$response)
throw new Exception('Response cannot be null');
$parts = explode('&', $response);
$token = new stdClass();
foreach ($parts as $part) {
list($k, $v) = explode('=', $part, 2);
$k = strtolower($k);
$token->$k = $v;
}
return $token;
}
/**
* Encode a value to RFC3986
* This is a convenience method to decode ~ symbols encoded
* by rawurldecode. This will encode all characters except
* the unreserved set, ALPHA, DIGIT, '-', '.', '_', '~'
* @link http://tools.ietf.org/html/rfc5849#section-3.6
* @param mixed $value
*/
private function encode($value)
{
return str_replace('%7E', '~', rawurlencode($value));
}
}
<?php
/**
* OAuth consumer using PHP cURL
* @author Ben Tadiar <ben@handcraftedbyben.co.uk>
* @link https://github.com/benthedesigner/dropbox
* @package Dropbox\OAuth
* @subpackage Consumer
*/
class Dropbox_OAuth_Consumer_Curl extends Dropbox_OAuth_Consumer_ConsumerAbstract
{
/**
* Default cURL options
* @var array
*/
protected $defaultOptions = array(
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
);
/**
* Store the last response form the API
* @var mixed
*/
protected $lastResponse = null;
/**
* Set properties and begin authentication
* @param string $key
* @param string $secret
*/
public function __construct($key, $secret)
{
// Check the cURL extension is loaded
if (!extension_loaded('curl')) {
throw new Exception('The cURL OAuth consumer requires the cURL extension');
}
$this->consumerKey = $key;
$this->consumerSecret = $secret;
}
/**
* Execute an API call
* @todo Improve error handling
* @param string $method The HTTP method
* @param string $url The API endpoint
* @param string $call The API method to call
* @param array $additional Additional parameters
* @return string|object stdClass
*/
public function fetch($method, $url, $call, $additional = array())
{
// Get the signed request URL
$request = $this->getSignedRequest($method, $url, $call, $additional);
// Initialise and execute a cURL request
$handle = curl_init($request['url']);
// Get the default options array
$options = $this->defaultOptions;
$options[CURLOPT_CAINFO] = dirname(__FILE__) . '/ca-bundle.pem';
if ($method == 'GET' && $this->outFile) { // GET
$options[CURLOPT_RETURNTRANSFER] = false;
$options[CURLOPT_HEADER] = false;
$options[CURLOPT_FILE] = $this->outFile;
$options[CURLOPT_BINARYTRANSFER] = true;
$this->outFile = null;
} elseif ($method == 'POST') { // POST
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $request['postfields'];
} elseif ($method == 'PUT' && $this->inFile) { // PUT
$options[CURLOPT_PUT] = true;
$options[CURLOPT_INFILE] = $this->inFile;
// @todo Update so the data is not loaded into memory to get its size
$options[CURLOPT_INFILESIZE] = strlen(stream_get_contents($this->inFile));
fseek($this->inFile, 0);
$this->inFile = null;
}
// Set the cURL options at once
@curl_setopt_array($handle, $options);
// Execute and parse the response
$response = curl_exec($handle);
//Check if a curl error has occured
if ($response === false)
throw new Exception("Error Processing Request: " . curl_error($handle));
curl_close($handle);
// Parse the response if it is a string
if (is_string($response)) {
$response = $this->parse($response);
}
// Set the last response
$this->lastResponse = $response;
// Check if an error occurred and throw an Exception
if (!empty($response['body']->error)) {
// var_dump( $response['body']->error );
// die();
// Dropbox returns error messages inconsistently...
if ($response['body']->error instanceof stdClass) {
$array = array_values((array) $response['body']->error);
$response['body']->error = $array[0];
}
// Throw an Exception with the appropriate with the appropriate code
throw new Exception($response['body']->error, $response['code']);
}
return $response;
}
/**
* Parse a cURL response
* @param string $response
* @return array
*/
private function parse($response)
{
// cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string
if (stripos($response, "HTTP/1.0 200 Connection established\r\n\r\n") !== false) {
$response = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $response);
}
// Explode the response into headers and body parts (separated by double EOL)
list($headers, $response) = explode("\r\n\r\n", $response, 2);
// Explode response headers
$lines = explode("\r\n", $headers);
// If the status code is 100, the API server must send a final response
// We need to explode the response again to get the actual response
if (preg_match('#^HTTP/1.1 100#', $lines[0])) {
list($headers, $response) = explode("\r\n\r\n", $response, 2);
$lines = explode("\r\n", $headers);
}
// Get the HTTP response code from the first line
$first = array_shift($lines);
$pattern = '#^HTTP/1.1 ([0-9]{3})#';
preg_match($pattern, $first, $matches);
$code = $matches[1];
// Parse the remaining headers into an associative array
$headers = array();
foreach ($lines as $line) {
list($k, $v) = explode(': ', $line, 2);
$headers[strtolower($k)] = $v;
}
// If the response body is not a JSON encoded string
// we'll return the entire response body
if (!$body = json_decode($response)) {
$body = $response;
}
return array('code' => $code, 'body' => $body, 'headers' => $headers);
}
/**
* Return the response for the last API request
* @return mixed
*/
public function getlastResponse()
{
return $this->lastResponse;
}
}
<?php
require_once(NINJA_FORMS_UPLOADS_DIR. "/includes/lib/dropbox/API.php");
require_once(NINJA_FORMS_UPLOADS_DIR. "/includes/lib/dropbox/OAuth/Consumer/ConsumerAbstract.php");
require_once(NINJA_FORMS_UPLOADS_DIR. "/includes/lib/dropbox/OAuth/Consumer/Curl.php");
class nf_dropbox
{
const CONSUMER_KEY = 'g80jscev5iosghi';
const CONSUMER_SECRET = 'hsy0xtrr3gjkd0i';
const RETRY_COUNT = 3;
private static $instance = null;
private
$dropbox,
$request_token,
$access_token,
$oauth_state,
$oauth,
$account_info_cache,
$settings,
$directory_cache = array()
;
public function __construct()
{
$this->init();
}
public function init()
{
$this->settings = get_option( 'ninja_forms_settings' );
if (!extension_loaded('curl')) {
throw new Exception(sprintf(
__('The cURL extension is not loaded. %sPlease ensure its installed and activated.%s', 'ninja-forms-upload'),
'<a href="http://php.net/manual/en/curl.installation.php">',
'</a>'
));
}
$this->oauth = new Dropbox_OAuth_Consumer_Curl(self::CONSUMER_KEY, self::CONSUMER_SECRET);
$this->oauth_state = $this->get_option('dropbox_oauth_state');
$this->request_token = $this->get_token('request');
$this->access_token = $this->get_token('access');
if ($this->oauth_state == 'request') {
//If we have not got an access token then we need to grab one
try {
$this->oauth->setToken($this->request_token);
$this->access_token = $this->oauth->getAccessToken();
$this->oauth_state = 'access';
$this->oauth->setToken($this->access_token);
$this->save_tokens();
//Supress the error because unlink, then init should be called
} catch (Exception $e) {}
} elseif ($this->oauth_state == 'access') {
$this->oauth->setToken($this->access_token);
} else {
//If we don't have an acess token then lets setup a new request
$this->request_token = $this->oauth->getRequestToken();
$this->oauth->setToken($this->request_token);
$this->oauth_state = 'request';
$this->save_tokens();
}
$this->dropbox = new Dropbox_API($this->oauth);
}
private function get_token($type)
{
$token = $this->get_option("dropbox_{$type}_token");
$token_secret = $this->get_option("dropbox_{$type}_token_secret");
$ret = new stdClass;
$ret->oauth_token = null;
$ret->oauth_token_secret = null;
if ($token && $token_secret) {
$ret = new stdClass;
$ret->oauth_token = $token;
$ret->oauth_token_secret = $token_secret;
}
return $ret;
}
public function is_authorized()
{
try {
$this->get_account_info();
return true;
} catch (Exception $e) {
return false;
}
}
public function get_authorize_url( $callback_url )
{
return $this->oauth->getAuthoriseUrl( $callback_url );
}
public function get_account_info()
{
if (!isset($this->account_info_cache)) {
$response = $this->dropbox->accountInfo();
$this->account_info_cache = $response['body'];
}
return $this->account_info_cache;
}
private function save_tokens()
{
$this->set_option('dropbox_oauth_state', $this->oauth_state);
if ($this->request_token) {
$this->set_option('dropbox_request_token', $this->request_token->oauth_token);
$this->set_option('dropbox_request_token_secret', $this->request_token->oauth_token_secret);
} else {
$this->set_option('dropbox_request_token', null);
$this->set_option('dropbox_request_token_secret', null);
}
if ($this->access_token) {
$this->set_option('dropbox_access_token', $this->access_token->oauth_token);
$this->set_option('dropbox_access_token_secret', $this->access_token->oauth_token_secret);
} else {
$this->set_option('dropbox_access_token', null);
$this->set_option('dropbox_access_token_secret', null);
}
$this->save_options();
return $this;
}
private function get_option( $key ) {
if ( isset ( $key ) && isset( $this->settings[$key] ) ) {
return $this->settings[$key];
} else {
return false;
}
}
private function set_option( $key, $value ) {
$this->settings[$key] = $value;
}
private function save_options() {
update_option( 'ninja_forms_settings', $this->settings );
}
public function upload_file( $file, $filename, $path = '' ) {
if ( $filename === '' ) {
$filename = $this->remove_secret( $file );
}
$i = 0;
while ( $i ++ < self::RETRY_COUNT ) {
try {
return $this->dropbox->putFile( $file, $filename, $path );
} catch ( Exception $e ) {
}
}
throw $e;
}
public function get_link( $path ) {
$response = $this->dropbox->media( $path );
if ( $response['code'] == 200 ) {
return $response['body']->url;
}
return false;
}
public function chunk_upload_file($path, $file, $processed_file)
{
$offest = $upload_id = null;
if ($processed_file) {
$offest = $processed_file->offset;
$upload_id = $processed_file->uploadid;
}
return $this->dropbox->chunkedUpload($file, $this->remove_secret($file), $path, true, $offest, $upload_id);
}
public function delete_file($file)
{
return $this->dropbox->delete($file);
}
public function create_directory($path)
{
try {
$this->dropbox->create($path);
} catch (Exception $e) {}
}
public function get_directory_contents($path)
{
if (!isset($this->directory_cache[$path])) {
try {
$this->directory_cache[$path] = array();
$response = $this->dropbox->metaData($path);
foreach ($response['body']->contents as $val) {
if (!$val->is_dir) {
$this->directory_cache[$path][] = basename($val->path);
}
}
} catch (Exception $e) {
$this->create_directory($path);
}
}
return $this->directory_cache[$path];
}
public function unlink_account()
{
$this->oauth->resetToken();
$this->request_token = null;
$this->access_token = null;
$this->oauth_state = null;
return $this->save_tokens();
}
public static function remove_secret($file, $basename = true)
{
if (preg_match('/-nf-secret$/', $file))
$file = substr($file, 0, strrpos($file, '.'));
if ($basename)
return basename($file);
return $file;
}
}
\ No newline at end of file
jQuery(document).ready(function($) {
/* * * Begin File Upload Settings JS * * */
$("#ninja_forms_reset_base_upload_dir").click(function(){
var default_base_dir = $("#ninja_forms_default_base_upload_dir").val();
var default_base_url = $("#ninja_forms_default_base_upload_url").val();
$("#base_upload_dir").val(default_base_dir);
$("#base_upload_url").val(default_base_url);
});
$(".ninja-forms-delete-upload").click(function(e){
e.preventDefault();
var answer = confirm("Delete this file?");
if(answer){
var upload_id = this.id.replace('delete_upload_', '');
$.post(ajaxurl, { upload_id: upload_id, action:"ninja_forms_delete_upload"}, function(response){
//alert(response);
$("#ninja_forms_upload_" + upload_id + "_tr").css("background-color", "#FF0000").fadeOut("slow", function(){
$(this).remove();
if($("#ninja_forms_uploads_tbody tr").length == 0){
var html = "<tr id='ninja_forms_files_empty' style=''><td colspan='7'>No files found</td></tr>";
$("#ninja_forms_uploads_tbody").append(html);
}
});
});
}
});
$(".ninja-forms-change-file-upload").click(function(e){
e.preventDefault();
var file_upload_id = this.id.replace('ninja_forms_change_file_upload_', '');
$("#ninja_forms_file_upload_" + file_upload_id).toggle();
});
$(document).on( 'click', '.ninja-forms-rename-help', function(event){
event.preventDefault();
if( !$("#tab-panel-upload_help").is(":visible") ){
$("#tab-link-upload_help").find("a").click();
$("#contextual-help-link").click().focus();
}
});
/* * * End File Upload Settings JS * * */
});
\ No newline at end of file
jQuery(document).ready(function(jQuery) {
/* * * Begin File Upload JS * * */
jQuery(".ninja-forms-change-file-upload").click(function(e){
e.preventDefault();
var file_upload_id = this.id.replace('ninja_forms_change_file_upload_', '');
jQuery("#ninja_forms_file_upload_" + file_upload_id).toggle();
});
jQuery(".ninja-forms-delete-file-upload").click(function(e){
e.preventDefault();
//var answer = confirm( ninja_forms_uploads_settings.delete );
//if(answer){
var file_upload_li = this.id.replace('_delete', '' );
file_upload_li += "_li";
jQuery("#" + file_upload_li).fadeOut('fast', function(){
jQuery("#" + file_upload_li).remove();
});
//}
});
jQuery( document ).on( 'submitResponse.uploads', function( e, response ) {
var success = response.success;
var form_settings = response.form_settings;
var hide_complete = form_settings.hide_complete;
var clear_complete = form_settings.clear_complete;
if ( success != false && clear_complete == 1 ) {
if( jQuery.isFunction( jQuery.fn.MultiFile ) ) {
jQuery('input:file.multi').MultiFile('reset');
}
}
});
/* * * End File Upload JS * * */
});
\ No newline at end of file
/*
### jQuery Multiple File Upload Plugin v1.48 - 2012-07-19 ###
* Home: http://www.fyneworks.com/jquery/multiple-file-upload/
* Code: http://code.google.com/p/jquery-multifile-plugin/
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
###
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3(L.1y)(6(a){a.7.2=6(b){3(5.N==0)8 5;3(R Q[0]=="14"){3(5.N>1){l c=Q;8 5.K(6(){a.7.2.Y(a(5),c)})}a.7.2[Q[0]].Y(5,a.2b(Q).2a(1)||[]);8 5}l b=a.G({},a.7.2.v,b||{});a("29").1m("2-M").P("2-M").1u(a.7.2.T);3(a.7.2.v.X){a.7.2.1i(a.7.2.v.X);a.7.2.v.X=V}5.1m(".2-17").P("2-17").K(6(){L.2=(L.2||0)+1;l c=L.2;l d={e:5,E:a(5),I:a(5).I()};3(R b=="28")b={k:b};l e=a.G({},a.7.2.v,b||{},(a.1e?d.E.1e():a.27?d.E.12():V)||{},{});3(!(e.k>0)){e.k=d.E.B("1I")}3(!(e.k>0)){e.k=(r(d.e.1n.u(/\\b(k|24)\\-([0-9]+)\\b/o)||[""]).u(/[0-9]+/o)||[""])[0];3(!(e.k>0))e.k=-1;23 e.k=r(e.k).u(/[0-9]+/o)[0]}e.k=18 22(e.k);e.j=e.j||d.E.B("j")||"";3(!e.j){e.j=d.e.1n.u(/\\b(j\\-[\\w\\|]+)\\b/o)||"";e.j=(18 r(e.j)).p(/^(j|1a)\\-/i,"")}a.G(d,e||{});d.s=a.G({},a.7.2.v.s,d.s);a.G(d,{n:0,C:[],1Y:[],1b:d.e.A||"2"+r(c),1s:6(a){8 d.1b+(a>0?"1W"+r(a):"")},z:6(b,c){l e=d[b],f=a(c).B("t");3(e){l g=e(c,f,d);3(g!=V)8 g}8 13}});3(r(d.j).N>1){d.j=d.j.p(/\\W+/g,"|").p(/^\\W|\\W$/g,"");d.1f=18 1U("\\\\.("+(d.j?d.j:"")+")$","o")}d.H=d.1b+"1T";d.E.1H(\'<J O="2-1H" A="\'+d.H+\'"></J>\');d.1k=a("#"+d.H+"");d.e.y=d.e.y||"m"+c+"[]";3(!d.F){d.1k.16(\'<J O="2-F" A="\'+d.H+\'1p"></J>\');d.F=a("#"+d.H+"1p")}d.F=a(d.F);d.Z=6(b,e){d.n++;b.2=d;3(e>0)b.A=b.y="";3(e>0)b.A=d.1s(e);b.y=r(d.1r.p(/\\$y/o,a(d.I).B("y")).p(/\\$A/o,a(d.I).B("A")).p(/\\$g/o,c).p(/\\$i/o,e));3(d.k>0&&d.n-1>d.k)b.10=13;d.11=d.C[e]=b;b=a(b);b.19("").B("t","")[0].t="";b.P("2-17");b.1S(6(){a(5).1O();3(!d.z("1L",5,d))8 q;l c="",f=r(5.t||"");3(d.j&&f&&!f.u(d.1f))c=d.s.1z.p("$1a",r(f.u(/\\.\\w{1,4}$/o)));1B(l g 26 d.C)3(d.C[g]&&d.C[g]!=5)3(d.C[g].t==f)c=d.s.1D.p("$m",f.u(/[^\\/\\\\]+$/o));l h=a(d.I).I();h.P("2");3(c!=""){d.1F(c);d.n--;d.Z(h[0],e);b.1G().1J(h);b.D();8 q}a(5).1C({1A:"1K",1x:"-1M"});b.1N(h);d.1w(5,e);d.Z(h[0],e+1);3(!d.z("1P",5,d))8 q});a(b).12("2",d)};d.1w=6(b,c){3(!d.z("1Q",b,d))8 q;l e=a(\'<J O="2-1R"></J>\'),f=r(b.t||""),g=a(\'<1v O="2-1h" 1h="\'+d.s.U.p("$m",f)+\'">\'+d.s.m.p("$m",f.u(/[^\\/\\\\]+$/o)[0])+"</1v>"),h=a(\'<a O="2-D" 1V="#\'+d.H+\'">\'+d.s.D+"</a>");d.F.16(e.16(h," ",g));h.1t(6(){3(!d.z("1X",b,d))8 q;d.n--;d.11.10=q;d.C[c]=V;a(b).D();a(5).1G().D();a(d.11).1C({1A:"",1x:""});a(d.11).S().19("").B("t","")[0].t="";3(!d.z("1Z",b,d))8 q;8 q});3(!d.z("20",b,d))8 q};3(!d.2)d.Z(d.e,0);d.n++;d.E.12("2",d)})};a.G(a.7.2,{S:6(){l b=a(5).12("2");3(b)b.F.21("a.2-D").1t();8 a(5)},T:6(b){b=(R b=="14"?b:"")||"1d";l c=[];a("15:m.2").K(6(){3(a(5).19()=="")c[c.N]=5});8 a(c).K(6(){5.10=13}).P(b)},1c:6(b){b=(R b=="14"?b:"")||"1d";8 a("15:m."+b).25(b).K(6(){5.10=q})},M:{},1i:6(b,c,d){l e,f;d=d||[];3(d.1l.1g().1E("1j")<0)d=[d];3(R b=="6"){a.7.2.T();f=b.Y(c||L,d);1q(6(){a.7.2.1c()},1o);8 f}3(b.1l.1g().1E("1j")<0)b=[b];1B(l g=0;g<b.N;g++){e=b[g]+"";3(e)(6(b){a.7.2.M[b]=a.7[b]||6(){};a.7[b]=6(){a.7.2.T();f=a.7.2.M[b].Y(5,Q);1q(6(){a.7.2.1c()},1o);8 f}})(e)}}});a.7.2.v={j:"",k:-1,1r:"$y",s:{D:"x",1z:"2c 2d 2e a $1a m.\\2f 2g...",m:"$m",U:"2h U: $m",1D:"2i m 2j 2k 2l U:\\n$m"},X:["1u","2m","2n","2o","2p"],1F:6(a){2q(a)}};a.7.S=6(){8 5.K(6(){2r{5.S()}2s(a){}})};a(6(){a("15[2t=m].2u").2()})})(1y)',62,155,'||MultiFile|if||this|function|fn|return|||||||||||accept|max|var|file||gi|replace|false|String|STRING|value|match|options|||name|trigger|id|attr|slaves|remove||list|extend|wrapID|clone|div|each|window|intercepted|length|class|addClass|arguments|typeof|reset|disableEmpty|selected|null||autoIntercept|apply|addSlave|disabled|current|data|true|string|input|append|applied|new|val|ext|instanceKey|reEnableEmpty|mfD|metadata|rxAccept|toString|title|intercept|Array|wrapper|constructor|not|className|1e3|_list|setTimeout|namePattern|generateID|click|submit|span|addToList|top|jQuery|denied|position|for|css|duplicate|indexOf|error|parent|wrap|maxlength|prepend|absolute|onFileSelect|3000px|after|blur|afterFileSelect|onFileAppend|label|change|_wrap|RegExp|href|_F|onFileRemove|files|afterFileRemove|afterFileAppend|find|Number|else|limit|removeClass|in|meta|number|form|slice|makeArray|You|cannot|select|nTry|again|File|This|has|already|been|ajaxSubmit|ajaxForm|validate|valid|alert|try|catch|type|multi'.split('|'),0,{}))
\ No newline at end of file
jQuery(document).ready(function(e){e("#ninja_forms_reset_base_upload_dir").click(function(){var t=e("#ninja_forms_default_base_upload_dir").val();var n=e("#ninja_forms_default_base_upload_url").val();e("#base_upload_dir").val(t);e("#base_upload_url").val(n)});e(".ninja-forms-delete-upload").click(function(t){t.preventDefault();var n=confirm("Delete this file?");if(n){var r=this.id.replace("delete_upload_","");e.post(ajaxurl,{upload_id:r,action:"ninja_forms_delete_upload"},function(t){e("#ninja_forms_upload_"+r+"_tr").css("background-color","#FF0000").fadeOut("slow",function(){e(this).remove();if(e("#ninja_forms_uploads_tbody tr").length==0){var t="<tr id='ninja_forms_files_empty' style=''><td colspan='7'>No files found</td></tr>";e("#ninja_forms_uploads_tbody").append(t)}})})}});e(".ninja-forms-change-file-upload").click(function(t){t.preventDefault();var n=this.id.replace("ninja_forms_change_file_upload_","");e("#ninja_forms_file_upload_"+n).toggle()});e(document).on("click",".ninja-forms-rename-help",function(t){t.preventDefault();if(!e("#tab-panel-upload_help").is(":visible")){e("#tab-link-upload_help").find("a").click();e("#contextual-help-link").click().focus()}})})
\ No newline at end of file
jQuery(document).ready(function(e){e(".ninja-forms-change-file-upload").click(function(t){t.preventDefault();var n=this.id.replace("ninja_forms_change_file_upload_","");e("#ninja_forms_file_upload_"+n).toggle()});e(".ninja-forms-delete-file-upload").click(function(t){t.preventDefault();var n=this.id.replace("_delete","");n+="_li";e("#"+n).fadeOut("fast",function(){e("#"+n).remove()})});e(document).on("submitResponse.uploads",function(t,n){var r=n.success;var i=n.form_settings;var s=i.hide_complete;var o=i.clear_complete;if(r!=false&&o==1){if(e.isFunction(e.fn.MultiFile)){e("input:file.multi").MultiFile("reset")}}})})
\ No newline at end of file
<?php
/*
Plugin Name: Ninja Forms - File Uploads
Plugin URI: http://ninjaforms.com
Description: File Uploads add-on for Ninja Forms.
Version: 3.3.14
Author: The WP Ninjas
Author URI: http://ninjaforms.com
Version Description: Merge branch 'release-3.3.14'
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'NF_FU_BASE_DIR', dirname(__FILE__) );
/**
* The main function responsible for returning the one true instance to functions everywhere.
*/
if( ! function_exists( 'NF_File_Uploads' ) ) {
function NF_File_Uploads()
{
// Load our main plugin class
require_once dirname(__FILE__) . '/includes/file-uploads.php';
$version = '3.3.14';
return NF_FU_File_Uploads::instance(__FILE__, $version);
}
}
NF_File_Uploads();
ForceType application/octet-stream
Header set Content-Disposition attachment
<FilesMatch "(?i)\.(gif|jpe?g|png)$">
ForceType none
Header unset Content-Disposition
</FilesMatch>
Header set X-Content-Type-Options nosniff
\ No newline at end of file
<?php if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class NF_FU_Admin_Controllers_CustomPaths {
public $identifier = '%';
public $data = array();
/**
* Get all shortcodes and descriptions
*
* @return array
*/
public function get_shortcodes() {
$shortcodes = array(
'filename' => __( 'Puts in the title of the file without any spaces', 'ninja-forms-uploads' ),
'formtitle' => __( 'Puts in the title of the current form without any spaces', 'ninja-forms-uploads' ),
'date' => __( 'Puts in the date in yyyy-mm-dd (1998-05-23) format', 'ninja-forms-uploads' ),
'month' => __( 'Puts in the month in mm (04) format', 'ninja-forms-uploads' ),
'day' => __( 'Puts in the day in dd (20) format', 'ninja-forms-uploads' ),
'year' => __( 'Puts in the year in yyyy (2011) format', 'ninja-forms-uploads' ),
'username' => __( 'Puts in the user\'s username if they are logged in', 'ninja-forms-uploads' ),
'userid' => __( 'Puts in the user\'s user ID if they are logged in', 'ninja-forms-uploads' ),
'displayname' => __( 'Puts in the user\'s display name if they are logged in', 'ninja-forms-uploads' ),
'firstname' => __( 'Puts in the user\'s first name if they are logged in', 'ninja-forms-uploads' ),
'lastname' => __( 'Puts in the user\'s last name if they are logged in', 'ninja-forms-uploads' ),
'random' => __( 'Puts in a random 5 character string', 'ninja-forms-uploads' ),
);
return $shortcodes;
}
/**
* Set data to be used in the replacing of shortcodes
*
* @param string $key
* @param mixed $value
*/
public function set_data( $key, $value ) {
$this->data[$key] = sanitize_file_name( $value );
}
/**
* Get shortcode as it appears in a string
*
* @param $shortcode
*
* @return string
*/
protected function get_shortcode_display( $shortcode ) {
return $this->identifier . $shortcode . $this->identifier;
}
/**
* Replace shortcodes with values in a string
*
* @param string $string
*
* @return string
*/
public function replace_shortcodes( $string ) {
$shortcodes = self::get_shortcodes();
foreach ( $shortcodes as $shortcode => $descp ) {
$string = $this->replace_shortcode( $string, $shortcode );
}
return $string;
}
/**
* Replace the custom filename with values of fields submitted using ID and Key
*
* @param string $string
* @param array $fields
*
* @return string
*/
public function replace_field_shortcodes( $string, $fields ) {
foreach( $fields as $field ) {
$find = array();
$find[] = $this->identifier . 'field_' . $field['id'] . $this->identifier;
$key = isset( $field['key'] ) ? $field['key'] : false;
if ( ! $key ) {
$key = Ninja_Forms()->form()->get_field( $field['id'] )->get_setting( 'key' );
}
$find[] = $this->identifier . 'field_' . $key . $this->identifier;
$user_value = $field['value'];
if ( is_array( $field['value'] ) ) {
$user_value = implode( ',', $field['value'] );
}
$replace = strtolower( sanitize_file_name( trim( $user_value ) ) );
$string = str_replace( $find, $replace, $string );
}
return $string;
}
/**
* Replace a single shortcode
*
* @param string $string
* @param string $shortcode
*
* @return string
*/
public function replace_shortcode( $string, $shortcode ) {
$find = $this->get_shortcode_display( $shortcode );
$replace = $this->get_value( $shortcode );
$string = str_replace( $find, $replace, $string );
return $string;
}
/**
* Get the shortcode value
*
* @param string $shortcode
*
* @return bool|string
*/
public function get_value( $shortcode ) {
$user_mapping = array(
'username' => 'user_nicename',
'userid' => 'ID',
'displayname' => 'display_name',
'firstname' => 'user_firstname',
'lastname' => 'user_lastname',
);
if ( isset( $user_mapping[ $shortcode ] ) ) {
if ( ! is_user_logged_in() ) {
return '';
}
$current_user = wp_get_current_user();
$field = $user_mapping[ $shortcode ];
return $current_user->{$field};
}
if ( in_array( $shortcode, array( 'formtitle', 'filename' ) ) ) {
/*
* If we haven't set the source data for the replacement, just return the shortcode
* to be replaced later
*/
if ( ! isset( $this->data[ $shortcode ] ) ) {
return $this->get_shortcode_display( $shortcode );
}
}
switch ( $shortcode ) {
case 'date':
$value = date( 'Y-m-d' );
break;
case 'month':
$value = date( 'm' );
break;
case 'day':
$value = date( 'd' );
break;
case 'year':
$value = date( 'Y' );
break;
case 'random':
$value = NF_FU_Helper::random_string( 5 );
break;
case 'formtitle':
$value = sanitize_file_name( sanitize_title( trim( $this->data[ $shortcode ] ) ) );
break;
case 'filename':
$value = sanitize_file_name( sanitize_title( trim( $this->data[ $shortcode ] ) ) );
break;
default:
$value = '';
}
return strtolower( $value );
}
}
\ No newline at end of file
<?php if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class NF_FU_Admin_Controllers_Settings {
/**
* @var array
*/
protected $settings;
/**
* Get settings for the plugin
*
* @return array
*/
public function get_settings() {
if ( is_null( $this->settings ) || empty( $this->settings ) ) {
$this->settings = Ninja_Forms()->get_settings();
}
return $this->settings;
}
/**
* Update settings for the plugin
*/
public function update_settings() {
update_option( 'ninja_forms_settings', $this->settings );
}
/**
* Set a setting
*
* @param string $key
* @param mixed $value
*/
public function set_setting( $key, $value ) {
$this->settings[ $key ] = $value;
}
/**
* Remove a setting
*
* @param string $key
*/
public function remove_setting( $key ) {
unset( $this->settings[ $key ] );
}
public function get_defined_name( $key ) {
return 'NF_FU_' . strtoupper( $key );
}
public function is_defined( $key ) {
$constant_name = $this->get_defined_name( $key );
return defined( $constant_name );
}
/**
* Get a setting
*
* @param string $key
* @param null|mixed $default
*
* @return mixed|null
*/
public function get_setting( $key, $default = null ) {
if ( $this->is_defined( $key ) ) {
$constant_name = $this->get_defined_name( $key );
return constant( $constant_name );
}
$settings = $this->get_settings();
if ( ! isset( $settings[ $key ] ) ) {
$config = NF_File_Uploads()->config( 'settings-upload', array( 'raw' => true ) );
if ( is_null( $default ) && isset( $config[ $key ]['default'] ) ) {
$default = $config[ $key ]['default'];
} else {
$default = '';
}
return $default;
}
$value = $settings[ $key ];
if ( 'max_filesize' === $key && empty( $value ) ) {
return $default;
}
return $value;
}
/**
* Get the custom upload directory formatted for use.
*
* @return mixed|null|string
*/
public function custom_upload_dir() {
$value = $this->get_setting( __FUNCTION__, '' );
if ( empty( $value ) ) {
return $value;
}
return '/' . trailingslashit( rtrim( $value, '/\\' ) );
}
/**
* Get the maximum size per file
*
* @param int $value File size in MB
*
* @return mixed|null
*/
public function file_size_bytes_from_mb( $value ) {
if ( empty( $value ) || $value == 0 ) {
return 0;
}
return (int) $value * 1048576;
}
/**
* Get max file size in MB
*
* @return int|mixed|null
*/
public function get_max_file_size_mb() {
$max_file_size_mb = $this->get_setting( 'max_filesize' );
return $max_file_size_mb;
}
}
\ No newline at end of file
<?php if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class NF_FU_Admin_Controllers_Uploads {
/**
* @var string
*/
protected static $base_dir;
/**
* @var string
*/
protected static $base_url;
/**
* @var string
*/
protected static $tmp_dir;
/**
* NF_FU_Admin_Controllers_Uploads constructor.
*/
public function __construct() {
add_action( 'ninja_forms_after_submission', array( $this, 'remove_files_from_server') );
add_action( 'ninja_forms_after_submission', array( $this, 'record_submission_id'), 11 );
}
/**
* Remove the file from the server if the field is not to be saved to the server.
* This happens on the latest hook possible after actions have been run.
*
* @param array $data
*/
public function remove_files_from_server( $data ) {
if ( ! isset( $data['fields'] ) || ! is_array( $data['fields'] ) ) {
return;
}
foreach( $data['fields'] as $field ) {
if ( NF_FU_File_Uploads::TYPE !== $field['type'] ) {
continue;
}
if ( ! isset( $field['save_to_server'] ) ) {
continue;
}
if ( "1" == $field['save_to_server'] ) {
continue;
}
if ( empty( $field['value'] ) ) {
continue;
}
foreach ( $field['value'] as $upload_id => $url ) {
$upload = $this->get( $upload_id );
$file_path = $upload->file_path;
if ( $this->is_uploading_to_external( $upload ) ) {
// File being uploaded to external services in the background
// Do not delete, the background jobs will take care of deleting the local file
continue;
}
if ( ! file_exists( $file_path ) ) {
continue;
}
// Delete local file
$result = unlink( $file_path );
if ( $result ) {
$upload_data = $upload->data;
$upload_data['removed_from_server'] = true;
NF_File_Uploads()->model->update( $upload_id, $upload_data );
}
}
}
}
/**
* Check the file is being uploaded to an external service
*
* @param $upload
*
* @return bool
*/
protected function is_uploading_to_external( $upload ) {
if ( ! isset( $upload->external_locations ) || ! is_array( $upload->external_locations ) ) {
return false;
}
foreach ( $upload->external_locations as $location => $uploaded ) {
if ( 0 == $uploaded ) {
return true;
}
}
return false;
}
/**
* Get the base upload directory
*
* @return string
*/
public function get_base_dir() {
if ( is_null( self::$base_dir ) ) {
$base_upload_dir = wp_upload_dir();
$base_upload_dir = $base_upload_dir['basedir'] . '/ninja-forms';
wp_mkdir_p( $base_upload_dir );
self::$base_dir = $base_upload_dir;
}
return self::$base_dir;
}
/**
* Get the URL base upload directory
*
* @return string
*/
public function get_base_url() {
if ( is_null( self::$base_url ) ) {
$base_upload_url = wp_upload_dir();
$base_upload_url = $base_upload_url['baseurl'] . '/ninja-forms';
self::$base_url = $base_upload_url;
}
return self::$base_url;
}
/**
* Get the temp upload directory
*
* @return string
*/
public function get_temp_dir() {
if ( is_null( self::$tmp_dir ) ) {
$base_upload_dir = $this->get_base_dir();
$tmp_upload_dir = $base_upload_dir . '/tmp';
$tmp_upload_dir = apply_filters( 'ninja_forms_uploads_tmp_dir', $tmp_upload_dir );
wp_mkdir_p( $tmp_upload_dir );
$this->maybe_create_tmp_htaccess( $tmp_upload_dir );
self::$tmp_dir = $tmp_upload_dir;
}
return self::$tmp_dir;
}
/**
* Copy .htaccess file to tmp directory for security
* https://github.com/blueimp/jQuery-File-Upload/wiki/Security#php
*
* @param string $tmp_upload_dir
*/
protected function maybe_create_tmp_htaccess( $tmp_upload_dir ) {
$dest = $tmp_upload_dir . '/.htaccess';
if ( file_exists( $dest ) ) {
return;
}
$source = dirname( NF_File_Uploads()->plugin_file_path ) . '/includes/.htaccess.txt';
@copy( $source, $dest );
}
/**
* Get the file path for the temp file
*
* @param string $filename
* @param bool $temp Use temp path
*
* @return string
*/
public function get_path( $filename = '', $temp = false ) {
$file_path = $temp ? $this->get_temp_dir() : $this->get_base_dir();
$field_id = isset( $this->field_id ) ? $this->field_id : null;
$file_path = apply_filters( 'ninja_forms_uploads_dir', $file_path, $field_id );
return trailingslashit( $file_path ) . $filename;
}
/**
* Get the URL of a file
*
* @param string $filename
*
* @return string
*/
public function get_url( $filename ) {
$field_id = isset( $this->field_id ) ? $this->field_id : null;
$file_url = apply_filters( 'ninja_forms_uploads_url', $this->get_base_url(), $field_id );
return trailingslashit( $file_url ) . $filename;
}
/**
* Get a file upload from the table
*
* @param int $id
*
* @return object|false
*/
public function get( $id ) {
$upload = NF_File_Uploads()->model->get( $id );
if ( is_null( $upload ) ) {
return false;
}
$data = unserialize( $upload->data );
foreach ( $data as $key => $value ) {
$upload->$key = $value;
}
$upload->data = $data;
return $upload;
}
/**
* Get the file URL for an upload
*
* @param string $url
* @param array $data
*
* @return string
*/
public function get_file_url( $url, $data ) {
return apply_filters( 'ninja_forms_uploads_file_url', $url, $data );
}
/**
* Create attachment in media library from the file
*
* @param string $file
* @param null|string $file_name
*
* @return array
*/
public function create_attachment( $file, $file_name = null ) {
if ( is_null( $file_name ) ) {
$file_name = basename( $file );
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$wp_filetype = wp_check_filetype( $file_name );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $file_name ),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $attachment, $file );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$attach_data['ninja_forms_upload_field'] = true;
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
/**
* Check if the uploaded file exists.
*
* @param $upload_data
*
* @return bool
*/
public function file_exists( $upload_data ) {
if ( 'server' !== $upload_data['upload_location'] ) {
// For now assume external files still exist
return true;
}
if ( isset( $upload_data['removed_from_server'] ) && $upload_data['removed_from_server'] ) {
return false;
}
return file_exists( $upload_data['file_path']);
}
/**
* Save the submission ID for each upload object.
*
* @param array $data
*/
public function record_submission_id( $data ) {
if ( ! isset( $data['actions']['save']['sub_id'] ) ) {
return;
}
if ( ! isset( $data['fields'] ) || ! is_array( $data['fields'] ) ) {
return;
}
$sub_id = $data['actions']['save']['sub_id'];
foreach ( $data['fields'] as $field ) {
if ( NF_FU_File_Uploads::TYPE !== $field['type'] ) {
continue;
}
if ( empty( $field['value'] ) ) {
continue;
}
foreach ( $field['value'] as $upload_id => $url ) {
$upload = $this->get( $upload_id );
$upload_data = $upload->data;
$upload_data['sub_id'] = $sub_id;
NF_File_Uploads()->model->update( $upload_id, $upload_data );
}
}
}
/**
* Get all uploads for a specific field and submission
*
* @param int $field_id
* @param int $submission_id
*
* @return array
*/
public function get_field_uploads_by_submission_id( $field_id, $submission_id ) {
global $wpdb;
$where = $wpdb->prepare( 'WHERE field_id = %1$d AND data like \'%%%"sub_id";i:%2$d%%%\'', $field_id, $submission_id );
return NF_File_Uploads()->model->fetch( $where );
}
}
\ No newline at end of file
<?php if ( ! defined( 'ABSPATH' ) ) {
exit;
}
final class NF_FU_Admin_Menus_Uploads extends NF_Abstracts_Submenu {
public $parent_slug = 'ninja-forms';
public $menu_slug = 'ninja-forms-uploads';
public $priority = 14;
public $table;
/**
* NF_FU_Admin_Menus_Uploads constructor.
*/
public function __construct() {
$this->page_title = __( 'File Uploads', 'ninja-forms-uploads' );
parent::__construct();
if( isset( $_POST[ 'update_ninja_forms_settings' ] ) ) {
$this->update_settings();
}
if ( ! defined( 'DOING_AJAX' ) ) {
add_action( 'admin_init', array( $this, 'maybe_redirect_to_remove_referrer' ) );
add_action( 'admin_init', array( 'NF_FU_Admin_UploadsTable', 'process_bulk_action' ) );
add_action( 'admin_init', array( 'NF_FU_Admin_UploadsTable', 'delete_upload' ) );
add_action( 'admin_notices', array( 'NF_FU_Admin_UploadsTable', 'action_notices' ) );
}
}
/**
* Get URL to the settings page
*
* @param string $tab
* @param array $args
*
* @param bool $esc
*
* @return string
*/
public function get_url( $tab = '', $args = array(), $esc = true ) {
$url = admin_url( 'admin.php' );
$defaults = array(
'page' => $this->menu_slug,
);
if ( $tab ) {
$args['tab'] = $tab;
}
$args = array_merge( $args, $defaults );
$url = add_query_arg( $args, $url );
if ( $esc ) {
$url = esc_url( $url );
}
return $url;
}
/**
* Get the tabs for the settings page
*
* @return mixed|void
*/
protected function get_tabs() {
$tabs = array(
'browse' => __( 'Browse Uploads', 'ninja-forms-uploads' ),
'settings' => __( 'Upload Settings', 'ninja-forms-uploads' ),
);
return apply_filters( 'ninja_forms_uploads_tabs', $tabs );
}
/**
* @param null $tabs
*
* @return mixed
*/
protected function get_active_tab( $tabs = null ) {
if ( is_null( $tabs ) ) {
$tabs = $this->get_tabs();
}
$tab_keys = array_keys( $tabs );
return ( isset( $_GET['tab'] ) ) ? $_GET['tab'] : reset( $tab_keys );
}
public function maybe_redirect_to_remove_referrer() {
if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'ninja-forms-uploads' ) {
return;
}
if ( ! empty( $_GET['_wp_http_referer'] ) ) {
wp_redirect( remove_query_arg( array(
'_wp_http_referer',
'_wpnonce',
), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
}
/**
*
*/
public function display() {
$tabs = $this->get_tabs();
$active_tab = $this->get_active_tab( $tabs );
$save_button_text = __( 'Save', 'ninja-forms-uploads');
$table = false;
if ( 'browse' === $active_tab ) {
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'jquery-ui-datepicker', Ninja_Forms::$url . 'deprecated/assets/css/jquery-ui-fresh.min.css' );
$table = new NF_FU_Admin_UploadsTable();
$table->prepare_items();
}
wp_enqueue_script( 'postbox' );
wp_enqueue_script( 'jquery-ui-draggable' );
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
NF_File_Uploads()->template( 'admin-menu-uploads', compact( 'tabs', 'active_tab', 'save_button_text', 'table' ) );
}
/**
* Handle saving settings
*/
protected function update_settings() {
if ( ! isset( $_POST['update_ninja_forms_settings'] ) ) {
return;
}
$plugin_settings = NF_File_Uploads()->controllers->settings->get_settings();
$whitelist = apply_filters( 'ninja_forms_file_uploads_settings_whitelist', NF_File_Uploads()->config( 'settings-upload' ) ) ;
$updates = false;
foreach ( $whitelist as $key => $setting ) {
$value = filter_input( INPUT_POST, $key );
if ( ! isset( $value ) ) {
continue;
}
if ( isset( $plugin_settings[ $key ] ) && $value === $plugin_settings[ $key ] ) {
continue;
}
if ( 'custom_upload_dir' !== $key ) {
$value = sanitize_text_field( $value );
}
NF_File_Uploads()->controllers->settings->set_setting( $key, $value );
$updates = true;
}
if ( $updates ) {
NF_File_Uploads()->controllers->settings->update_settings();
}
}
}