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.

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