WordPress File Upload - Version 4.12.0

Version Description

  • corrected bug where export data file was not deleted after download
  • corrected bug in FTP credentials configurator about double backslash (\) issue
  • added cookies user state handler that has been integrated with dboption as 'Cookies (DBOption)' to comply with Wordpress directives not to use session
  • 'Cookies (DBOption)' user state handler has been set as the default one
  • added advanced option WFU_US_DBOPTION_BASE so that dboption can also work with session
  • added advanced option WFU_US_SESSION_LEGACY to use the old session functionality of the plugin, having session_start() in header
  • added auto-adjustment of user state handler to 'dboption' during activation (or update) of the plugin
  • bug "Error: [] cURL error 28" in Wordpress Site Health disappears when setting user state handler to 'Cookies (DBOption)' or when WFU_US_SESSION_LEGACY advanced option is false
  • added the ability to run PHP processes in queue, which is necessary for correctly handling uploads when user state handler is dboption
Download this release

Release Info

Developer nickboss
Plugin Icon 128x128 WordPress File Upload
Version 4.12.0
Comparing to
See all releases

Code changes from version 4.11.2 to 4.12.0

js/wordpress_file_upload_adminfunctions.js CHANGED
@@ -151,7 +151,7 @@ function wfu_update_ftpinfobase_value(e){e=e||window.event;var item=e.target;var
151
  if(ftpinfo.error){item.classList.add("ftpinfo_error");ftpinfo_username.classList.add("ftpinfo_error");ftpinfo_password.classList.add("ftpinfo_error");ftpinfo_domain.classList.add("ftpinfo_error");ftpinfo_port.classList.add("ftpinfo_error");ftpinfo_sftp.classList.add("ftpinfo_error")}else{item.classList.remove("ftpinfo_error");ftpinfo_username.classList.remove("ftpinfo_error");ftpinfo_password.classList.remove("ftpinfo_error");ftpinfo_domain.classList.remove("ftpinfo_error");ftpinfo_port.classList.remove("ftpinfo_error");
152
  ftpinfo_sftp.classList.remove("ftpinfo_error")}ftpinfo_username.value=ftpinfo.data.username;ftpinfo_password.value=ftpinfo.data.password;ftpinfo_domain.value=ftpinfo.data.ftpdomain;ftpinfo_port.value=ftpinfo.data.port;ftpinfo_sftp.checked=ftpinfo.data.sftp;item.freezetool=false;if(val!==item.oldVal){item.oldVal=val;document.getElementById("wfu_attribute_value_"+attribute).value=val;wfu_generate_shortcode()}}
153
  function wfu_update_ftpinfotool_value(e){var item=document.querySelector(".ftpinfo_btn").previousElementSibling;if(!item.freezetool){var attribute=item.id.replace("wfu_attribute_","");var ftpinfo_username=document.getElementById("ftpinfo_username").value;var ftpinfo_password=document.getElementById("ftpinfo_password").value;var ftpinfo_domain=document.getElementById("ftpinfo_domain").value;var ftpinfo_port=document.getElementById("ftpinfo_port").value;var ftpinfo_sftp=document.getElementById("ftpinfo_sftp").checked;
154
- if(ftpinfo_sftp)ftpinfo_port="s"+ftpinfo_port;var ftpdata=ftpinfo_username.replace(/:/g,"\\:").replace(/@/g,"\\@");if(ftpinfo_password!="")ftpdata+=":"+ftpinfo_password.replace(/:/g,"\\:").replace(/@/g,"\\@");ftpdata+="@"+ftpinfo_domain;if(ftpinfo_port!="")ftpdata+=":"+ftpinfo_port;item.value=ftpdata;wfu_update_ftpinfobase_value({target:item})}}
155
  function wfu_update_formfield_value(e){e=e||window.event;var item=e.target;var attribute=item.id.match(/^wfu_formfield_(.*?)_/)[1];var containers=document.querySelectorAll("div#wfu_attribute_"+attribute+" .wfu_formdata_line_container");var val="";for(var i=0;i<containers.length;i++){var part="";var ind=containers[i].id.match(/^wfu_formfield_.*?_(.*?)_/)[1];var key=attribute+"_"+ind;var label=document.getElementById("wfu_formfield_"+key+"_label").value;if(label.trim()!=""){part=label.trim();var type=
156
  document.getElementById("wfu_formfield_"+key+"_type").value;var typeprops=window["wfu_attribute_"+attribute+"_typeprops"];part+="|t:"+type;if(typeprops[type].labelposition.substr(0,4)=="show")part+="|s:"+document.getElementById("wfu_formfield_"+key+"_labelposition").value;if(typeprops[type].required.substr(0,4)=="show")part+="|r:"+(document.getElementById("wfu_formfield_"+key+"_required").checked?"1":"0");if(typeprops[type].donotautocomplete.substr(0,4)=="show")part+="|a:"+(document.getElementById("wfu_formfield_"+
157
  key+"_donotautocomplete").checked?"1":"0");if(typeprops[type].validate.substr(0,4)=="show")part+="|v:"+(document.getElementById("wfu_formfield_"+key+"_validate").checked?"1":"0");if(typeprops[type].typehook.substr(0,4)=="show")part+="|h:"+(document.getElementById("wfu_formfield_"+key+"_typehook").checked?"1":"0");if(typeprops[type].hintposition.substr(0,4)=="show")part+="|p:"+document.getElementById("wfu_formfield_"+key+"_hintposition").value;if(typeprops[type]["default"].substr(0,4)=="show")part+=
@@ -186,7 +186,7 @@ function wfu_update_columns(attribute){var target=document.getElementById("wfu_a
186
  function wfu_GetHttpRequestObject(){var xhr=null;try{xhr=new XMLHttpRequest}catch(e$0){try{xhr=new ActiveXObject("Msxml2.XMLHTTP")}catch(e2){try{xhr=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}if(xhr==null&&window.createRequest)try{xmlhttp=window.createRequest()}catch(e$1){}return xhr}
187
  function wfu_plugin_encode_string(str){var i=0;var newstr="";var num;var hex="";for(i=0;i<str.length;i++){num=str.charCodeAt(i);if(num>=2048)num=((num&16773120|917504)<<4)+((num&4032|8192)<<2)+(num&63|128);else if(num>=128)num=((num&65472|12288)<<2)+(num&63|128);hex=num.toString(16);if(hex.length==1||hex.length==3||hex.length==5)hex="0"+hex;newstr+=hex}return newstr}
188
  function wfu_plugin_decode_string(str){var i=0;var newstr="";var num,val;while(i<str.length){num=parseInt(str.substr(i,2),16);if(num<128)val=num;else if(num<224)val=((num&31)<<6)+(parseInt(str.substr(i+=2,2),16)&63);else val=((num&15)<<12)+((parseInt(str.substr(i+=2,2),16)&63)<<6)+(parseInt(str.substr(i+=2,2),16)&63);newstr+=String.fromCharCode(val);i+=2}return newstr}
189
- function wfu_randomString(len){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var string_length=len;var randomstring="";for(var i=0;i<string_length;i++){var rnum=Math.floor(Math.random()*chars.length);randomstring+=chars.substring(rnum,rnum+1)}return randomstring}
190
  function wfu_schedule_save_shortcode(){var d=new Date;var dt=ShortcodeNextSave-d.getTime();if(ShortcodeTimeOut!=null){clearTimeout(ShortcodeTimeOut);ShortcodeTimeOut=null}if(dt<=0)wfu_save_shortcode();else ShortcodeTimeOut=setTimeout(function(){wfu_save_shortcode()},dt)}function wfu_check_page_obsolescence(){if(PageObsolete||PageUpdating||document.getElementById("wfu_shortcode_postid").value=="")return}
191
  function wfu_save_shortcode(){if(typeof window.fromGutenberg!="undefined"){document.getElementById("wfu_shortcode").value=wfu_plugin_decode_string(document.getElementById("wfu_shortcode_original_enc").value);window.plugin_window.wfu_save_from_editor(window.blockId);return}if(PageObsolete)return;var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;PageUpdating=true;document.getElementById("wfu_update_failed_message").style.display="none";var url=AdminParams.wfu_ajax_url;params=new Array(8);params[0]=
192
  new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_save_shortcode";params[1]=new Array(2);params[1][0]="shortcode";params[1][1]=wfu_plugin_encode_string(ShortcodeString);params[2]=new Array(2);params[2][0]="shortcode_original";params[2][1]=document.getElementById("wfu_shortcode_original_enc").value;params[3]=new Array(2);params[3][0]="post_id";params[3][1]=document.getElementById("wfu_shortcode_postid").value;params[4]=new Array(2);params[4][0]="post_hash";params[4][1]=document.getElementById("wfu_shortcode_posthash").value;
@@ -229,9 +229,9 @@ rgb);var item=document.getElementById("wfu_attribute_"+attribute+"_color");item.
229
  wfu_update_triplecolor_value({target:item})}else if(type=="ftpinfo"){var item=document.getElementById("wfu_attribute_"+attribute);item.value=value;wfu_update_text_value({target:item})}else if(type=="folderlist"){var items=wfu_parse_folderlist_js(value);var opts=document.getElementById("wfu_attribute_"+attribute).options;while(opts.length>0)opts.remove(0);var opt,subfolder,subfolder_raw,text,stars,subvalue;for(var i=0;i<items.path.length;i++){subfolder=items.path[i];if(subfolder.substr(subfolder.length,
230
  1)=="/")subfolder=subfolder.substr(0,subfolder.length-1);subfolder_raw=subfolder.split("/");subfolder=subfolder_raw[subfolder_raw.length-1];stars=parseInt(items.level[i]);text="";subvalue="";for(var j=0;j<stars;j++){text+="&nbsp;&nbsp;&nbsp;";subvalue+="*"}text+=items.label[i];if(items["default"][i])subvalue+="&";if(subfolder=="")subvalue+="{root}/"+items.label[i];else subvalue+=subfolder+items.label[i];opt=document.createElement("option");if(items["default"][i])opt.className="wfu_select_folders_option_default";
231
  else opt.className="";opt.value=wfu_plugin_encode_string(subvalue);opt.innerHTML=text;opts.add(opt)}opt=document.createElement("option");opt.value="";opt.innerHTML="";opts.add(opt);var list=document.getElementById("wfu_attribute_"+attribute);list.data=wfu_decode_subfolder_list(attribute);wfu_subfolders_update_toolnav(attribute);item=list;if(value!==item.oldVal){item.oldVal=value;document.getElementById("wfu_attribute_value_"+attribute).value=value;wfu_generate_shortcode()}}}
232
- function wfu_decode_ftpinfo(ftpdata){var ret={error:true,data:{username:"",password:"",ftpdomain:"",port:"",sftp:false}};var ftpdata_flat=ftpdata.replace(/\\:/g,"\\_").replace(/\\@/g,"\\_");var pos1=ftpdata_flat.indexOf(":");var pos2=ftpdata_flat.indexOf("@");if(pos1>-1&&pos2>-1&&pos2>pos1){ret.error=false;ret.data.username=ftpdata.substr(0,pos1).replace(/\\:/g,":").replace(/\\@/g,"@");ret.data.password=ftpdata.substr(pos1+1,pos2-pos1-1).replace(/\\:/g,":").replace(/\\@/g,"@");var ftp_host=ftpdata.substr(pos2+
233
- 1);ret.data.ftpdomain=ftp_host.replace(/:.*/,"");if(ret.data.ftpdomain.trim()=="")ret.error=true;var ftp_port=ftp_host.replace(/^[^:]*:?/,"");if(ftp_port.substr(0,1)=="s"){ret.data.sftp=true;ftp_port=ftp_port.substr(1)}ret.data.port=ftp_port}else if(pos2>-1){ret.error=false;ret.data.username=ftpdata.substr(0,pos2).replace(/\\:/g,":").replace(/\\@/g,"@");var ftp_host=ftpdata.substr(pos2+1);ret.data.ftpdomain=ftp_host.replace(/:.*/,"");if(ret.data.ftpdomain.trim()=="")ret.error=true;var ftp_port=ftp_host.replace(/^[^:]*:?/,
234
- "");if(ftp_port.substr(0,1)=="s"){ret.data.sftp=true;ftp_port=ftp_port.substr(1)}ret.data.port=ftp_port}else if(pos1>-1){ret.error=true;ret.data.username=ftpdata.substr(0,pos1).replace(/\\:/g,":").replace(/\\@/g,"@");ret.data.password=ftpdata.substr(pos1+1).replace(/\\:/g,":").replace(/\\@/g,"@")}else{ret.error=true;ret.data.username=ftpdata.replace(/\\:/g,":").replace(/\\@/g,"@")}return ret}
235
  function wfu_ftpinfotool_toggle(){var ftpinfobtn=document.querySelector(".ftpinfo_btn");var ftpinfotool=document.querySelector(".ftpinfo_tool");if(ftpinfotool.classList.contains("hidden")){ftpinfobtn.innerHTML="Close";ftpinfotool.classList.remove("hidden")}else{ftpinfobtn.innerHTML="Edit";ftpinfotool.classList.add("hidden")}}
236
  function wfu_parse_folderlist_js(list){var ret=Object();ret.path=Array();ret.label=Array();ret.level=Array();ret["default"]=Array();if(list.substr(0,4)=="auto")return ret;var subfolders=list.split(",");if(subfolders.length==0)return ret;if(subfolders.length==1&&subfolders[0].trim()=="")return ret;var dir_levels=["root"];var prev_level=0;var level0_count=0;var _default=-1;var subfolder,star_count,start_spaces,is_default,subfolder_dir,subfolder_label,subfolder_path;for(var i=0;i<subfolders.length;i++){subfolder=
237
  subfolders[i].trim();star_count=0;start_spaces="";is_default=false;while(star_count<subfolder.length)if(subfolder.substr(star_count,1)=="*"){star_count++;start_spaces+="&nbsp;&nbsp;&nbsp;"}else break;if(star_count-prev_level<=1&&(star_count>0||level0_count==0)){subfolder=subfolder.substr(star_count,subfolder.length-star_count);if(subfolder.substr(0,1)=="&"){subfolder=subfolder.substr(1);is_default=true}subfolder_items=subfolder.split("/");if(subfolder_items.length<2)subfolder_items.push("");if(subfolder_items[1]!=
@@ -243,10 +243,11 @@ function colourNameToHex(colour){var colours={"aliceblue":"#f0f8ff","antiquewhit
243
  "lightgrey":"#d3d3d3","lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a","lightseagreen":"#20b2aa","lightskyblue":"#87cefa","lightslategray":"#778899","lightsteelblue":"#b0c4de","lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32","linen":"#faf0e6","magenta":"#ff00ff","maroon":"#800000","mediumaquamarine":"#66cdaa","mediumblue":"#0000cd","mediumorchid":"#ba55d3","mediumpurple":"#9370d8","mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee","mediumspringgreen":"#00fa9a",
244
  "mediumturquoise":"#48d1cc","mediumvioletred":"#c71585","midnightblue":"#191970","mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5","navajowhite":"#ffdead","navy":"#000080","oldlace":"#fdf5e6","olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500","orangered":"#ff4500","orchid":"#da70d6","palegoldenrod":"#eee8aa","palegreen":"#98fb98","paleturquoise":"#afeeee","palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9","peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd",
245
  "powderblue":"#b0e0e6","purple":"#800080","red":"#ff0000","rosybrown":"#bc8f8f","royalblue":"#4169e1","saddlebrown":"#8b4513","salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57","seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0","skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090","snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4","tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347","turquoise":"#40e0d0","violet":"#ee82ee","wheat":"#f5deb3",
246
- "white":"#ffffff","whitesmoke":"#f5f5f5","yellow":"#ffff00","yellowgreen":"#9acd32"};if(typeof colours[colour.toLowerCase()]!="undefined")return colours[colour.toLowerCase()];return false}
247
  function wfu_download_file(filepath_enc,ii){var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;var nonce="";var nonce_elem=document.getElementById("wfu_download_file_nonce");if(nonce_elem)nonce=nonce_elem.value;if(nonce=="")return;var url=AdminParams.wfu_ajax_url;params=new Array(3);params[0]=new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_download_file_invoker";params[1]=new Array(2);params[1][0]="file";params[1][1]=filepath_enc;params[2]=new Array(2);params[2][0]="nonce";params[2][1]=
248
  nonce;var parameters="";for(var i=0;i<params.length;i++)parameters+=(i>0?"&":"")+params[i][0]+"="+encodeURI(params[i][1]);xhr.open("POST",url,true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.onreadystatechange=function(){if(xhr.readyState==4)if(xhr.status==200){var start_text="wfu_ajax_action_download_file_invoker:";var pos=xhr.responseText.indexOf(start_text);if(pos==-1)pos=xhr.responseText.length;var messages=xhr.responseText.substr(0,pos);var response=xhr.responseText.substr(pos+
249
- start_text.length,xhr.responseText.length-pos-start_text.length);pos=response.indexOf(":");var txt_header=response.substr(0,pos);txt_value=response.substr(pos+1,response.length-pos-1);if(txt_header.substr(0,16)=="wfu_download_id;"){var download_id=txt_header.substr(16);var container=document.getElementById("wfu_file_download_container_"+ii);container.innerHTML=txt_value;setTimeout("wfu_download_file_monitor('"+filepath_enc+"', "+ii+", '"+download_id+"')",100)}}};xhr.send(parameters)}
 
250
  function wfu_download_file_monitor(filepath_enc,ii,id){var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;var url=AdminParams.wfu_ajax_url;params=new Array(3);params[0]=new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_download_file_monitor";params[1]=new Array(2);params[1][0]="file";params[1][1]=filepath_enc;params[2]=new Array(2);params[2][0]="id";params[2][1]=id;var parameters="";for(var i=0;i<params.length;i++)parameters+=(i>0?"&":"")+params[i][0]+"="+encodeURI(params[i][1]);
251
  xhr.open("POST",url,true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.onreadystatechange=function(){if(xhr.readyState==4)if(xhr.status==200){var start_text="wfu_ajax_action_download_file_monitor:";var pos=xhr.responseText.indexOf(start_text);if(pos==-1)pos=xhr.responseText.length;var messages=xhr.responseText.substr(0,pos);var response=xhr.responseText.substr(pos+start_text.length,xhr.responseText.length-pos-start_text.length);pos=response.indexOf(":");var txt_header=
252
  response.substr(0,pos);txt_value=response.substr(pos+1,response.length-pos-1);if(txt_header!="repeat"){var container=document.getElementById("wfu_file_download_container_"+ii);container.innerHTML=""}else if(txt_header=="repeat")setTimeout("wfu_download_file_monitor('"+filepath_enc+"', "+ii+", '"+txt_value+"')",100)}};xhr.send(parameters)}
151
  if(ftpinfo.error){item.classList.add("ftpinfo_error");ftpinfo_username.classList.add("ftpinfo_error");ftpinfo_password.classList.add("ftpinfo_error");ftpinfo_domain.classList.add("ftpinfo_error");ftpinfo_port.classList.add("ftpinfo_error");ftpinfo_sftp.classList.add("ftpinfo_error")}else{item.classList.remove("ftpinfo_error");ftpinfo_username.classList.remove("ftpinfo_error");ftpinfo_password.classList.remove("ftpinfo_error");ftpinfo_domain.classList.remove("ftpinfo_error");ftpinfo_port.classList.remove("ftpinfo_error");
152
  ftpinfo_sftp.classList.remove("ftpinfo_error")}ftpinfo_username.value=ftpinfo.data.username;ftpinfo_password.value=ftpinfo.data.password;ftpinfo_domain.value=ftpinfo.data.ftpdomain;ftpinfo_port.value=ftpinfo.data.port;ftpinfo_sftp.checked=ftpinfo.data.sftp;item.freezetool=false;if(val!==item.oldVal){item.oldVal=val;document.getElementById("wfu_attribute_value_"+attribute).value=val;wfu_generate_shortcode()}}
153
  function wfu_update_ftpinfotool_value(e){var item=document.querySelector(".ftpinfo_btn").previousElementSibling;if(!item.freezetool){var attribute=item.id.replace("wfu_attribute_","");var ftpinfo_username=document.getElementById("ftpinfo_username").value;var ftpinfo_password=document.getElementById("ftpinfo_password").value;var ftpinfo_domain=document.getElementById("ftpinfo_domain").value;var ftpinfo_port=document.getElementById("ftpinfo_port").value;var ftpinfo_sftp=document.getElementById("ftpinfo_sftp").checked;
154
+ if(ftpinfo_sftp)ftpinfo_port="s"+ftpinfo_port;var ftpdata=ftpinfo_username.replace(/:/g,"\\\\:").replace(/@/g,"\\\\@");if(ftpinfo_password!="")ftpdata+=":"+ftpinfo_password.replace(/:/g,"\\\\:").replace(/@/g,"\\\\@");ftpdata+="@"+ftpinfo_domain;if(ftpinfo_port!="")ftpdata+=":"+ftpinfo_port;item.value=ftpdata;wfu_update_ftpinfobase_value({target:item})}}
155
  function wfu_update_formfield_value(e){e=e||window.event;var item=e.target;var attribute=item.id.match(/^wfu_formfield_(.*?)_/)[1];var containers=document.querySelectorAll("div#wfu_attribute_"+attribute+" .wfu_formdata_line_container");var val="";for(var i=0;i<containers.length;i++){var part="";var ind=containers[i].id.match(/^wfu_formfield_.*?_(.*?)_/)[1];var key=attribute+"_"+ind;var label=document.getElementById("wfu_formfield_"+key+"_label").value;if(label.trim()!=""){part=label.trim();var type=
156
  document.getElementById("wfu_formfield_"+key+"_type").value;var typeprops=window["wfu_attribute_"+attribute+"_typeprops"];part+="|t:"+type;if(typeprops[type].labelposition.substr(0,4)=="show")part+="|s:"+document.getElementById("wfu_formfield_"+key+"_labelposition").value;if(typeprops[type].required.substr(0,4)=="show")part+="|r:"+(document.getElementById("wfu_formfield_"+key+"_required").checked?"1":"0");if(typeprops[type].donotautocomplete.substr(0,4)=="show")part+="|a:"+(document.getElementById("wfu_formfield_"+
157
  key+"_donotautocomplete").checked?"1":"0");if(typeprops[type].validate.substr(0,4)=="show")part+="|v:"+(document.getElementById("wfu_formfield_"+key+"_validate").checked?"1":"0");if(typeprops[type].typehook.substr(0,4)=="show")part+="|h:"+(document.getElementById("wfu_formfield_"+key+"_typehook").checked?"1":"0");if(typeprops[type].hintposition.substr(0,4)=="show")part+="|p:"+document.getElementById("wfu_formfield_"+key+"_hintposition").value;if(typeprops[type]["default"].substr(0,4)=="show")part+=
186
  function wfu_GetHttpRequestObject(){var xhr=null;try{xhr=new XMLHttpRequest}catch(e$0){try{xhr=new ActiveXObject("Msxml2.XMLHTTP")}catch(e2){try{xhr=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}if(xhr==null&&window.createRequest)try{xmlhttp=window.createRequest()}catch(e$1){}return xhr}
187
  function wfu_plugin_encode_string(str){var i=0;var newstr="";var num;var hex="";for(i=0;i<str.length;i++){num=str.charCodeAt(i);if(num>=2048)num=((num&16773120|917504)<<4)+((num&4032|8192)<<2)+(num&63|128);else if(num>=128)num=((num&65472|12288)<<2)+(num&63|128);hex=num.toString(16);if(hex.length==1||hex.length==3||hex.length==5)hex="0"+hex;newstr+=hex}return newstr}
188
  function wfu_plugin_decode_string(str){var i=0;var newstr="";var num,val;while(i<str.length){num=parseInt(str.substr(i,2),16);if(num<128)val=num;else if(num<224)val=((num&31)<<6)+(parseInt(str.substr(i+=2,2),16)&63);else val=((num&15)<<12)+((parseInt(str.substr(i+=2,2),16)&63)<<6)+(parseInt(str.substr(i+=2,2),16)&63);newstr+=String.fromCharCode(val);i+=2}return newstr}
189
+ function wfu_decode_array_from_string(str){var arr_str=wfu_plugin_decode_string(str);var arr=null;try{arr=JSON.parse(arr_str)}catch(e){}return arr}function wfu_randomString(len){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var string_length=len;var randomstring="";for(var i=0;i<string_length;i++){var rnum=Math.floor(Math.random()*chars.length);randomstring+=chars.substring(rnum,rnum+1)}return randomstring}
190
  function wfu_schedule_save_shortcode(){var d=new Date;var dt=ShortcodeNextSave-d.getTime();if(ShortcodeTimeOut!=null){clearTimeout(ShortcodeTimeOut);ShortcodeTimeOut=null}if(dt<=0)wfu_save_shortcode();else ShortcodeTimeOut=setTimeout(function(){wfu_save_shortcode()},dt)}function wfu_check_page_obsolescence(){if(PageObsolete||PageUpdating||document.getElementById("wfu_shortcode_postid").value=="")return}
191
  function wfu_save_shortcode(){if(typeof window.fromGutenberg!="undefined"){document.getElementById("wfu_shortcode").value=wfu_plugin_decode_string(document.getElementById("wfu_shortcode_original_enc").value);window.plugin_window.wfu_save_from_editor(window.blockId);return}if(PageObsolete)return;var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;PageUpdating=true;document.getElementById("wfu_update_failed_message").style.display="none";var url=AdminParams.wfu_ajax_url;params=new Array(8);params[0]=
192
  new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_save_shortcode";params[1]=new Array(2);params[1][0]="shortcode";params[1][1]=wfu_plugin_encode_string(ShortcodeString);params[2]=new Array(2);params[2][0]="shortcode_original";params[2][1]=document.getElementById("wfu_shortcode_original_enc").value;params[3]=new Array(2);params[3][0]="post_id";params[3][1]=document.getElementById("wfu_shortcode_postid").value;params[4]=new Array(2);params[4][0]="post_hash";params[4][1]=document.getElementById("wfu_shortcode_posthash").value;
229
  wfu_update_triplecolor_value({target:item})}else if(type=="ftpinfo"){var item=document.getElementById("wfu_attribute_"+attribute);item.value=value;wfu_update_text_value({target:item})}else if(type=="folderlist"){var items=wfu_parse_folderlist_js(value);var opts=document.getElementById("wfu_attribute_"+attribute).options;while(opts.length>0)opts.remove(0);var opt,subfolder,subfolder_raw,text,stars,subvalue;for(var i=0;i<items.path.length;i++){subfolder=items.path[i];if(subfolder.substr(subfolder.length,
230
  1)=="/")subfolder=subfolder.substr(0,subfolder.length-1);subfolder_raw=subfolder.split("/");subfolder=subfolder_raw[subfolder_raw.length-1];stars=parseInt(items.level[i]);text="";subvalue="";for(var j=0;j<stars;j++){text+="&nbsp;&nbsp;&nbsp;";subvalue+="*"}text+=items.label[i];if(items["default"][i])subvalue+="&";if(subfolder=="")subvalue+="{root}/"+items.label[i];else subvalue+=subfolder+items.label[i];opt=document.createElement("option");if(items["default"][i])opt.className="wfu_select_folders_option_default";
231
  else opt.className="";opt.value=wfu_plugin_encode_string(subvalue);opt.innerHTML=text;opts.add(opt)}opt=document.createElement("option");opt.value="";opt.innerHTML="";opts.add(opt);var list=document.getElementById("wfu_attribute_"+attribute);list.data=wfu_decode_subfolder_list(attribute);wfu_subfolders_update_toolnav(attribute);item=list;if(value!==item.oldVal){item.oldVal=value;document.getElementById("wfu_attribute_value_"+attribute).value=value;wfu_generate_shortcode()}}}
232
+ function wfu_decode_ftpinfo(ftpdata){var ret={error:true,data:{username:"",password:"",ftpdomain:"",port:"",sftp:false}};var ftpdata_flat=ftpdata.replace(/\\\\:/g,"\\\\_").replace(/\\\\@/g,"\\\\_");var pos1=ftpdata_flat.indexOf(":");var pos2=ftpdata_flat.indexOf("@");if(pos1>-1&&pos2>-1&&pos2>pos1){ret.error=false;ret.data.username=ftpdata.substr(0,pos1).replace(/\\\\:/g,":").replace(/\\\\@/g,"@");ret.data.password=ftpdata.substr(pos1+1,pos2-pos1-1).replace(/\\\\:/g,":").replace(/\\\\@/g,"@");var ftp_host=
233
+ ftpdata.substr(pos2+1);ret.data.ftpdomain=ftp_host.replace(/:.*/,"");if(ret.data.ftpdomain.trim()=="")ret.error=true;var ftp_port=ftp_host.replace(/^[^:]*:?/,"");if(ftp_port.substr(0,1)=="s"){ret.data.sftp=true;ftp_port=ftp_port.substr(1)}ret.data.port=ftp_port}else if(pos2>-1){ret.error=false;ret.data.username=ftpdata.substr(0,pos2).replace(/\\\\:/g,":").replace(/\\\\@/g,"@");var ftp_host=ftpdata.substr(pos2+1);ret.data.ftpdomain=ftp_host.replace(/:.*/,"");if(ret.data.ftpdomain.trim()=="")ret.error=
234
+ true;var ftp_port=ftp_host.replace(/^[^:]*:?/,"");if(ftp_port.substr(0,1)=="s"){ret.data.sftp=true;ftp_port=ftp_port.substr(1)}ret.data.port=ftp_port}else if(pos1>-1){ret.error=true;ret.data.username=ftpdata.substr(0,pos1).replace(/\\\\:/g,":").replace(/\\\\@/g,"@");ret.data.password=ftpdata.substr(pos1+1).replace(/\\\\:/g,":").replace(/\\\\@/g,"@")}else{ret.error=true;ret.data.username=ftpdata.replace(/\\\\:/g,":").replace(/\\\\@/g,"@")}return ret}
235
  function wfu_ftpinfotool_toggle(){var ftpinfobtn=document.querySelector(".ftpinfo_btn");var ftpinfotool=document.querySelector(".ftpinfo_tool");if(ftpinfotool.classList.contains("hidden")){ftpinfobtn.innerHTML="Close";ftpinfotool.classList.remove("hidden")}else{ftpinfobtn.innerHTML="Edit";ftpinfotool.classList.add("hidden")}}
236
  function wfu_parse_folderlist_js(list){var ret=Object();ret.path=Array();ret.label=Array();ret.level=Array();ret["default"]=Array();if(list.substr(0,4)=="auto")return ret;var subfolders=list.split(",");if(subfolders.length==0)return ret;if(subfolders.length==1&&subfolders[0].trim()=="")return ret;var dir_levels=["root"];var prev_level=0;var level0_count=0;var _default=-1;var subfolder,star_count,start_spaces,is_default,subfolder_dir,subfolder_label,subfolder_path;for(var i=0;i<subfolders.length;i++){subfolder=
237
  subfolders[i].trim();star_count=0;start_spaces="";is_default=false;while(star_count<subfolder.length)if(subfolder.substr(star_count,1)=="*"){star_count++;start_spaces+="&nbsp;&nbsp;&nbsp;"}else break;if(star_count-prev_level<=1&&(star_count>0||level0_count==0)){subfolder=subfolder.substr(star_count,subfolder.length-star_count);if(subfolder.substr(0,1)=="&"){subfolder=subfolder.substr(1);is_default=true}subfolder_items=subfolder.split("/");if(subfolder_items.length<2)subfolder_items.push("");if(subfolder_items[1]!=
243
  "lightgrey":"#d3d3d3","lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a","lightseagreen":"#20b2aa","lightskyblue":"#87cefa","lightslategray":"#778899","lightsteelblue":"#b0c4de","lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32","linen":"#faf0e6","magenta":"#ff00ff","maroon":"#800000","mediumaquamarine":"#66cdaa","mediumblue":"#0000cd","mediumorchid":"#ba55d3","mediumpurple":"#9370d8","mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee","mediumspringgreen":"#00fa9a",
244
  "mediumturquoise":"#48d1cc","mediumvioletred":"#c71585","midnightblue":"#191970","mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5","navajowhite":"#ffdead","navy":"#000080","oldlace":"#fdf5e6","olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500","orangered":"#ff4500","orchid":"#da70d6","palegoldenrod":"#eee8aa","palegreen":"#98fb98","paleturquoise":"#afeeee","palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9","peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd",
245
  "powderblue":"#b0e0e6","purple":"#800080","red":"#ff0000","rosybrown":"#bc8f8f","royalblue":"#4169e1","saddlebrown":"#8b4513","salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57","seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0","skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090","snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4","tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347","turquoise":"#40e0d0","violet":"#ee82ee","wheat":"#f5deb3",
246
+ "white":"#ffffff","whitesmoke":"#f5f5f5","yellow":"#ffff00","yellowgreen":"#9acd32"};if(typeof colours[colour.toLowerCase()]!="undefined")return colours[colour.toLowerCase()];return false}function wfu_add_cookies(cookies){for(var i=0;i<cookies.length;i++){var date=new Date;date.setTime(date.getTime()+cookies[i].expires*1E3);document.cookie=cookies[i].name+"="+cookies[i].value+"; expires="+date.toUTCString()+"; path=/"}}
247
  function wfu_download_file(filepath_enc,ii){var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;var nonce="";var nonce_elem=document.getElementById("wfu_download_file_nonce");if(nonce_elem)nonce=nonce_elem.value;if(nonce=="")return;var url=AdminParams.wfu_ajax_url;params=new Array(3);params[0]=new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_download_file_invoker";params[1]=new Array(2);params[1][0]="file";params[1][1]=filepath_enc;params[2]=new Array(2);params[2][0]="nonce";params[2][1]=
248
  nonce;var parameters="";for(var i=0;i<params.length;i++)parameters+=(i>0?"&":"")+params[i][0]+"="+encodeURI(params[i][1]);xhr.open("POST",url,true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.onreadystatechange=function(){if(xhr.readyState==4)if(xhr.status==200){var start_text="wfu_ajax_action_download_file_invoker:";var pos=xhr.responseText.indexOf(start_text);if(pos==-1)pos=xhr.responseText.length;var messages=xhr.responseText.substr(0,pos);var response=xhr.responseText.substr(pos+
249
+ start_text.length,xhr.responseText.length-pos-start_text.length);pos=response.indexOf(":");var txt_header=response.substr(0,pos);txt_value=response.substr(pos+1,response.length-pos-1);if(txt_header.substr(0,16)=="wfu_download_id;"){var download_id=txt_header.substr(16);var container=document.getElementById("wfu_file_download_container_"+ii);var props=wfu_decode_array_from_string(txt_value);if(props){container.innerHTML=props.html;if(props.js!=""){var script=document.createElement("SCRIPT");script.type=
250
+ "text/javascript";script.text=props.js;container.appendChild(script)}setTimeout("wfu_download_file_monitor('"+filepath_enc+"', "+ii+", '"+download_id+"')",100)}}}};xhr.send(parameters)}
251
  function wfu_download_file_monitor(filepath_enc,ii,id){var xhr=wfu_GetHttpRequestObject();if(xhr==null)return;var url=AdminParams.wfu_ajax_url;params=new Array(3);params[0]=new Array(2);params[0][0]="action";params[0][1]="wfu_ajax_action_download_file_monitor";params[1]=new Array(2);params[1][0]="file";params[1][1]=filepath_enc;params[2]=new Array(2);params[2][0]="id";params[2][1]=id;var parameters="";for(var i=0;i<params.length;i++)parameters+=(i>0?"&":"")+params[i][0]+"="+encodeURI(params[i][1]);
252
  xhr.open("POST",url,true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.onreadystatechange=function(){if(xhr.readyState==4)if(xhr.status==200){var start_text="wfu_ajax_action_download_file_monitor:";var pos=xhr.responseText.indexOf(start_text);if(pos==-1)pos=xhr.responseText.length;var messages=xhr.responseText.substr(0,pos);var response=xhr.responseText.substr(pos+start_text.length,xhr.responseText.length-pos-start_text.length);pos=response.indexOf(":");var txt_header=
253
  response.substr(0,pos);txt_value=response.substr(pos+1,response.length-pos-1);if(txt_header!="repeat"){var container=document.getElementById("wfu_file_download_container_"+ii);container.innerHTML=""}else if(txt_header=="repeat")setTimeout("wfu_download_file_monitor('"+filepath_enc+"', "+ii+", '"+txt_value+"')",100)}};xhr.send(parameters)}
lib/wfu_admin.php CHANGED
@@ -1,5 +1,25 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wordpress_file_upload_admin_init() {
4
  $uri = $_SERVER['REQUEST_URI'];
5
  $is_admin = current_user_can( 'manage_options' );
@@ -11,6 +31,32 @@ function wordpress_file_upload_admin_init() {
11
  ( is_admin() && $can_open_composer && strpos($uri, "admin.php") !== false ) ) {
12
  //apply wfu_before_admin_scripts to get additional settings
13
  $changable_data = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  $ret_data = apply_filters('wfu_before_admin_scripts', $changable_data);
15
  //if $ret_data contains 'return_value' key then no scripts will be
16
  //registered
@@ -36,6 +82,29 @@ function wordpress_file_upload_admin_init() {
36
  elseif ( is_admin() && $is_admin && strpos($uri, "admin.php") !== false ) {
37
  //apply wfu_before_admin_scripts to get additional settings
38
  $changable_data = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  $ret_data = apply_filters('wfu_before_uploadedfiles_admin_scripts', $changable_data);
40
  //if $ret_data contains 'return_value' key then no scripts will be
41
  //registered
@@ -57,6 +126,13 @@ function wordpress_file_upload_admin_init() {
57
  }
58
  }
59
 
 
 
 
 
 
 
 
60
  function wordpress_file_upload_add_admin_pages() {
61
  global $wpdb;
62
  global $wfu_uploadedfiles_hook_suffix;
@@ -99,6 +175,14 @@ function wordpress_file_upload_add_admin_pages() {
99
  add_action('admin_print_scripts', 'wfu_enqueue_uploadedfiles_adminbar_scripts');
100
  }
101
 
 
 
 
 
 
 
 
 
102
  function wfu_enqueue_admin_scripts() {
103
  $uri = $_SERVER['REQUEST_URI'];
104
  $is_admin = current_user_can( 'manage_options' );
@@ -109,6 +193,7 @@ function wfu_enqueue_admin_scripts() {
109
  ( is_admin() && $can_open_composer && strpos($uri, "admin.php") !== false ) ) {
110
  //apply wfu_before_admin_scripts to get additional settings
111
  $changable_data = array();
 
112
  $ret_data = apply_filters('wfu_before_admin_scripts', $changable_data);
113
  //if $ret_data contains 'return_value' key then no scripts will be
114
  //enqueued
@@ -131,12 +216,21 @@ function wfu_enqueue_admin_scripts() {
131
  }
132
  }
133
 
 
 
 
 
 
 
 
 
134
  function wfu_enqueue_uploadedfiles_admin_scripts() {
135
  $uri = $_SERVER['REQUEST_URI'];
136
  $is_admin = current_user_can( 'manage_options' );
137
  if ( is_admin() && $is_admin && strpos($uri, "admin.php") !== false ) {
138
  //apply wfu_before_admin_scripts to get additional settings
139
  $changable_data = array();
 
140
  $ret_data = apply_filters('wfu_before_uploadedfiles_admin_scripts', $changable_data);
141
  //if $ret_data contains 'return_value' key then no scripts will be
142
  //enqueued
@@ -155,6 +249,14 @@ function wfu_enqueue_uploadedfiles_admin_scripts() {
155
  }
156
  }
157
 
 
 
 
 
 
 
 
 
158
  function wfu_enqueue_uploadedfiles_adminbar_scripts() {
159
  $is_admin = current_user_can( 'manage_options' );
160
  if ( is_admin() && $is_admin ) {
@@ -164,6 +266,13 @@ function wfu_enqueue_uploadedfiles_adminbar_scripts() {
164
  }
165
 
166
 
 
 
 
 
 
 
 
167
  function wordpress_file_upload_install() {
168
  global $wpdb;
169
  global $wfu_tb_log_version;
@@ -234,11 +343,42 @@ function wordpress_file_upload_install() {
234
  dbDelta($sql);
235
  update_option("wordpress_file_upload_table_dbxqueue_version", $wfu_tb_dbxqueue_version);
236
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  }
238
 
 
 
 
 
 
 
 
239
  function wordpress_file_upload_uninstall() {
240
  }
241
 
 
 
 
 
 
 
 
 
242
  function wordpress_file_upload_update_db_check() {
243
  global $wfu_tb_log_version;
244
  global $wfu_tb_userdata_version;
@@ -251,7 +391,14 @@ function wordpress_file_upload_update_db_check() {
251
  }
252
  }
253
 
254
- // This is the callback function that generates dashboard page content
 
 
 
 
 
 
 
255
  function wordpress_file_upload_manage_dashboard() {
256
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
257
  $_POST = stripslashes_deep($_POST);
@@ -446,8 +593,16 @@ function wordpress_file_upload_manage_dashboard() {
446
  echo $echo_str;
447
  }
448
 
449
- // This is the callback function that generates dashboard page content when
450
- // loaded by a non-admin user who is able to edit posts or pages
 
 
 
 
 
 
 
 
451
  function wordpress_file_upload_manage_dashboard_editor() {
452
  $_POST = stripslashes_deep($_POST);
453
  $_GET = stripslashes_deep($_GET);
@@ -469,6 +624,18 @@ function wordpress_file_upload_manage_dashboard_editor() {
469
  echo $echo_str;
470
  }
471
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  function wfu_manage_mainmenu($message = '') {
473
  if ( !current_user_can( 'manage_options' ) ) return;
474
 
@@ -590,6 +757,19 @@ function wfu_manage_mainmenu($message = '') {
590
  return $echo_str;
591
  }
592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593
  function wfu_manage_mainmenu_editor($message = '') {
594
  if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) ) return;
595
 
@@ -608,6 +788,20 @@ function wfu_manage_mainmenu_editor($message = '') {
608
  return $echo_str;
609
  }
610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
  function wfu_generate_dashboard_menu($dlp, $active) {
612
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
613
  $siteurl = site_url();
@@ -626,12 +820,20 @@ function wfu_generate_dashboard_menu($dlp, $active) {
626
  return $echo_str;
627
  }
628
 
629
- function wfu_test_function() {
630
- $str = 'hello τεστ A piñata Ёнвидюнт';
631
-
632
- echo "pass: ".$str;
633
- }
634
-
 
 
 
 
 
 
 
 
635
  function wfu_construct_post_list($posts) {
636
  $ids = array();
637
  $list = array();
@@ -645,7 +847,8 @@ function wfu_construct_post_list($posts) {
645
  array_push($ids[$post->post_type], $post->ID);
646
  $id_keys[$post->ID] = $key;
647
  }
648
- //create post list in tree order; items are sorted by post status (publish, private, draft) and then by title
 
649
  $i = 0;
650
  while ( $i < count($posts) ) {
651
  $post = $posts[$i];
@@ -697,6 +900,18 @@ function wfu_construct_post_list($posts) {
697
  return $list;
698
  }
699
 
 
 
 
 
 
 
 
 
 
 
 
 
700
  function wfu_flatten_post_list($list) {
701
  $flat = array();
702
  if ( !is_array($list) ) return $flat;
@@ -713,17 +928,57 @@ function wfu_flatten_post_list($list) {
713
  return $flat;
714
  }
715
 
 
 
 
 
 
 
 
 
 
 
716
  function wfu_manage_instances() {
717
  $echo_str = wfu_manage_instances_of_shortcode('wordpress_file_upload', 'Uploader Instances', 'uploader', 1);
718
 
719
  return $echo_str;
720
  }
721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722
  function wfu_manage_instances_of_shortcode($tag, $title, $slug, $inc) {
723
  global $wp_registered_widgets, $wp_registered_sidebars;
724
 
725
  $siteurl = site_url();
726
  $args = array( 'post_type' => array( "post", "page" ), 'post_status' => "publish,private,draft", 'posts_per_page' => -1 );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727
  $args = apply_filters("_wfu_get_posts", $args, "manage_instances");
728
  $posts = get_posts($args);
729
  $wfu_shortcodes = array();
@@ -851,6 +1106,18 @@ function wfu_manage_instances_of_shortcode($tag, $title, $slug, $inc) {
851
  return $echo_str;
852
  }
853
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  function wfu_get_content_shortcodes($post, $tag) {
855
  global $shortcode_tags;
856
  $found_shortcodes = array();
@@ -864,6 +1131,24 @@ function wfu_get_content_shortcodes($post, $tag) {
864
  return $found_shortcodes;
865
  }
866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867
  function wfu_match_shortcode_nested($tag, $post, $hash, $content, $position, &$found_shortcodes) {
868
  if ( false === strpos( $content, '[' ) ) return false;
869
  preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
@@ -881,6 +1166,22 @@ function wfu_match_shortcode_nested($tag, $post, $hash, $content, $position, &$f
881
  return false;
882
  }
883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884
  function wfu_check_edit_shortcode($data) {
885
  $post = get_post($data['post_id']);
886
  $content = $post->post_content;
@@ -889,6 +1190,19 @@ function wfu_check_edit_shortcode($data) {
889
  return ( $hash == $data['post_hash'] );
890
  }
891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
892
  function wfu_add_shortcode($postid, $tag) {
893
  $post = get_post($postid);
894
  $new_content = '['.$tag.']'.$post->post_content;
@@ -896,6 +1210,27 @@ function wfu_add_shortcode($postid, $tag) {
896
  return ( wp_update_post( wfu_slash($new_post) ) === 0 ? false : true );
897
  }
898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899
  function wfu_replace_shortcode($data, $new_shortcode) {
900
  $post = get_post($data['post_id']);
901
  $new_content = substr($post->post_content, 0, $data['position']).$new_shortcode.substr($post->post_content, (int)$data['position'] + strlen($data['shortcode']));
@@ -903,6 +1238,19 @@ function wfu_replace_shortcode($data, $new_shortcode) {
903
  return ( wp_update_post( wfu_slash($new_post) ) === 0 ? false : true );
904
  }
905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906
  function wfu_delete_shortcode_prompt($data_enc) {
907
  $siteurl = site_url();
908
  $data = wfu_decode_array_from_string(wfu_get_shortcode_data_from_safe($data_enc));
@@ -926,6 +1274,19 @@ function wfu_delete_shortcode_prompt($data_enc) {
926
  return $echo_str;
927
  }
928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929
  function wfu_delete_shortcode($data) {
930
  //check if user is allowed to perform this action
931
  if ( !current_user_can( 'manage_options' ) ) return false;
@@ -939,6 +1300,18 @@ function wfu_delete_shortcode($data) {
939
  return $res;
940
  }
941
 
 
 
 
 
 
 
 
 
 
 
 
 
942
  function wfu_media_editor_properties() {
943
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
944
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
@@ -955,4 +1328,4 @@ function wfu_media_editor_properties() {
955
  echo $echo_str;
956
  }
957
 
958
- ?>
1
  <?php
2
 
3
+ /**
4
+ * Initialize Dashboard Area of Plugin
5
+ *
6
+ * This file initializes the Dashboard area of the plugin; it registers the
7
+ * Dashboard menu pages and processes Dashboard requests.
8
+ *
9
+ * @link /lib/wfu_admin.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 2.1.2
14
+ */
15
+
16
+ /**
17
+ * Register Dashboard Styles and Scripts.
18
+ *
19
+ * This function registers styles and scripts for Dashboard area.
20
+ *
21
+ * @since 2.4.6
22
+ */
23
  function wordpress_file_upload_admin_init() {
24
  $uri = $_SERVER['REQUEST_URI'];
25
  $is_admin = current_user_can( 'manage_options' );
31
  ( is_admin() && $can_open_composer && strpos($uri, "admin.php") !== false ) ) {
32
  //apply wfu_before_admin_scripts to get additional settings
33
  $changable_data = array();
34
+ /**
35
+ * Execute Custom Actions Before Loading Admin Scripts.
36
+ *
37
+ * This filter allows to execute custom actions before scripts and
38
+ * styles of the plugin's main Dashboard area are loaded. Loading of
39
+ * plugin's scripts and styles can be completely customised.
40
+ *
41
+ * @since 4.1.0
42
+ *
43
+ * @param array $changable_data {
44
+ * Controls loading of frontpage scripts.
45
+ *
46
+ * @type mixed $return_value Optional. If it is set then no
47
+ * frontpage scripts will be loaded.
48
+ * @type string $correct_NextGenGallery_incompatibility Optional. If
49
+ * it is set to "true" then JQuery UI styles will not be
50
+ * loaded in order to avoid incompatibility with NextGEN
51
+ * Gallery plugin.
52
+ * @type string $correct_JQueryUI_incompatibility Optional. If it is
53
+ * set to "true" then JQuery UI styles will not be loaded
54
+ * (same as previous parameter).
55
+ * @type string $exclude_datepicker Optional. If it is set to "true"
56
+ * then jQuery datepicker styles and scripts will not be
57
+ * loaded.
58
+ * }
59
+ */
60
  $ret_data = apply_filters('wfu_before_admin_scripts', $changable_data);
61
  //if $ret_data contains 'return_value' key then no scripts will be
62
  //registered
82
  elseif ( is_admin() && $is_admin && strpos($uri, "admin.php") !== false ) {
83
  //apply wfu_before_admin_scripts to get additional settings
84
  $changable_data = array();
85
+ /**
86
+ * Execute Custom Actions Before Loading Uploaded Files Scripts.
87
+ *
88
+ * This filter allows to execute custom actions before scripts and
89
+ * styles of the plugin's Uploaded Files Dashboard page are loaded.
90
+ * Loading of plugin's scripts and styles can be completely customised.
91
+ *
92
+ * @since 4.7.0
93
+ *
94
+ * @param array $changable_data {
95
+ * Controls loading of frontpage scripts.
96
+ *
97
+ * @type mixed $return_value Optional. If it is set then no
98
+ * frontpage scripts will be loaded.
99
+ * @type string $correct_NextGenGallery_incompatibility Optional. If
100
+ * it is set to "true" then JQuery UI styles will not be
101
+ * loaded in order to avoid incompatibility with NextGEN
102
+ * Gallery plugin.
103
+ * @type string $correct_JQueryUI_incompatibility Optional. If it is
104
+ * set to "true" then JQuery UI styles will not be loaded
105
+ * (same as previous parameter).
106
+ * }
107
+ */
108
  $ret_data = apply_filters('wfu_before_uploadedfiles_admin_scripts', $changable_data);
109
  //if $ret_data contains 'return_value' key then no scripts will be
110
  //registered
126
  }
127
  }
128
 
129
+ /**
130
+ * Register Dashboard Menu Pages.
131
+ *
132
+ * This function registers the Dashboard pages of the plugin.
133
+ *
134
+ * @since 2.1.2
135
+ */
136
  function wordpress_file_upload_add_admin_pages() {
137
  global $wpdb;
138
  global $wfu_uploadedfiles_hook_suffix;
175
  add_action('admin_print_scripts', 'wfu_enqueue_uploadedfiles_adminbar_scripts');
176
  }
177
 
178
+ /**
179
+ * Enqueue Main Dashboard Page Styles and Scripts.
180
+ *
181
+ * This function registers the styles and scripts of the plugin's main
182
+ * Dashboard page.
183
+ *
184
+ * @since 2.4.6
185
+ */
186
  function wfu_enqueue_admin_scripts() {
187
  $uri = $_SERVER['REQUEST_URI'];
188
  $is_admin = current_user_can( 'manage_options' );
193
  ( is_admin() && $can_open_composer && strpos($uri, "admin.php") !== false ) ) {
194
  //apply wfu_before_admin_scripts to get additional settings
195
  $changable_data = array();
196
+ /** This filter is documented above */
197
  $ret_data = apply_filters('wfu_before_admin_scripts', $changable_data);
198
  //if $ret_data contains 'return_value' key then no scripts will be
199
  //enqueued
216
  }
217
  }
218
 
219
+ /**
220
+ * Enqueue Uploaded Files Dashboard Page Styles and Scripts.
221
+ *
222
+ * This function registers the styles and scripts of the plugin's Uploaded Files
223
+ * Dashboard page.
224
+ *
225
+ * @since 4.7.0
226
+ */
227
  function wfu_enqueue_uploadedfiles_admin_scripts() {
228
  $uri = $_SERVER['REQUEST_URI'];
229
  $is_admin = current_user_can( 'manage_options' );
230
  if ( is_admin() && $is_admin && strpos($uri, "admin.php") !== false ) {
231
  //apply wfu_before_admin_scripts to get additional settings
232
  $changable_data = array();
233
+ /** This filter is documented above */
234
  $ret_data = apply_filters('wfu_before_uploadedfiles_admin_scripts', $changable_data);
235
  //if $ret_data contains 'return_value' key then no scripts will be
236
  //enqueued
249
  }
250
  }
251
 
252
+ /**
253
+ * Enqueue Admin Bar Styles and Scripts.
254
+ *
255
+ * This function registers the styles and scripts of the plugin for the Admin
256
+ * Bar.
257
+ *
258
+ * @since 4.8.0
259
+ */
260
  function wfu_enqueue_uploadedfiles_adminbar_scripts() {
261
  $is_admin = current_user_can( 'manage_options' );
262
  if ( is_admin() && $is_admin ) {
266
  }
267
 
268
 
269
+ /**
270
+ * Initialize Tables.
271
+ *
272
+ * This function initializes the plugin's database tables and other actions.
273
+ *
274
+ * @since 2.4.1
275
+ */
276
  function wordpress_file_upload_install() {
277
  global $wpdb;
278
  global $wfu_tb_log_version;
343
  dbDelta($sql);
344
  update_option("wordpress_file_upload_table_dbxqueue_version", $wfu_tb_dbxqueue_version);
345
  }
346
+ //adjust user state handler to 'dboption' except if there are active hooks
347
+ //that use session; adjustment will be done only once
348
+ if ( WFU_VAR("WFU_US_HANDLER_CHANGED") == "false" ) {
349
+ $envars = get_option("wfu_environment_variables", array());
350
+ {
351
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
352
+ if ( $plugin_options["userstatehandler"] != "dboption" ) wfu_update_setting("userstatehandler", "dboption");
353
+ if ( WFU_VAR("WFU_US_DBOPTION_BASE") != "cookies" ) {
354
+ $GLOBALS["WFU_GLOBALS"]["WFU_US_DBOPTION_BASE"][3] = "cookies";
355
+ $envars["WFU_US_DBOPTION_BASE"] = "cookies";
356
+ }
357
+ }
358
+ $GLOBALS["WFU_GLOBALS"]["WFU_US_HANDLER_CHANGED"][3] = "true";
359
+ $envars["WFU_US_HANDLER_CHANGED"] = "true";
360
+ update_option("wfu_environment_variables", $envars);
361
+ }
362
  }
363
 
364
+ /**
365
+ * Actions Before Uninstalling Plugin.
366
+ *
367
+ * This function performs actions before uninstalling the plugin.
368
+ *
369
+ * @since 4.4.0
370
+ */
371
  function wordpress_file_upload_uninstall() {
372
  }
373
 
374
+ /**
375
+ * Actions After Plugins are Loaded.
376
+ *
377
+ * This function performs actions after plugin are loaded. It updates the
378
+ * database tables in necessary.
379
+ *
380
+ * @since 2.4.1
381
+ */
382
  function wordpress_file_upload_update_db_check() {
383
  global $wfu_tb_log_version;
384
  global $wfu_tb_userdata_version;
391
  }
392
  }
393
 
394
+ /**
395
+ * Process Dashboard Requests.
396
+ *
397
+ * This function processes Dashboard requests and shows main Dashboard pages of
398
+ * the plugin in Settings.
399
+ *
400
+ * @since 2.1.2
401
+ */
402
  function wordpress_file_upload_manage_dashboard() {
403
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
404
  $_POST = stripslashes_deep($_POST);
593
  echo $echo_str;
594
  }
595
 
596
+ /**
597
+ * Process Dashboard Requests for Non-Admin Users.
598
+ *
599
+ * This function processes Dashboard requests and shows the shortcode composer
600
+ * to users that are not admins but who can edit posts or pages. It also lets
601
+ * extensions implement their own actions when receiving Dashboard requests by
602
+ * non-admin users.
603
+ *
604
+ * @since 4.11.0
605
+ */
606
  function wordpress_file_upload_manage_dashboard_editor() {
607
  $_POST = stripslashes_deep($_POST);
608
  $_GET = stripslashes_deep($_GET);
624
  echo $echo_str;
625
  }
626
 
627
+ /**
628
+ * Display the Main Dashboard Page.
629
+ *
630
+ * This function displays the Main Dashboard page of the plugin.
631
+ *
632
+ * @since 2.5.2
633
+ *
634
+ * @param string $message Optional. A message to display on top when showing
635
+ * Main page of the plugin in Dashboard.
636
+ *
637
+ * @return string The HTML output of the plugin's Main Dashboard page.
638
+ */
639
  function wfu_manage_mainmenu($message = '') {
640
  if ( !current_user_can( 'manage_options' ) ) return;
641
 
757
  return $echo_str;
758
  }
759
 
760
+ /**
761
+ * Default Dashboard Page for Non-Admin Users.
762
+ *
763
+ * This function displays the plugin's default Dashboard page for non-admin
764
+ * users who can edit pages or posts.
765
+ *
766
+ * @since 4.11.0
767
+ *
768
+ * @param string $message Optional. A message to display on top when showing
769
+ * the default Dashboard page of the plugin for non-admin users.
770
+ *
771
+ * @return string The HTML output of the plugin's default Dashboard page.
772
+ */
773
  function wfu_manage_mainmenu_editor($message = '') {
774
  if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) ) return;
775
 
788
  return $echo_str;
789
  }
790
 
791
+ /**
792
+ * Main Dashboard Page Tabs.
793
+ *
794
+ * This function generates the tabs of the plugin's main area in Dashboard.
795
+ *
796
+ * @since 3.6.0
797
+ *
798
+ * @redeclarable
799
+ *
800
+ * @param string $dlp Identation string before the beginning of each HTML line.
801
+ * @param string $active The name of the tab that it is active.
802
+ *
803
+ * @return string The HTML output of the tabs.
804
+ */
805
  function wfu_generate_dashboard_menu($dlp, $active) {
806
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
807
  $siteurl = site_url();
820
  return $echo_str;
821
  }
822
 
823
+ /**
824
+ * Generate List of Posts in Tree Order.
825
+ *
826
+ * This function converts a flat array of posts into a tree structure, where an
827
+ * individual item of the returned array may contain a nested array of children.
828
+ * Items of the same parent and level are sorted by post status (publish,
829
+ * private, draft) and then by title.
830
+ *
831
+ * @since 2.7.6
832
+ *
833
+ * @param array $posts The initial flat array of posts.
834
+ *
835
+ * @return array The returned list of posts in tree order.
836
+ */
837
  function wfu_construct_post_list($posts) {
838
  $ids = array();
839
  $list = array();
847
  array_push($ids[$post->post_type], $post->ID);
848
  $id_keys[$post->ID] = $key;
849
  }
850
+ //create post list in tree order; items are sorted by post status (publish,
851
+ //private, draft) and then by title
852
  $i = 0;
853
  while ( $i < count($posts) ) {
854
  $post = $posts[$i];
900
  return $list;
901
  }
902
 
903
+ /**
904
+ * Flatten Tree List of Posts.
905
+ *
906
+ * This function converts a list that contains posts in tree order into a flat
907
+ * list (array) of posts.
908
+ *
909
+ * @since 2.7.6
910
+ *
911
+ * @param array $list The initial tree list of posts.
912
+ *
913
+ * @return array The returned flat list of posts.
914
+ */
915
  function wfu_flatten_post_list($list) {
916
  $flat = array();
917
  if ( !is_array($list) ) return $flat;
928
  return $flat;
929
  }
930
 
931
+ /**
932
+ * Generate List of Instances of All Plugin' Shortcodes.
933
+ *
934
+ * This function generates a tabular list of all instances of all plugin's
935
+ * shortcodes.
936
+ *
937
+ * @since 2.5.2
938
+ *
939
+ * @return string The HTML code of the list of instances of all the shortcodes.
940
+ */
941
  function wfu_manage_instances() {
942
  $echo_str = wfu_manage_instances_of_shortcode('wordpress_file_upload', 'Uploader Instances', 'uploader', 1);
943
 
944
  return $echo_str;
945
  }
946
 
947
+ /**
948
+ * Generate List of Instances of A Plugin' Shortcode.
949
+ *
950
+ * This function generates a tabular list of all instances of a plugin's
951
+ * shortcode.
952
+ *
953
+ * @since 3.1.0
954
+ *
955
+ * @param string $tag The shortcode tag.
956
+ * @param string $title The title of the list
957
+ * @param string $slug A slug of the shortcode.
958
+ * @param integer $inc The increment number of this list of instances.
959
+ *
960
+ * @return string The HTML code of the list of instances of the shortcode.
961
+ */
962
  function wfu_manage_instances_of_shortcode($tag, $title, $slug, $inc) {
963
  global $wp_registered_widgets, $wp_registered_sidebars;
964
 
965
  $siteurl = site_url();
966
  $args = array( 'post_type' => array( "post", "page" ), 'post_status' => "publish,private,draft", 'posts_per_page' => -1 );
967
+ /**
968
+ * Filter Arguments for Getting List of Posts.
969
+ *
970
+ * This filter allows to customize the arguments passed to get_posts()
971
+ * function to get a list of posts. By default the plugin will get a list of
972
+ * all posts and pages. If the website contains too many posts this
973
+ * operation may take time and delay loading of the page. So this filter can
974
+ * be used to optimize this operation.
975
+ *
976
+ * @since 4.0.0
977
+ *
978
+ * @param array $args Arguments to retrieve posts.
979
+ * @param string $operation A parameter designating in which operation this
980
+ * filter is used.
981
+ */
982
  $args = apply_filters("_wfu_get_posts", $args, "manage_instances");
983
  $posts = get_posts($args);
984
  $wfu_shortcodes = array();
1106
  return $echo_str;
1107
  }
1108
 
1109
+ /**
1110
+ * Get Shortcodes Contained In A Post.
1111
+ *
1112
+ * This function returns an array of shortcodes contained inside a post.
1113
+ *
1114
+ * @since 2.5.4
1115
+ *
1116
+ * @param object $post The post to check for shortcodes.
1117
+ * @param string $tag The shortcode tag to look for.
1118
+ *
1119
+ * @return array An array of shortcodes contained inside the post.
1120
+ */
1121
  function wfu_get_content_shortcodes($post, $tag) {
1122
  global $shortcode_tags;
1123
  $found_shortcodes = array();
1131
  return $found_shortcodes;
1132
  }
1133
 
1134
+ /**
1135
+ * Match Shortcodes.
1136
+ *
1137
+ * This function matches all shortcodes inside post contents. It performs
1138
+ * matching recursively in order to identify shortcodes contained in other
1139
+ * shortcodes.
1140
+ *
1141
+ * @since 2.7.6
1142
+ *
1143
+ * @param string $tag The shortcode tag to look for.
1144
+ * @param object $post The post to check for shortcodes.
1145
+ * @param string $hash A unique hash representing the current contents of the
1146
+ * post.
1147
+ * @param string $content The content where to look for shortcodes.
1148
+ * @param integer $position The starting position of content.
1149
+ * @param array $found_shortcodes An array of already found shortcodes that must
1150
+ * be filled by additional shortcodes found from this function.
1151
+ */
1152
  function wfu_match_shortcode_nested($tag, $post, $hash, $content, $position, &$found_shortcodes) {
1153
  if ( false === strpos( $content, '[' ) ) return false;
1154
  preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
1166
  return false;
1167
  }
1168
 
1169
+ /**
1170
+ * Check Whether Shortcode Can Be Edited.
1171
+ *
1172
+ * This function checks whether the shortcode submitted for editing can actually
1173
+ * be edited. It checks whether the hash of the post, where the shortcode is
1174
+ * contained, is the same with the one stored in the shortcode data. If it is
1175
+ * not, then this means that the page contents have changed, so the shortcode
1176
+ * cannot be edited and the user will have to reload the page before editing the
1177
+ * shortcode.
1178
+ *
1179
+ * @since 2.6.0
1180
+ *
1181
+ * @param array $data The shortcode data to check.
1182
+ *
1183
+ * @return bool True if the shortcode can be edited, false otherwise.
1184
+ */
1185
  function wfu_check_edit_shortcode($data) {
1186
  $post = get_post($data['post_id']);
1187
  $content = $post->post_content;
1190
  return ( $hash == $data['post_hash'] );
1191
  }
1192
 
1193
+ /**
1194
+ * Add Shortcode Inside Post.
1195
+ *
1196
+ * This function adds a shortcode at the beginning of post's contents.
1197
+ *
1198
+ * @since 2.7.6
1199
+ *
1200
+ * @param integer $postid The post ID where to add the shortcode.
1201
+ * $param string $tag The shortcode tag to add in post.
1202
+ *
1203
+ * @return bool True if the shortcode was added successfully inside the post,
1204
+ * false otherwise.
1205
+ */
1206
  function wfu_add_shortcode($postid, $tag) {
1207
  $post = get_post($postid);
1208
  $new_content = '['.$tag.']'.$post->post_content;
1210
  return ( wp_update_post( wfu_slash($new_post) ) === 0 ? false : true );
1211
  }
1212
 
1213
+ /**
1214
+ * Replace Shortcode Inside Post.
1215
+ *
1216
+ * This function replaces a shortcode inside post's contents.
1217
+ *
1218
+ * @since 2.6.0
1219
+ *
1220
+ * @param array $data {
1221
+ * Contains information about the shortcode.
1222
+ *
1223
+ * $type integer $post_id The ID of the post that contains the shortcode.
1224
+ * $type string $post_hash A hash that represents the current post contents.
1225
+ * $type string $shortcode The shortcode string to be replaced.
1226
+ * $type integer $position The position of the shortcode inside post's
1227
+ * contents.
1228
+ * }
1229
+ * $param string $new_shortcode The new shortcode.
1230
+ *
1231
+ * @return bool True if the shortcode was replaced successfully, false
1232
+ * otherwise.
1233
+ */
1234
  function wfu_replace_shortcode($data, $new_shortcode) {
1235
  $post = get_post($data['post_id']);
1236
  $new_content = substr($post->post_content, 0, $data['position']).$new_shortcode.substr($post->post_content, (int)$data['position'] + strlen($data['shortcode']));
1238
  return ( wp_update_post( wfu_slash($new_post) ) === 0 ? false : true );
1239
  }
1240
 
1241
+ /**
1242
+ * Generate Page for Confirmation of Deletion of Shortcode.
1243
+ *
1244
+ * This function generates the HTML code of the page to ask from the user to
1245
+ * confirm deletion of the selected shortcode.
1246
+ *
1247
+ * @since 2.7.0
1248
+ *
1249
+ * $param string $data_enc Code that represents the shortcode data stored in
1250
+ * safe.
1251
+ *
1252
+ * @return string The HTML code of the deletion confirmation page.
1253
+ */
1254
  function wfu_delete_shortcode_prompt($data_enc) {
1255
  $siteurl = site_url();
1256
  $data = wfu_decode_array_from_string(wfu_get_shortcode_data_from_safe($data_enc));
1274
  return $echo_str;
1275
  }
1276
 
1277
+ /**
1278
+ * Deletion Shortcode.
1279
+ *
1280
+ * This function deletes a shortcode from page contents.
1281
+ *
1282
+ * @since 2.7.0
1283
+ *
1284
+ * $param array $data Code that represents the shortcode data stored in
1285
+ * safe. See {@see wfu_replace_shortcode()} for a list of supported
1286
+ * arguments.
1287
+ *
1288
+ * @return bool True if deletion succeeded, false otherwise.
1289
+ */
1290
  function wfu_delete_shortcode($data) {
1291
  //check if user is allowed to perform this action
1292
  if ( !current_user_can( 'manage_options' ) ) return false;
1300
  return $res;
1301
  }
1302
 
1303
+ /**
1304
+ * Add Custom Properties to Media Editor.
1305
+ *
1306
+ * When "Show Custom Fields in Media Library" option in plugin's Settings is
1307
+ * true then Media Library attachments created by uploaded files will contain
1308
+ * custom fields corresponding to the uploaded files' userdata (if any). This
1309
+ * function shows these custom fields when editing the Media Library attachment.
1310
+ *
1311
+ * @since 3.7.2
1312
+ *
1313
+ * @redeclarable
1314
+ */
1315
  function wfu_media_editor_properties() {
1316
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1317
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1328
  echo $echo_str;
1329
  }
1330
 
1331
+ ?>
lib/wfu_admin_browser.php CHANGED
@@ -1,5 +1,34 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_browse_files($basedir_code, $page = -1, $only_table_rows = false) {
4
  $siteurl = site_url();
5
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
@@ -472,6 +501,20 @@ function wfu_browse_files($basedir_code, $page = -1, $only_table_rows = false) {
472
  return $echo_str;
473
  }
474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  function wfu_adminbrowser_file_actions($file, $params) {
476
  $siteurl = site_url();
477
  $actions = array(
@@ -486,7 +529,7 @@ function wfu_adminbrowser_file_actions($file, $params) {
486
  array( '<a href="'.$siteurl.'/wp-admin/options-general.php?page=wordpress_file_upload&action=delete_file&file='.$file["code"].'&referer='.$file["referer_code"].'" title="Delete this file">Delete</a>' ),
487
  array( '<a href="javascript:wfu_download_file(\''.$file["code"].'\', '.$file["index"].');" title="Download this file">Download</a>' )
488
  );
489
- //add file actions if file is already included
490
  $actions["can_be_included"] += array(
491
  array(
492
  '<a id="wfu_include_file_'.$file["index"].'_a" href="javascript:wfu_include_file(\''.$file["code"].'\', '.$file["index"].');" title="Include file in plugin\'s database">Include File</a>',
@@ -498,6 +541,19 @@ function wfu_adminbrowser_file_actions($file, $params) {
498
  return $actions;
499
  }
500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  function wfu_user_owns_file($userid, $filerec) {
502
  if ( 0 == $userid )
503
  return false;
@@ -505,6 +561,18 @@ function wfu_user_owns_file($userid, $filerec) {
505
  return false;
506
  }
507
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  function wfu_current_user_owes_file($filepath) {
509
  //first check if file has a restricted extension; for security reasons some file extensions cannot be owned
510
  if ( wfu_file_extension_blacklisted($filepath) ) return false;
@@ -516,6 +584,20 @@ function wfu_current_user_owes_file($filepath) {
516
  return wfu_user_owns_file($user->ID, $filerec);
517
  }
518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  function wfu_current_user_allowed_action($action, $filepath) {
520
  //first get file data from database, if exist
521
  $filerec = wfu_get_file_rec($filepath, false);
@@ -529,6 +611,21 @@ function wfu_current_user_allowed_action($action, $filepath) {
529
  return $user;
530
  }
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  function wfu_current_user_allowed_action_remote($action, $filepath, $userid) {
533
  //first get file data from database, if exist
534
  $filerec = wfu_get_file_rec($filepath, false);
@@ -541,6 +638,20 @@ function wfu_current_user_allowed_action_remote($action, $filepath, $userid) {
541
  return true;
542
  }
543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
  function wfu_rename_file_prompt($file_code, $type, $error) {
545
  if ( $type == 'dir' ) return;
546
 
@@ -595,6 +706,19 @@ function wfu_rename_file_prompt($file_code, $type, $error) {
595
  return $echo_str;
596
  }
597
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  function wfu_move_file_prompt($file_code, $error) {
599
  $siteurl = site_url();
600
 
@@ -664,6 +788,18 @@ function wfu_move_file_prompt($file_code, $error) {
664
  return $echo_str;
665
  }
666
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  function wfu_rename_file($file_code, $type) {
668
  if ( $type == 'dir' ) return;
669
 
@@ -713,6 +849,17 @@ function wfu_rename_file($file_code, $type) {
713
  return ( $error == "" );
714
  }
715
 
 
 
 
 
 
 
 
 
 
 
 
716
  function wfu_move_file($file_code) {
717
  $user = wp_get_current_user();
718
  $is_admin = current_user_can( 'manage_options' );
@@ -773,6 +920,19 @@ function wfu_move_file($file_code) {
773
  return ( $error == "" );
774
  }
775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
776
  function wfu_delete_file_prompt($file_code, $type, $referer) {
777
  if ( $type == 'dir' ) return;
778
 
@@ -836,6 +996,18 @@ function wfu_delete_file_prompt($file_code, $type, $referer) {
836
  return $echo_str;
837
  }
838
 
 
 
 
 
 
 
 
 
 
 
 
 
839
  function wfu_delete_file($file_code, $type) {
840
  if ( $type == 'dir' ) return;
841
 
@@ -871,6 +1043,19 @@ function wfu_delete_file($file_code, $type) {
871
  return true;
872
  }
873
 
 
 
 
 
 
 
 
 
 
 
 
 
 
874
  function wfu_create_dir_prompt($dir_code, $error) {
875
  return;
876
 
@@ -914,6 +1099,17 @@ function wfu_create_dir_prompt($dir_code, $error) {
914
  return $echo_str;
915
  }
916
 
 
 
 
 
 
 
 
 
 
 
 
917
  function wfu_create_dir($dir_code) {
918
  return;
919
 
@@ -945,6 +1141,20 @@ function wfu_create_dir($dir_code) {
945
  return ( $error == "" );
946
  }
947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948
  function wfu_include_file_prompt($file_code, $referer) {
949
  if ( !current_user_can( 'manage_options' ) ) return;
950
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
@@ -999,6 +1209,17 @@ function wfu_include_file_prompt($file_code, $referer) {
999
  return $echo_str;
1000
  }
1001
 
 
 
 
 
 
 
 
 
 
 
 
1002
  function wfu_include_file($file_code) {
1003
  if ( !current_user_can( 'manage_options' ) ) return;
1004
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
@@ -1028,6 +1249,21 @@ function wfu_include_file($file_code) {
1028
  return true;
1029
  }
1030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1031
  function wfu_file_details($file_code, $errorstatus, $invoker = '') {
1032
  $siteurl = site_url();
1033
  $allow_obsolete = false;
@@ -1150,6 +1386,21 @@ function wfu_file_details($file_code, $errorstatus, $invoker = '') {
1150
  $echo_str .= "\n\t\t\t\t\t\t\t".'<select id="wfu_filedetails_users" disabled="disabled">';
1151
  //get all users
1152
  $args = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1153
  $args = apply_filters("_wfu_get_users", $args, "edit_file_details");
1154
  $users = get_users($args);
1155
  foreach ( $users as $userid => $user )
@@ -1288,6 +1539,18 @@ function wfu_file_details($file_code, $errorstatus, $invoker = '') {
1288
  return $echo_str;
1289
  }
1290
 
 
 
 
 
 
 
 
 
 
 
 
 
1291
  function wfu_edit_filedetails($file_code) {
1292
  global $wpdb;
1293
  $table_name2 = $wpdb->prefix . "wfu_userdata";
1
  <?php
2
 
3
+ /**
4
+ * File Browser Page in Dashboard Area of Plugin
5
+ *
6
+ * This file contains functions related to File Browser page of plugin's
7
+ * Dashboard area.
8
+ *
9
+ * @link /lib/wfu_admin_browser.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 3.7.1
14
+ */
15
+
16
+ /**
17
+ * Display the File Browser Page.
18
+ *
19
+ * This function displays the File Browser page of the plugin's Dashboard area.
20
+ *
21
+ * @since 2.2.1
22
+ *
23
+ * @param string $basedir_code A code string corresponding to the folder to be
24
+ * displayed.
25
+ * @param integer $page Optional. The page to display in case folder contents
26
+ * are paginated.
27
+ * @param bool $only_table_rows Optional. Return only the HTML code of the table
28
+ * rows.
29
+ *
30
+ * @return string The HTML output of the plugin's File Browser Dashboard page.
31
+ */
32
  function wfu_browse_files($basedir_code, $page = -1, $only_table_rows = false) {
33
  $siteurl = site_url();
34
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
501
  return $echo_str;
502
  }
503
 
504
+ /**
505
+ * Add Actions to Displayed Files.
506
+ *
507
+ * This function sets the actions that can be applied on the displayed files.
508
+ * Filters can customize these actions.
509
+ *
510
+ * @since 4.1.0
511
+ *
512
+ * @param array $file An array containing properties of the file.
513
+ * @param array $params An array of custom parameters to pass to file actions
514
+ * filter.
515
+ *
516
+ * @return array An array of actions that can be executed on the file.
517
+ */
518
  function wfu_adminbrowser_file_actions($file, $params) {
519
  $siteurl = site_url();
520
  $actions = array(
529
  array( '<a href="'.$siteurl.'/wp-admin/options-general.php?page=wordpress_file_upload&action=delete_file&file='.$file["code"].'&referer='.$file["referer_code"].'" title="Delete this file">Delete</a>' ),
530
  array( '<a href="javascript:wfu_download_file(\''.$file["code"].'\', '.$file["index"].');" title="Download this file">Download</a>' )
531
  );
532
+ //add file actions if file can be included
533
  $actions["can_be_included"] += array(
534
  array(
535
  '<a id="wfu_include_file_'.$file["index"].'_a" href="javascript:wfu_include_file(\''.$file["code"].'\', '.$file["index"].');" title="Include file in plugin\'s database">Include File</a>',
541
  return $actions;
542
  }
543
 
544
+ /**
545
+ * Check if User Owns a File.
546
+ *
547
+ * This function checks if a user is the owner of a specific file. It will
548
+ * return true if the user in an administrator.
549
+ *
550
+ * @since 3.8.5
551
+ *
552
+ * @param integer $userid The ID of the user to check.
553
+ * @param object $filerec The database record of the file.
554
+ *
555
+ * @return bool True if the user owns the file, false otherwise.
556
+ */
557
  function wfu_user_owns_file($userid, $filerec) {
558
  if ( 0 == $userid )
559
  return false;
561
  return false;
562
  }
563
 
564
+ /**
565
+ * Check if Current User Owns a File.
566
+ *
567
+ * This function checks if the current user is the owner of a specific file. It
568
+ * will first check if the file extension is valid.
569
+ *
570
+ * @since 3.0.0
571
+ *
572
+ * @param string $filepath The full path of the file to check.
573
+ *
574
+ * @return bool True if the user owns the file, false otherwise.
575
+ */
576
  function wfu_current_user_owes_file($filepath) {
577
  //first check if file has a restricted extension; for security reasons some file extensions cannot be owned
578
  if ( wfu_file_extension_blacklisted($filepath) ) return false;
584
  return wfu_user_owns_file($user->ID, $filerec);
585
  }
586
 
587
+ /**
588
+ * Check if Current User is Allowed to Execute an Action on a File.
589
+ *
590
+ * This function checks if the current user is allowed to execute a specific
591
+ * action on a file.
592
+ *
593
+ * @since 2.4.1
594
+ *
595
+ * @param string $action A file action to check.
596
+ * @param string $filepath The full path of the file to check.
597
+ *
598
+ * @return object|null Returns the current WP_User object if current user is
599
+ * allowed to execute the action on the file or null otherwise.
600
+ */
601
  function wfu_current_user_allowed_action($action, $filepath) {
602
  //first get file data from database, if exist
603
  $filerec = wfu_get_file_rec($filepath, false);
611
  return $user;
612
  }
613
 
614
+ /**
615
+ * Check if User is Allowed to Execute an Action on a File.
616
+ *
617
+ * This function checks if a user is allowed to execute a specific action on a
618
+ * file.
619
+ *
620
+ * @since 2.6.0
621
+ *
622
+ * @param string $action A file action to check.
623
+ * @param string $filepath The full path of the file to check.
624
+ * @param integer $userid The ID of the user to check.
625
+ *
626
+ * @return bool|null Returns true if current user is allowed to execute the
627
+ * action on the file or null otherwise.
628
+ */
629
  function wfu_current_user_allowed_action_remote($action, $filepath, $userid) {
630
  //first get file data from database, if exist
631
  $filerec = wfu_get_file_rec($filepath, false);
638
  return true;
639
  }
640
 
641
+ /**
642
+ * Confirm Renaming of File.
643
+ *
644
+ * This function shows a page to confirm renaming of a file.
645
+ *
646
+ * @since 2.2.1
647
+ *
648
+ * @param string $file_code A code corresponding to the file/dir to be renamed.
649
+ * @param string $type Rename dir or file. Can take the values 'dir' or 'file'.
650
+ * @param string $error An error message to show on top of the page in case an
651
+ * error occured during renaming.
652
+ *
653
+ * @return string The HTML code of the confirmation page.
654
+ */
655
  function wfu_rename_file_prompt($file_code, $type, $error) {
656
  if ( $type == 'dir' ) return;
657
 
706
  return $echo_str;
707
  }
708
 
709
+ /**
710
+ * Confirm Moving of File.
711
+ *
712
+ * This function shows a page to confirm moving of a file to a new location.
713
+ *
714
+ * @since 4.10.3
715
+ *
716
+ * @param string $file_code A code corresponding to the file to be moved.
717
+ * @param string $error An error message to show on top of the page in case an
718
+ * error occured during move.
719
+ *
720
+ * @return string The HTML code of the confirmation page.
721
+ */
722
  function wfu_move_file_prompt($file_code, $error) {
723
  $siteurl = site_url();
724
 
788
  return $echo_str;
789
  }
790
 
791
+ /**
792
+ * Execute Renaming of File.
793
+ *
794
+ * This function renames a file.
795
+ *
796
+ * @since 2.2.1
797
+ *
798
+ * @param string $file_code A code corresponding to the file/dir to be renamed.
799
+ * @param string $type Rename dir or file. Can take the values 'dir' or 'file'.
800
+ *
801
+ * @return bool True if renaming of file succeeded, false otherwise.
802
+ */
803
  function wfu_rename_file($file_code, $type) {
804
  if ( $type == 'dir' ) return;
805
 
849
  return ( $error == "" );
850
  }
851
 
852
+ /**
853
+ * Execute Moving of File.
854
+ *
855
+ * This function moves a file to another location.
856
+ *
857
+ * @since 4.10.3
858
+ *
859
+ * @param string $file_code A code corresponding to the file to be moved.
860
+ *
861
+ * @return bool True if move of file succeeded, false otherwise.
862
+ */
863
  function wfu_move_file($file_code) {
864
  $user = wp_get_current_user();
865
  $is_admin = current_user_can( 'manage_options' );
920
  return ( $error == "" );
921
  }
922
 
923
+ /**
924
+ * Confirm Deletion of File.
925
+ *
926
+ * This function shows a page to confirm deletion of a file.
927
+ *
928
+ * @since 2.2.1
929
+ *
930
+ * @param string $file_code A code corresponding to the file/dir to be deleted.
931
+ * @param string $type Delete dir or file. Can take the values 'dir' or 'file'.
932
+ * @param string $referer The page that initiated the deletion of the file.
933
+ *
934
+ * @return string The HTML code of the confirmation page.
935
+ */
936
  function wfu_delete_file_prompt($file_code, $type, $referer) {
937
  if ( $type == 'dir' ) return;
938
 
996
  return $echo_str;
997
  }
998
 
999
+ /**
1000
+ * Execute Deletion of File.
1001
+ *
1002
+ * This function deletes a file.
1003
+ *
1004
+ * @since 2.2.1
1005
+ *
1006
+ * @param string $file_code A code corresponding to the file/dir to be deleted.
1007
+ * @param string $type Delete dir or file. Can take the values 'dir' or 'file'.
1008
+ *
1009
+ * @return bool True if deletion of file succeeded, false otherwise.
1010
+ */
1011
  function wfu_delete_file($file_code, $type) {
1012
  if ( $type == 'dir' ) return;
1013
 
1043
  return true;
1044
  }
1045
 
1046
+ /**
1047
+ * Confirm Creation of a Directory.
1048
+ *
1049
+ * This function shows a page to confirm creation of a directory.
1050
+ *
1051
+ * @since 2.2.1
1052
+ *
1053
+ * @param string $dir_code A code corresponding to the dir to be created.
1054
+ * @param string $error An error message to show on top of the page in case an
1055
+ * error occured during creation.
1056
+ *
1057
+ * @return string The HTML code of the confirmation page.
1058
+ */
1059
  function wfu_create_dir_prompt($dir_code, $error) {
1060
  return;
1061
 
1099
  return $echo_str;
1100
  }
1101
 
1102
+ /**
1103
+ * Execute Creation of Directory.
1104
+ *
1105
+ * This function creates a new directory.
1106
+ *
1107
+ * @since 2.2.1
1108
+ *
1109
+ * @param string $dir_code A code corresponding to the dir to be created.
1110
+ *
1111
+ * @return bool True if creation of dir succeeded, false otherwise.
1112
+ */
1113
  function wfu_create_dir($dir_code) {
1114
  return;
1115
 
1141
  return ( $error == "" );
1142
  }
1143
 
1144
+ /**
1145
+ * Confirm Inclusion of File in Plugin's Database.
1146
+ *
1147
+ * This function shows a page to confirm inclusion of a file in plugin's
1148
+ * database.
1149
+ *
1150
+ * @since 3.8.5
1151
+ *
1152
+ * @param string $file_code A code corresponding to the file to be included.
1153
+ * @param string $type Rename dir or file. Can take the values 'dir' or 'file'.
1154
+ * @param string $referer The page that initiated the inclusion of the file.
1155
+ *
1156
+ * @return string The HTML code of the confirmation page.
1157
+ */
1158
  function wfu_include_file_prompt($file_code, $referer) {
1159
  if ( !current_user_can( 'manage_options' ) ) return;
1160
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1209
  return $echo_str;
1210
  }
1211
 
1212
+ /**
1213
+ * Execute Inclusion of File in Plugin's Database.
1214
+ *
1215
+ * This function includes a file in plugin's database.
1216
+ *
1217
+ * @since 3.8.5
1218
+ *
1219
+ * @param string $file_code A code corresponding to the file to be included.
1220
+ *
1221
+ * @return bool True if inclusion of file succeeded, false otherwise.
1222
+ */
1223
  function wfu_include_file($file_code) {
1224
  if ( !current_user_can( 'manage_options' ) ) return;
1225
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1249
  return true;
1250
  }
1251
 
1252
+ /**
1253
+ * Show File Details Page.
1254
+ *
1255
+ * This function shows a page displaying details of the uploaded file.
1256
+ *
1257
+ * @since 2.4.1
1258
+ *
1259
+ * @param string $file_code A code corresponding to the file to be included.
1260
+ * @param string $errorstatus Error status. If it has the value 'error' then an
1261
+ * error will be shown on top of the page.
1262
+ * @param string $invoker Optional. The page URL that initiated file details
1263
+ * page.
1264
+ *
1265
+ * @return string The HTML code of File Details page.
1266
+ */
1267
  function wfu_file_details($file_code, $errorstatus, $invoker = '') {
1268
  $siteurl = site_url();
1269
  $allow_obsolete = false;
1386
  $echo_str .= "\n\t\t\t\t\t\t\t".'<select id="wfu_filedetails_users" disabled="disabled">';
1387
  //get all users
1388
  $args = array();
1389
+ /**
1390
+ * Filter Arguments for Getting List of Users.
1391
+ *
1392
+ * This filter allows to customize the arguments passed to get_users()
1393
+ * function to get a list of users. By default the plugin will get a
1394
+ * list of all users. If the website contains too many users this
1395
+ * operation may take time and delay loading of the page. So this filter
1396
+ * can be used to optimize this operation.
1397
+ *
1398
+ * @since 4.11.0
1399
+ *
1400
+ * @param array $args Arguments to retrieve users.
1401
+ * @param string $operation A parameter designating in which operation
1402
+ * the filter is used.
1403
+ */
1404
  $args = apply_filters("_wfu_get_users", $args, "edit_file_details");
1405
  $users = get_users($args);
1406
  foreach ( $users as $userid => $user )
1539
  return $echo_str;
1540
  }
1541
 
1542
+ /**
1543
+ * Change File Details.
1544
+ *
1545
+ * This function modifies the database record of an uploaded file, as well as
1546
+ * any associated user data field records.
1547
+ *
1548
+ * @since 2.4.1
1549
+ *
1550
+ * @param string $file_code A code corresponding to the file to be modified.
1551
+ *
1552
+ * @return bool True if modification of file succeeded, false otherwise.
1553
+ */
1554
  function wfu_edit_filedetails($file_code) {
1555
  global $wpdb;
1556
  $table_name2 = $wpdb->prefix . "wfu_userdata";
lib/wfu_admin_composer.php CHANGED
@@ -1,5 +1,34 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_shortcode_composer($data = '', $shortcode_tag = 'wordpress_file_upload', $referer = 'page') {
4
  global $wp_roles;
5
  $siteurl = site_url();
@@ -496,6 +525,7 @@ function wfu_shortcode_composer($data = '', $shortcode_tag = 'wordpress_file_upl
496
  }
497
  elseif ( $def['type'] == "userlist" ) {
498
  $args = array();
 
499
  $args = apply_filters("_wfu_get_users", $args, "shortcode_composer");
500
  $users = get_users($args);
501
  $selected = explode(",", $def['value']);
@@ -543,6 +573,7 @@ function wfu_shortcode_composer($data = '', $shortcode_tag = 'wordpress_file_upl
543
  $echo_str .= $dlp."\t\t".'</td></tr><tr>';
544
  }
545
  $postargs = array( 'post_type' => $def['listitems'], 'post_status' => "publish,private,draft", 'posts_per_page' => -1 );
 
546
  $postargs = apply_filters("_wfu_get_posts", $postargs, "visual_editor");
547
  $posts = get_posts($postargs);
548
  $list = wfu_construct_post_list($posts);
@@ -907,6 +938,21 @@ function wfu_shortcode_composer($data = '', $shortcode_tag = 'wordpress_file_upl
907
  echo $echo_str;
908
  }
909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
910
  function wfu_insert_variables($variables, $class) {
911
  $ret = "";
912
  foreach ( $variables as $variable )
1
  <?php
2
 
3
+ /**
4
+ * Shortcode Composer Page
5
+ *
6
+ * This file contains functions related to the shortcode composer page of the
7
+ * plugin. The shortcode composer is a visual editor of the plugin's shortcodes
8
+ * so that they can be configured easily by administrators.
9
+ *
10
+ * @link /lib/wfu_admin_composer.php
11
+ *
12
+ * @package WordPress File Upload Plugin
13
+ * @subpackage Core Components
14
+ * @since 2.4.1
15
+ */
16
+
17
+ /**
18
+ * Display the Shortcode Composer.
19
+ *
20
+ * This function displays the shortcode composer for a specific shortcode.
21
+ *
22
+ * @since 2.1.2
23
+ *
24
+ * @param string|array $data Optional. If this function was called for an
25
+ * existing shortcode, this param holds data of the shortcode. If it was
26
+ * called for a new shortcode, it contains an empty string.
27
+ * @param string $shortcode_tag Optional. The shortcode tag.
28
+ * @param string $referer Optional. The page that called this function.
29
+ *
30
+ * @return string The HTML output of the shortcode composer.
31
+ */
32
  function wfu_shortcode_composer($data = '', $shortcode_tag = 'wordpress_file_upload', $referer = 'page') {
33
  global $wp_roles;
34
  $siteurl = site_url();
525
  }
526
  elseif ( $def['type'] == "userlist" ) {
527
  $args = array();
528
+ /** This filter is documented in lib/wfu_admin_browser.php */
529
  $args = apply_filters("_wfu_get_users", $args, "shortcode_composer");
530
  $users = get_users($args);
531
  $selected = explode(",", $def['value']);
573
  $echo_str .= $dlp."\t\t".'</td></tr><tr>';
574
  }
575
  $postargs = array( 'post_type' => $def['listitems'], 'post_status' => "publish,private,draft", 'posts_per_page' => -1 );
576
+ /** This filter is documented in lib/wfu_admin.php */
577
  $postargs = apply_filters("_wfu_get_posts", $postargs, "visual_editor");
578
  $posts = get_posts($postargs);
579
  $list = wfu_construct_post_list($posts);
938
  echo $echo_str;
939
  }
940
 
941
+ /**
942
+ * Insert Variables in an Attribute.
943
+ *
944
+ * This function generates the HTML code of the variables that are shown below
945
+ * the attribute which they refer to.
946
+ *
947
+ * @since 2.1.3
948
+ *
949
+ * @param array $variables. The array of variables to display below the
950
+ * attribute.
951
+ * @param string $class A class name to set in the elements of the generated
952
+ * HTML code.
953
+ *
954
+ * @return string The HTML output of the variables.
955
+ */
956
  function wfu_insert_variables($variables, $class) {
957
  $ret = "";
958
  foreach ( $variables as $variable )
lib/wfu_admin_log.php CHANGED
@@ -1,5 +1,34 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_view_log($page = 1, $only_table_rows = false, $located_rec = -1) {
4
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5
  global $wpdb;
1
  <?php
2
 
3
+ /**
4
+ * View Log Page in Dashboard Area of Plugin
5
+ *
6
+ * This file contains functions related to View Log page of plugin's Dashboard
7
+ * area.
8
+ *
9
+ * @link /lib/wfu_admin_log.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 2.4.1
14
+ */
15
+
16
+ /**
17
+ * Display the View Log Page.
18
+ *
19
+ * This function displays the View Log page of the plugin's Dashboard area.
20
+ *
21
+ * @since 2.4.1
22
+ *
23
+ * @param integer $page Optional. The page to display in case log contents are
24
+ * paginated.
25
+ * @param bool $only_table_rows Optional. Return only the HTML code of the table
26
+ * rows.
27
+ * @param bool $located_rec Optional. The unique ID of a log record to focus and
28
+ * highlight.
29
+ *
30
+ * @return string The HTML output of the plugin's View Log Dashboard page.
31
+ */
32
  function wfu_view_log($page = 1, $only_table_rows = false, $located_rec = -1) {
33
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
34
  global $wpdb;
lib/wfu_admin_maintenance.php CHANGED
@@ -1,5 +1,31 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_maintenance_actions($message = '') {
4
  if ( !current_user_can( 'manage_options' ) ) return wfu_manage_mainmenu();
5
 
@@ -114,6 +140,19 @@ function wfu_maintenance_actions($message = '') {
114
  echo $echo_str;
115
  }
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  function wfu_sync_database_controller($nonce) {
118
  if ( !current_user_can( 'manage_options' ) ) return -1;
119
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return -1;
@@ -121,6 +160,18 @@ function wfu_sync_database_controller($nonce) {
121
  return wfu_sync_database();
122
  }
123
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  function wfu_clean_log_parse_data($data) {
125
  $ret = array( "result" => true );
126
  $data = sanitize_text_field($data);
@@ -169,6 +220,18 @@ function wfu_clean_log_parse_data($data) {
169
  return $ret;
170
  }
171
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  function wfu_clean_log_where_query($data) {
173
  $query = "";
174
  if ( $data["code"] == "0" ) $query = " WHERE date_from < '".date('Y-m-d H:i:s', $data["dateold"])."'";
@@ -181,6 +244,20 @@ function wfu_clean_log_where_query($data) {
181
  return $query;
182
  }
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  function wfu_clean_log_prompt($nonce, $data_enc) {
185
  global $wpdb;
186
  $table_name1 = $wpdb->prefix . "wfu_log";
@@ -254,6 +331,19 @@ function wfu_clean_log_prompt($nonce, $data_enc) {
254
  return $echo_str;
255
  }
256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  function wfu_clean_log() {
258
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
259
  global $wpdb;
@@ -306,6 +396,19 @@ function wfu_clean_log() {
306
  return array( "recs_count" => $recs_count, "files_count" => $files_count );
307
  }
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  function wfu_purge_data_prompt($nonce) {
310
  $siteurl = site_url();
311
 
@@ -333,6 +436,19 @@ function wfu_purge_data_prompt($nonce) {
333
  return $echo_str;
334
  }
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  function wfu_purge_data() {
337
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
338
  global $wpdb;
@@ -377,6 +493,19 @@ function wfu_purge_data() {
377
  }
378
 
379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  function wfu_process_all_transfers($clearfiles = false) {
381
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
382
  global $wpdb;
@@ -388,6 +517,19 @@ function wfu_process_all_transfers($clearfiles = false) {
388
  wfu_schedule_transfermanager(true);
389
  }
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  function wfu_reset_all_transfers_controller($nonce) {
392
  if ( !current_user_can( 'manage_options' ) ) return false;
393
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return false;
@@ -397,6 +539,19 @@ function wfu_reset_all_transfers_controller($nonce) {
397
  return true;
398
  }
399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  function wfu_clear_all_transfers_controller($nonce) {
401
  if ( !current_user_can( 'manage_options' ) ) return false;
402
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return false;
1
  <?php
2
 
3
+ /**
4
+ * Maintenance Actions Page in Dashboard Area of Plugin
5
+ *
6
+ * This file contains functions related to Maintenance Actions page of plugin's
7
+ * Dashboard area.
8
+ *
9
+ * @link /lib/wfu_admin_maintenance.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 3.7.1
14
+ */
15
+
16
+ /**
17
+ * Display the Maintenance Actions Page.
18
+ *
19
+ * This function displays the Maintenance Actions page of the plugin's Dashboard
20
+ * area.
21
+ *
22
+ * @since 3.3.1
23
+ *
24
+ * @param string $message Optional. A message to display on top of the page.
25
+ *
26
+ * @return string The HTML output of the plugin's Maintenance Actions Dashboard
27
+ * page.
28
+ */
29
  function wfu_maintenance_actions($message = '') {
30
  if ( !current_user_can( 'manage_options' ) ) return wfu_manage_mainmenu();
31
 
140
  echo $echo_str;
141
  }
142
 
143
+ /**
144
+ * Check and Execute Database Synchronization.
145
+ *
146
+ * This function performs security checks whether database synchronization can
147
+ * be executed and then executes this operation.
148
+ *
149
+ * @since 4.6.0
150
+ *
151
+ * @param string $nonce A string that verifies that the request came from
152
+ * Maintenance Actions page.
153
+ *
154
+ * @return int The number of records affected by synchronization.
155
+ */
156
  function wfu_sync_database_controller($nonce) {
157
  if ( !current_user_can( 'manage_options' ) ) return -1;
158
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return -1;
160
  return wfu_sync_database();
161
  }
162
 
163
+ /**
164
+ * Prepare Data for Log Cleaning.
165
+ *
166
+ * This function prepares data for executing log cleaning operation.
167
+ *
168
+ * @since 4.6.0
169
+ *
170
+ * @param string $data An encoded string containing information about what
171
+ * records to clean.
172
+ *
173
+ * @return array An array containing log cleaning data.
174
+ */
175
  function wfu_clean_log_parse_data($data) {
176
  $ret = array( "result" => true );
177
  $data = sanitize_text_field($data);
220
  return $ret;
221
  }
222
 
223
+ /**
224
+ * Prepare Query for Log Cleaning.
225
+ *
226
+ * This function prepares the SQL WHERE clause of the query for log cleaning.
227
+ *
228
+ * @since 4.9.1
229
+ *
230
+ * @param array $data An array containing log cleaning data.
231
+ *
232
+ * @return string An SQL WHERE clause that defines which database records will
233
+ * be affected by log cleaning operation.
234
+ */
235
  function wfu_clean_log_where_query($data) {
236
  $query = "";
237
  if ( $data["code"] == "0" ) $query = " WHERE date_from < '".date('Y-m-d H:i:s', $data["dateold"])."'";
244
  return $query;
245
  }
246
 
247
+ /**
248
+ * Confirm Log Cleaning Operation.
249
+ *
250
+ * This function shows a page to confirm log cleaning operation.
251
+ *
252
+ * @since 3.3.1
253
+ *
254
+ * @param string $nonce A string that verifies that the request came from
255
+ * Maintenance Actions page.
256
+ * @param string $data_enc An encoded string containing information about what
257
+ * records to clean.
258
+ *
259
+ * @return string The HTML code of the confirmation page.
260
+ */
261
  function wfu_clean_log_prompt($nonce, $data_enc) {
262
  global $wpdb;
263
  $table_name1 = $wpdb->prefix . "wfu_log";
331
  return $echo_str;
332
  }
333
 
334
+ /**
335
+ * Execute Log Cleaning.
336
+ *
337
+ * This function cleans the database log based on criteria selected by the
338
+ * admin.
339
+ *
340
+ * @since 3.3.1
341
+ *
342
+ * @redeclarable
343
+ *
344
+ * @return array An array containing the number of records and files affected by
345
+ * cleaning operation.
346
+ */
347
  function wfu_clean_log() {
348
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
349
  global $wpdb;
396
  return array( "recs_count" => $recs_count, "files_count" => $files_count );
397
  }
398
 
399
+ /**
400
+ * Confirm Purge of Data Operation.
401
+ *
402
+ * This function shows a page to confirm purge of data operation. Purge
403
+ * operation deletes all plugin data from the website.
404
+ *
405
+ * @since 4.9.1
406
+ *
407
+ * @param string $nonce A string that verifies that the request came from
408
+ * Maintenance Actions page.
409
+ *
410
+ * @return string The HTML code of the confirmation page.
411
+ */
412
  function wfu_purge_data_prompt($nonce) {
413
  $siteurl = site_url();
414
 
436
  return $echo_str;
437
  }
438
 
439
+ /**
440
+ * Purge Plugin Data.
441
+ *
442
+ * This function deletes all plugin data from the website. It drops the tables
443
+ * of the plugin from the database, it deletes all plugin options and all plugin
444
+ * data stored in session.
445
+ *
446
+ * @since 4.9.1
447
+ *
448
+ * @redeclarable
449
+ *
450
+ * @return bool Always true.
451
+ */
452
  function wfu_purge_data() {
453
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
454
  global $wpdb;
493
  }
494
 
495
 
496
+ /**
497
+ * Update File Transfers.
498
+ *
499
+ * This function causes the file transfers manager to re-check the pending file
500
+ * tranfers immediately.
501
+ *
502
+ * @since 4.6.0
503
+ *
504
+ * @redeclarable
505
+ *
506
+ * @param bool $clearfiles Optional. If it is true then all pending file
507
+ * transfers will be cleared.
508
+ */
509
  function wfu_process_all_transfers($clearfiles = false) {
510
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
511
  global $wpdb;
517
  wfu_schedule_transfermanager(true);
518
  }
519
 
520
+ /**
521
+ * Check and Execute Reset of File Transfers.
522
+ *
523
+ * This function performs security checks whether reset of file transfers can be
524
+ * executed and then executes this operation.
525
+ *
526
+ * @since 4.6.0
527
+ *
528
+ * @param string $nonce A string that verifies that the request came from
529
+ * Maintenance Actions page.
530
+ *
531
+ * @return bool Always true.
532
+ */
533
  function wfu_reset_all_transfers_controller($nonce) {
534
  if ( !current_user_can( 'manage_options' ) ) return false;
535
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return false;
539
  return true;
540
  }
541
 
542
+ /**
543
+ * Check and Execute Clear of File Transfers.
544
+ *
545
+ * This function performs security checks whether clear of file transfers can be
546
+ * executed and then executes this operation.
547
+ *
548
+ * @since 4.6.0
549
+ *
550
+ * @param string $nonce A string that verifies that the request came from
551
+ * Maintenance Actions page.
552
+ *
553
+ * @return bool Always true.
554
+ */
555
  function wfu_clear_all_transfers_controller($nonce) {
556
  if ( !current_user_can( 'manage_options' ) ) return false;
557
  if ( !wp_verify_nonce($nonce, 'wfu_maintenance_actions') ) return false;
lib/wfu_admin_settings.php CHANGED
@@ -1,5 +1,27 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_settings_definitions() {
4
  $settings = array(
5
  "version" => array("number", "1.0"),
@@ -9,7 +31,7 @@ function wfu_settings_definitions() {
9
  "personaldata" => array("number", ""),
10
  "postmethod" => array("number", ""),
11
  "modsecurity" => array("number", ""),
12
- "userstatehandler" => array("number", ""),
13
  "relaxcss" => array("number", ""),
14
  "admindomain" => array("number", ""),
15
  "mediacustom" => array("number", ""),
@@ -20,12 +42,32 @@ function wfu_settings_definitions() {
20
  "captcha_secretkey" => array("string", ""),
21
  "browser_permissions" => array("array", "")
22
  );
 
 
 
 
 
 
 
 
 
 
23
  $settings = apply_filters("_wfu_settings_definitions", $settings);
24
 
25
  return $settings;
26
  }
27
 
28
-
 
 
 
 
 
 
 
 
 
 
29
  function wfu_encode_plugin_options($plugin_options) {
30
  $settings = wfu_settings_definitions();
31
  $encoded_options = array();
@@ -41,6 +83,17 @@ function wfu_encode_plugin_options($plugin_options) {
41
  return implode(";", $encoded_options);
42
  }
43
 
 
 
 
 
 
 
 
 
 
 
 
44
  function wfu_decode_plugin_options($encoded_options) {
45
  $settings = wfu_settings_definitions();
46
  foreach ( $settings as $setting => $data )
@@ -61,6 +114,17 @@ function wfu_decode_plugin_options($encoded_options) {
61
  return $plugin_options;
62
  }
63
 
 
 
 
 
 
 
 
 
 
 
 
64
  function wfu_manage_settings($message = '') {
65
  if ( !current_user_can( 'manage_options' ) ) return;
66
 
@@ -132,10 +196,10 @@ function wfu_manage_settings($message = '') {
132
  $echo_str .= "\n\t\t\t\t\t\t".'</th>';
133
  $echo_str .= "\n\t\t\t\t\t\t".'<td>';
134
  $echo_str .= "\n\t\t\t\t\t\t\t".'<select name="wfu_userstatehandler" id="wfu_userstatehandler" value="'.$plugin_options['userstatehandler'].'">';
135
- $echo_str .= "\n\t\t\t\t\t\t\t\t".'<option value="session"'.( $plugin_options['userstatehandler'] == 'session' || $plugin_options['userstatehandler'] == '' ? ' selected="selected"' : '' ).'>Session (default)</option>';
136
- $echo_str .= "\n\t\t\t\t\t\t\t\t".'<option value="dboption"'.( $plugin_options['userstatehandler'] == 'dboption' ? ' selected="selected"' : '' ).'>DB Option</option>';
137
  $echo_str .= "\n\t\t\t\t\t\t\t".'</select>';
138
- $echo_str .= "\n\t\t\t\t\t\t\t".'<p style="cursor: text; font-size:9px; padding: 0px; margin: 0px; width: 95%; color: #AAAAAA;">Current value: <strong>'.( $plugin_options['userstatehandler'] == 'session' || $plugin_options['userstatehandler'] == '' ? 'Session' : ( $plugin_options['userstatehandler'] == 'dboption' ? 'DB Option' : 'Session' ) ).'</strong></p>';
139
  $echo_str .= "\n\t\t\t\t\t\t".'</td>';
140
  $echo_str .= "\n\t\t\t\t\t".'</tr>';
141
  $echo_str .= "\n\t\t\t\t\t".'<tr>';
@@ -200,6 +264,15 @@ function wfu_manage_settings($message = '') {
200
  }
201
 
202
 
 
 
 
 
 
 
 
 
 
203
  function wfu_update_settings() {
204
  if ( !current_user_can( 'manage_options' ) ) return;
205
  if ( !check_admin_referer('wfu_edit_admin_settings') ) return;
@@ -237,5 +310,22 @@ function wfu_update_settings() {
237
  return true;
238
  }
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
  ?>
1
  <?php
2
 
3
+ /**
4
+ * Settings Page in Dashboard Area of Plugin
5
+ *
6
+ * This file contains functions related to Settings page of plugin's Dashboard
7
+ * area.
8
+ *
9
+ * @link /lib/wfu_admin_settings.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 3.0.0
14
+ */
15
+
16
+ /**
17
+ * Initialize Plugin's Settings.
18
+ *
19
+ * This function initializes the plugin's settings.
20
+ *
21
+ * @since 4.1.0
22
+ *
23
+ * @return array Array containing plugin settings and their default values.
24
+ */
25
  function wfu_settings_definitions() {
26
  $settings = array(
27
  "version" => array("number", "1.0"),
31
  "personaldata" => array("number", ""),
32
  "postmethod" => array("number", ""),
33
  "modsecurity" => array("number", ""),
34
+ "userstatehandler" => array("number", "dboption"),
35
  "relaxcss" => array("number", ""),
36
  "admindomain" => array("number", ""),
37
  "mediacustom" => array("number", ""),
42
  "captcha_secretkey" => array("string", ""),
43
  "browser_permissions" => array("array", "")
44
  );
45
+ /**
46
+ * Customize settings definitions.
47
+ *
48
+ * This filter allows extensions to add their own settings.
49
+ *
50
+ * @since 4.1.0
51
+ *
52
+ * @param array $settings Array containing plugin settings and their
53
+ * default values.
54
+ */
55
  $settings = apply_filters("_wfu_settings_definitions", $settings);
56
 
57
  return $settings;
58
  }
59
 
60
+ /**
61
+ * Encode Plugin Settings.
62
+ *
63
+ * This function encodes the plugin settings array into a string.
64
+ *
65
+ * @since 2.1.3
66
+ *
67
+ * @param array $plugin_options The plugin settings.
68
+ *
69
+ * @return string The encoded plugin settings.
70
+ */
71
  function wfu_encode_plugin_options($plugin_options) {
72
  $settings = wfu_settings_definitions();
73
  $encoded_options = array();
83
  return implode(";", $encoded_options);
84
  }
85
 
86
+ /**
87
+ * Decode Plugin Settings.
88
+ *
89
+ * This function decodes the plugin settings string into an array.
90
+ *
91
+ * @since 2.1.3
92
+ *
93
+ * @param string $encoded_options The encoded plugin settings.
94
+ *
95
+ * @return array The decoded plugin settings.
96
+ */
97
  function wfu_decode_plugin_options($encoded_options) {
98
  $settings = wfu_settings_definitions();
99
  foreach ( $settings as $setting => $data )
114
  return $plugin_options;
115
  }
116
 
117
+ /**
118
+ * Display the Settings Page.
119
+ *
120
+ * This function displays the Settings page of the plugin's Dashboard area.
121
+ *
122
+ * @since 2.1.2
123
+ *
124
+ * @param string $message Optional. A message to display on top of the page.
125
+ *
126
+ * @return string The HTML output of the plugin's Settings Dashboard page.
127
+ */
128
  function wfu_manage_settings($message = '') {
129
  if ( !current_user_can( 'manage_options' ) ) return;
130
 
196
  $echo_str .= "\n\t\t\t\t\t\t".'</th>';
197
  $echo_str .= "\n\t\t\t\t\t\t".'<td>';
198
  $echo_str .= "\n\t\t\t\t\t\t\t".'<select name="wfu_userstatehandler" id="wfu_userstatehandler" value="'.$plugin_options['userstatehandler'].'">';
199
+ $echo_str .= "\n\t\t\t\t\t\t\t\t".'<option value="dboption"'.( $plugin_options['userstatehandler'] == 'dboption' ? ' selected="selected"' : '' ).'>Cookies/DB (default)</option>';
200
+ $echo_str .= "\n\t\t\t\t\t\t\t\t".'<option value="session"'.( $plugin_options['userstatehandler'] == 'session' || $plugin_options['userstatehandler'] == '' ? ' selected="selected"' : '' ).'>Session</option>';
201
  $echo_str .= "\n\t\t\t\t\t\t\t".'</select>';
202
+ $echo_str .= "\n\t\t\t\t\t\t\t".'<p style="cursor: text; font-size:9px; padding: 0px; margin: 0px; width: 95%; color: #AAAAAA;">Current value: <strong>'.( $plugin_options['userstatehandler'] == 'session' || $plugin_options['userstatehandler'] == '' ? 'Session' : ( $plugin_options['userstatehandler'] == 'dboption' ? 'Cookies/DB' : 'Session' ) ).'</strong></p>';
203
  $echo_str .= "\n\t\t\t\t\t\t".'</td>';
204
  $echo_str .= "\n\t\t\t\t\t".'</tr>';
205
  $echo_str .= "\n\t\t\t\t\t".'<tr>';
264
  }
265
 
266
 
267
+ /**
268
+ * Update Settings.
269
+ *
270
+ * This function updates plugin's settings.
271
+ *
272
+ * @since 2.1.2
273
+ *
274
+ * @return bool Always true.
275
+ */
276
  function wfu_update_settings() {
277
  if ( !current_user_can( 'manage_options' ) ) return;
278
  if ( !check_admin_referer('wfu_edit_admin_settings') ) return;
310
  return true;
311
  }
312
 
313
+ /**
314
+ * Update a Plugin Setting.
315
+ *
316
+ * This function updates an individual plugin setting.
317
+ *
318
+ * @since 4.12.0
319
+ *
320
+ * @param string $option The plugin option to change.
321
+ * @param mixed $value The new value of the option.
322
+ */
323
+ function wfu_update_setting($option, $value) {
324
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
325
+ $plugin_options[$option] = $value;
326
+ $encoded_options = wfu_encode_plugin_options($plugin_options);
327
+ update_option( "wordpress_file_upload_options", $encoded_options );
328
+ }
329
+
330
 
331
  ?>
lib/wfu_admin_uploadedfiles.php CHANGED
@@ -1,5 +1,26 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_uploadedfiles_menu() {
4
  $_GET = stripslashes_deep($_GET);
5
  $tag = (!empty($_GET['tag']) ? $_GET['tag'] : '1');
@@ -7,6 +28,20 @@ function wfu_uploadedfiles_menu() {
7
  echo wfu_uploadedfiles_manager($page);
8
  }
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
11
  global $wpdb;
12
  $table_name1 = $wpdb->prefix . "wfu_log";
@@ -175,7 +210,18 @@ function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
175
  $properties['media']['remarks'] = 'File is associated with Media item ID <strong>'.$filedata["media"]["attach_id"].'</strong>';
176
  }
177
  $properties['ftp']['visible'] = $file_in_ftp;
178
- //allow scripts to customize $properties
 
 
 
 
 
 
 
 
 
 
 
179
  $properties = apply_filters("_wfu_uploadefiles_file_properties", $properties, $filerec, $i);
180
 
181
  //update actions
@@ -215,7 +261,18 @@ function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
215
  $actions['download']['visible'] = true;
216
  $actions['download']['href'] = $download_href;
217
  }
218
- //allow scripts to customize $actions
 
 
 
 
 
 
 
 
 
 
 
219
  $actions = apply_filters("_wfu_uploadefiles_file_actions", $actions, $filerec, $i);
220
 
221
  //update default file link action
@@ -241,7 +298,18 @@ function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
241
  }
242
  $default_link = '<a href="'.$download_href.'" title="Download file">'.$file_relpath.'</a>';
243
  }
244
- //allow scripts to customize default file link action
 
 
 
 
 
 
 
 
 
 
 
245
  $default_link = apply_filters("_wfu_uploadefiles_file_link", $default_link, $filerec, $i);
246
 
247
  $displayed_data["file"] = $default_link;
@@ -269,11 +337,36 @@ function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
269
  $echo_str .= "\n".'</div>';
270
  }
271
 
272
- //allow scripts to customize HTML output before return
 
 
 
 
 
 
 
 
 
 
 
273
  $echo_str = apply_filters("_wfu_uploadedfiles_output", $echo_str, $page, $only_table_rows);
274
  return $echo_str;
275
  }
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  function wfu_uploadedfiles_get_filerecs($page) {
278
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
279
  global $wpdb;
@@ -316,6 +409,17 @@ function wfu_uploadedfiles_get_filerecs($page) {
316
  return $ret;
317
  }
318
 
 
 
 
 
 
 
 
 
 
 
 
319
  function wfu_init_uploadedfiles_properties() {
320
  $props["status"] = array(
321
  "icon" => "obsolete",
@@ -364,6 +468,17 @@ function wfu_init_uploadedfiles_properties() {
364
  return $props;
365
  }
366
 
 
 
 
 
 
 
 
 
 
 
 
367
  function wfu_init_uploadedfiles_actions() {
368
  $def_actions["details"] = array(
369
  "icon" => "dashicons-info",
@@ -426,6 +541,21 @@ function wfu_init_uploadedfiles_actions() {
426
  return $actions;
427
  }
428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  function wfu_render_uploadedfiles_properties($props, $index) {
430
  $a = func_get_args(); switch(WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out)) { case 'X': break; case 'R': return $out; break; case 'D': die($out); break; }
431
  $i = 0;
@@ -445,6 +575,20 @@ function wfu_render_uploadedfiles_properties($props, $index) {
445
  return $echo_str;
446
  }
447
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  function wfu_render_uploadedfiles_actions($actions) {
449
  $a = func_get_args(); switch(WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out)) { case 'X': break; case 'R': return $out; break; case 'D': die($out); break; }
450
  $i = 0;
@@ -461,6 +605,13 @@ function wfu_render_uploadedfiles_actions($actions) {
461
  return $echo_str;
462
  }
463
 
 
 
 
 
 
 
 
464
  function wfu_admin_toolbar_new_uploads() {
465
  global $wp_admin_bar;
466
 
@@ -485,6 +636,14 @@ function wfu_admin_toolbar_new_uploads() {
485
  }
486
  }
487
 
 
 
 
 
 
 
 
 
488
  function wfu_uploadedfiles_screen_options() {
489
  global $wfu_uploadedfiles_hook_suffix;
490
 
1
  <?php
2
 
3
+ /**
4
+ * Uploaded Files Page in Dashboard Area of Plugin
5
+ *
6
+ * This file contains functions related to Uploaded Files page of plugin's
7
+ * Dashboard area.
8
+ *
9
+ * @link /lib/wfu_admin_uploadedfiles.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 4.7.0
14
+ */
15
+
16
+ /**
17
+ * Process Dashboard Requests for Uploaded Files Page
18
+ *
19
+ * This function processes Dashboard requests and shows main Uploaded Files page
20
+ * of the plugin.
21
+ *
22
+ * @since 4.7.0
23
+ */
24
  function wfu_uploadedfiles_menu() {
25
  $_GET = stripslashes_deep($_GET);
26
  $tag = (!empty($_GET['tag']) ? $_GET['tag'] : '1');
28
  echo wfu_uploadedfiles_manager($page);
29
  }
30
 
31
+ /**
32
+ * Display the Uploaded Files Page.
33
+ *
34
+ * This function displays the Uploaded Files page of the plugin.
35
+ *
36
+ * @since 4.7.0
37
+ *
38
+ * @param integer $page Optional. The page to display in case contents are
39
+ * paginated.
40
+ * @param bool $only_table_rows Optional. Return only the HTML code of the table
41
+ * rows.
42
+ *
43
+ * @return string The HTML output of the plugin's Uploaded Files Dashboard page.
44
+ */
45
  function wfu_uploadedfiles_manager($page = 1, $only_table_rows = false) {
46
  global $wpdb;
47
  $table_name1 = $wpdb->prefix . "wfu_log";
210
  $properties['media']['remarks'] = 'File is associated with Media item ID <strong>'.$filedata["media"]["attach_id"].'</strong>';
211
  }
212
  $properties['ftp']['visible'] = $file_in_ftp;
213
+ /**
214
+ * Customize Uploaded File Properties.
215
+ *
216
+ * This filter allows scripts to customize the list of properties of an
217
+ * uploaded file.
218
+ *
219
+ * @since 4.8.0
220
+ *
221
+ * @param array $properties The list of properties of the file.
222
+ * @param object $filerec The database record of the uploaded file.
223
+ * @param integer $i The file's index in the list of uploaded files.
224
+ */
225
  $properties = apply_filters("_wfu_uploadefiles_file_properties", $properties, $filerec, $i);
226
 
227
  //update actions
261
  $actions['download']['visible'] = true;
262
  $actions['download']['href'] = $download_href;
263
  }
264
+ /**
265
+ * Customize Uploaded File Actions.
266
+ *
267
+ * This filter allows scripts to customize the list of actions of an
268
+ * uploaded file.
269
+ *
270
+ * @since 4.8.0
271
+ *
272
+ * @param array $actions The list of actions of the file.
273
+ * @param object $filerec The database record of the uploaded file.
274
+ * @param integer $i The file's index in the list of uploaded files.
275
+ */
276
  $actions = apply_filters("_wfu_uploadefiles_file_actions", $actions, $filerec, $i);
277
 
278
  //update default file link action
298
  }
299
  $default_link = '<a href="'.$download_href.'" title="Download file">'.$file_relpath.'</a>';
300
  }
301
+ /**
302
+ * Customize Default File Link.
303
+ *
304
+ * This filter allows scripts to customize the default file link action
305
+ * of an uploaded file.
306
+ *
307
+ * @since 4.8.0
308
+ *
309
+ * @param string $default_link The default file link action.
310
+ * @param object $filerec The database record of the uploaded file.
311
+ * @param integer $i The file's index in the list of uploaded files.
312
+ */
313
  $default_link = apply_filters("_wfu_uploadefiles_file_link", $default_link, $filerec, $i);
314
 
315
  $displayed_data["file"] = $default_link;
337
  $echo_str .= "\n".'</div>';
338
  }
339
 
340
+ /**
341
+ * Customize Uploaded Files Page Output.
342
+ *
343
+ * This filter allows scripts to customize the HTML code of Uploaded Files
344
+ * Dashboard page.
345
+ *
346
+ * @since 4.8.0
347
+ *
348
+ * @param string $echo_str The HTML code of Uploaded Files page.
349
+ * @param integer $page The current shown page of uploaded files list.
350
+ * @param bool $only_table_rows Return only HTML code of table rows.
351
+ */
352
  $echo_str = apply_filters("_wfu_uploadedfiles_output", $echo_str, $page, $only_table_rows);
353
  return $echo_str;
354
  }
355
 
356
+ /**
357
+ * Get List of Uploaded Files.
358
+ *
359
+ * This function returns the list of uploaded files to be displayed in Uploaded
360
+ * Files Dashboard page.
361
+ *
362
+ * @since 4.9.1
363
+ *
364
+ * @redeclarable
365
+ *
366
+ * @param integer $page The page number where the uploaded files belong.
367
+ *
368
+ * @return array An array holding the list of uploaded files.
369
+ */
370
  function wfu_uploadedfiles_get_filerecs($page) {
371
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
372
  global $wpdb;
409
  return $ret;
410
  }
411
 
412
+ /**
413
+ * Generate Default List of Properties of an Uploaded File.
414
+ *
415
+ * This function generates the list of default properties of an uploaded file.
416
+ * Each property has an icon, a title (when the mouse hovers over the icon) and
417
+ * remarks (shown in Remarks column when the mouse hovers over the icon).
418
+ *
419
+ * @since 4.7.0
420
+ *
421
+ * @return array An array of properties of an uploaded file.
422
+ */
423
  function wfu_init_uploadedfiles_properties() {
424
  $props["status"] = array(
425
  "icon" => "obsolete",
468
  return $props;
469
  }
470
 
471
+ /**
472
+ * Generate Default List of Actions of an Uploaded File.
473
+ *
474
+ * This function generates the list of default actions of an uploaded file. Each
475
+ * action has an icon, a title (when the mouse hovers over the icon) and a link
476
+ * URL (the action itself).
477
+ *
478
+ * @since 4.7.0
479
+ *
480
+ * @return array An array of properties of an uploaded file.
481
+ */
482
  function wfu_init_uploadedfiles_actions() {
483
  $def_actions["details"] = array(
484
  "icon" => "dashicons-info",
541
  return $actions;
542
  }
543
 
544
+ /**
545
+ * Display Properties of an Uploaded File.
546
+ *
547
+ * This function generates the HTML code of the properties of an uploaded file
548
+ * that will be shown in Properties column.
549
+ *
550
+ * @since 4.7.0
551
+ *
552
+ * @redeclarable
553
+ *
554
+ * @param array $props The properties of the uploaded file.
555
+ * @param integer $index The index of the uploaded file.
556
+ *
557
+ * @return string The HTML code of the properties of an uploaded file.
558
+ */
559
  function wfu_render_uploadedfiles_properties($props, $index) {
560
  $a = func_get_args(); switch(WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out)) { case 'X': break; case 'R': return $out; break; case 'D': die($out); break; }
561
  $i = 0;
575
  return $echo_str;
576
  }
577
 
578
+ /**
579
+ * Display Actions of an Uploaded File.
580
+ *
581
+ * This function generates the HTML code of the actions of an uploaded file that
582
+ * will be shown in Actions column.
583
+ *
584
+ * @since 4.7.0
585
+ *
586
+ * @redeclarable
587
+ *
588
+ * @param array $actions The actions of the uploaded file.
589
+ *
590
+ * @return string The HTML code of the actions of an uploaded file.
591
+ */
592
  function wfu_render_uploadedfiles_actions($actions) {
593
  $a = func_get_args(); switch(WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out)) { case 'X': break; case 'R': return $out; break; case 'D': die($out); break; }
594
  $i = 0;
605
  return $echo_str;
606
  }
607
 
608
+ /**
609
+ * Display Unread Uploaded File in Admin Bar.
610
+ *
611
+ * This function displays the number of unread uploaded files in Admin Bar.
612
+ *
613
+ * @since 4.8.0
614
+ */
615
  function wfu_admin_toolbar_new_uploads() {
616
  global $wp_admin_bar;
617
 
636
  }
637
  }
638
 
639
+ /**
640
+ * Display Files Per Page in Uploaded Files Screen Options.
641
+ *
642
+ * This function displays the number of uploaded files per page to display in
643
+ * the screen options section of Uploaded Files Dashboard page.
644
+ *
645
+ * @since 4.8.0
646
+ */
647
  function wfu_uploadedfiles_screen_options() {
648
  global $wfu_uploadedfiles_hook_suffix;
649
 
lib/wfu_ajaxactions.php CHANGED
@@ -1,803 +1,1314 @@
1
- <?php
2
-
3
- function wfu_ajax_action_send_email_notification() {
4
- $_POST = stripslashes_deep($_POST);
5
-
6
- $user = wp_get_current_user();
7
- if ( 0 == $user->ID ) $is_admin = false;
8
- else $is_admin = current_user_can('manage_options');
9
-
10
- $params_index = sanitize_text_field($_POST['params_index']);
11
- $session_token = sanitize_text_field($_POST['session_token']);
12
-
13
- $arr = wfu_get_params_fields_from_index($params_index, $session_token);
14
- //check referer using server sessions to avoid CSRF attacks
15
- $sid = $arr['shortcode_id'];
16
- if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
17
- if ( $user->user_login != $arr['user_login'] ) die();
18
-
19
- $params_str = get_option('wfu_params_'.$arr['unique_id']);
20
- $params = wfu_decode_array_from_string($params_str);
21
-
22
- //check whether email notifications are activated
23
- if ( $params["notify"] != "true" ) die();
24
-
25
- $uniqueid = ( isset($_POST['uniqueuploadid_'.$sid]) ? sanitize_text_field($_POST['uniqueuploadid_'.$sid]) : "" );
26
- //uniqueid cannot be empty and cannot be "no-ajax"
27
- if ( $uniqueid == "" || $uniqueid == "no-ajax" ) die();
28
-
29
- //retrieve the list of uploaded files from session
30
- $target_path_list = array();
31
- $all_files_count = 0;
32
- if ( WFU_USVAR_exists("filedata_".$uniqueid) && is_array(WFU_USVAR("filedata_".$uniqueid)) ) {
33
- $all_files_count = count(WFU_USVAR("filedata_".$uniqueid));
34
- foreach ( WFU_USVAR("filedata_".$uniqueid) as $file ) {
35
- if ( $file["upload_result"] == "success" || $file["upload_result"] == "warning" )
36
- array_push($target_path_list, $file["filepath"]);
37
- }
38
- }
39
- $uploaded_files_count = count($target_path_list);
40
- $nofileupload = ( $params["allownofile"] == "true" && $all_files_count == 0 );
41
- $force_notifications = ( WFU_VAR("WFU_FORCE_NOTIFICATIONS") == "true" );
42
-
43
- //in case no files have been uploaded and this is not a nofileupload
44
- //situation and Force Email Notifications option is not active then abort
45
- if ( $uploaded_files_count == 0 && !$nofileupload && !$force_notifications ) die();
46
-
47
- /* initialize return array */
48
- $params_output_array["version"] = "full";
49
- $params_output_array["general"]['shortcode_id'] = $params["uploadid"];
50
- $params_output_array["general"]['unique_id'] = $uniqueid;
51
- $params_output_array["general"]['state'] = 0;
52
- $params_output_array["general"]['files_count'] = 0;
53
- $params_output_array["general"]['update_wpfilebase'] = "";
54
- $params_output_array["general"]['redirect_link'] = "";
55
- $params_output_array["general"]['upload_finish_time'] = "";
56
- $params_output_array["general"]['message'] = "";
57
- $params_output_array["general"]['message_type'] = "";
58
- $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
59
- $params_output_array["general"]['admin_messages']['notify'] = "";
60
- $params_output_array["general"]['admin_messages']['redirect'] = "";
61
- $params_output_array["general"]['admin_messages']['other'] = "";
62
- $params_output_array["general"]['errors']['wpfilebase'] = "";
63
- $params_output_array["general"]['errors']['notify'] = "";
64
- $params_output_array["general"]['errors']['redirect'] = "";
65
- $params_output_array["general"]['color'] = "black";
66
- $params_output_array["general"]['bgcolor'] = "#F5F5F5";
67
- $params_output_array["general"]['borcolor'] = "#D3D3D3";
68
- $params_output_array["general"]['notify_by_email'] = 0;
69
- $params_output_array["general"]['fail_message'] = WFU_ERROR_UNKNOWN;
70
-
71
- //retrieve userdata, first get default userdata from $params
72
- $userdata_fields = $params["userdata_fields"];
73
- //remove any honeypot fields and initialize default values
74
- foreach ( $userdata_fields as $userdata_key => $userdata_field )
75
- if ( $userdata_field["type"] == "honeypot" ) unset($userdata_fields[$userdata_key]);
76
- else $userdata_fields[$userdata_key]["value"] = "";
77
- //then retrieve userdata from session if files exist
78
- if ( $all_files_count > 0 && WFU_USVAR_exists("filedata_".$uniqueid) && is_array(WFU_USVAR("filedata_".$uniqueid)) ) {
79
- foreach ( WFU_USVAR("filedata_".$uniqueid) as $file ) {
80
- if ( isset($file["user_data"]) ) {
81
- $userdata_fields = array();
82
- foreach ( $file["user_data"] as $userdata_key => $userdata_field )
83
- $userdata_fields[$userdata_key] = array( "label" => $userdata_field["label"], "value" => $userdata_field["value"] );
84
- break;
85
- }
86
- }
87
- }
88
- //in case there are no files in session (because allownofile attribute is
89
- //active and the user did not select any files for upload) then retrieve
90
- //userdata from the database based on uploadid
91
- else {
92
- $userdata_saved = wfu_get_userdata_from_uploadid($uniqueid);
93
- if ( $userdata_saved != null && is_array($userdata_saved) ) {
94
- $userdata_fields = array();
95
- foreach ( $userdata_saved as $userdata_saved_rec )
96
- $userdata_fields[$userdata_saved_rec->propkey] = array( "label" => $userdata_saved_rec->property, "value" => $userdata_saved_rec->propvalue );
97
- }
98
- }
99
-
100
- $send_error = wfu_send_notification_email($user, $target_path_list, $userdata_fields, $params);
101
-
102
- /* suppress any errors if user is not admin */
103
- if ( !$is_admin ) $send_error = "";
104
-
105
- if ( $send_error != "" ) {
106
- $params_output_array["general"]['admin_messages']['notify'] = $send_error;
107
- $params_output_array["general"]['errors']['notify'] = "error";
108
- }
109
-
110
- /* construct safe output */
111
- $sout = "0;".WFU_VAR("WFU_DEFAULTMESSAGECOLORS").";0";
112
-
113
- $echo_str = "wfu_fileupload_success::".$sout.":".wfu_encode_array_to_string($params_output_array);
114
- // allow an internal hook to process the final output
115
- $echo_str = apply_filters('_wfu_ajax_action_send_email_notification', $echo_str);
116
-
117
- die($echo_str);
118
- }
119
-
120
- function wfu_ajax_action_ask_server() {
121
- if ( !isset($_REQUEST['session_token']) || !isset($_REQUEST['sid']) || !isset($_REQUEST['unique_id']) ) die();
122
-
123
- $_REQUEST = stripslashes_deep($_REQUEST);
124
-
125
- $session_token = sanitize_text_field( $_REQUEST["session_token"] );
126
- $sid = sanitize_text_field( $_REQUEST["sid"] );
127
- $unique_id = wfu_sanitize_code($_REQUEST['unique_id']);
128
- if ( $session_token == "" ) die();
129
- //check referrer using Wordpress nonces and server sessions to avoid CSRF attacks
130
- check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
131
- if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
132
-
133
- //prepare parameters for before-upload filters
134
- $ret = array( "status" => "", "echo" => "" );
135
- //retrieve file names and sizes from request parameters
136
- $filenames_raw = ( isset($_REQUEST['filenames']) ? $_REQUEST['filenames'] : "" );
137
- $filenames = array();
138
- if ( trim($filenames_raw) != "" ) $filenames = explode(";", $filenames_raw);
139
- foreach ( $filenames as $ind => $filename ) $filenames[$ind] = esc_attr(wfu_plugin_decode_string(trim($filename)));
140
- $filesizes_raw = ( isset($_REQUEST['filesizes']) ? $_REQUEST['filesizes'] : "" );
141
- $filesizes = array();
142
- if ( trim($filesizes_raw) != "" ) $filesizes = explode(";", $filesizes_raw);
143
- foreach ( $filesizes as $ind => $filesize ) $filesizes[$ind] = wfu_sanitize_int($filesize);
144
- $files = array();
145
- foreach ( $filenames as $ind => $filename ) {
146
- $filesize = "";
147
- if ( isset($filesizes[$ind]) ) $filesize = $filesizes[$ind];
148
- array_push($files, array( "filename" => $filename, "filesize" => $filesize ));
149
- }
150
- $attr = array( "sid" => $sid, "unique_id" => $unique_id, "files" => $files );
151
- //execute before upload filters
152
- $echo_str = "";
153
- //first execute any custom filters created by admin
154
- if ( has_filter("wfu_before_upload") ) {
155
- $changable_data = array( "error_message" => "", "js_script" => "" );
156
- $changable_data = apply_filters("wfu_before_upload", $changable_data, $attr);
157
- if ( $changable_data["error_message"] == "" ) $ret["status"] = "success";
158
- else {
159
- $ret["status"] = "error";
160
- $echo_str .= "CBUV[".$changable_data["error_message"]."]";
161
- }
162
- if ( $changable_data["js_script"] != "" ) $echo_str .= "CBUVJS[".wfu_plugin_encode_string($changable_data["js_script"])."]";
163
- }
164
- //then execute internal filters of extensions
165
- $ret = apply_filters("_wfu_before_upload", $ret, $attr);
166
- $echo_str .= $ret["echo"];
167
- //in case that no filters were executed, because $ret["status"] is
168
- //empty, then this call to wfu_ajax_action_ask_server was erroneous
169
- if ( $ret["status"] == "" ) $ret["status"] = "die";
170
- //create an internal flag stored in session regarding the status of this
171
- //upload, that will be used to verify or not the upload
172
- if ( $ret["status"] == "success" ) WFU_USVAR_store("wfu_uploadstatus_".$attr["unique_id"], 1);
173
- else WFU_USVAR_store("wfu_uploadstatus_".$attr["unique_id"], 0);
174
-
175
- if ( $ret["status"] == "success" || $ret["status"] == "error" )
176
- echo "wfu_askserver_".$ret["status"].":".$echo_str;
177
-
178
- die();
179
- }
180
-
181
- function wfu_ajax_action_cancel_upload() {
182
- if ( !isset($_REQUEST['session_token']) || !isset($_REQUEST['sid']) || !isset($_REQUEST['unique_id']) ) die();
183
-
184
- $_REQUEST = stripslashes_deep($_REQUEST);
185
-
186
- $session_token = sanitize_text_field( $_REQUEST["session_token"] );
187
- $sid = sanitize_text_field( $_REQUEST["sid"] );
188
- $unique_id = wfu_sanitize_code($_REQUEST['unique_id']);
189
- if ( $session_token == "" ) die();
190
- //check referrer using Wordpress nonces and server sessions to avoid CSRF attacks
191
- check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
192
- if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
193
-
194
- //setting status to 0 denotes cancelling of the upload
195
- WFU_USVAR_store("wfu_uploadstatus_".$unique_id, 0);
196
-
197
- die("success");
198
- }
199
-
200
- function wfu_ajax_action_callback() {
201
- if ( !isset($_REQUEST['session_token']) ) die();
202
-
203
- $_REQUEST = stripslashes_deep($_REQUEST);
204
- $_POST = stripslashes_deep($_POST);
205
-
206
- $session_token = sanitize_text_field( $_REQUEST["session_token"] );
207
- if ( $session_token == "" ) die();
208
- check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
209
-
210
- if ( !isset($_REQUEST['params_index']) ) die();
211
-
212
- $params_index = sanitize_text_field( $_REQUEST["params_index"] );
213
-
214
- if ( $params_index == "" ) die();
215
-
216
- $user = wp_get_current_user();
217
- $arr = wfu_get_params_fields_from_index($params_index, $session_token);
218
- $sid = $arr['shortcode_id'];
219
- //check referrer using server sessions to avoid CSRF attacks
220
- if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) {
221
- $echo_str = "Session failed!<br/><br/>Session Data:<br/>";
222
- $echo_str .= print_r(wfu_sanitize(WFU_USALL()), true);
223
- $echo_str .= "<br/><br/>Post Data:<br/>";
224
- $echo_str .= print_r(wfu_sanitize($_POST), true);
225
- $echo_str .= 'force_errorabort_code';
226
- $echo_str = apply_filters('_wfu_upload_session_failed', $echo_str);
227
- die($echo_str);
228
- }
229
-
230
- if ( $user->user_login != $arr['user_login'] ) {
231
- $echo_str = "User failed!<br/><br/>User Data:<br/>";
232
- $echo_str .= print_r(wfu_sanitize($user), true);
233
- $echo_str .= "<br/><br/>Post Data:<br/>";
234
- $echo_str .= print_r(wfu_sanitize($_POST), true);
235
- $echo_str .= "<br/><br/>Params Data:<br/>";
236
- $echo_str .= print_r(wfu_sanitize($arr), true);
237
- $echo_str .= 'force_errorabort_code';
238
- $echo_str = apply_filters('_wfu_upload_user_failed', $echo_str);
239
- die($echo_str);
240
- }
241
-
242
- //if force_connection_close is set, then the first pass to this callback script is for closing the previous connection
243
- if ( isset($_POST["force_connection_close"]) && $_POST["force_connection_close"] === "1" ) {
244
- header("Connection: Close");
245
- die(apply_filters('_wfu_upload_force_connection_close', 'success'));
246
- }
247
-
248
- //get the unique id of the upload
249
- $unique_id = ( isset($_POST['uniqueuploadid_'.$sid]) ? sanitize_text_field($_POST['uniqueuploadid_'.$sid]) : "" );
250
- if ( strlen($unique_id) != 10 ) die(apply_filters('_wfu_upload_uniqueid_failed', 'force_errorabort_code'));
251
-
252
- //if before upload actions have been executed and they have rejected the
253
- //upload, but for some reason (hack attempt) the upload continued, then
254
- //terminate it
255
- if ( WFU_USVAR_exists("wfu_uploadstatus_".$unique_id) && WFU_USVAR("wfu_uploadstatus_".$unique_id) == 0 ) die('force_errorabort_code');
256
-
257
- //get stored shortcode parameters
258
- $params_str = get_option('wfu_params_'.$arr['unique_id']);
259
- $params = wfu_decode_array_from_string($params_str);
260
-
261
- //if upload has finished then perform post upload actions
262
- if ( isset($_POST["upload_finished"]) && $_POST["upload_finished"] === "1" ) {
263
- $echo_str = "";
264
- //execute after upload filters
265
- $ret = wfu_execute_after_upload_filters($sid, $unique_id, $params);
266
- if ( $ret["js_script"] != "" ) $echo_str = "CBUVJS[".wfu_plugin_encode_string($ret["js_script"])."]";
267
- die($echo_str);
268
- }
269
-
270
- //check if honeypot userdata fields have been added to the form and if they
271
- //contain any data; if wfu_check_remove_honeypot_fields returns true this
272
- //means that at least one honeypot field has beed filled with a value and
273
- //the upload must be aborted because it was not done by a human
274
- if ( $params["userdata"] == "true" && wfu_check_remove_honeypot_fields($params["userdata_fields"], 'hiddeninput_'.$sid.'_userdata_') ) die("force_abortsuccess_code");
275
-
276
- //apply filters to determine if the upload will continue or stop
277
- $ret = array( "status" => "", "echo" => "" );
278
- $attr = array( "sid" => $sid, "unique_id" => $unique_id, "params" => $params );
279
- $ret = apply_filters("_wfu_pre_upload_check", $ret, $attr);
280
- if ( $ret["status"] == "die" ) die($ret["echo"]);
281
-
282
- //if this is the first pass of an upload attempt then perform pre-upload actions
283
- if ( !WFU_USVAR_exists('wfu_upload_first_pass_'.$unique_id) || WFU_USVAR('wfu_upload_first_pass_'.$unique_id) != 'true' ) {
284
- WFU_USVAR_store('wfu_upload_first_pass_'.$unique_id, 'true');
285
- }
286
-
287
- if ( !isset($_POST["subdir_sel_index"]) ) die();
288
- $subdir_sel_index = sanitize_text_field( $_POST["subdir_sel_index"] );
289
- $params['subdir_selection_index'] = $subdir_sel_index;
290
- WFU_USVAR_store('wfu_check_refresh_'.$params["uploadid"], 'do not process');
291
-
292
- //update consent status of user
293
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
294
- $params["consent_result"] = wfu_check_user_consent($user);
295
- $require_consent = ( $plugin_options["personaldata"] == "1" && ( $params["notrememberconsent"] == "true" || $params["consent_result"] == "" ) && $params["askconsent"] == "true" );
296
- if ( $require_consent ) {
297
- if ( !isset($_POST['consent_result']) ) die();
298
- $consent_result = ( $_POST['consent_result'] == "yes" ? "yes" : ( $_POST['consent_result'] == "no" ? "no" : "" ) );
299
- $params["consent_result"] = ( $_POST['consent_result'] == "yes" ? "1" : ( $_POST['consent_result'] == "no" ? "0" : "" ) );
300
- wfu_update_user_consent($user, $consent_result);
301
- }
302
-
303
- $wfu_process_file_array = wfu_process_files($params, 'ajax');
304
- // extract safe_output from wfu_process_file_array and pass it as separate part of the response text
305
- $safe_output = $wfu_process_file_array["general"]['safe_output'];
306
- unset($wfu_process_file_array["general"]['safe_output']);
307
- // get javascript code that has been defined in wfu_after_file_upload action
308
- $js_script = wfu_plugin_encode_string($wfu_process_file_array["general"]['js_script']);
309
- unset($wfu_process_file_array["general"]['js_script']);
310
-
311
- $echo_str = "wfu_fileupload_success:".$js_script.":".$safe_output.":".wfu_encode_array_to_string($wfu_process_file_array);
312
- $echo_str = apply_filters('_wfu_upload_callback_success', $echo_str);
313
- die($echo_str);
314
- }
315
-
316
- function wfu_ajax_action_save_shortcode() {
317
- $is_admin = current_user_can( 'manage_options' );
318
- $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
319
- if ( !$is_admin && !$can_open_composer ) die();
320
- if ( !isset($_POST['shortcode']) || !isset($_POST['shortcode_original']) || !isset($_POST['post_id']) || !isset($_POST['post_hash']) || !isset($_POST['shortcode_position']) || !isset($_POST['shortcode_tag']) || !isset($_POST['widget_id']) ) die();
321
-
322
- $_POST = stripslashes_deep($_POST);
323
-
324
- //sanitize parameters
325
- $shortcode = wfu_sanitize_code($_POST['shortcode']);
326
- $shortcode_original = wfu_sanitize_code($_POST['shortcode_original']);
327
- $post_id = wfu_sanitize_int($_POST['post_id']);
328
- $post_hash = wfu_sanitize_code($_POST['post_hash']);
329
- $shortcode_position = wfu_sanitize_int($_POST['shortcode_position']);
330
- $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
331
- $widget_id = sanitize_text_field($_POST['widget_id']);
332
-
333
- $shortcode = wfu_sanitize_shortcode(wfu_plugin_decode_string($shortcode), $shortcode_tag);
334
-
335
- if ( $post_id == "" && $widget_id == "" ) {
336
- die();
337
- }
338
- else {
339
- $data['post_id'] = $post_id;
340
- $data['post_hash'] = $post_hash;
341
- $data['shortcode'] = wfu_plugin_decode_string($shortcode_original);
342
- $data['position'] = $shortcode_position;
343
- if ( $post_id != "" && !wfu_check_edit_shortcode($data) ) $echo_str = "wfu_save_shortcode:fail:post_modified";
344
- else {
345
- if ( $widget_id == "" ) {
346
- $new_shortcode = "[".$shortcode_tag." ".$shortcode."]";
347
- if ( wfu_replace_shortcode($data, $new_shortcode) ) {
348
- $post = get_post($post_id);
349
- $hash = hash('md5', $post->post_content);
350
- $echo_str = "wfu_save_shortcode:success:".$hash;
351
- }
352
- else $echo_str = "wfu_save_shortcode:fail:post_update_failed";
353
- }
354
- else {
355
- $widget_obj = wfu_get_widget_obj_from_id($widget_id);
356
- if ( $widget_obj === false ) $echo_str = "wfu_save_shortcode:fail:post_update_failed";
357
- else {
358
- $widget_sidebar = is_active_widget(false, $widget_id, "wordpress_file_upload_widget");
359
- if ( !$widget_sidebar ) $echo_str = "wfu_save_shortcode:fail:post_update_failed";
360
- else {
361
- $widget_obj->update_external($shortcode);
362
- $hash = $data['post_hash'];
363
- $echo_str = "wfu_save_shortcode:success:".$hash;
364
- }
365
- }
366
- }
367
- }
368
- }
369
-
370
- $echo_str = apply_filters('_wfu_ajax_action_save_shortcode', $echo_str);
371
- die($echo_str);
372
- }
373
-
374
- function wfu_ajax_action_check_page_contents() {
375
- if ( !current_user_can( 'manage_options' ) ) die();
376
- if ( !isset($_POST['post_id']) || !isset($_POST['post_hash']) ) die();
377
- if ( $_POST['post_id'] == "" ) die();
378
-
379
- $_POST = stripslashes_deep($_POST);
380
-
381
- $data['post_id'] = wfu_sanitize_int($_POST['post_id']);
382
- $data['post_hash'] = wfu_sanitize_code($_POST['post_hash']);
383
- if ( wfu_check_edit_shortcode($data) ) $echo_str = "wfu_check_page_contents:current:";
384
- else $echo_str = "wfu_check_page_contents:obsolete:";
385
-
386
- $echo_str = apply_filters('_wfu_ajax_action_check_page_contents', $echo_str);
387
- die($echo_str);
388
- }
389
-
390
- function wfu_ajax_action_edit_shortcode() {
391
- global $wp_registered_widgets;
392
- global $wp_registered_sidebars;
393
-
394
- $is_admin = current_user_can( 'manage_options' );
395
- $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
396
- if ( !$is_admin && !$can_open_composer ) die();
397
- if ( !isset($_POST['upload_id']) || !isset($_POST['post_id']) || !isset($_POST['post_hash']) || !isset($_POST['shortcode_tag']) || !isset($_POST['widget_id']) ) die();
398
-
399
- $_POST = stripslashes_deep($_POST);
400
-
401
- //sanitize parameters
402
- $upload_id = sanitize_text_field($_POST['upload_id']);
403
- $widget_id = sanitize_text_field($_POST['widget_id']);
404
- $post_id = wfu_sanitize_int($_POST['post_id']);
405
- $post_hash = wfu_sanitize_code($_POST['post_hash']);
406
- $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
407
-
408
- $keyname = "uploadid";
409
- if ( $shortcode_tag == "wordpress_file_upload_browser" ) $keyname = "browserid";
410
-
411
- $data['post_id'] = $post_id;
412
- $data['post_hash'] = $post_hash;
413
- if ( wfu_check_edit_shortcode($data) ) {
414
- if ( $widget_id == "" ) {
415
- $post = get_post($data['post_id']);
416
- //get default value for uploadid
417
- if ( $shortcode_tag == "wordpress_file_upload_browser" ) $defs = wfu_browser_attribute_definitions();
418
- else $defs = wfu_attribute_definitions();
419
- $default = "";
420
- foreach ( $defs as $key => $def ) {
421
- if ( $def['attribute'] == $keyname ) {
422
- $default = $def['value'];
423
- break;
424
- }
425
- }
426
- //get page shortcodes
427
- $wfu_shortcodes = wfu_get_content_shortcodes($post, $shortcode_tag);
428
- //find the shortcodes' uploadid and the correct one
429
- $validkey = -1;
430
- foreach ( $wfu_shortcodes as $key => $data ) {
431
- $shortcode = trim(substr($data['shortcode'], strlen('['.$shortcode_tag), -1));
432
- $shortcode_attrs = wfu_shortcode_string_to_array($shortcode);
433
- if ( array_key_exists($keyname, $shortcode_attrs) ) $uploadid = $shortcode_attrs[$keyname];
434
- else $uploadid = $default;
435
- if ( $uploadid == $upload_id ) {
436
- $validkey = $key;
437
- break;
438
- }
439
- }
440
- if ( $validkey == -1 ) die();
441
- $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($wfu_shortcodes[$validkey]));
442
- }
443
- else {
444
- $widget_obj = wfu_get_widget_obj_from_id($widget_id);
445
- if ( $widget_obj === false ) die();
446
- $widget_sidebar = is_active_widget(false, $widget_id, "wordpress_file_upload_widget");
447
- if ( !$widget_sidebar ) die();
448
- if ( isset($wp_registered_sidebars[$widget_sidebar]) && isset($wp_registered_sidebars[$widget_sidebar]['name']) ) $widget_sidebar = $wp_registered_sidebars[$widget_sidebar]['name'];
449
- $data['shortcode'] = $widget_obj->shortcode();
450
- $data['position'] = 0;
451
- $data['widgetid'] = $widget_id;
452
- $data['sidebar'] = $widget_sidebar;
453
- $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($data));
454
- }
455
- if( $is_admin ) $url = site_url().'/wp-admin/options-general.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc;
456
- //conditional that will open the shortcode composer for non-admin users
457
- //who can edit posts or pages
458
- else $url = site_url().'/wp-admin/admin.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc;
459
- $echo_str = "wfu_edit_shortcode:success:".wfu_plugin_encode_string($url);
460
- }
461
- else $echo_str = "wfu_edit_shortcode:check_page_obsolete:".WFU_ERROR_PAGE_OBSOLETE;
462
-
463
- $echo_str = apply_filters('_wfu_ajax_action_edit_shortcode', $echo_str);
464
- die($echo_str);
465
- }
466
-
467
- function wfu_ajax_action_gutedit_shortcode() {
468
- $is_admin = current_user_can( 'manage_options' );
469
- $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
470
- if ( !$is_admin && !$can_open_composer ) die();
471
- if ( !isset($_POST['shortcode']) || !isset($_POST['post_id']) || !isset($_POST['shortcode_tag']) ) die();
472
-
473
- $_POST = stripslashes_deep($_POST);
474
-
475
- //sanitize parameters
476
- $shortcode = wfu_sanitize_code($_POST['shortcode']);
477
- $post_id = wfu_sanitize_int($_POST['post_id']);
478
- $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
479
-
480
- $shortcode = wfu_sanitize_shortcode(wfu_plugin_decode_string($shortcode), $shortcode_tag);
481
-
482
- if ( $post_id == "" ) die();
483
-
484
- $data['shortcode'] = '['.$shortcode_tag.' '.$shortcode.']';
485
- $data['post_id'] = $post_id;
486
- $data['post_hash'] = '';
487
- $data['position'] = 0;
488
- $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($data));
489
- if ( $is_admin ) $url = site_url().'/wp-admin/options-general.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc.'&referer=guteditor';
490
- //conditional that will open the shortcode composer for non-admin users who
491
- //can edit posts or pages
492
- else $url = site_url().'/wp-admin/admin.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc.'&referer=guteditor';
493
-
494
- $echo_str = "wfu_gutedit_shortcode:success:".wfu_plugin_encode_string($url);
495
- $echo_str = apply_filters('_wfu_ajax_action_gutedit_shortcode', $echo_str);
496
- die($echo_str);
497
- }
498
-
499
- function wfu_ajax_action_read_subfolders() {
500
- if ( !isset($_POST['folder1']) || !isset($_POST['folder2']) ) die();
501
-
502
- $_POST = stripslashes_deep($_POST);
503
-
504
- $folder1 = wfu_sanitize_code($_POST['folder1']);
505
- $folder1 = wfu_sanitize_url(wfu_plugin_decode_string($folder1));
506
- $folder2 = wfu_sanitize_code($_POST['folder2']);
507
- $folder2 = wfu_sanitize_url(wfu_plugin_decode_string($folder2));
508
- if ( wfu_plugin_encode_string($folder1) != $_POST['folder1'] || wfu_plugin_encode_string($folder2) != $_POST['folder2'] ) die();
509
-
510
- $temp_params = array( 'uploadpath' => $folder1, 'accessmethod' => 'normal', 'ftpinfo' => '', 'useftpdomain' => 'false' );
511
- $path = wfu_upload_plugin_full_path($temp_params);
512
-
513
- if ( !is_dir($path) ) die(apply_filters('_wfu_ajax_action_read_subfolders', 'wfu_read_subfolders:error:Parent folder is not valid! Cannot retrieve subfolder list.'));
514
-
515
- $path2 = $folder2;
516
- $dirlist = "";
517
- if ( $handle = opendir($path) ) {
518
- $blacklist = array('.', '..');
519
- while ( false !== ($file = readdir($handle)) )
520
- if ( !in_array($file, $blacklist) ) {
521
- $filepath = $path.$file;
522
- if ( is_dir($filepath) ) {
523
- if ( $file == $path2 ) $file = '[['.$file.']]';
524
- $dirlist .= ( $dirlist == "" ? "" : "," ).$file;
525
- }
526
- }
527
- closedir($handle);
528
- }
529
- if ( $path2 != "" ) {
530
- $dirlist2 = $path2;
531
- $path .= $path2."/";
532
- if ( is_dir($path) ) {
533
- if ( $handle = opendir($path) ) {
534
- $blacklist = array('.', '..');
535
- while ( false !== ($file = readdir($handle)) )
536
- if ( !in_array($file, $blacklist) ) {
537
- $filepath = $path.$file;
538
- if ( is_dir($filepath) )
539
- $dirlist2 .= ",*".$file;
540
- }
541
- closedir($handle);
542
- }
543
- }
544
- $dirlist = str_replace('[['.$path2.']]', $dirlist2, $dirlist);
545
- }
546
-
547
- die(apply_filters('_wfu_ajax_action_read_subfolders', "wfu_read_subfolders:success:".wfu_plugin_encode_string($dirlist)));
548
- }
549
-
550
- function wfu_ajax_action_download_file_invoker() {
551
- global $wfu_user_state_handler;
552
-
553
- $_POST = stripslashes_deep($_POST);
554
- $_GET = stripslashes_deep($_GET);
555
-
556
- $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
557
- $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
558
- if ( $file_code == '' || $nonce == '' ) die();
559
-
560
- //security check to avoid CSRF attacks
561
- if ( !wp_verify_nonce($nonce, 'wfu_download_file_invoker') ) die();
562
-
563
- //check if user is allowed to download files
564
- if ( !current_user_can( 'manage_options' ) ) {
565
- die();
566
- }
567
-
568
- $file_code = sanitize_text_field($file_code);
569
- //if file_code is exportdata, then export of data has been requested and
570
- //we need to create a file with export data and recreate file_code
571
- if ( substr($file_code, 0, 10) == "exportdata" && current_user_can( 'manage_options' ) ) {
572
- $params = null;
573
- $params_str = substr($file_code, 11);
574
- if ( trim($params_str) != "" ) $params = json_decode($params_str, true);
575
- $filepath = wfu_export_uploaded_files($params);
576
- if ( $filepath === false ) die();
577
- $file_code = "exportdata".wfu_safe_store_filepath($filepath);
578
- //store filepath in session otherwise it can not be retrieved by
579
- //downloader script
580
- WFU_USVAR_store_session('wfu_storage_'.substr($file_code, 10), $filepath);
581
- }
582
- //else get the file path from the safe
583
- else {
584
- $filepath = wfu_get_filepath_from_safe($file_code);
585
- if ( $filepath === false ) die();
586
- $filepath = wfu_path_rel2abs(wfu_flatten_path($filepath));
587
- //reject download of blacklisted file types for security reasons
588
- if ( wfu_file_extension_blacklisted($filepath) ) {
589
- die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:not_allowed:'.( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_NOTALLOWED : 'You are not allowed to download this file!' )));
590
- }
591
- //for front-end browser apply wfu_browser_check_file_action filter to allow or restrict the download
592
- if ( isset($_POST['browser']) ) {
593
- $changable_data["error_message"] = "";
594
- $filerec = wfu_get_file_rec($filepath, true);
595
- $userdata = array();
596
- foreach ( $filerec->userdata as $data )
597
- array_push($userdata, array( "label" => $data->property, "value" => $data->propvalue ));
598
- $additional_data = array(
599
- "file_action" => "download",
600
- "filepath" => $filepath,
601
- "uploaduser" => $filerec->uploaduserid,
602
- "userdata" => $userdata
603
- );
604
- $changable_data = apply_filters("wfu_browser_check_file_action", $changable_data, $additional_data);
605
- if ( $changable_data["error_message"] != "" )
606
- die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:not_allowed:'.$changable_data["error_message"]));
607
- }
608
- //for back-end browser check if user is allowed to perform this action on this file
609
- if ( !wfu_current_user_owes_file($filepath) ) die();
610
- //store filepath in session otherwise it can not be retrieved by
611
- //downloader script
612
- WFU_USVAR_store_session('wfu_storage_'.$file_code, wfu_get_filepath_from_safe($file_code));
613
- }
614
-
615
- //generate download unique id to monitor this download
616
- $download_id = wfu_create_random_string(16);
617
- //store download status of this download in session, so that it can be
618
- //retrieved by downloader script
619
- WFU_USVAR_store_session('wfu_download_status_'.$download_id, 'starting');
620
- //generate download ticket which expires in 30sec and store it in session
621
- //it will be used as security measure for the downloader script, which runs outside Wordpress environment
622
- WFU_USVAR_store_session('wfu_download_ticket_'.$download_id, time() + 30);
623
- //generate download monitor ticket which expires in 30sec and store it in session
624
- //it will be used as security measure for the monitor script that will check download status
625
- WFU_USVAR_store_session('wfu_download_monitor_ticket_'.$download_id, time() + 30);
626
-
627
- //store translatable strings to session so that they can be used by a script
628
- //that runs outside Wordpress environment
629
- WFU_USVAR_store_session('wfu_browser_downloadfile_notexist', ( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_NOTEXIST : 'File does not exist!' ));
630
- WFU_USVAR_store_session('wfu_browser_downloadfile_failed', ( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_FAILED : 'Could not download file!' ));
631
-
632
- //this routine returns a dynamically created iframe element, that will call the actual download script;
633
- //the actual download script runs outside Wordpress environment in order to ensure that no php warnings
634
- //or echo from other plugins is generated, that could scramble the downloaded file;
635
- //a ticket, similar to nonces, is passed to the download script to check that it is not a CSRF attack; moreover,the ticket is destroyed
636
- //by the time it is consumed by the download script, so it cannot be used again
637
- $response = '<iframe src="'.WFU_DOWNLOADER_URL.'?file='.$file_code.'&ticket='.$download_id.'" style="display: none;"></iframe>';
638
-
639
- die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:wfu_download_id;'.$download_id.':'.$response));
640
- }
641
-
642
- function wfu_ajax_action_download_file_monitor() {
643
- $_POST = stripslashes_deep($_POST);
644
- $_GET = stripslashes_deep($_GET);
645
-
646
- $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
647
- $id = (isset($_POST['id']) ? $_POST['id'] : (isset($_GET['id']) ? $_GET['id'] : ''));
648
- if ( $file_code == '' || $id == '' ) die();
649
- $id = wfu_sanitize_code($id);
650
-
651
- //ensure that this is not a CSRF attack by checking validity of a security ticket
652
- if ( !WFU_USVAR_exists_session('wfu_download_monitor_ticket_'.$id) || time() > WFU_USVAR_session('wfu_download_monitor_ticket_'.$id) ) die();
653
- //destroy monitor ticket so it cannot be used again
654
- WFU_USVAR_unset_session('wfu_download_monitor_ticket_'.$id);
655
-
656
- //initiate loop of 30secs to check the download status of the file;
657
- //the download status is controlled by the actual download script;
658
- //if the file finishes within the 30secs of the loop, then this routine logs the action and notifies
659
- //the client side about the download status of the file, otherwise an instruction
660
- //to the client side to repeat this routine and wait for another 30secs is dispatched
661
- $end_time = time() + 30;
662
- $upload_ended = false;
663
- while ( time() < $end_time ) {
664
- $upload_ended = ( WFU_USVAR_exists_session('wfu_download_status_'.$id) ? ( WFU_USVAR_session('wfu_download_status_'.$id) == 'downloaded' || WFU_USVAR_session('wfu_download_status_'.$id) == 'failed' ? true : false ) : false );
665
- if ( $upload_ended ) break;
666
- usleep(100);
667
- }
668
-
669
- if ( $upload_ended ) {
670
- $user = wp_get_current_user();
671
- // $filepath = wfu_plugin_decode_string($file_code);
672
- $filepath = wfu_get_filepath_from_safe($file_code);
673
- if ( $filepath === false ) die();
674
- $filepath = wfu_path_rel2abs(wfu_flatten_path($filepath));
675
- wfu_log_action('download', $filepath, $user->ID, '', 0, 0, '', null);
676
- die(apply_filters('_wfu_ajax_action_download_file_monitor', 'wfu_ajax_action_download_file_monitor:'.WFU_USVAR_session('wfu_download_status_'.$id).':'));
677
- }
678
- else {
679
- //regenerate monitor ticket
680
- WFU_USVAR_store_session('wfu_download_monitor_ticket_'.$id, time() + 30);
681
- die(apply_filters('_wfu_ajax_action_download_file_monitor', 'wfu_ajax_action_download_file_monitor:repeat:'.$id));
682
- }
683
- }
684
-
685
- function wfu_ajax_action_get_historylog_page() {
686
- if ( !isset($_POST['token']) || !isset($_POST['page']) ) die();
687
- check_ajax_referer( 'wfu-historylog-page', 'token' );
688
- if ( !current_user_can( 'manage_options' ) ) die();
689
- if ( WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") <= 0 ) die();
690
-
691
- $_POST = stripslashes_deep($_POST);
692
-
693
- $page = wfu_sanitize_int($_POST['page']);
694
- $rows = wfu_view_log($page, true);
695
-
696
- die(apply_filters('_wfu_ajax_action_get_historylog_page', 'wfu_historylog_page_success:'.wfu_plugin_encode_string($rows)));
697
- }
698
-
699
- function wfu_ajax_action_get_uploadedfiles_page() {
700
- if ( !isset($_POST['token']) || !isset($_POST['page']) ) die();
701
- check_ajax_referer( 'wfu-uploadedfiles-page', 'token' );
702
- if ( !current_user_can( 'manage_options' ) ) die();
703
- if ( WFU_VAR("WFU_UPLOADEDFILES_TABLE_MAXROWS") <= 0 ) die();
704
-
705
- $_POST = stripslashes_deep($_POST);
706
-
707
- $page = wfu_sanitize_int($_POST['page']);
708
- $rows = wfu_uploadedfiles_manager($page, true);
709
-
710
- die(apply_filters('_wfu_ajax_action_get_uploadedfiles_page', 'wfu_uploadedfiles_page_success:'.wfu_plugin_encode_string($rows)));
711
- }
712
-
713
- function wfu_ajax_action_get_adminbrowser_page() {
714
- if ( !isset($_POST['code']) || !isset($_POST['token']) || !isset($_POST['page']) ) die();
715
-
716
- $_POST = stripslashes_deep($_POST);
717
-
718
- check_ajax_referer( 'wfu-adminbrowser-page', 'token' );
719
- if ( !current_user_can( 'manage_options' ) ) die();
720
- if ( WFU_VAR("WFU_ADMINBROWSER_TABLE_MAXROWS") <= 0 ) die();
721
-
722
- $code = wfu_sanitize_code($_POST['code']);
723
- $page = wfu_sanitize_int($_POST['page']);
724
- //get list of files
725
- $rows = wfu_browse_files($code, $page, true);
726
-
727
- die(apply_filters('_wfu_ajax_action_get_adminbrowser_page', 'wfu_adminbrowser_page_success:'.wfu_plugin_encode_string($rows)));
728
- }
729
-
730
- function wfu_ajax_action_include_file() {
731
- $_POST = stripslashes_deep($_POST);
732
- $_GET = stripslashes_deep($_GET);
733
-
734
- $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
735
- $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
736
- if ( $file_code == '' || $nonce == '' ) die();
737
-
738
- if ( !current_user_can( 'manage_options' ) ) die();
739
- //security check to avoid CSRF attacks
740
- if ( !wp_verify_nonce($nonce, 'wfu_include_file') ) die();
741
-
742
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
743
- if ( $plugin_options['includeotherfiles'] != "1" ) die();
744
-
745
- $dec_file = wfu_get_filepath_from_safe($file_code);
746
- if ( $dec_file === false ) die();
747
-
748
- $user = wp_get_current_user();
749
- $dec_file = wfu_path_rel2abs(wfu_flatten_path($dec_file));
750
- $fileid = wfu_log_action('include', $dec_file, $user->ID, '', '', get_current_blog_id(), '', null);
751
-
752
- if ( $fileid !== false ) {
753
- die(apply_filters('_wfu_ajax_action_include_file', "wfu_include_file:success:".$fileid));
754
- }
755
- else die(apply_filters('_wfu_ajax_action_include_file', 'wfu_include_file:fail:'));
756
- }
757
-
758
- function wfu_ajax_action_notify_wpfilebase() {
759
- $_POST = stripslashes_deep($_POST);
760
- $_GET = stripslashes_deep($_GET);
761
-
762
- $params_index = (isset($_POST['params_index']) ? $_POST['params_index'] : (isset($_GET['params_index']) ? $_GET['params_index'] : ''));
763
- $session_token = (isset($_POST['session_token']) ? $_POST['session_token'] : (isset($_GET['session_token']) ? $_GET['session_token'] : ''));
764
- if ( $params_index == '' || $session_token == '' ) die();
765
-
766
- $params_index = sanitize_text_field($params_index);
767
- $session_token = sanitize_text_field($session_token);
768
-
769
- $arr = wfu_get_params_fields_from_index($params_index, $session_token);
770
- //check referer using server sessions to avoid CSRF attacks
771
- if ( WFU_USVAR("wfu_token_".$arr['shortcode_id']) != $session_token ) die();
772
-
773
- do_action('wpfilebase_sync');
774
-
775
- die();
776
- }
777
-
778
- function wfu_ajax_action_pdusers_get_users() {
779
- $_POST = stripslashes_deep($_POST);
780
- $_GET = stripslashes_deep($_GET);
781
-
782
- $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
783
- $query = (isset($_POST['query']) ? $_POST['query'] : (isset($_GET['query']) ? $_GET['query'] : ''));
784
- if ( $nonce == '' || $query == '' ) die();
785
-
786
- if ( !current_user_can( 'manage_options' ) ) die();
787
- //security check to avoid CSRF attacks
788
- if ( !wp_verify_nonce($nonce, 'wfu_edit_policy') ) die();
789
-
790
- $query = sanitize_text_field($query);
791
- $args = array(
792
- 'search' => $query,
793
- 'search_columns' => array( 'user_login', 'display_name' ),
794
- 'fields' => array( 'user_login', 'display_name' ),
795
- 'number' => 100
796
- );
797
- $args = apply_filters("_wfu_get_users", $args, "manage_pdusers");
798
- $users = get_users($args);
799
-
800
- die("pdusers_get_users:".wfu_encode_array_to_string($users));
801
- }
802
-
803
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * AJAX Handlers of the Plugin
5
+ *
6
+ * This file contains AJAX handlers of the plugin.
7
+ *
8
+ * @link /lib/wfu_ajaxactions.php
9
+ *
10
+ * @package WordPress File Upload Plugin
11
+ * @subpackage Core Components
12
+ * @since 2.1.2
13
+ */
14
+
15
+ /**
16
+ * Execute Email Notification Dispatching
17
+ *
18
+ * This function sends an email notification after files have been uploaded.
19
+ *
20
+ * @since 2.1.2
21
+ */
22
+ function wfu_ajax_action_send_email_notification() {
23
+ $_POST = stripslashes_deep($_POST);
24
+
25
+ $user = wp_get_current_user();
26
+ if ( 0 == $user->ID ) $is_admin = false;
27
+ else $is_admin = current_user_can('manage_options');
28
+
29
+ $params_index = sanitize_text_field($_POST['params_index']);
30
+ $session_token = sanitize_text_field($_POST['session_token']);
31
+
32
+ $arr = wfu_get_params_fields_from_index($params_index, $session_token);
33
+ //check referer using server sessions to avoid CSRF attacks
34
+ $sid = $arr['shortcode_id'];
35
+ if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
36
+ if ( $user->user_login != $arr['user_login'] ) die();
37
+
38
+ $params_str = get_option('wfu_params_'.$arr['unique_id']);
39
+ $params = wfu_decode_array_from_string($params_str);
40
+
41
+ //check whether email notifications are activated
42
+ if ( $params["notify"] != "true" ) die();
43
+
44
+ $uniqueid = ( isset($_POST['uniqueuploadid_'.$sid]) ? sanitize_text_field($_POST['uniqueuploadid_'.$sid]) : "" );
45
+ //uniqueid cannot be empty and cannot be "no-ajax"
46
+ if ( $uniqueid == "" || $uniqueid == "no-ajax" ) die();
47
+
48
+ //retrieve the list of uploaded files from session
49
+ $target_path_list = array();
50
+ $all_files_count = 0;
51
+ if ( WFU_USVAR_exists("filedata_".$uniqueid) && is_array(WFU_USVAR("filedata_".$uniqueid)) ) {
52
+ $all_files_count = count(WFU_USVAR("filedata_".$uniqueid));
53
+ foreach ( WFU_USVAR("filedata_".$uniqueid) as $file ) {
54
+ if ( $file["upload_result"] == "success" || $file["upload_result"] == "warning" )
55
+ array_push($target_path_list, $file["filepath"]);
56
+ }
57
+ }
58
+ $uploaded_files_count = count($target_path_list);
59
+ $nofileupload = ( $params["allownofile"] == "true" && $all_files_count == 0 );
60
+ $force_notifications = ( WFU_VAR("WFU_FORCE_NOTIFICATIONS") == "true" );
61
+
62
+ //in case no files have been uploaded and this is not a nofileupload
63
+ //situation and Force Email Notifications option is not active then abort
64
+ if ( $uploaded_files_count == 0 && !$nofileupload && !$force_notifications ) die();
65
+
66
+ /* initialize return array */
67
+ $params_output_array["version"] = "full";
68
+ $params_output_array["general"]['shortcode_id'] = $params["uploadid"];
69
+ $params_output_array["general"]['unique_id'] = $uniqueid;
70
+ $params_output_array["general"]['state'] = 0;
71
+ $params_output_array["general"]['files_count'] = 0;
72
+ $params_output_array["general"]['update_wpfilebase'] = "";
73
+ $params_output_array["general"]['redirect_link'] = "";
74
+ $params_output_array["general"]['upload_finish_time'] = "";
75
+ $params_output_array["general"]['message'] = "";
76
+ $params_output_array["general"]['message_type'] = "";
77
+ $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
78
+ $params_output_array["general"]['admin_messages']['notify'] = "";
79
+ $params_output_array["general"]['admin_messages']['redirect'] = "";
80
+ $params_output_array["general"]['admin_messages']['other'] = "";
81
+ $params_output_array["general"]['errors']['wpfilebase'] = "";
82
+ $params_output_array["general"]['errors']['notify'] = "";
83
+ $params_output_array["general"]['errors']['redirect'] = "";
84
+ $params_output_array["general"]['color'] = "black";
85
+ $params_output_array["general"]['bgcolor'] = "#F5F5F5";
86
+ $params_output_array["general"]['borcolor'] = "#D3D3D3";
87
+ $params_output_array["general"]['notify_by_email'] = 0;
88
+ $params_output_array["general"]['fail_message'] = WFU_ERROR_UNKNOWN;
89
+
90
+ //retrieve userdata, first get default userdata from $params
91
+ $userdata_fields = $params["userdata_fields"];
92
+ //remove any honeypot fields and initialize default values
93
+ foreach ( $userdata_fields as $userdata_key => $userdata_field )
94
+ if ( $userdata_field["type"] == "honeypot" ) unset($userdata_fields[$userdata_key]);
95
+ else $userdata_fields[$userdata_key]["value"] = "";
96
+ //then retrieve userdata from session if files exist
97
+ if ( $all_files_count > 0 && WFU_USVAR_exists("filedata_".$uniqueid) && is_array(WFU_USVAR("filedata_".$uniqueid)) ) {
98
+ foreach ( WFU_USVAR("filedata_".$uniqueid) as $file ) {
99
+ if ( isset($file["user_data"]) ) {
100
+ $userdata_fields = array();
101
+ foreach ( $file["user_data"] as $userdata_key => $userdata_field )
102
+ $userdata_fields[$userdata_key] = array( "label" => $userdata_field["label"], "value" => $userdata_field["value"] );
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ //in case there are no files in session (because allownofile attribute is
108
+ //active and the user did not select any files for upload) then retrieve
109
+ //userdata from the database based on uploadid
110
+ else {
111
+ $userdata_saved = wfu_get_userdata_from_uploadid($uniqueid);
112
+ if ( $userdata_saved != null && is_array($userdata_saved) ) {
113
+ $userdata_fields = array();
114
+ foreach ( $userdata_saved as $userdata_saved_rec )
115
+ $userdata_fields[$userdata_saved_rec->propkey] = array( "label" => $userdata_saved_rec->property, "value" => $userdata_saved_rec->propvalue );
116
+ }
117
+ }
118
+
119
+ $send_error = wfu_send_notification_email($user, $target_path_list, $userdata_fields, $params);
120
+
121
+ /* suppress any errors if user is not admin */
122
+ if ( !$is_admin ) $send_error = "";
123
+
124
+ if ( $send_error != "" ) {
125
+ $params_output_array["general"]['admin_messages']['notify'] = $send_error;
126
+ $params_output_array["general"]['errors']['notify'] = "error";
127
+ }
128
+
129
+ /* construct safe output */
130
+ $sout = "0;".WFU_VAR("WFU_DEFAULTMESSAGECOLORS").";0";
131
+
132
+ $echo_str = "wfu_fileupload_success::".$sout.":".wfu_encode_array_to_string($params_output_array);
133
+ /**
134
+ * Customise Email Notification Result.
135
+ *
136
+ * This filter allows scripts to customise the result of email notification
137
+ * operation.
138
+ *
139
+ * @since 4.0.0
140
+ *
141
+ * @param string $echo_str The result of email notification operation.
142
+ */
143
+ $echo_str = apply_filters('_wfu_ajax_action_send_email_notification', $echo_str);
144
+
145
+ die($echo_str);
146
+ }
147
+
148
+ /**
149
+ * Execute Pre-Upload Actions
150
+ *
151
+ * This function executes server-side actions before the upload starts, in order
152
+ * to determine whether the upload will continue, or any other custom actions.
153
+ *
154
+ * @since 3.7.0
155
+ */
156
+ function wfu_ajax_action_ask_server() {
157
+ if ( !isset($_REQUEST['session_token']) || !isset($_REQUEST['sid']) || !isset($_REQUEST['unique_id']) ) die();
158
+
159
+ $_REQUEST = stripslashes_deep($_REQUEST);
160
+
161
+ $session_token = sanitize_text_field( $_REQUEST["session_token"] );
162
+ $sid = sanitize_text_field( $_REQUEST["sid"] );
163
+ $unique_id = wfu_sanitize_code($_REQUEST['unique_id']);
164
+ if ( $session_token == "" ) die();
165
+ //check referrer using Wordpress nonces and server sessions to avoid CSRF attacks
166
+ check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
167
+ if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
168
+
169
+ //prepare parameters for before-upload filters
170
+ $ret = array( "status" => "", "echo" => "" );
171
+ //retrieve file names and sizes from request parameters
172
+ $filenames_raw = ( isset($_REQUEST['filenames']) ? $_REQUEST['filenames'] : "" );
173
+ $filenames = array();
174
+ if ( trim($filenames_raw) != "" ) $filenames = explode(";", $filenames_raw);
175
+ foreach ( $filenames as $ind => $filename ) $filenames[$ind] = esc_attr(wfu_plugin_decode_string(trim($filename)));
176
+ $filesizes_raw = ( isset($_REQUEST['filesizes']) ? $_REQUEST['filesizes'] : "" );
177
+ $filesizes = array();
178
+ if ( trim($filesizes_raw) != "" ) $filesizes = explode(";", $filesizes_raw);
179
+ foreach ( $filesizes as $ind => $filesize ) $filesizes[$ind] = wfu_sanitize_int($filesize);
180
+ $files = array();
181
+ foreach ( $filenames as $ind => $filename ) {
182
+ $filesize = "";
183
+ if ( isset($filesizes[$ind]) ) $filesize = $filesizes[$ind];
184
+ array_push($files, array( "filename" => $filename, "filesize" => $filesize ));
185
+ }
186
+ $attr = array( "sid" => $sid, "unique_id" => $unique_id, "files" => $files );
187
+ //execute before upload filters
188
+ $echo_str = "";
189
+ //first execute any custom filters created by admin
190
+ if ( has_filter("wfu_before_upload") ) {
191
+ $changable_data = array( "error_message" => "", "js_script" => "" );
192
+ /**
193
+ * Execute Custom Actions Before Upload Starts.
194
+ *
195
+ * This filter allows to execute custom actions before upload starts. It
196
+ * can cancel the upload returning an error message.
197
+ *
198
+ * @since 3.7.0
199
+ *
200
+ * @param array $changable_data {
201
+ * Controls the upload.
202
+ *
203
+ * @type string $error_message An error message to display if the
204
+ * upload must be cancelled.
205
+ * @type string $js_script Javascript code to execute on user's
206
+ * browser after this filter finishes.
207
+ * }
208
+ * @param array $attr {
209
+ * Various attributes of the upload.
210
+ *
211
+ * @type string $sid The ID of the shortcode.
212
+ * @type string $unique_id The unique ID of the upload.
213
+ * @type array $files {
214
+ * Contains an array of the uploaded files.
215
+ *
216
+ * @type array $file {
217
+ * Contains information for each uploaded file.
218
+ *
219
+ * @type string $filename The filename of the file.
220
+ * @type int $filesize The size of the file.
221
+ * }
222
+ * }
223
+ * }
224
+ */
225
+ $changable_data = apply_filters("wfu_before_upload", $changable_data, $attr);
226
+ if ( $changable_data["error_message"] == "" ) $ret["status"] = "success";
227
+ else {
228
+ $ret["status"] = "error";
229
+ $echo_str .= "CBUV[".$changable_data["error_message"]."]";
230
+ }
231
+ if ( $changable_data["js_script"] != "" ) $echo_str .= "CBUVJS[".wfu_plugin_encode_string($changable_data["js_script"])."]";
232
+ }
233
+ /**
234
+ * Execute Custom Internal Actions Before Upload Starts.
235
+ *
236
+ * This filter allows to execute custom internal actions by extensions
237
+ * before upload starts. It can cancel the upload.
238
+ *
239
+ * @since 3.7.0
240
+ *
241
+ * @param array $ret {
242
+ * Controls the upload and output of this function.
243
+ *
244
+ * @type string $status The status of the upload. It must be 'success'
245
+ * or 'error'.
246
+ * @type string $echo Additional content to the echoed by the function.
247
+ * }
248
+ * @param array $attr {
249
+ * Various attributes of the upload.
250
+ *
251
+ * @type string $sid The ID of the shortcode.
252
+ * @type string $unique_id The unique ID of the upload.
253
+ * @type array $files {
254
+ * Contains an array of the uploaded files.
255
+ *
256
+ * @type array $file {
257
+ * Contains information for each uploaded file.
258
+ *
259
+ * @type string $filename The filename of the file.
260
+ * @type int $filesize The size of the file.
261
+ * }
262
+ * }
263
+ * }
264
+ */
265
+ $ret = apply_filters("_wfu_before_upload", $ret, $attr);
266
+ $echo_str .= $ret["echo"];
267
+ //in case that no filters were executed, because $ret["status"] is
268
+ //empty, then this call to wfu_ajax_action_ask_server was erroneous
269
+ if ( $ret["status"] == "" ) $ret["status"] = "die";
270
+ //create an internal flag stored in session regarding the status of this
271
+ //upload, that will be used to verify or not the upload
272
+ if ( $ret["status"] == "success" ) WFU_USVAR_store("wfu_uploadstatus_".$attr["unique_id"], 1);
273
+ else WFU_USVAR_store("wfu_uploadstatus_".$attr["unique_id"], 0);
274
+
275
+ if ( $ret["status"] == "success" || $ret["status"] == "error" )
276
+ echo "wfu_askserver_".$ret["status"].":".$echo_str;
277
+
278
+ die();
279
+ }
280
+
281
+ /**
282
+ * Execute Cancellation of Classic Upload
283
+ *
284
+ * This function sets the necessary User State variables to denote cancellation
285
+ * of the upload that was requested by the user. This function applies only to
286
+ * classic (non-AJAX) uploads.
287
+ *
288
+ * @since 4.0.0
289
+ */
290
+ function wfu_ajax_action_cancel_upload() {
291
+ if ( !isset($_REQUEST['session_token']) || !isset($_REQUEST['sid']) || !isset($_REQUEST['unique_id']) ) die();
292
+
293
+ $_REQUEST = stripslashes_deep($_REQUEST);
294
+
295
+ $session_token = sanitize_text_field( $_REQUEST["session_token"] );
296
+ $sid = sanitize_text_field( $_REQUEST["sid"] );
297
+ $unique_id = wfu_sanitize_code($_REQUEST['unique_id']);
298
+ if ( $session_token == "" ) die();
299
+ //check referrer using Wordpress nonces and server sessions to avoid CSRF attacks
300
+ check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
301
+ if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) die();
302
+
303
+ //setting status to 0 denotes cancelling of the upload
304
+ WFU_USVAR_store("wfu_uploadstatus_".$unique_id, 0);
305
+
306
+ die("success");
307
+ }
308
+
309
+ /**
310
+ * Execute AJAX Upload
311
+ *
312
+ * This function is the main callback of an AJAX upload of a whole file or a
313
+ * chunk. It performs security checks to verify the user, then it performs pre-
314
+ * upload actions, then it executes wfu_process_files() function that processes
315
+ * and saves the files and then performs post-upload actions and filters.
316
+ *
317
+ * @since 2.1.2
318
+ *
319
+ * @global string $wfu_user_state_handler The defined User State handler.
320
+ */
321
+ function wfu_ajax_action_callback() {
322
+ global $wfu_user_state_handler;
323
+ if ( !isset($_REQUEST['session_token']) ) die();
324
+
325
+ $_REQUEST = stripslashes_deep($_REQUEST);
326
+ $_POST = stripslashes_deep($_POST);
327
+
328
+ $session_token = sanitize_text_field( $_REQUEST["session_token"] );
329
+ if ( $session_token == "" ) die();
330
+ check_ajax_referer( 'wfu-uploader-nonce', 'wfu_uploader_nonce' );
331
+
332
+ if ( !isset($_REQUEST['params_index']) ) die();
333
+
334
+ $params_index = sanitize_text_field( $_REQUEST["params_index"] );
335
+
336
+ if ( $params_index == "" ) die();
337
+
338
+ $user = wp_get_current_user();
339
+ $arr = wfu_get_params_fields_from_index($params_index, $session_token);
340
+ $sid = $arr['shortcode_id'];
341
+ //check referrer using server sessions to avoid CSRF attacks
342
+ if ( WFU_USVAR("wfu_token_".$sid) != $session_token ) {
343
+ $echo_str = "Session failed!<br/><br/>Session Data:<br/>";
344
+ $echo_str .= print_r(wfu_sanitize(WFU_USALL()), true);
345
+ $echo_str .= "<br/><br/>Post Data:<br/>";
346
+ $echo_str .= print_r(wfu_sanitize($_POST), true);
347
+ $echo_str .= 'force_errorabort_code';
348
+ /**
349
+ * Customise Output on Session Error.
350
+ *
351
+ * This filter allows scripts to customise output of the function in
352
+ * case of session error.
353
+ *
354
+ * @since 3.11.0
355
+ *
356
+ * @param string $echo_str The output in case of session error.
357
+ */
358
+ $echo_str = apply_filters('_wfu_upload_session_failed', $echo_str);
359
+ die($echo_str);
360
+ }
361
+
362
+ if ( $user->user_login != $arr['user_login'] ) {
363
+ $echo_str = "User failed!<br/><br/>User Data:<br/>";
364
+ $echo_str .= print_r(wfu_sanitize($user), true);
365
+ $echo_str .= "<br/><br/>Post Data:<br/>";
366
+ $echo_str .= print_r(wfu_sanitize($_POST), true);
367
+ $echo_str .= "<br/><br/>Params Data:<br/>";
368
+ $echo_str .= print_r(wfu_sanitize($arr), true);
369
+ $echo_str .= 'force_errorabort_code';
370
+ /**
371
+ * Customise Output on User Error.
372
+ *
373
+ * This filter allows scripts to customise output of the function in
374
+ * case of user error.
375
+ *
376
+ * @since 3.11.0
377
+ *
378
+ * @param string $echo_str The output in case of user error.
379
+ */
380
+ $echo_str = apply_filters('_wfu_upload_user_failed', $echo_str);
381
+ die($echo_str);
382
+ }
383
+
384
+ //if force_connection_close is set, then the first pass to this callback
385
+ //script is for closing the previous connection
386
+ if ( isset($_POST["force_connection_close"]) && $_POST["force_connection_close"] === "1" ) {
387
+ header("Connection: Close");
388
+ /**
389
+ * Customise Output on Forced Connection Close.
390
+ *
391
+ * This filter allows scripts to customise return of the function in
392
+ * case of forced connection close.
393
+ *
394
+ * @since 3.11.0
395
+ *
396
+ * @param string $echo_str The return in case of forced connection
397
+ * close.
398
+ */
399
+ die(apply_filters('_wfu_upload_force_connection_close', 'success'));
400
+ }
401
+
402
+ //get the unique id of the upload
403
+ $unique_id = ( isset($_POST['uniqueuploadid_'.$sid]) ? sanitize_text_field($_POST['uniqueuploadid_'.$sid]) : "" );
404
+ if ( strlen($unique_id) != 10 ) {
405
+ /**
406
+ * Customise Output on Unique ID Fail.
407
+ *
408
+ * This filter allows scripts to customise return of the function in
409
+ * case that the retrieved unique ID is invalid.
410
+ *
411
+ * @since 3.11.0
412
+ *
413
+ * @param string $echo_str The return in case of unique ID fail.
414
+ */
415
+ die(apply_filters('_wfu_upload_uniqueid_failed', 'force_errorabort_code'));
416
+ }
417
+
418
+ //if before upload actions have been executed and they have rejected the
419
+ //upload, but for some reason (hack attempt) the upload continued, then
420
+ //terminate it
421
+ if ( WFU_USVAR_exists("wfu_uploadstatus_".$unique_id) && WFU_USVAR("wfu_uploadstatus_".$unique_id) == 0 ) die('force_errorabort_code');
422
+
423
+ //get stored shortcode parameters
424
+ $params_str = get_option('wfu_params_'.$arr['unique_id']);
425
+ $params = wfu_decode_array_from_string($params_str);
426
+
427
+ //if upload has finished then perform post upload actions
428
+ if ( isset($_POST["upload_finished"]) && $_POST["upload_finished"] === "1" ) {
429
+ //remove any queues that were generated during the upload process
430
+ wfu_remove_queue($unique_id);
431
+ $echo_str = "";
432
+ //execute after upload filters
433
+ $ret = wfu_execute_after_upload_filters($sid, $unique_id, $params);
434
+ if ( $ret["js_script"] != "" ) $echo_str = "CBUVJS[".wfu_plugin_encode_string($ret["js_script"])."]";
435
+ die($echo_str);
436
+ }
437
+
438
+ //check if honeypot userdata fields have been added to the form and if they
439
+ //contain any data; if wfu_check_remove_honeypot_fields returns true this
440
+ //means that at least one honeypot field has beed filled with a value and
441
+ //the upload must be aborted because it was not done by a human
442
+ if ( $params["userdata"] == "true" && wfu_check_remove_honeypot_fields($params["userdata_fields"], 'hiddeninput_'.$sid.'_userdata_') ) die("force_abortsuccess_code");
443
+
444
+ //apply filters to determine if the upload will continue or stop
445
+ $ret = array( "status" => "", "echo" => "" );
446
+ $attr = array( "sid" => $sid, "unique_id" => $unique_id, "params" => $params );
447
+ /**
448
+ * Execute Pre-Upload Checks.
449
+ *
450
+ * This is an internal filter which allows to execute custom actions right
451
+ * before an upload starts. It can cancel the upload.
452
+ *
453
+ * @since 3.7.0
454
+ *
455
+ * @param array $ret {
456
+ * Controls the Upload.
457
+ *
458
+ * @type string $status Status of the upload. If it is 'die' then the
459
+ * upload will be cancelled.
460
+ * @type string $echo A message to return in case of upload
461
+ * cancellation.
462
+ * }
463
+ * @param array $attr {
464
+ * Various attributes of the upload.
465
+ *
466
+ * @type string $sid The ID of the shortcode.
467
+ * @type string $unique_id The unique ID of the upload.
468
+ * @type array $params The shortcode parameters of the upload form.
469
+ */
470
+ $ret = apply_filters("_wfu_pre_upload_check", $ret, $attr);
471
+ if ( $ret["status"] == "die" ) die($ret["echo"]);
472
+
473
+ //if this is the first pass of an upload attempt then perform pre-upload actions
474
+ if ( !WFU_USVAR_exists('wfu_upload_first_pass_'.$unique_id) || WFU_USVAR('wfu_upload_first_pass_'.$unique_id) != 'true' ) {
475
+ WFU_USVAR_store('wfu_upload_first_pass_'.$unique_id, 'true');
476
+ }
477
+
478
+ if ( !isset($_POST["subdir_sel_index"]) ) die();
479
+ $subdir_sel_index = sanitize_text_field( $_POST["subdir_sel_index"] );
480
+ $params['subdir_selection_index'] = $subdir_sel_index;
481
+ WFU_USVAR_store('wfu_check_refresh_'.$params["uploadid"], 'do not process');
482
+
483
+ //update consent status of user
484
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
485
+ $params["consent_result"] = wfu_check_user_consent($user);
486
+ $require_consent = ( $plugin_options["personaldata"] == "1" && ( $params["notrememberconsent"] == "true" || $params["consent_result"] == "" ) && $params["askconsent"] == "true" );
487
+ if ( $require_consent ) {
488
+ if ( !isset($_POST['consent_result']) ) die();
489
+ $consent_result = ( $_POST['consent_result'] == "yes" ? "yes" : ( $_POST['consent_result'] == "no" ? "no" : "" ) );
490
+ $params["consent_result"] = ( $_POST['consent_result'] == "yes" ? "1" : ( $_POST['consent_result'] == "no" ? "0" : "" ) );
491
+ wfu_update_user_consent($user, $consent_result);
492
+ }
493
+
494
+ if ( $wfu_user_state_handler == "dboption" )
495
+ $proc_ret = wfu_run_process_in_queue($unique_id, "wfu_process_files", array( $params, 'ajax' ));
496
+ else {
497
+ $proc_ret["result"] = true;
498
+ $proc_ret["output"] = wfu_process_files($params, 'ajax');
499
+ }
500
+ $echo_str = "";
501
+ if ( $proc_ret["result"] ) {
502
+ $wfu_process_file_array = $proc_ret["output"];
503
+ //extract safe_output from wfu_process_file_array and pass it as
504
+ //separate part of the response text
505
+ $safe_output = $wfu_process_file_array["general"]['safe_output'];
506
+ unset($wfu_process_file_array["general"]['safe_output']);
507
+ //get javascript code that has been defined in wfu_after_file_upload
508
+ //action
509
+ $js_script = wfu_plugin_encode_string($wfu_process_file_array["general"]['js_script']);
510
+ unset($wfu_process_file_array["general"]['js_script']);
511
+
512
+ $echo_str = "wfu_fileupload_success:".$js_script.":".$safe_output.":".wfu_encode_array_to_string($wfu_process_file_array);
513
+ }
514
+ elseif ( $proc_ret["error"] == "abort_thread" ) wfu_advance_queue($unique_id);
515
+ /**
516
+ * Customise Output of Successful AJAX Upload.
517
+ *
518
+ * This filter allows scripts to customise return of the function in case
519
+ * that the AJAX upload was successful.
520
+ *
521
+ * @since 3.11.0
522
+ *
523
+ * @param string $echo_str The return in case of successful AJAX upload.
524
+ */
525
+ $echo_str = apply_filters('_wfu_upload_callback_success', $echo_str);
526
+ die($echo_str);
527
+ }
528
+
529
+ /**
530
+ * Execute Saving of Shortcode
531
+ *
532
+ * This function executes saving of a shortcode after it has been edited through
533
+ * the shortcode composer.
534
+ *
535
+ * @since 2.1.3
536
+ */
537
+ function wfu_ajax_action_save_shortcode() {
538
+ $is_admin = current_user_can( 'manage_options' );
539
+ $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
540
+ if ( !$is_admin && !$can_open_composer ) die();
541
+ if ( !isset($_POST['shortcode']) || !isset($_POST['shortcode_original']) || !isset($_POST['post_id']) || !isset($_POST['post_hash']) || !isset($_POST['shortcode_position']) || !isset($_POST['shortcode_tag']) || !isset($_POST['widget_id']) ) die();
542
+
543
+ $_POST = stripslashes_deep($_POST);
544
+
545
+ //sanitize parameters
546
+ $shortcode = wfu_sanitize_code($_POST['shortcode']);
547
+ $shortcode_original = wfu_sanitize_code($_POST['shortcode_original']);
548
+ $post_id = wfu_sanitize_int($_POST['post_id']);
549
+ $post_hash = wfu_sanitize_code($_POST['post_hash']);
550
+ $shortcode_position = wfu_sanitize_int($_POST['shortcode_position']);
551
+ $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
552
+ $widget_id = sanitize_text_field($_POST['widget_id']);
553
+
554
+ $shortcode = wfu_sanitize_shortcode(wfu_plugin_decode_string($shortcode), $shortcode_tag);
555
+
556
+ if ( $post_id == "" && $widget_id == "" ) {
557
+ die();
558
+ }
559
+ else {
560
+ $data['post_id'] = $post_id;
561
+ $data['post_hash'] = $post_hash;
562
+ $data['shortcode'] = wfu_plugin_decode_string($shortcode_original);
563
+ $data['position'] = $shortcode_position;
564
+ if ( $post_id != "" && !wfu_check_edit_shortcode($data) ) $echo_str = "wfu_save_shortcode:fail:post_modified";
565
+ else {
566
+ if ( $widget_id == "" ) {
567
+ $new_shortcode = "[".$shortcode_tag." ".$shortcode."]";
568
+ if ( wfu_replace_shortcode($data, $new_shortcode) ) {
569
+ $post = get_post($post_id);
570
+ $hash = hash('md5', $post->post_content);
571
+ $echo_str = "wfu_save_shortcode:success:".$hash;
572
+ }
573
+ else $echo_str = "wfu_save_shortcode:fail:post_update_failed";
574
+ }
575
+ else {
576
+ $widget_obj = wfu_get_widget_obj_from_id($widget_id);
577
+ if ( $widget_obj === false ) $echo_str = "wfu_save_shortcode:fail:post_update_failed";
578
+ else {
579
+ $widget_sidebar = is_active_widget(false, $widget_id, "wordpress_file_upload_widget");
580
+ if ( !$widget_sidebar ) $echo_str = "wfu_save_shortcode:fail:post_update_failed";
581
+ else {
582
+ $widget_obj->update_external($shortcode);
583
+ $hash = $data['post_hash'];
584
+ $echo_str = "wfu_save_shortcode:success:".$hash;
585
+ }
586
+ }
587
+ }
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Customise Output on Shortcode Saving.
593
+ *
594
+ * This filter allows scripts to customise return of the function after
595
+ * finish of it.
596
+ *
597
+ * @since 3.11.0
598
+ *
599
+ * @param string $echo_str The return of the function.
600
+ */
601
+ $echo_str = apply_filters('_wfu_ajax_action_save_shortcode', $echo_str);
602
+ die($echo_str);
603
+ }
604
+
605
+ /**
606
+ * Execute Checking of Post Contents
607
+ *
608
+ * This function executes checking of post contents to determine whether they
609
+ * are current or obsolete (they have changed).
610
+ *
611
+ * @since 2.6.0
612
+ */
613
+ function wfu_ajax_action_check_page_contents() {
614
+ if ( !current_user_can( 'manage_options' ) ) die();
615
+ if ( !isset($_POST['post_id']) || !isset($_POST['post_hash']) ) die();
616
+ if ( $_POST['post_id'] == "" ) die();
617
+
618
+ $_POST = stripslashes_deep($_POST);
619
+
620
+ $data['post_id'] = wfu_sanitize_int($_POST['post_id']);
621
+ $data['post_hash'] = wfu_sanitize_code($_POST['post_hash']);
622
+ if ( wfu_check_edit_shortcode($data) ) $echo_str = "wfu_check_page_contents:current:";
623
+ else $echo_str = "wfu_check_page_contents:obsolete:";
624
+
625
+ /**
626
+ * Customise Output of Post Contents Checking Function.
627
+ *
628
+ * This filter allows scripts to customise return of this function after
629
+ * finish of it.
630
+ *
631
+ * @since 3.11.0
632
+ *
633
+ * @param string $echo_str The return of the function.
634
+ */
635
+ $echo_str = apply_filters('_wfu_ajax_action_check_page_contents', $echo_str);
636
+ die($echo_str);
637
+ }
638
+
639
+ /**
640
+ * Initiate Editing of Shortcode
641
+ *
642
+ * This function invokes the shortcode composer in order to edit a shortcode. It
643
+ * applies when editing a shortcode from Main page of the plugin in Dashboard or
644
+ * from a front-end post or page or from a sidebar.
645
+ *
646
+ * @since 2.6.0
647
+ */
648
+ function wfu_ajax_action_edit_shortcode() {
649
+ global $wp_registered_widgets;
650
+ global $wp_registered_sidebars;
651
+
652
+ $is_admin = current_user_can( 'manage_options' );
653
+ $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
654
+ if ( !$is_admin && !$can_open_composer ) die();
655
+ if ( !isset($_POST['upload_id']) || !isset($_POST['post_id']) || !isset($_POST['post_hash']) || !isset($_POST['shortcode_tag']) || !isset($_POST['widget_id']) ) die();
656
+
657
+ $_POST = stripslashes_deep($_POST);
658
+
659
+ //sanitize parameters
660
+ $upload_id = sanitize_text_field($_POST['upload_id']);
661
+ $widget_id = sanitize_text_field($_POST['widget_id']);
662
+ $post_id = wfu_sanitize_int($_POST['post_id']);
663
+ $post_hash = wfu_sanitize_code($_POST['post_hash']);
664
+ $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
665
+
666
+ $keyname = "uploadid";
667
+ if ( $shortcode_tag == "wordpress_file_upload_browser" ) $keyname = "browserid";
668
+
669
+ $data['post_id'] = $post_id;
670
+ $data['post_hash'] = $post_hash;
671
+ if ( wfu_check_edit_shortcode($data) ) {
672
+ if ( $widget_id == "" ) {
673
+ $post = get_post($data['post_id']);
674
+ //get default value for uploadid
675
+ if ( $shortcode_tag == "wordpress_file_upload_browser" ) $defs = wfu_browser_attribute_definitions();
676
+ else $defs = wfu_attribute_definitions();
677
+ $default = "";
678
+ foreach ( $defs as $key => $def ) {
679
+ if ( $def['attribute'] == $keyname ) {
680
+ $default = $def['value'];
681
+ break;
682
+ }
683
+ }
684
+ //get page shortcodes
685
+ $wfu_shortcodes = wfu_get_content_shortcodes($post, $shortcode_tag);
686
+ //find the shortcodes' uploadid and the correct one
687
+ $validkey = -1;
688
+ foreach ( $wfu_shortcodes as $key => $data ) {
689
+ $shortcode = trim(substr($data['shortcode'], strlen('['.$shortcode_tag), -1));
690
+ $shortcode_attrs = wfu_shortcode_string_to_array($shortcode);
691
+ if ( array_key_exists($keyname, $shortcode_attrs) ) $uploadid = $shortcode_attrs[$keyname];
692
+ else $uploadid = $default;
693
+ if ( $uploadid == $upload_id ) {
694
+ $validkey = $key;
695
+ break;
696
+ }
697
+ }
698
+ if ( $validkey == -1 ) die();
699
+ $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($wfu_shortcodes[$validkey]));
700
+ }
701
+ else {
702
+ $widget_obj = wfu_get_widget_obj_from_id($widget_id);
703
+ if ( $widget_obj === false ) die();
704
+ $widget_sidebar = is_active_widget(false, $widget_id, "wordpress_file_upload_widget");
705
+ if ( !$widget_sidebar ) die();
706
+ if ( isset($wp_registered_sidebars[$widget_sidebar]) && isset($wp_registered_sidebars[$widget_sidebar]['name']) ) $widget_sidebar = $wp_registered_sidebars[$widget_sidebar]['name'];
707
+ $data['shortcode'] = $widget_obj->shortcode();
708
+ $data['position'] = 0;
709
+ $data['widgetid'] = $widget_id;
710
+ $data['sidebar'] = $widget_sidebar;
711
+ $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($data));
712
+ }
713
+ if( $is_admin ) $url = site_url().'/wp-admin/options-general.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc;
714
+ //conditional that will open the shortcode composer for non-admin users
715
+ //who can edit posts or pages
716
+ else $url = site_url().'/wp-admin/admin.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc;
717
+ $echo_str = "wfu_edit_shortcode:success:".wfu_plugin_encode_string($url);
718
+ }
719
+ else $echo_str = "wfu_edit_shortcode:check_page_obsolete:".WFU_ERROR_PAGE_OBSOLETE;
720
+
721
+ /**
722
+ * Customise Output of Shortcode Editing Initiation Function.
723
+ *
724
+ * This filter allows scripts to customise return of this function after
725
+ * finish of it.
726
+ *
727
+ * @since 3.11.0
728
+ *
729
+ * @param string $echo_str The return of the function.
730
+ */
731
+ $echo_str = apply_filters('_wfu_ajax_action_edit_shortcode', $echo_str);
732
+ die($echo_str);
733
+ }
734
+
735
+ /**
736
+ * Initiate Editing of Shortcode in Gutenberg Editor
737
+ *
738
+ * This function invokes the shortcode composer in order to edit a shortcode. It
739
+ * applies when editing a shortcode from the new Gutenberg page editor of
740
+ * Wordpress.
741
+ *
742
+ * @since 4.11.0
743
+ */
744
+ function wfu_ajax_action_gutedit_shortcode() {
745
+ $is_admin = current_user_can( 'manage_options' );
746
+ $can_open_composer = ( WFU_VAR("WFU_SHORTCODECOMPOSER_NOADMIN") == "true" && ( current_user_can( 'edit_pages' ) || current_user_can( 'edit_posts' ) ) );
747
+ if ( !$is_admin && !$can_open_composer ) die();
748
+ if ( !isset($_POST['shortcode']) || !isset($_POST['post_id']) || !isset($_POST['shortcode_tag']) ) die();
749
+
750
+ $_POST = stripslashes_deep($_POST);
751
+
752
+ //sanitize parameters
753
+ $shortcode = wfu_sanitize_code($_POST['shortcode']);
754
+ $post_id = wfu_sanitize_int($_POST['post_id']);
755
+ $shortcode_tag = wfu_sanitize_tag($_POST['shortcode_tag']);
756
+
757
+ $shortcode = wfu_sanitize_shortcode(wfu_plugin_decode_string($shortcode), $shortcode_tag);
758
+
759
+ if ( $post_id == "" ) die();
760
+
761
+ $data['shortcode'] = '['.$shortcode_tag.' '.$shortcode.']';
762
+ $data['post_id'] = $post_id;
763
+ $data['post_hash'] = '';
764
+ $data['position'] = 0;
765
+ $data_enc = wfu_safe_store_shortcode_data(wfu_encode_array_to_string($data));
766
+ if ( $is_admin ) $url = site_url().'/wp-admin/options-general.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc.'&referer=guteditor';
767
+ //conditional that will open the shortcode composer for non-admin users who
768
+ //can edit posts or pages
769
+ else $url = site_url().'/wp-admin/admin.php?page=wordpress_file_upload&tag='.$shortcode_tag.'&action=edit_shortcode&data='.$data_enc.'&referer=guteditor';
770
+
771
+ $echo_str = "wfu_gutedit_shortcode:success:".wfu_plugin_encode_string($url);
772
+ /**
773
+ * Customise Output of Gutenberg Shortcode Editing Initiation Function.
774
+ *
775
+ * This filter allows scripts to customise return of this function after
776
+ * finish of it.
777
+ *
778
+ * @since 4.11.0
779
+ *
780
+ * @param string $echo_str The return of the function.
781
+ */
782
+ $echo_str = apply_filters('_wfu_ajax_action_gutedit_shortcode', $echo_str);
783
+ die($echo_str);
784
+ }
785
+
786
+ /**
787
+ * Retrieve Subfolder Structure of a Folder
788
+ *
789
+ * This function is used to retrieve the subfolder structure of a folder,
790
+ * together with the subfolder structure of one of the subfolders. It is used
791
+ * when defining the subfolders of the subfolders element of the upload form
792
+ * using the shortcoe composer.
793
+ *
794
+ * @since 2.4.1
795
+ */
796
+ function wfu_ajax_action_read_subfolders() {
797
+ if ( !isset($_POST['folder1']) || !isset($_POST['folder2']) ) die();
798
+
799
+ $_POST = stripslashes_deep($_POST);
800
+
801
+ $folder1 = wfu_sanitize_code($_POST['folder1']);
802
+ $folder1 = wfu_sanitize_url(wfu_plugin_decode_string($folder1));
803
+ $folder2 = wfu_sanitize_code($_POST['folder2']);
804
+ $folder2 = wfu_sanitize_url(wfu_plugin_decode_string($folder2));
805
+ if ( wfu_plugin_encode_string($folder1) != $_POST['folder1'] || wfu_plugin_encode_string($folder2) != $_POST['folder2'] ) die();
806
+
807
+ $temp_params = array( 'uploadpath' => $folder1, 'accessmethod' => 'normal', 'ftpinfo' => '', 'useftpdomain' => 'false' );
808
+ $path = wfu_upload_plugin_full_path($temp_params);
809
+
810
+ if ( !is_dir($path) ) {
811
+ /**
812
+ * Customise Output of Shortcode Subfolder Structure Retrieval.
813
+ *
814
+ * This filter allows scripts to customise return of this function after
815
+ * finish of it.
816
+ *
817
+ * @since 3.11.0
818
+ *
819
+ * @param string $echo_str The return of the function.
820
+ */
821
+ die(apply_filters('_wfu_ajax_action_read_subfolders', 'wfu_read_subfolders:error:Parent folder is not valid! Cannot retrieve subfolder list.'));
822
+ }
823
+
824
+ $path2 = $folder2;
825
+ $dirlist = "";
826
+ if ( $handle = opendir($path) ) {
827
+ $blacklist = array('.', '..');
828
+ while ( false !== ($file = readdir($handle)) )
829
+ if ( !in_array($file, $blacklist) ) {
830
+ $filepath = $path.$file;
831
+ if ( is_dir($filepath) ) {
832
+ if ( $file == $path2 ) $file = '[['.$file.']]';
833
+ $dirlist .= ( $dirlist == "" ? "" : "," ).$file;
834
+ }
835
+ }
836
+ closedir($handle);
837
+ }
838
+ if ( $path2 != "" ) {
839
+ $dirlist2 = $path2;
840
+ $path .= $path2."/";
841
+ if ( is_dir($path) ) {
842
+ if ( $handle = opendir($path) ) {
843
+ $blacklist = array('.', '..');
844
+ while ( false !== ($file = readdir($handle)) )
845
+ if ( !in_array($file, $blacklist) ) {
846
+ $filepath = $path.$file;
847
+ if ( is_dir($filepath) )
848
+ $dirlist2 .= ",*".$file;
849
+ }
850
+ closedir($handle);
851
+ }
852
+ }
853
+ $dirlist = str_replace('[['.$path2.']]', $dirlist2, $dirlist);
854
+ }
855
+
856
+ /** This filter is documnted above. */
857
+ die(apply_filters('_wfu_ajax_action_read_subfolders', "wfu_read_subfolders:success:".wfu_plugin_encode_string($dirlist)));
858
+ }
859
+
860
+ /**
861
+ * Initiate a File Download
862
+ *
863
+ * This function initiates a file download. It will first check whether the user
864
+ * has the right to download the file. Then it will return an iframe element
865
+ * that will start the download. Short life tokens are used in order to avoid
866
+ * CSRF attacks. Download is executed outside Wordpress enviroment because some
867
+ * times Wordpress environment outputs warnings that are downloaded with the
868
+ * file, resulting in a broken download.
869
+ *
870
+ * @since 2.6.0
871
+ */
872
+ function wfu_ajax_action_download_file_invoker() {
873
+ global $wfu_user_state_handler;
874
+
875
+ $_POST = stripslashes_deep($_POST);
876
+ $_GET = stripslashes_deep($_GET);
877
+
878
+ $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
879
+ $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
880
+ if ( $file_code == '' || $nonce == '' ) die();
881
+
882
+ //security check to avoid CSRF attacks
883
+ if ( !wp_verify_nonce($nonce, 'wfu_download_file_invoker') ) die();
884
+
885
+ //check if user is allowed to download files
886
+ if ( !current_user_can( 'manage_options' ) ) {
887
+ die();
888
+ }
889
+
890
+ $cookies = array();
891
+ $use_cookies = ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "cookies" );
892
+ $file_code = sanitize_text_field($file_code);
893
+ //if file_code is exportdata, then export of data has been requested and
894
+ //we need to create a file with export data and recreate file_code
895
+ if ( substr($file_code, 0, 10) == "exportdata" && current_user_can( 'manage_options' ) ) {
896
+ $params = null;
897
+ $params_str = substr($file_code, 11);
898
+ if ( trim($params_str) != "" ) $params = json_decode($params_str, true);
899
+ $filepath = wfu_export_uploaded_files($params);
900
+ if ( $filepath === false ) die();
901
+ $file_code = "exportdata".wfu_safe_store_filepath($filepath);
902
+ //store filepath in user state otherwise it can not be retrieved by
903
+ //downloader script
904
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_storage_'.substr($file_code, 10), $filepath);
905
+ else array_push($cookies, '{name: "wfu_storage_'.substr($file_code, 10).'", value: "'.$filepath.'", expires: 30}');
906
+ }
907
+ //else get the file path from the safe
908
+ else {
909
+ $filepath = wfu_get_filepath_from_safe($file_code);
910
+ if ( $filepath === false ) die();
911
+ $filepath = wfu_path_rel2abs(wfu_flatten_path($filepath));
912
+ //reject download of blacklisted file types for security reasons
913
+ if ( wfu_file_extension_blacklisted($filepath) ) {
914
+ /**
915
+ * Customise Output of Download Initiation Operation.
916
+ *
917
+ * This filter allows scripts to customise return of this function
918
+ * after finish of it.
919
+ *
920
+ * @since 3.11.0
921
+ *
922
+ * @param string $echo_str The return of the function.
923
+ */
924
+ die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:not_allowed:'.( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_NOTALLOWED : 'You are not allowed to download this file!' )));
925
+ }
926
+ //for front-end browser apply wfu_browser_check_file_action filter to
927
+ //allow or restrict the download
928
+ if ( isset($_POST['browser']) ) {
929
+ $changable_data["error_message"] = "";
930
+ $filerec = wfu_get_file_rec($filepath, true);
931
+ $userdata = array();
932
+ foreach ( $filerec->userdata as $data )
933
+ array_push($userdata, array( "label" => $data->property, "value" => $data->propvalue ));
934
+ $additional_data = array(
935
+ "file_action" => "download",
936
+ "filepath" => $filepath,
937
+ "uploaduser" => $filerec->uploaduserid,
938
+ "userdata" => $userdata
939
+ );
940
+ /**
941
+ * Check if Action is Allowed in Front-End File Browser.
942
+ *
943
+ * This filter allows scripts to check whether the action on a file
944
+ * from the front-end file browser is allowed.
945
+ *
946
+ * @since 3.7.2
947
+ *
948
+ * @param array $changable_data {
949
+ * Controls allowance or rejection of the action.
950
+ *
951
+ * @type string $error_message An error message to return in
952
+ * case the action must be rejected.
953
+ * }
954
+ * @param array $additional_data {
955
+ * Additional data of the file action operation.
956
+ *
957
+ * @type string $file_action The performed action.
958
+ * @type string $filepath The full path of the file.
959
+ * @type string $uploaduser The ID of the user who uploaded
960
+ * the file.
961
+ * @type array $userdata Each item of the array contains the
962
+ * label and value of any additional userdata exist
963
+ * together with the file.
964
+ * }
965
+ */
966
+ $changable_data = apply_filters("wfu_browser_check_file_action", $changable_data, $additional_data);
967
+ if ( $changable_data["error_message"] != "" )
968
+ /** This filter is documented above. */
969
+ die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:not_allowed:'.$changable_data["error_message"]));
970
+ }
971
+ //for back-end browser check if user is allowed to perform this action
972
+ //on this file
973
+ if ( !wfu_current_user_owes_file($filepath) ) die();
974
+ //store filepath in user state otherwise it can not be retrieved by
975
+ //downloader script
976
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_storage_'.$file_code, wfu_get_filepath_from_safe($file_code));
977
+ else array_push($cookies, '{name: "wfu_storage_'.$file_code.'", value: "'.wfu_get_filepath_from_safe($file_code).'", expires: 30}');
978
+ }
979
+
980
+ //generate download unique id to monitor this download
981
+ $download_id = wfu_create_random_string(16);
982
+ //store download status of this download in user state, so that it can be
983
+ //changed by downloader script; it is noted that the downloader script
984
+ //does not load WP environment, so in case of dboption it cannot access the
985
+ //download status (which is stored in the database); however the downloader
986
+ //script does not need to read it; it only needs to change it after the
987
+ //download; so after the download, the downloader script loads WP
988
+ //environment, so that it can change download status
989
+ WFU_USVAR_store('wfu_download_status_'.$download_id, 'starting');
990
+ //generate download ticket which expires in 30sec and store it in user
991
+ //state; it will be used as security measure for the downloader script,
992
+ //which runs outside Wordpress environment; it is noted that the downloader
993
+ //script needs to read download ticket before the download; however in the
994
+ //case of dboption the only way to achieve this is to store it in a cookie
995
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_download_ticket_'.$download_id, time() + 30);
996
+ else array_push($cookies, '{name: "wfu_download_ticket_'.$download_id.'", value: '.(time() + 30).', expires: 30}');
997
+ //generate download monitor ticket which expires in 30sec and store it in
998
+ //user state; it will be used as security measure for the monitor script
999
+ //that will check download status; it is noted that there is no reason to
1000
+ //store download monitor ticket in a cookie in case of dboption, because it
1001
+ //is not needed to be read by the downloader script
1002
+ WFU_USVAR_store('wfu_download_monitor_ticket_'.$download_id, time() + 30);
1003
+
1004
+ //store ABSPATH in user state so that it can be used by download script;
1005
+ //again, in case of dboption, the only way the downloader script can read it
1006
+ //is to store it in a cookie
1007
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_ABSPATH', wfu_abspath());
1008
+ else array_push($cookies, '{name: "wfu_ABSPATH", value: "'.urlencode(wfu_abspath()).'", expires: 30}');
1009
+ //store translatable strings to user state so that they can be used by a
1010
+ //script that runs outside Wordpress environment
1011
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_browser_downloadfile_notexist', ( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_NOTEXIST : 'File does not exist!' ));
1012
+ else array_push($cookies, '{name: "wfu_browser_downloadfile_notexist", value: "'.( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_NOTEXIST : 'File does not exist!' ).'", expires: 30}');
1013
+ if ( !$use_cookies ) WFU_USVAR_store_session('wfu_browser_downloadfile_failed', ( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_FAILED : 'Could not download file!' ));
1014
+ else array_push($cookies, '{name: "wfu_browser_downloadfile_failed", value: "'.( isset($_POST['browser']) ? WFU_BROWSER_DOWNLOADFILE_FAILED : 'Could not download file!' ).'", expires: 30}');
1015
+
1016
+ //this routine returns a dynamically created iframe element, that will call
1017
+ //the actual download script; the actual download script runs outside
1018
+ //Wordpress environment in order to ensure that no php warnings or echo from
1019
+ //other plugins is generated, that could scramble the downloaded file; a
1020
+ //ticket, similar to nonces, is passed to the download script to check that
1021
+ //it is not a CSRF attack; moreover,the ticket is destroyed by the time it
1022
+ //is consumed by the download script, so it cannot be used again
1023
+ $response["html"] = '<iframe src="'.WFU_DOWNLOADER_URL.'?file='.$file_code.'&ticket='.$download_id.'&handler='.$wfu_user_state_handler.'&session_legacy='.( WFU_VAR("WFU_US_SESSION_LEGACY") == "true" ? '1' : '0' ).'&dboption_base='.WFU_VAR("WFU_US_DBOPTION_BASE").'" style="display: none;"></iframe>';
1024
+ //if user state handler is set to dboption (cookies), then tickets and other
1025
+ //variables must pass to the download script as cookies; the cookies are
1026
+ //passed in the response of this function, so that the client browser can
1027
+ //add them in cookies by executing wfu_add_cookies() function
1028
+ $response["js"] = ( count($cookies) > 0 ? 'wfu_add_cookies(['.implode(", ", $cookies).']);' : '' );
1029
+ $response = wfu_encode_array_to_string($response);
1030
+
1031
+ /** This filter is documented above. */
1032
+ die(apply_filters('_wfu_ajax_action_download_file_invoker', 'wfu_ajax_action_download_file_invoker:wfu_download_id;'.$download_id.':'.$response));
1033
+ }
1034
+
1035
+ /**
1036
+ * Monitor a File Download
1037
+ *
1038
+ * This function monitors a file download and performs post-download actions in
1039
+ * case the download has ended.
1040
+ *
1041
+ * @since 2.6.0
1042
+ */
1043
+ function wfu_ajax_action_download_file_monitor() {
1044
+ $_POST = stripslashes_deep($_POST);
1045
+ $_GET = stripslashes_deep($_GET);
1046
+
1047
+ $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
1048
+ $id = (isset($_POST['id']) ? $_POST['id'] : (isset($_GET['id']) ? $_GET['id'] : ''));
1049
+ if ( $file_code == '' || $id == '' ) die();
1050
+ $id = wfu_sanitize_code($id);
1051
+
1052
+ //ensure that this is not a CSRF attack by checking validity of a security
1053
+ //ticket
1054
+ if ( !WFU_USVAR_exists('wfu_download_monitor_ticket_'.$id) || time() > WFU_USVAR('wfu_download_monitor_ticket_'.$id) ) {
1055
+ WFU_USVAR_unset('wfu_download_monitor_ticket_'.$id);
1056
+ WFU_USVAR_unset('wfu_download_status_'.$id);
1057
+ die();
1058
+ }
1059
+ //destroy monitor ticket so it cannot be used again
1060
+ WFU_USVAR_unset('wfu_download_monitor_ticket_'.$id);
1061
+
1062
+ //initiate loop of 30secs to check the download status of the file;
1063
+ //the download status is controlled by the actual download script;
1064
+ //if the file finishes within the 30secs of the loop, then this routine logs
1065
+ //the action and notifies the client side about the download status of the
1066
+ //file, otherwise an instruction to the client side to repeat this routine
1067
+ //and wait for another 30secs is dispatched
1068
+ $end_time = time() + 30;
1069
+ $upload_ended = false;
1070
+ while ( time() < $end_time ) {
1071
+ $upload_ended = ( WFU_USVAR_exists('wfu_download_status_'.$id) ? ( WFU_USVAR('wfu_download_status_'.$id) == 'downloaded' || WFU_USVAR('wfu_download_status_'.$id) == 'failed' ? true : false ) : false );
1072
+ if ( $upload_ended ) break;
1073
+ usleep(100);
1074
+ }
1075
+
1076
+ if ( $upload_ended ) {
1077
+ $upload_result = WFU_USVAR('wfu_download_status_'.$id);
1078
+ WFU_USVAR_unset('wfu_download_status_'.$id);
1079
+ $user = wp_get_current_user();
1080
+ // $filepath = wfu_plugin_decode_string($file_code);
1081
+ $filepath = wfu_get_filepath_from_safe($file_code);
1082
+ if ( $filepath === false ) die();
1083
+ $filepath = wfu_path_rel2abs(wfu_flatten_path($filepath));
1084
+ wfu_log_action('download', $filepath, $user->ID, '', 0, 0, '', null);
1085
+ /**
1086
+ * Customise Output of Download Monitoring Operation.
1087
+ *
1088
+ * This filter allows scripts to customise return of this function after
1089
+ * finish of it.
1090
+ *
1091
+ * @since 3.11.0
1092
+ *
1093
+ * @param string $echo_str The return of the function.
1094
+ */
1095
+ die(apply_filters('_wfu_ajax_action_download_file_monitor', 'wfu_ajax_action_download_file_monitor:'.$upload_result.':'));
1096
+ }
1097
+ else {
1098
+ //regenerate monitor ticket
1099
+ WFU_USVAR_store('wfu_download_monitor_ticket_'.$id, time() + 30);
1100
+ /** This filter is documented above. */
1101
+ die(apply_filters('_wfu_ajax_action_download_file_monitor', 'wfu_ajax_action_download_file_monitor:repeat:'.$id));
1102
+ }
1103
+ }
1104
+
1105
+ /**
1106
+ * Get View Log Page
1107
+ *
1108
+ * This function returns the HTML code of a specific page of View Log feature of
1109
+ * the plugin in Dashboard.
1110
+ *
1111
+ * @since 3.5.0
1112
+ */
1113
+ function wfu_ajax_action_get_historylog_page() {
1114
+ if ( !isset($_POST['token']) || !isset($_POST['page']) ) die();
1115
+ check_ajax_referer( 'wfu-historylog-page', 'token' );
1116
+ if ( !current_user_can( 'manage_options' ) ) die();
1117
+ if ( WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") <= 0 ) die();
1118
+
1119
+ $_POST = stripslashes_deep($_POST);
1120
+
1121
+ $page = wfu_sanitize_int($_POST['page']);
1122
+ $rows = wfu_view_log($page, true);
1123
+
1124
+ /**
1125
+ * Customise Output of View Log Page Retrieval.
1126
+ *
1127
+ * This filter allows scripts to customise return of this function after
1128
+ * finish of it.
1129
+ *
1130
+ * @since 3.11.0
1131
+ *
1132
+ * @param string $echo_str The return of the function.
1133
+ */
1134
+ die(apply_filters('_wfu_ajax_action_get_historylog_page', 'wfu_historylog_page_success:'.wfu_plugin_encode_string($rows)));
1135
+ }
1136
+
1137
+ /**
1138
+ * Get Uploaded Files Page
1139
+ *
1140
+ * This function returns the HTML code of a specific page of Uploaded Files area
1141
+ * of the plugin in Dashboard.
1142
+ *
1143
+ * @since 4.7.0
1144
+ */
1145
+ function wfu_ajax_action_get_uploadedfiles_page() {
1146
+ if ( !isset($_POST['token']) || !isset($_POST['page']) ) die();
1147
+ check_ajax_referer( 'wfu-uploadedfiles-page', 'token' );
1148
+ if ( !current_user_can( 'manage_options' ) ) die();
1149
+ if ( WFU_VAR("WFU_UPLOADEDFILES_TABLE_MAXROWS") <= 0 ) die();
1150
+
1151
+ $_POST = stripslashes_deep($_POST);
1152
+
1153
+ $page = wfu_sanitize_int($_POST['page']);
1154
+ $rows = wfu_uploadedfiles_manager($page, true);
1155
+
1156
+ /**
1157
+ * Customise Output of Uploaded Files Page Retrieval.
1158
+ *
1159
+ * This filter allows scripts to customise return of this function after
1160
+ * finish of it.
1161
+ *
1162
+ * @since 4.7.0
1163
+ *
1164
+ * @param string $echo_str The return of the function.
1165
+ */
1166
+ die(apply_filters('_wfu_ajax_action_get_uploadedfiles_page', 'wfu_uploadedfiles_page_success:'.wfu_plugin_encode_string($rows)));
1167
+ }
1168
+
1169
+ /**
1170
+ * Get File Browser Page
1171
+ *
1172
+ * This function returns the HTML code of a specific page of File Browser
1173
+ * feature of the plugin in Dashboard.
1174
+ *
1175
+ * @since 4.6.1
1176
+ */
1177
+ function wfu_ajax_action_get_adminbrowser_page() {
1178
+ if ( !isset($_POST['code']) || !isset($_POST['token']) || !isset($_POST['page']) ) die();
1179
+
1180
+ $_POST = stripslashes_deep($_POST);
1181
+
1182
+ check_ajax_referer( 'wfu-adminbrowser-page', 'token' );
1183
+ if ( !current_user_can( 'manage_options' ) ) die();
1184
+ if ( WFU_VAR("WFU_ADMINBROWSER_TABLE_MAXROWS") <= 0 ) die();
1185
+
1186
+ $code = wfu_sanitize_code($_POST['code']);
1187
+ $page = wfu_sanitize_int($_POST['page']);
1188
+ //get list of files
1189
+ $rows = wfu_browse_files($code, $page, true);
1190
+
1191
+ /**
1192
+ * Customise Output of File Browser Page Retrieval.
1193
+ *
1194
+ * This filter allows scripts to customise return of this function after
1195
+ * finish of it.
1196
+ *
1197
+ * @since 4.6.1
1198
+ *
1199
+ * @param string $echo_str The return of the function.
1200
+ */
1201
+ die(apply_filters('_wfu_ajax_action_get_adminbrowser_page', 'wfu_adminbrowser_page_success:'.wfu_plugin_encode_string($rows)));
1202
+ }
1203
+
1204
+ /**
1205
+ * Include a File in Plugin Database
1206
+ *
1207
+ * This function includes a file in the plugin database.
1208
+ *
1209
+ * @since 3.8.2
1210
+ */
1211
+ function wfu_ajax_action_include_file() {
1212
+ $_POST = stripslashes_deep($_POST);
1213
+ $_GET = stripslashes_deep($_GET);
1214
+
1215
+ $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
1216
+ $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
1217
+ if ( $file_code == '' || $nonce == '' ) die();
1218
+
1219
+ if ( !current_user_can( 'manage_options' ) ) die();
1220
+ //security check to avoid CSRF attacks
1221
+ if ( !wp_verify_nonce($nonce, 'wfu_include_file') ) die();
1222
+
1223
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1224
+ if ( $plugin_options['includeotherfiles'] != "1" ) die();
1225
+
1226
+ $dec_file = wfu_get_filepath_from_safe($file_code);
1227
+ if ( $dec_file === false ) die();
1228
+
1229
+ $user = wp_get_current_user();
1230
+ $dec_file = wfu_path_rel2abs(wfu_flatten_path($dec_file));
1231
+ $fileid = wfu_log_action('include', $dec_file, $user->ID, '', '', get_current_blog_id(), '', null);
1232
+
1233
+ if ( $fileid !== false ) {
1234
+ /**
1235
+ * Customise Output of File Inclusion Operation.
1236
+ *
1237
+ * This filter allows scripts to customise return of this function after
1238
+ * finish of it.
1239
+ *
1240
+ * @since 3.11.0
1241
+ *
1242
+ * @param string $echo_str The return of the function.
1243
+ */
1244
+ die(apply_filters('_wfu_ajax_action_include_file', "wfu_include_file:success:".$fileid));
1245
+ }
1246
+ /** This filter is documented above. */
1247
+ else die(apply_filters('_wfu_ajax_action_include_file', 'wfu_include_file:fail:'));
1248
+ }
1249
+
1250
+ /**
1251
+ * Update WPFilebase Manager Plugin
1252
+ *
1253
+ * This function instructs WPFilebase Manager plugin to synchronize its list of
1254
+ * files, after a file upload.
1255
+ *
1256
+ * @since 2.4.1
1257
+ */
1258
+ function wfu_ajax_action_notify_wpfilebase() {
1259
+ $_POST = stripslashes_deep($_POST);
1260
+ $_GET = stripslashes_deep($_GET);
1261
+
1262
+ $params_index = (isset($_POST['params_index']) ? $_POST['params_index'] : (isset($_GET['params_index']) ? $_GET['params_index'] : ''));
1263
+ $session_token = (isset($_POST['session_token']) ? $_POST['session_token'] : (isset($_GET['session_token']) ? $_GET['session_token'] : ''));
1264
+ if ( $params_index == '' || $session_token == '' ) die();
1265
+
1266
+ $params_index = sanitize_text_field($params_index);
1267
+ $session_token = sanitize_text_field($session_token);
1268
+
1269
+ $arr = wfu_get_params_fields_from_index($params_index, $session_token);
1270
+ //check referer using server sessions to avoid CSRF attacks
1271
+ if ( WFU_USVAR("wfu_token_".$arr['shortcode_id']) != $session_token ) die();
1272
+
1273
+ //execute WPFilebase plugin sunchronization by calling 'wpfilebase_sync'
1274
+ //action
1275
+ do_action('wpfilebase_sync');
1276
+
1277
+ die();
1278
+ }
1279
+
1280
+ /**
1281
+ * Get List of Users
1282
+ *
1283
+ * This function returns a list of users meeting specific criteria. Only the
1284
+ * first 100 users will be returned, for avoiding performance issues.
1285
+ *
1286
+ * @since 4.5.0
1287
+ */
1288
+ function wfu_ajax_action_pdusers_get_users() {
1289
+ $_POST = stripslashes_deep($_POST);
1290
+ $_GET = stripslashes_deep($_GET);
1291
+
1292
+ $nonce = (isset($_POST['nonce']) ? $_POST['nonce'] : (isset($_GET['nonce']) ? $_GET['nonce'] : ''));
1293
+ $query = (isset($_POST['query']) ? $_POST['query'] : (isset($_GET['query']) ? $_GET['query'] : ''));
1294
+ if ( $nonce == '' || $query == '' ) die();
1295
+
1296
+ if ( !current_user_can( 'manage_options' ) ) die();
1297
+ //security check to avoid CSRF attacks
1298
+ if ( !wp_verify_nonce($nonce, 'wfu_edit_policy') ) die();
1299
+
1300
+ $query = sanitize_text_field($query);
1301
+ $args = array(
1302
+ 'search' => $query,
1303
+ 'search_columns' => array( 'user_login', 'display_name' ),
1304
+ 'fields' => array( 'user_login', 'display_name' ),
1305
+ 'number' => 100
1306
+ );
1307
+ /** This filter is documented in lib/wfu_admin_browser.php */
1308
+ $args = apply_filters("_wfu_get_users", $args, "manage_pdusers");
1309
+ $users = get_users($args);
1310
+
1311
+ die("pdusers_get_users:".wfu_encode_array_to_string($users));
1312
+ }
1313
+
1314
+ ?>
lib/wfu_attributes.php CHANGED
@@ -1,5 +1,27 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_component_definitions() {
4
  $components = array(
5
  array(
@@ -89,6 +111,17 @@ function wfu_component_definitions() {
89
  return $components;
90
  }
91
 
 
 
 
 
 
 
 
 
 
 
 
92
  function wfu_category_definitions() {
93
  $cats = array(
94
  "general" => "General",
@@ -106,6 +139,16 @@ function wfu_category_definitions() {
106
  return $cats;
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
109
  function wfu_formfield_definitions() {
110
  //field properties have 2 parts separated by "/"; the first part determines if the property will be shown to the user (show or hide); the second part determines default value)
111
  //when making changes in the structure of formfield definitions, the following are affected:
@@ -618,6 +661,15 @@ function wfu_formfield_definitions() {
618
  return $formfields;
619
  }
620
 
 
 
 
 
 
 
 
 
 
621
  function wfu_attribute_definitions() {
622
  $defs = array(
623
  array(
1
  <?php
2
 
3
+ /**
4
+ * Definition of Various Attributes of the Plugin
5
+ *
6
+ * This file contains definition of shortcode and formfield attributes of the
7
+ * plugin.
8
+ *
9
+ * @link /lib/wfu_attributes.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 2.1.2
14
+ */
15
+
16
+ /**
17
+ * Definition of Uploader Form Elements
18
+ *
19
+ * This function defines the elements of the plugin upload form.
20
+ *
21
+ * @since 2.1.2
22
+ *
23
+ * @return array The list of uploader form elements (components).
24
+ */
25
  function wfu_component_definitions() {
26
  $components = array(
27
  array(
111
  return $components;
112
  }
113
 
114
+ /**
115
+ * Definition of Uploader Form Attribute Categories
116
+ *
117
+ * This function defines the categories of the plugin uploader shortcode
118
+ * attributes. These categories show up as different tabs of the shortcode
119
+ * composer.
120
+ *
121
+ * @since 2.1.2
122
+ *
123
+ * @return array The list of uploader form attribute categories.
124
+ */
125
  function wfu_category_definitions() {
126
  $cats = array(
127
  "general" => "General",
139
  return $cats;
140
  }
141
 
142
+ /**
143
+ * Definition of Uploader Form Custom Fields
144
+ *
145
+ * This function defines the plugin upload form custom fields and their
146
+ * attributes.
147
+ *
148
+ * @since 3.3.0
149
+ *
150
+ * @return array The list of upload form custom fields.
151
+ */
152
  function wfu_formfield_definitions() {
153
  //field properties have 2 parts separated by "/"; the first part determines if the property will be shown to the user (show or hide); the second part determines default value)
154
  //when making changes in the structure of formfield definitions, the following are affected:
661
  return $formfields;
662
  }
663
 
664
+ /**
665
+ * Definition of Uploader Form Attributes
666
+ *
667
+ * This function defines the plugin uploader shortcode attributes.
668
+ *
669
+ * @since 2.1.2
670
+ *
671
+ * @return array The list of uploader form attributes.
672
+ */
673
  function wfu_attribute_definitions() {
674
  $defs = array(
675
  array(
lib/wfu_blocks.php CHANGED
@@ -1,6 +1,34 @@
1
  <?php
2
 
3
- /* Prepare the uploadform generic element */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  function wfu_prepare_base_block($params, $additional_params, $occurrence_index) {
5
  //prepare data for template
6
  $data["ID"] = $params["uploadid"];
@@ -18,7 +46,22 @@ function wfu_prepare_base_block($params, $additional_params, $occurrence_index)
18
  return $base_item;
19
  }
20
 
21
- /* Prepare the visual editor button */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  function wfu_prepare_visualeditorbutton_block($params, $additional_params, $occurrence_index) {
23
  if ( isset($params["uploadid"]) ) {
24
  $ID = $params["uploadid"];
@@ -54,7 +97,22 @@ function wfu_prepare_visualeditorbutton_block($params, $additional_params, $occu
54
  }
55
 
56
 
57
- /* Prepare information about directory or selection of target subdirectory */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  function wfu_prepare_subfolders_block($params, $additional_params, $occurrence_index) {
59
  //prepare data for template
60
  $data["ID"] = $params["uploadid"];
@@ -114,7 +172,22 @@ function wfu_prepare_subfolders_block($params, $additional_params, $occurrence_i
114
  return $subfolders_item;
115
  }
116
 
117
- /* Prepare the title */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  function wfu_prepare_title_block($params, $additional_params, $occurrence_index) {
119
  //prepare data for template
120
  $data["ID"] = $params["uploadid"];
@@ -142,7 +215,22 @@ function wfu_prepare_title_block($params, $additional_params, $occurrence_index)
142
  return $title_item;
143
  }
144
 
145
- /* Prepare the text box showing filename */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  function wfu_prepare_textbox_block($params, $additional_params, $occurrence_index) {
147
  //prepare data for template
148
  $data["ID"] = $params["uploadid"];
@@ -174,7 +262,22 @@ function wfu_prepare_textbox_block($params, $additional_params, $occurrence_inde
174
  return $textbox_item;
175
  }
176
 
177
- /* Prepare the upload form (required) */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  function wfu_prepare_uploadform_block($params, $additional_params, $occurrence_index) {
179
  //prepare data for template
180
  $data["ID"] = $params["uploadid"];
@@ -229,7 +332,22 @@ function wfu_prepare_uploadform_block($params, $additional_params, $occurrence_i
229
  return $uploadform_item;
230
  }
231
 
232
- /* Prepare the submit button */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  function wfu_prepare_submit_block($params, $additional_params, $occurrence_index) {
234
  //prepare data for template
235
  $data["ID"] = $params["uploadid"];
@@ -265,7 +383,22 @@ function wfu_prepare_submit_block($params, $additional_params, $occurrence_index
265
  }
266
 
267
 
268
- /* Prepare the webcam */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  function wfu_prepare_webcam_block($params, $additional_params, $occurrence_index) {
270
  //prepare data for template
271
  $data["ID"] = $params["uploadid"];
@@ -314,7 +447,22 @@ function wfu_prepare_webcam_block($params, $additional_params, $occurrence_index
314
  return $webcam_item;
315
  }
316
 
317
- /* Prepare the progress bar */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  function wfu_prepare_progressbar_block($params, $additional_params, $occurrence_index) {
319
  //prepare data for template
320
  $data["ID"] = $params["uploadid"];
@@ -345,7 +493,22 @@ function wfu_prepare_progressbar_block($params, $additional_params, $occurrence_
345
  return $progressbar_item;
346
  }
347
 
348
- /* Prepare the message block */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  function wfu_prepare_message_block($params, $additional_params, $occurrence_index) {
350
  //prepare data for template
351
  $data["ID"] = $params["uploadid"];
@@ -471,7 +634,22 @@ function wfu_prepare_message_block($params, $additional_params, $occurrence_inde
471
  return $message_item;
472
  }
473
 
474
- /* Prepare the user data block */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  function wfu_prepare_userdata_block($params, $additional_params, $occurrence_index) {
476
  $data["ID"] = $params["uploadid"];
477
  $data["width"] = $additional_params['widths']['userdata'];
@@ -585,7 +763,22 @@ function wfu_prepare_userdata_block($params, $additional_params, $occurrence_ind
585
  return $userdata_item;
586
  }
587
 
588
- /* Prepare the consent question block */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  function wfu_prepare_consent_block($params, $additional_params, $occurrence_index) {
590
  //prepare data for template
591
  $data["ID"] = $params["uploadid"];
1
  <?php
2
 
3
+ /**
4
+ * Plugin Upload Form Blocks
5
+ *
6
+ * This file contains functions related to preparation of the elements of the
7
+ * upload form of the plugin.
8
+ *
9
+ * @link /lib/wfu_blocks.php
10
+ *
11
+ * @package WordPress File Upload Plugin
12
+ * @subpackage Core Components
13
+ * @since 2.1.2
14
+ */
15
+
16
+ /**
17
+ * Prepare the Upload Form Generic Element.
18
+ *
19
+ * This function prepares the display properties of the generic top-level
20
+ * element of the plugin's upload form.
21
+ *
22
+ * @since 4.1.0
23
+ *
24
+ * @param array $params The uploader shortcode attributes.
25
+ * @param array $additional_params A list of additional parameters passed to the
26
+ * function.
27
+ * @param integer $occurrence_index The occurrence index of this element inside
28
+ * the upload form.
29
+ *
30
+ * @return array The display properties of the generic top-level element.
31
+ */
32
  function wfu_prepare_base_block($params, $additional_params, $occurrence_index) {
33
  //prepare data for template
34
  $data["ID"] = $params["uploadid"];
46
  return $base_item;
47
  }
48
 
49
+ /**
50
+ * Prepare the Upload Form Visual Editor Element.
51
+ *
52
+ * This function prepares the display properties of the visual editor element of
53
+ * the plugin's upload form.
54
+ *
55
+ * @since 4.0.0
56
+ *
57
+ * @param array $params The uploader shortcode attributes.
58
+ * @param array $additional_params A list of additional parameters passed to the
59
+ * function.
60
+ * @param integer $occurrence_index The occurrence index of this element inside
61
+ * the upload form.
62
+ *
63
+ * @return array The display properties of the visual editor element.
64
+ */
65
  function wfu_prepare_visualeditorbutton_block($params, $additional_params, $occurrence_index) {
66
  if ( isset($params["uploadid"]) ) {
67
  $ID = $params["uploadid"];
97
  }
98
 
99
 
100
+ /**
101
+ * Prepare the Upload Form Subfolders Element.
102
+ *
103
+ * This function prepares the display properties of the subfolders element of
104
+ * the plugin's upload form.
105
+ *
106
+ * @since 2.1.2
107
+ *
108
+ * @param array $params The uploader shortcode attributes.
109
+ * @param array $additional_params A list of additional parameters passed to the
110
+ * function.
111
+ * @param integer $occurrence_index The occurrence index of this element inside
112
+ * the upload form.
113
+ *
114
+ * @return array The display properties of the subfolders element.
115
+ */
116
  function wfu_prepare_subfolders_block($params, $additional_params, $occurrence_index) {
117
  //prepare data for template
118
  $data["ID"] = $params["uploadid"];
172
  return $subfolders_item;
173
  }
174
 
175
+ /**
176
+ * Prepare the Upload Form Title Element.
177
+ *
178
+ * This function prepares the display properties of the title element of the
179
+ * plugin's upload form.
180
+ *
181
+ * @since 2.1.2
182
+ *
183
+ * @param array $params The uploader shortcode attributes.
184
+ * @param array $additional_params A list of additional parameters passed to the
185
+ * function.
186
+ * @param integer $occurrence_index The occurrence index of this element inside
187
+ * the upload form.
188
+ *
189
+ * @return array The display properties of the title element.
190
+ */
191
  function wfu_prepare_title_block($params, $additional_params, $occurrence_index) {
192
  //prepare data for template
193
  $data["ID"] = $params["uploadid"];
215
  return $title_item;
216
  }
217
 
218
+ /**
219
+ * Prepare the Upload Form Filename Element.
220
+ *
221
+ * This function prepares the display properties of the filename (textbox)
222
+ * element of the plugin's upload form.
223
+ *
224
+ * @since 2.1.2
225
+ *
226
+ * @param array $params The uploader shortcode attributes.
227
+ * @param array $additional_params A list of additional parameters passed to the
228
+ * function.
229
+ * @param integer $occurrence_index The occurrence index of this element inside
230
+ * the upload form.
231
+ *
232
+ * @return array The display properties of the filename element.
233
+ */
234
  function wfu_prepare_textbox_block($params, $additional_params, $occurrence_index) {
235
  //prepare data for template
236
  $data["ID"] = $params["uploadid"];
262
  return $textbox_item;
263
  }
264
 
265
+ /**
266
+ * Prepare the Upload Form Main Form Element.
267
+ *
268
+ * This function prepares the display properties of the form element of the
269
+ * plugin's upload form. This element also contains the select button element.
270
+ *
271
+ * @since 2.1.2
272
+ *
273
+ * @param array $params The uploader shortcode attributes.
274
+ * @param array $additional_params A list of additional parameters passed to the
275
+ * function.
276
+ * @param integer $occurrence_index The occurrence index of this element inside
277
+ * the upload form.
278
+ *
279
+ * @return array The display properties of the main form element.
280
+ */
281
  function wfu_prepare_uploadform_block($params, $additional_params, $occurrence_index) {
282
  //prepare data for template
283
  $data["ID"] = $params["uploadid"];
332
  return $uploadform_item;
333
  }
334
 
335
+ /**
336
+ * Prepare the Upload Form Submit Button Element.
337
+ *
338
+ * This function prepares the display properties of the submit button element of
339
+ * the plugin's upload form.
340
+ *
341
+ * @since 2.1.2
342
+ *
343
+ * @param array $params The uploader shortcode attributes.
344
+ * @param array $additional_params A list of additional parameters passed to the
345
+ * function.
346
+ * @param integer $occurrence_index The occurrence index of this element inside
347
+ * the upload form.
348
+ *
349
+ * @return array The display properties of the submit button element.
350
+ */
351
  function wfu_prepare_submit_block($params, $additional_params, $occurrence_index) {
352
  //prepare data for template
353
  $data["ID"] = $params["uploadid"];
383
  }
384
 
385
 
386
+ /**
387
+ * Prepare the Upload Form Webcam Element.
388
+ *
389
+ * This function prepares the display properties of the webcam element of the
390
+ * plugin's upload form.
391
+ *
392
+ * @since 3.8.0
393
+ *
394
+ * @param array $params The uploader shortcode attributes.
395
+ * @param array $additional_params A list of additional parameters passed to the
396
+ * function.
397
+ * @param integer $occurrence_index The occurrence index of this element inside
398
+ * the upload form.
399
+ *
400
+ * @return array The display properties of the webcam element.
401
+ */
402
  function wfu_prepare_webcam_block($params, $additional_params, $occurrence_index) {
403
  //prepare data for template
404
  $data["ID"] = $params["uploadid"];
447
  return $webcam_item;
448
  }
449
 
450
+ /**
451
+ * Prepare the Upload Form Progress Bar Element.
452
+ *
453
+ * This function prepares the display properties of the progress bar element of
454
+ * the plugin's upload form.
455
+ *
456
+ * @since 3.8.0
457
+ *
458
+ * @param array $params The uploader shortcode attributes.
459
+ * @param array $additional_params A list of additional parameters passed to the
460
+ * function.
461
+ * @param integer $occurrence_index The occurrence index of this element inside
462
+ * the upload form.
463
+ *
464
+ * @return array The display properties of the progress bar element.
465
+ */
466
  function wfu_prepare_progressbar_block($params, $additional_params, $occurrence_index) {
467
  //prepare data for template
468
  $data["ID"] = $params["uploadid"];
493
  return $progressbar_item;
494
  }
495
 
496
+ /**
497
+ * Prepare the Upload Form Message Element.
498
+ *
499
+ * This function prepares the display properties of the message element of the
500
+ * plugin's upload form.
501
+ *
502
+ * @since 2.1.2
503
+ *
504
+ * @param array $params The uploader shortcode attributes.
505
+ * @param array $additional_params A list of additional parameters passed to the
506
+ * function.
507
+ * @param integer $occurrence_index The occurrence index of this element inside
508
+ * the upload form.
509
+ *
510
+ * @return array The display properties of the message element.
511
+ */
512
  function wfu_prepare_message_block($params, $additional_params, $occurrence_index) {
513
  //prepare data for template
514
  $data["ID"] = $params["uploadid"];
634
  return $message_item;
635
  }
636
 
637
+ /**
638
+ * Prepare the Upload Form User Data Element.
639
+ *
640
+ * This function prepares the display properties of the user data element of the
641
+ * plugin's upload form.
642
+ *
643
+ * @since 2.1.2
644
+ *
645
+ * @param array $params The uploader shortcode attributes.
646
+ * @param array $additional_params A list of additional parameters passed to the
647
+ * function.
648
+ * @param integer $occurrence_index The occurrence index of this element inside
649
+ * the upload form.
650
+ *
651
+ * @return array The display properties of the user data element.
652
+ */
653
  function wfu_prepare_userdata_block($params, $additional_params, $occurrence_index) {
654
  $data["ID"] = $params["uploadid"];
655
  $data["width"] = $additional_params['widths']['userdata'];
763
  return $userdata_item;
764
  }
765
 
766
+ /**
767
+ * Prepare the Upload Form Consent Element.
768
+ *
769
+ * This function prepares the display properties of the consent element of the
770
+ * plugin's upload form.
771
+ *
772
+ * @since 4.5.0
773
+ *
774
+ * @param array $params The uploader shortcode attributes.
775
+ * @param array $additional_params A list of additional parameters passed to the
776
+ * function.
777
+ * @param integer $occurrence_index The occurrence index of this element inside
778
+ * the upload form.
779
+ *
780
+ * @return array The display properties of the consent element.
781
+ */
782
  function wfu_prepare_consent_block($params, $additional_params, $occurrence_index) {
783
  //prepare data for template
784
  $data["ID"] = $params["uploadid"];
lib/wfu_constants.php CHANGED
@@ -1,467 +1,503 @@
1
- <?php
2
-
3
- $siteurl = site_url();
4
-
5
- /************ Translatable Strings ************/
6
- function wfu_initialize_i18n_strings() {
7
- if ( defined("WFU_I18_LOADED") ) return;
8
- DEFINE("WFU_I18_LOADED", 1);
9
- //plugin default values
10
- DEFINE("WFU_UPLOADTITLE", __('Upload files', 'wp-file-upload'));
11
- DEFINE("WFU_SELECTBUTTON", __('Select File', 'wp-file-upload'));
12
- DEFINE("WFU_UPLOADBUTTON", __('Upload File', 'wp-file-upload'));
13
- DEFINE("WFU_NOTIFYSUBJECT", __('File Upload Notification', 'wp-file-upload'));
14
- DEFINE("WFU_NOTIFYMESSAGE", __("Dear Recipient,%n%%n% This is an automatic delivery message to notify you that a new file has been uploaded.%n%%n%Best Regards", 'wp-file-upload'));
15
- DEFINE("WFU_SUCCESSMESSAGE", __('File %filename% uploaded successfully', 'wp-file-upload'));
16
- DEFINE("WFU_WARNINGMESSAGE", __('File %filename% uploaded successfully but with warnings', 'wp-file-upload'));
17
- DEFINE("WFU_ERRORMESSAGE", __('File %filename% not uploaded', 'wp-file-upload'));
18
- DEFINE("WFU_WAITMESSAGE", __('File %filename% is being uploaded', 'wp-file-upload'));
19
- DEFINE("WFU_USERDATALABEL", __('Your message', 'wp-file-upload')."|t:text|s:left|r:0|a:0|p:inline|d:");
20
- DEFINE("WFU_CAPTCHAPROMPT", __('Please fill in the above words: ', 'wp-file-upload'));
21
- DEFINE("WFU_UPLOADMEDIABUTTON", __('Upload Media', 'wp-file-upload'));
22
- DEFINE("WFU_VIDEONAME", __('videostream', 'wp-file-upload'));
23
- DEFINE("WFU_IMAGENAME", __('screenshot', 'wp-file-upload'));
24
- DEFINE("WFU_CONSENTQUESTION", __('By activating this option I agree to let the website keep my personal data', 'wp-file-upload'));
25
- DEFINE("WFU_CONSENTREJECTMESSAGE", __('You have denied to let the website keep your personal data. Upload cannot continue!', 'wp-file-upload'));
26
- //browser default values
27
- DEFINE("WFU_FILETITLE", __('File', 'wp-file-upload'));
28
- DEFINE("WFU_DATETITLE", __('Date', 'wp-file-upload'));
29
- DEFINE("WFU_SIZETITLE", __('Size', 'wp-file-upload'));
30
- DEFINE("WFU_USERTITLE", __('User', 'wp-file-upload'));
31
- DEFINE("WFU_POSTTITLE", __('Page', 'wp-file-upload'));
32
- DEFINE("WFU_FIELDSTITLE", __('User Fields', 'wp-file-upload'));
33
- DEFINE("WFU_DOWNLOADLABEL", __('Download', 'wp-file-upload'));
34
- DEFINE("WFU_DOWNLOADTITLE", __('Download this file', 'wp-file-upload'));
35
- DEFINE("WFU_DELETELABEL", __('Delete', 'wp-file-upload'));
36
- DEFINE("WFU_DELETETITLE", __('Delete this file', 'wp-file-upload'));
37
- DEFINE("WFU_SORTTITLE", __('Sort list based on this column', 'wp-file-upload'));
38
- DEFINE("WFU_GUESTTITLE", __('guest', 'wp-file-upload'));
39
- DEFINE("WFU_UNKNOWNTITLE", __('unknown', 'wp-file-upload'));
40
- //error messages
41
- DEFINE("WFU_ERROR_ADMIN_FTPDIR_RESOLVE", __("Error. Could not resolve ftp target filedir. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
42
- DEFINE("WFU_ERROR_ADMIN_FTPINFO_INVALID", __("Error. Invalid ftp information. Check 'ftpinfo' attribute.", "wp-file-upload"));
43
- DEFINE("WFU_ERROR_ADMIN_FTPINFO_EXTRACT", __("Error. Could not extract ftp information from 'ftpinfo' attribute. Check its syntax.", "wp-file-upload"));
44
- DEFINE("WFU_ERROR_ADMIN_FTPFILE_RESOLVE", __("Error. Could not resolve ftp target filename. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
45
- DEFINE("WFU_ERROR_ADMIN_FTPSOURCE_FAIL", __("Error. Could not open source file for ftp upload. Check if file is accessible.", "wp-file-upload"));
46
- DEFINE("WFU_ERROR_ADMIN_FTPTRANSFER_FAIL", __("Error. Could not send data to ftp target file.", "wp-file-upload"));
47
- DEFINE("WFU_ERROR_ADMIN_FTPHOST_FAIL", __("Error. Could not connect to ftp host. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
48
- DEFINE("WFU_ERROR_ADMIN_FTPLOGIN_FAIL", __("Error. Could not authenticate to ftp host. Check username and password in 'ftpinfo' attribute.", "wp-file-upload"));
49
- DEFINE("WFU_ERROR_ADMIN_SFTPINIT_FAIL", __("Error. Could not initialize sftp subsystem. Please check if the server supports sftp.", "wp-file-upload"));
50
- DEFINE("WFU_ERROR_ADMIN_SFTP_UNSUPPORTED", __("Error. The web server does not support sftp.", "wp-file-upload"));
51
- DEFINE("WFU_ERROR_ADMIN_FILE_PHP_SIZE", __("Error. The upload size limit of PHP directive upload_max_filesize is preventing the upload of big files.\nPHP directive upload_max_filesize limit is: ".ini_get("upload_max_filesize").".\nTo increase the limit change the value of the directive from php.ini.\nIf you don't have access to php.ini, then try adding the following line to your .htaccess file:\n\nphp_value upload_max_filesize 10M\n\n(adjust the size according to your needs)\n\nThe file .htaccess is found in your website root directory (where index.php is found).\nIf your don't have this file, then create it.\nIf this does not work either, then contact your domain provider.", "wp-file-upload"));
52
- DEFINE("WFU_ERROR_ADMIN_FILE_PHP_TIME", __("The upload time limit of PHP directive max_input_time is preventing the upload of big files.\nPHP directive max_input_time limit is: ".ini_get("max_input_time")." seconds.\nTo increase the limit change the value of the directive from php.ini.\nIf you don't have access to php.ini, then add the following line to your .htaccess file:\n\nphp_value max_input_time 500\n\n(adjust the time according to your needs)\n\nThe file .htaccess is found in your website root directory (where index.php is found).\nIf your don't have this file, then create it.\nIf this does not work either, then contact your domain provider.", "wp-file-upload"));
53
- DEFINE("WFU_ERROR_ADMIN_DIR_PERMISSION", __("Error. Permission denied to write to target folder.\nCheck and correct read/write permissions of target folder.", "wp-file-upload"));
54
- DEFINE("WFU_ERROR_ADMIN_FILE_WRONGEXT", __("Error. This file was rejected because its extension is not correct. Its proper filename is: ", "wp-file-upload"));
55
- DEFINE("WFU_ERROR_ADMIN_DOS_ATTACK", __("Too many files are uploaded in a short period of time. This may be a Denial-Of-Service attack, so file was rejected. Please check the upload log for suspicious behaviour.", "wp-file-upload"));
56
- DEFINE("WFU_ERROR_DOS_ATTACK", __("File not uploaded in order to prevent overflow of the website. Please contact administrator.", "wp-file-upload"));
57
- DEFINE("WFU_ERROR_DIR_EXIST", __("Target folder doesn't exist.", "wp-file-upload"));
58
- DEFINE("WFU_ERROR_DIR_NOTEMP", __("Upload failed! Missing a temporary folder.", "wp-file-upload"));
59
- DEFINE("WFU_ERROR_DIR_PERMISSION", __("Upload failed! Permission denied to write to target folder.", "wp-file-upload"));
60
- DEFINE("WFU_ERROR_FILE_ALLOW", __("File not allowed.", "wp-file-upload"));
61
- DEFINE("WFU_ERROR_FILE_REJECT", __("File is suspicious and was rejected.", "wp-file-upload"));
62
- DEFINE("WFU_ERROR_FILE_PLUGIN_SIZE", __("The uploaded file exceeds the file size limit.", "wp-file-upload"));
63
- DEFINE("WFU_ERROR_FILE_PLUGIN_2GBSIZE", __("The uploaded file exceeds 2GB and is not supported by this server.", "wp-file-upload"));
64
- DEFINE("WFU_ERROR_FILE_PHP_SIZE", __("Upload failed! The uploaded file exceeds the file size limit of the server. Please contact the administrator.", "wp-file-upload"));
65
- DEFINE("WFU_ERROR_FILE_PHP_TIME", __("Upload failed! The duration of the upload exceeded the time limit of the server. Please contact the administrator.", "wp-file-upload"));
66
- DEFINE("WFU_ERROR_FILE_HTML_SIZE", __("Upload failed! The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.", "wp-file-upload"));
67
- DEFINE("WFU_ERROR_FILE_PARTIAL", __("Upload failed! The uploaded file was only partially uploaded.", "wp-file-upload"));
68
- DEFINE("WFU_ERROR_FILE_NOTHING", __("Upload failed! No file was uploaded.", "wp-file-upload"));
69
- DEFINE("WFU_ERROR_FILE_WRITE", __("Upload failed! Failed to write file to disk.", "wp-file-upload"));
70
- DEFINE("WFU_ERROR_FILE_MOVE", __("Upload failed! Error occured while moving temporary file. Please contact administrator.", "wp-file-upload"));
71
- DEFINE("WFU_ERROR_FILE_CANCELLED", __("Upload cancelled!", "wp-file-upload"));
72
- DEFINE("WFU_ERROR_UPLOAD_STOPPED", __("Upload failed! A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.", "wp-file-upload"));
73
- DEFINE("WFU_ERROR_UPLOAD_FAILED_WHILE", __("Upload failed! Error occured while attemting to upload the file.", "wp-file-upload"));
74
- DEFINE("WFU_ERROR_UPLOAD_FAILED", __("Upload failed!", "wp-file-upload"));
75
- DEFINE("WFU_ERROR_UPLOAD_NOFILESELECTED", __("No file!", "wp-file-upload"));
76
- DEFINE("WFU_ERROR_UPLOAD_CANCELLED", __("Upload failed! The upload has been canceled by the user or the browser dropped the connection.", "wp-file-upload"));
77
- DEFINE("WFU_ERROR_UNKNOWN", __("Upload failed! Unknown error.", "wp-file-upload"));
78
- DEFINE("WFU_ERROR_CONTACT_ADMIN", __("Please contact the administrator.", "wp-file-upload"));
79
- DEFINE("WFU_ERROR_REMOTESERVER_NORESULT", __("No result from remote server!", "wp-file-upload"));
80
- DEFINE("WFU_ERROR_JSONPARSE_FILEMESSAGE", __(" but with warnings", "wp-file-upload"));
81
- DEFINE("WFU_ERROR_JSONPARSE_MESSAGE", __("Warning: JSON parse error.", "wp-file-upload"));
82
- DEFINE("WFU_ERROR_JSONPARSE_ADMINMESSAGE", __("Upload parameters of this file, passed as JSON string to the handler, could not be parsed.", "wp-file-upload"));
83
- DEFINE("WFU_ERROR_JSONPARSE_HEADERMESSAGE", __("Warning: JSON parse error.", "wp-file-upload"));
84
- DEFINE("WFU_ERROR_JSONPARSE_HEADERADMINMESSAGE", __("UploadStates, passed as JSON string to the handler, could not be parsed.", "wp-file-upload"));
85
- DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE0", __("Redirection to classic form functionality occurred due to unknown error.", "wp-file-upload"));
86
- DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE1", __("Redirection to classic form functionality occurred because AJAX is not supported.", "wp-file-upload"));
87
- DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE2", __("Redirection to classic form functionality occurred because HTML5 is not supported.", "wp-file-upload"));
88
- DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE3", __("Redirection to classic form functionality occurred due to JSON parse error.", "wp-file-upload"));
89
- DEFINE("WFU_ERROR_ENABLE_POPUPS", __("Please enable popup windows from the browser's settings!", "wp-file-upload"));
90
- DEFINE("WFU_ERROR_USERDATA_EMPTY", __("cannot be empty!", "wp-file-upload"));
91
- DEFINE("WFU_ERROR_USERDATANUMBER_INVALID", __("number not valid!", "wp-file-upload"));
92
- DEFINE("WFU_ERROR_USERDATAEMAIL_INVALID", __("email not valid!", "wp-file-upload"));
93
- DEFINE("WFU_ERROR_USERDATACONFIRMEMAIL_NOMATCH", __("emails do not match!", "wp-file-upload"));
94
- DEFINE("WFU_ERROR_USERDATACONFIRMEMAIL_NOBASE", __("no base email field in group!", "wp-file-upload"));
95
- DEFINE("WFU_ERROR_USERDATACONFIRMPASSWORD_NOMATCH", __("passwords do not match!", "wp-file-upload"));
96
- DEFINE("WFU_ERROR_USERDATACONFIRMPASSWORD_NOBASE", __("no base password field in group!", "wp-file-upload"));
97
- DEFINE("WFU_ERROR_USERDATACHECKBOX_NOTCHECKED", __("checkbox unchecked!", "wp-file-upload"));
98
- DEFINE("WFU_ERROR_USERDATARADIO_NOTSELECTED", __("no option selected!", "wp-file-upload"));
99
- DEFINE("WFU_ERROR_USERDATALIST_NOITEMSELECTED", __("no item selected!", "wp-file-upload"));
100
- DEFINE("WFU_ERROR_SAME_PLUGINID", __("There are more than one instances of the plugin in this page with the same id. Please change it.", "wp-file-upload"));
101
- DEFINE("WFU_ERROR_PAGE_OBSOLETE", __("Cannot edit the shortcode because the page has been modified. Please reload the page.", "wp-file-upload"));
102
- DEFINE("WFU_ERROR_WEBCAM_NOTSUPPORTED", __("Your browser does not support webcam capture!", "wp-file-upload"));
103
- DEFINE("WFU_ERROR_WEBCAM_VIDEO_NOTSUPPORTED", __("Your browser does not support video recording from the webcam!", "wp-file-upload"));
104
- DEFINE("WFU_ERROR_WEBCAM_VIDEO_NOTHINGRECORDED", __("No video was recorded!", "wp-file-upload"));
105
- DEFINE("WFU_ERROR_CAPTCHA_OLDPHP", __("ERROR: Captcha not supported! You have an old PHP version. Upgrade your PHP or use RecaptchaV2 (no account).", "wp-file-upload"));
106
- DEFINE("WFU_ERROR_CAPTCHA_MULTIPLE_NOTALLOWED", __("ERROR: Only one instance of RecaptchaV1 can exist on the same page. Please notify administrator.", "wp-file-upload"));
107
- DEFINE("WFU_ERROR_CAPTCHA_MULTIPLE_NOTALLOWED_ADMIN", __("ERROR: Only one instance of RecaptchaV1 can exist on the same page. Please use RecaptchaV1 (no account).", "wp-file-upload"));
108
- DEFINE("WFU_ERROR_CAPTCHA_NOSITEKEY", __("ERROR: No site key. Please contact administrator!", "wp-file-upload"));
109
- DEFINE("WFU_ERROR_CAPTCHA_NOSITEKEY_ADMIN", __("ERROR: No site key defined! Please go to the plugin settings in Dashboard to define Google Recaptcha keys.", "wp-file-upload"));
110
- DEFINE("WFU_ERROR_CAPTCHA_NOCHALLENGE", __("Bad captcha image!", "wp-file-upload"));
111
- DEFINE("WFU_ERROR_CAPTCHA_NOINPUT", __("No input!", "wp-file-upload"));
112
- DEFINE("WFU_ERROR_CAPTCHA_EMPTY", __("Captcha not completed!", "wp-file-upload"));
113
- DEFINE("WFU_ERROR_CAPTCHA_WRONGCAPTCHA", __("Wrong captcha!", "wp-file-upload"));
114
- DEFINE("WFU_ERROR_CAPTCHA_REFRESHING", __("Error refreshing captcha!", "wp-file-upload"));
115
- DEFINE("WFU_ERROR_CAPTCHA_UNKNOWNERROR", __("Unknown captcha error!", "wp-file-upload"));
116
- DEFINE("WFU_ERROR_CAPTCHA_NOTSUPPORTED", __("Captcha not supported by your browser!", "wp-file-upload"));
117
- DEFINE("WFU_ERROR_CAPTCHA_MISSINGINPUTSECRET", __("the secret parameter is missing", "wp-file-upload"));
118
- DEFINE("WFU_ERROR_CAPTCHA_INVALIDINPUTSECRET", __("the secret parameter is invalid or malformed", "wp-file-upload"));
119
- DEFINE("WFU_ERROR_CAPTCHA_MISSINGINPUTRESPONSE", __("the response parameter is missing", "wp-file-upload"));
120
- DEFINE("WFU_ERROR_CAPTCHA_INVALIDINPUTRESPONSE", __("the response parameter is invalid or malformed", "wp-file-upload"));
121
- DEFINE("WFU_ERROR_REDIRECTION_NODRAGDROP", __("Please do not use drag drop due to an internal problem.", "wp-file-upload"));
122
- DEFINE("WFU_ERROR_CHUNKEDUPLOAD_UNIQUEIDEMPTY", __("Error during chunked upload. Unique ID empty in chunk %d", "wp-file-upload"));
123
- DEFINE("WFU_ERROR_CHUNKEDUPLOAD_NOTALLOWED", __("Chunked upload is not allowed!", "wp-file-upload"));
124
- DEFINE("WFU_ERROR_CHUNKEDUPLOAD_ABORTED", __("Chunked upload aborted due to error in previous chunk!", "wp-file-upload"));
125
- DEFINE("WFU_ERROR_CHUNKEDUPLOAD_CONCATFAILED", __("Chunked upload failed, final file could not be created!", "wp-file-upload"));
126
- DEFINE("WFU_ERROR_ADMIN_CHUNKWRITEFAILED", __("Could not write file chuck to destination on chunk %d", "wp-file-upload"));
127
- DEFINE("WFU_ERROR_ADMIN_CHUNKENLARGEFAILED", __("Could not enlarge destination file on chunk %d", "wp-file-upload"));
128
- DEFINE("WFU_ERROR_ADMIN_CHUNKHANDLEFAILED", __("Could not open file handles on chunk %d", "wp-file-upload"));
129
- DEFINE("WFU_BROWSER_DOWNLOADFILE_NOTALLOWED", __("You are not allowed to download this file!", "wp-file-upload"));
130
- DEFINE("WFU_BROWSER_DOWNLOADFILE_NOTEXIST", __("File does not exist!", "wp-file-upload"));
131
- DEFINE("WFU_BROWSER_DOWNLOADFILE_FAILED", __("Could not download file!", "wp-file-upload"));
132
- DEFINE("WFU_BROWSER_DELETEFILE_NOTALLOWED", __("You are not allowed to delete this file!", "wp-file-upload"));
133
- DEFINE("WFU_BROWSER_DELETEFILE_FAILED", __("File was not deleted!", "wp-file-upload"));
134
- DEFINE("WFU_BROWSER_DELETEFILES_ALLFAILED", __("No file was deleted!", "wp-file-upload"));
135
- DEFINE("WFU_BROWSER_DELETEFILES_SOMEFAILED", __("Some files were not deleted!", "wp-file-upload"));
136
- //warning messages
137
- DEFINE("WFU_WARNING_FILE_EXISTS", __("Upload skipped! File already exists.", "wp-file-upload"));
138
- DEFINE("WFU_WARNING_FILE_SUSPICIOUS", __("The extension of the file does not match its contents.", "wp-file-upload"));
139
- DEFINE("WFU_WARNING_ADMIN_FILE_SUSPICIOUS", __("Upload succeeded but the file is suspicious because its contents do not match its extension. Its proper filename is: ", "wp-file-upload"));
140
- DEFINE("WFU_WARNING_NOFILES_SELECTED", __("No files have been selected!", "wp-file-upload"));
141
- DEFINE("WFU_WARNING_CONSENT_NOTCOMPLETED", __("Please complete the consent question before continuing the upload!", "wp-file-upload"));
142
- DEFINE("WFU_WARNING_WPFILEBASE_NOTUPDATED_NOFILES", __("WPFilebase Plugin not updated because there were no files uploaded.", "wp-file-upload"));
143
- DEFINE("WFU_WARNING_NOTIFY_NOTSENT_NOFILES", __("Notification email was not sent because there were no files uploaded.", "wp-file-upload"));
144
- DEFINE("WFU_WARNING_NOTIFY_NOTSENT_NORECIPIENTS", __("Notification email was not sent because no recipients were defined. Please check notifyrecipients attribute in the shortcode.", "wp-file-upload"));
145
- DEFINE("WFU_WARNING_NOTIFY_NOTSENT_UNKNOWNERROR", __("Notification email was not sent due to an error. Please check notifyrecipients, notifysubject and notifymessage attributes for errors.", "wp-file-upload"));
146
- DEFINE("WFU_WARNING_REDIRECT_NOTEXECUTED_EMPTY", __("Redirection not executed because redirection link is empty. Please check redirectlink attribute.", "wp-file-upload"));
147
- DEFINE("WFU_WARNING_REDIRECT_NOTEXECUTED_FILESFAILED", __("Redirection not executed because not all files were successfully uploaded.", "wp-file-upload"));
148
- DEFINE("WFU_WARNING_POTENTIAL_DOS_EMAIL_SUBJECT", __("Potential Denial-Of-Service Attack on {SITE}", "wp-file-upload"));
149
- DEFINE("WFU_WARNING_POTENTIAL_DOS_EMAIL_MESSAGE", __("Hello admin\n\nThis is a message from Wordpress File Upload Plugin to notify you that a potential Denial-Of-Service attack has been detected on {SITE}.\n\nThe plugin detected more than {FILENUM} uploads within {INTERVAL} seconds.\n\nAll file uploads that exceed this limit are rejected to protect the website from overflowing.\n\nPlease check the upload history log in the plugin's area in Dashboard for any suspicious behaviour.\n\nA new message will follow if the situation remains.\n\nThanks", "wp-file-upload"));
150
- DEFINE("WFU_WARNING_ALT_IPTANUS_SERVER_ACTIVATED", __("You have activated an alternative insecure Iptanus Services Server. For details please contact info@iptanus.com.", "wp-file-upload"));
151
- DEFINE("WFU_WARNING_IPTANUS_SERVER_UNREACHABLE", __("Iptanus Services Server is unreachable. This may cause problems on some plugin functions. Please read this :article: for resolution.", "wp-file-upload"));
152
- //admin area messages
153
- DEFINE("WFU_DASHBOARD_ADD_SHORTCODE_REJECTED", __("Failed to add the shortcode to the page/post. Please try again. If the message persists, contact administrator.", "wp-file-upload"));
154
- DEFINE("WFU_DASHBOARD_EDIT_SHORTCODE_REJECTED", __("Failed to edit the shortcode because the contents of the page changed. Try again to edit the shortcode.", "wp-file-upload"));
155
- DEFINE("WFU_DASHBOARD_DELETE_SHORTCODE_REJECTED", __("Failed to delete the shortcode because the contents of the page changed. Try again to delete it.", "wp-file-upload"));
156
- DEFINE("WFU_DASHBOARD_PAGE_OBSOLETE", __("The page containing the shortcode has been modified and it is no longer valid. Please go back to reload the shortcode.", "wp-file-upload"));
157
- DEFINE("WFU_DASHBOARD_UPDATE_SHORTCODE_REJECTED", __("Failed to update the shortcode because the contents of the page changed. Go back to reload the shortcode.", "wp-file-upload"));
158
- DEFINE("WFU_DASHBOARD_UPDATE_SHORTCODE_FAILED", __("Failed to update the shortcode. Please try again. If the problem persists, go back and reload the shortcode.", "wp-file-upload"));
159
- //test messages
160
- DEFINE("WFU_TESTMESSAGE_MESSAGE", __('This is a test message', 'wp-file-upload'));
161
- DEFINE("WFU_TESTMESSAGE_ADMINMESSAGE", __('This is a test administrator message', 'wp-file-upload'));
162
- DEFINE("WFU_TESTMESSAGE_FILE1_HEADER", __('File testfile 1 under test', 'wp-file-upload'));
163
- DEFINE("WFU_TESTMESSAGE_FILE1_MESSAGE", __('File testfile 1 message', 'wp-file-upload'));
164
- DEFINE("WFU_TESTMESSAGE_FILE1_ADMINMESSAGE", __('File testfile 1 administrator message', 'wp-file-upload'));
165
- DEFINE("WFU_TESTMESSAGE_FILE2_HEADER", __('File testfile 2 under test', 'wp-file-upload'));
166
- DEFINE("WFU_TESTMESSAGE_FILE2_MESSAGE", __('File testfile 2 message', 'wp-file-upload'));
167
- DEFINE("WFU_TESTMESSAGE_FILE2_ADMINMESSAGE", __('File testfile 2 administrator message', 'wp-file-upload'));
168
- //variables tool-tips
169
- DEFINE("WFU_VARIABLE_TITLE_USERID", __("Insert variable %userid% inside text. It will be replaced by the id of the current user.", "wp-file-upload"));
170
- DEFINE("WFU_VARIABLE_TITLE_USERNAME", __("Insert variable %username% inside text. It will be replaced by the username of the current user.", "wp-file-upload"));
171
- DEFINE("WFU_VARIABLE_TITLE_USEREMAIL", __("Insert variable %useremail% inside text. It will be replaced by the email of the current user.", "wp-file-upload"));
172
- DEFINE("WFU_VARIABLE_TITLE_FILENAME", __("Insert variable %filename% inside text. It will be replaced by the filename of the uploaded file.", "wp-file-upload"));
173
- DEFINE("WFU_VARIABLE_TITLE_FILEPATH", __("Insert variable %filepath% inside text. It will be replaced by the full filepath of the uploaded file.", "wp-file-upload"));
174
- DEFINE("WFU_VARIABLE_TITLE_BLOGID", __("Insert variable %blogid% inside text. It will be replaced by the blog id of the website.", "wp-file-upload"));
175
- DEFINE("WFU_VARIABLE_TITLE_PAGEID", __("Insert variable %pageid% inside text. It will be replaced by the id of the current page.", "wp-file-upload"));
176
- DEFINE("WFU_VARIABLE_TITLE_PAGETITLE", __("Insert variable %pagetitle% inside text. It will be replaced by the title of the current page.", "wp-file-upload"));
177
- DEFINE("WFU_VARIABLE_TITLE_USERDATAXXX", __("Insert variable %userdataXXX% inside text. Select the user field from the drop-down list. It will be replaced by the value that the user entered in this field.", "wp-file-upload"));
178
- DEFINE("WFU_VARIABLE_TITLE_N", __("Insert variable %n% inside text to denote a line change.", "wp-file-upload"));
179
- //other plugin values
180
- DEFINE("WFU_WARNINGMESSAGE_NOSAVE", __('File %filename% uploaded successfully but not saved', 'wp-file-upload'));
181
- DEFINE("WFU_NOTIFY_TESTMODE", __("Test Mode", "wp-file-upload"));
182
- DEFINE("WFU_SUBDIR_SELECTDIR", __("select dir...", "wp-file-upload"));
183
- DEFINE("WFU_SUBDIR_TYPEDIR", __("type dir", "wp-file-upload"));
184
- DEFINE("WFU_SUCCESSMESSAGE_DETAILS", __('Upload path: %filepath%', 'wp-file-upload'));
185
- DEFINE("WFU_FAILMESSAGE_DETAILS", __('Failed upload path: %filepath%', 'wp-file-upload'));
186
- DEFINE("WFU_USERDATA_REQUIREDLABEL", __(' (required)', 'wp-file-upload'));
187
- DEFINE("WFU_PAGEEXIT_PROMPT", __('Files are being uploaded. Are you sure you want to exit the page?', 'wp-file-upload'));
188
- DEFINE("WFU_MESSAGE_CAPTCHA_CHECKING", __("checking captcha...", "wp-file-upload"));
189
- DEFINE("WFU_MESSAGE_CAPTCHA_REFRESHING", __("refreshing...", "wp-file-upload"));
190
- DEFINE("WFU_MESSAGE_CAPTCHA_OK", __("correct captcha", "wp-file-upload"));
191
- DEFINE("WFU_CONFIRMBOX_CAPTION", __("click to continue the upload", "wp-file-upload"));
192
- DEFINE("WFU_BROWSER_DELETEFILE_PROMPT", __("Are you sure you want to delete this file?", "wp-file-upload"));
193
- DEFINE("WFU_BROWSER_DELETEFILES_PROMPT", __("Are you sure you want to delete these files?", "wp-file-upload"));
194
- DEFINE("WFU_BROWSER_BULKACTION_TITLE", __("Bulk Actions", "wp-file-upload"));
195
- DEFINE("WFU_BROWSER_BULKACTION_LABEL", __("Apply", "wp-file-upload"));
196
- DEFINE("WFU_PAGINATION_PAGE", __("Page", "wp-file-upload"));
197
- DEFINE("WFU_PAGINATION_OF", __("of ", "wp-file-upload"));
198
- DEFINE("WFU_CANCEL_UPLOAD_PROMPT", __("Are you sure that you want to cancel the upload?", "wp-file-upload"));
199
- DEFINE("WFU_FILE_CANCEL_HINT", __("cancel upload of this file", "wp-file-upload"));
200
- DEFINE("WFU_UPLOAD_STATE0", __("Upload in progress", "wp-file-upload"));
201
- DEFINE("WFU_UPLOAD_STATE1", __("Upload in progress with warnings!", "wp-file-upload"));
202
- DEFINE("WFU_UPLOAD_STATE2", __("Upload in progress but some files already failed!", "wp-file-upload"));
203
- DEFINE("WFU_UPLOAD_STATE3", __("Upload in progress but no files uploaded so far!", "wp-file-upload"));
204
- DEFINE("WFU_UPLOAD_STATE4", __("All files uploaded successfully", "wp-file-upload"));
205
- DEFINE("WFU_UPLOAD_STATE5", __("All files uploaded successfully but there are warnings!", "wp-file-upload"));
206
- DEFINE("WFU_UPLOAD_STATE5_SINGLEFILE", __("File uploaded successfully but there are warnings!", "wp-file-upload"));
207
- DEFINE("WFU_UPLOAD_STATE6", __("Some files failed to upload!", "wp-file-upload"));
208
- DEFINE("WFU_UPLOAD_STATE7", __("All files failed to upload", "wp-file-upload"));
209
- DEFINE("WFU_UPLOAD_STATE7_SINGLEFILE", __("File failed to upload", "wp-file-upload"));
210
- DEFINE("WFU_UPLOAD_STATE8", __("There are no files to upload!", "wp-file-upload"));
211
- DEFINE("WFU_UPLOAD_STATE9", __("Test upload message", "wp-file-upload"));
212
- DEFINE("WFU_UPLOAD_STATE10", __("JSON parse warning!", "wp-file-upload"));
213
- DEFINE("WFU_UPLOAD_STATE11", __("please wait while redirecting...", "wp-file-upload"));
214
- DEFINE("WFU_UPLOAD_STATE12", __("Upload failed!", "wp-file-upload"));
215
- DEFINE("WFU_UPLOAD_STATE13", __("Submitting data", "wp-file-upload"));
216
- DEFINE("WFU_UPLOAD_STATE14", __("Data submitted successfully!", "wp-file-upload"));
217
- DEFINE("WFU_UPLOAD_STATE15", __("Data were not submitted!", "wp-file-upload"));
218
- DEFINE("WFU_UPLOAD_STATE16", __("Cancelling upload", "wp-file-upload"));
219
- DEFINE("WFU_UPLOAD_STATE17", __("Upload cancelled!", "wp-file-upload"));
220
- DEFINE("WFU_UPLOAD_STATE18", __("Upload succeeded!", "wp-file-upload"));
221
- DEFINE("WFU_UPLOAD_STATE19", __("Upload completed but no files were saved!", "wp-file-upload"));
222
- DEFINE("WFU_UPLOAD_STATE19_SINGLEFILE", __("File was not saved due to personal data policy!", "wp-file-upload"));
223
- DEFINE("WFU_PAGE_PLUGINEDITOR_BUTTONTITLE", __("Open visual shortcode editor in new window", "wp-file-upload"));
224
- DEFINE("WFU_PAGE_PLUGINEDITOR_LOADING", __("loading visual editor", "wp-file-upload"));
225
- DEFINE("WFU_CONFIRM_CLEARFILES", __("Clear file list?", "wp-file-upload"));
226
- DEFINE("WFU_DROP_HERE_MESSAGE", __('DROP HERE', 'wp-file-upload'));
227
- //webcam values
228
- DEFINE("WFU_WEBCAM_RECVIDEO_BTN", __('record video', 'wp-file-upload'));
229
- DEFINE("WFU_WEBCAM_TAKEPIC_BTN", __('take a picture', 'wp-file-upload'));
230
- DEFINE("WFU_WEBCAM_TURNONOFF_BTN", __('turn webcam on/off', 'wp-file-upload'));
231
- DEFINE("WFU_WEBCAM_GOLIVE_BTN", __('go live again', 'wp-file-upload'));
232
- DEFINE("WFU_WEBCAM_STOPREC_BTN", __('end recording', 'wp-file-upload'));
233
- DEFINE("WFU_WEBCAM_PLAY_BTN", __('play', 'wp-file-upload'));
234
- DEFINE("WFU_WEBCAM_PAUSE_BTN", __('pause', 'wp-file-upload'));
235
- DEFINE("WFU_WEBCAM_GOBACK_BTN", __('go to the beginning', 'wp-file-upload'));
236
- DEFINE("WFU_WEBCAM_GOFWD_BTN", __('go to the end', 'wp-file-upload'));
237
- //widget values
238
- DEFINE("WFU_WIDGET_PLUGINFORM_TITLE", __('Wordpress File Upload Form', 'wp-file-upload'));
239
- DEFINE("WFU_WIDGET_PLUGINFORM_DESCRIPTION", __('Wordpress File Upload plugin uploader for sidebars', 'wp-file-upload'));
240
- DEFINE("WFU_WIDGET_SIDEBAR_DEFAULTTITLE", __('Upload Files', 'wp-file-upload'));
241
- }
242
-
243
- /*********** Environment Variables ************/
244
- //plugin default values
245
- $GLOBALS["WFU_GLOBALS"] = array(
246
- "WFU_UPLOADID" => array( "Default Upload ID", "string", "1", "The default upload ID of the uploader shortcode. It can be any integer from 1 and above." ),
247
- "WFU_SINGLEBUTTON" => array( "Default Single-Button Status", "string", "false", "The default single-button status of the uploader shortcode. It can be 'true' or 'false'." ),
248
- "WFU_UPLOADROLE" => array( "Default Upload Role", "string", "all,guests", "The default upload role of the uploader shortcode. It can be a comma-separated list of role slugs, including keywords 'all' and 'guests'." ),
249
- "WFU_UPLOADPATH" => array( "Default Upload Path", "string", "uploads", "The default upload path of the uploader shortcode. It must be a folder relative to wp-content dir." ),
250
- "WFU_FITMODE" => array( "Default Fit Mode", "string", "fixed", "The default fit mode of the uploader shortcode. It can be 'fixed' or 'responsive'." ),
251
- "WFU_ALLOWNOFILE" => array( "Default Allow No File Mode", "string", "false", "The default mode for allowing no file uploads. If it is set to 'true' then an upload form can be submitted even if a file has not been selected. It can be 'true' or 'false'." ),
252
- "WFU_ALLOWNOFILE" => array( "Default Allow No File Mode", "string", "false", "The default mode for allowing no file uploads. If it is set to 'true' then an upload form can be submitted even if a file has not been selected. It can be 'true' or 'false'." ),
253
- "WFU_RESETMODE" => array( "Default Reset Form Mode", "string", "always", "The default reset mode of the upload form. It can be 'always', 'onsuccess' or 'never'." ),
254
- "WFU_FORCEFILENAME" => array( "Default Force Filename State", "string", "false", "The default force filename state (force plugin to leave filename unchanged) of the uploader shortcode. It can be 'true' or 'false'." ),
255
- "WFU_UPLOADPATTERNS" => array( "Default Upload Extensions", "string", "*.*", "The default allowed file extensions of the uploader shortcode. It can be a comma-separated list of wildcard extensions." ),
256
- "WFU_MAXSIZE" => array( "Default Maximum File Size", "string", "50", "The default maximum allowed file size of the uploader shortcode in Megabytes. It can be any positive number." ),
257
- "WFU_ACCESSMETHOD" => array( "Default Access Method", "string", "normal", "The default access method (of the website filesystem) of the uploader shortcode. It can be 'normal' or 'ftp'." ),
258
- "WFU_FTPINFO" => array( "Default FTP Access Information", "string", "", "The default FTP access parameters of the uploader shortcode. It's syntax is 'username:password@ftp_domain'." ),
259
- "WFU_USEFTPDOMAIN" => array( "Default Use FTP Domain State", "string", "false", "The default use FTP domain state (use the FTP domain defined in ftpinfo to store the uploaded files) of the uploader shortcode. It can be 'true' or 'false'." ),
260
- "WFU_FTPPASSIVEMODE" => array( "Default FTP Passive Mode State", "string", "false", "The default FTP passive mode (use passive mode or not for FTP access) of the uploader shortcode. It can be 'true' or 'false'." ),
261
- "WFU_FTPFILEPERMISSIONS" => array( "Default FTP File Permissions", "string", "", "The default FTP passive mode (use passive mode or not for FTP access) of the uploader shortcode. It can be 'true' or 'false'." ),
262
- "WFU_DUBLICATESPOLICY" => array( "Default Duplicate File Action", "string", "overwrite", "The default duplicate file action of the uploader shortcode. It can be 'overwrite', 'reject' or 'mantain both'." ),
263
- "WFU_UNIQUEPATTERN" => array( "Default Duplicate File Pattern", "string", "index", "The default duplicate file pattern of the uploader shortcode. It can be 'index' or 'datetimestamp'." ),
264
- "WFU_FILEBASELINK" => array( "Default WPFilebase Update State", "string", "false", "The default WPFilebase plugin update state of the uploader shortcode. It can be 'true' or 'false'." ),
265
- "WFU_NOTIFY" => array( "Default Email Notification State", "string", "false", "The default email notification state of the uploader shortcode. It can be 'true' or 'false'." ),
266
- "WFU_NOTIFYRECIPIENTS" => array( "Default Email Recipients", "string", "", "The default email recipients of the uploader shortcode. It can be a comma-separated list of email addresses." ),
267
- "WFU_NOTIFYHEADERS" => array( "Default Email Headers", "string", "", "The default email headers of the uploader shortcode." ),
268
- "WFU_ATTACHFILE" => array( "Default Attach File State", "string", "false", "The default attach file to email state of the uploader shortcode. It can be 'true' or 'false'." ),
269
- "WFU_REDIRECT" => array( "Default Redirection State", "string", "false", "The default redirection state of the uploader shortcode. It can be 'true' or 'false'." ),
270
- "WFU_REDIRECTLINK" => array( "Default Redirect URL", "string", "", "The default redirect URL of the uploader shortcode." ),
271
- "WFU_ADMINMESSAGES" => array( "Default State for Admin Messages", "string", "false", "The default state of displaying or not admin messages of the uploader shortcode. It can be 'true' or 'false'." ),
272
- "WFU_SUCCESSMESSAGECOLORS" => array( "Default Colors for Success Message", "string", "#006600,#EEFFEE,#006666", "The default color triplet (text, background and border colors) of success message of the uploader shortcode." ),
273
- "WFU_WARNINGMESSAGECOLORS" => array( "Default Colors for Warning Message", "string", "#F88017,#FEF2E7,#633309", "The default color triplet (text, background and border colors) of warning message of the uploader shortcode." ),
274
- "WFU_FAILMESSAGECOLORS" => array( "Default Colors for Fail Message", "string", "#660000,#FFEEEE,#666600", "The default color triplet (text, background and border colors) of fail message of the uploader shortcode." ),
275
- "WFU_WAITMESSAGECOLORS" => array( "Default Colors for Wait Message", "string", "#666666,#EEEEEE,#333333", "The default color triplet (text, background and border colors) of wait message of the uploader shortcode." ),
276
- "WFU_SHOWTARGETFOLDER" => array( "Default State for Target Folder", "string", "false", "The default state of displaying or not the target folder of the uploader shortcode. It can be 'true' or 'false'." ),
277
- "WFU_TARGETFOLDERLABEL" => array( "Default Text for Target Folder Label", "string", "Upload Directory", "The default text of the target folder label of the uploader shortcode." ),
278
- "WFU_ASKFORSUBFOLDERS" => array( "Default Subfolders State", "string", "false", "The default state of displaying or not a list of subfolders of the uploader shortcode. It can be 'true' or 'false'." ),
279
- "WFU_SUBFOLDERLABEL" => array( "Default Text of Subfolders Label", "string", "Select Subfolder", "The default text of subfolders label of the uploader shortcode." ),
280
- "WFU_SUBFOLDERTREE" => array( "Default Subfolders List", "string", "", "The default list of subfolders of the uploader shortcode. Check plugin's support page for syntax." ),
281
- "WFU_FORCECLASSIC" => array( "Default Disable AJAX State", "string", "false", "The default state of disabling or not AJAX functionality of the uploader shortcode. It can be 'true' or 'false'." ),
282
- "WFU_TESTMODE" => array( "Default Test Mode State", "string", "false", "The default state of test mode of the uploader shortcode. It can be 'true' or 'false'." ),
283
- "WFU_DEBUGMODE" => array( "Default Debug Mode State", "string", "false", "The default state of debug mode of the uploader shortcode. It can be 'true' or 'false'." ),
284
- "WFU_WIDTHS" => array( "Default Element Widths", "string", "", "The default widths of the elements of the uploader shortcode. It is a comma-separated list of element widths." ),
285
- "WFU_HEIGHTS" => array( "Default Element Heights", "string", "", "The default heights of the elements of the uploader shortcode. It is a comma-separated list of element heights." ),
286
- "WFU_PLACEMENTS" => array( "Default Element Placements", "string", "title/filename+selectbutton+uploadbutton/subfolders"."/userdata"."/message", "The default placements of the elements of the uploader shortcode. Check plugin's support page for syntax." ),
287
- "WFU_USERDATA" => array( "Default User Fields State", "string", "false", "The default state of custom user fields of the uploader shortcode. It can be 'true' or 'false'." ),
288
- "WFU_MEDIALINK" => array( "Default Add to Media State", "string", "false", "The default state for adding files to Media of the uploader shortcode. It can be 'true' or 'false'." ),
289
- "WFU_POSTLINK" => array( "Default Attachment to Post State", "string", "false", "The default state for attaching files to current post of the uploader shortcode. It can be 'true' or 'false'." ),
290
- "WFU_WEBCAM" => array( "Default Webcam State", "string", "false", "The default state for webcam capture. It can be 'true' or 'false'." ),
291
- "WFU_AUDIOCAPTURE" => array( "Default Capture Audio State", "string", "false", "The default state of audio capture. If it is set to 'true' then audio will be captured, together with video from the webcam. It can be 'true' or 'false'." ),
292
- "WFU_WEBCAMMODE" => array( "Default Webcam Mode", "string", "capture video", "The default webcam capture mode. It can be 'capture video', 'take photos' or 'both'." ),
293
- "WFU_VIDEOWIDTH" => array( "Default Video Width", "string", "", "The default preferable video width for webcam capture. It can be any positive integer in pixels." ),
294
- "WFU_VIDEOHEIGHT" => array( "Default Video Height", "string", "", "The default preferable video height for webcam capture. It can be any positive integer in pixels." ),
295
- "WFU_VIDEOASPECTRATIO" => array( "Default Video Aspect Ratio", "string", "", "The default preferable video aspect ratio for webcam video capture. It can be any positive value." ),
296
- "WFU_VIDEOFRAMERATE" => array( "Default Video Frame Rate", "string", "", "The default preferable video frame rate for webcam video capture. It can be any positive value in frames/sec." ),
297
- "WFU_CAMERAFACING" => array( "Default Camera Facing Mode", "string", "any", "The default preferable camera to be used for video/screenshot capture. It can be 'any', 'front' or 'back'." ),
298
- "WFU_MAXRECORDTIME" => array( "Default Maximum Record Time", "string", "10", "The default maximum video recording time in seconds. The default value is 10 seconds." ),
299
- "WFU_ASKCONSENT" => array( "Default Ask Consent State", "string", "false", "The default state of personal data consent request. The default value is false." ),
300
- "WFU_PERSONALDATATYPES" => array( "Default Personal Data Types", "string", "userdata", "The default personal data types. The default value is 'userdata'." ),
301
- "WFU_NOTREMEMBERCONSENT" => array( "Default Do Not Remember Consent Answer State", "string", "false", "The default state about remembering or not user's answer on consent question. The default value is true." ),
302
- "WFU_CONSENTREJECTUPLOAD" => array( "Default Reject Upload on Consent Denial State", "string", "false", "The default state of continuing or rejecting the upload depending on consent answer. The default value is true." ),
303
- "WFU_CONSENTFORMAT" => array( "Default Consent Format", "string", "radio", "The default format of consent question. The default value is 'checkbox'." ),
304
- "WFU_CONSENTPRESELECT" => array( "Default Consent Preselect State", "string", "none", "The default preselect state of consent question when checkbox format is active. The default value is false." )
305
- );
306
- //other plugin values
307
- $GLOBALS["WFU_GLOBALS"] += array(
308
- "WFU_DEBUG" => array( "Plugin Debug Mode", "string", "OFF", "If DEBUG mode is activated then advanced hook of plugin's function can be performed. This option may make the plugin slower, so use it very carefully. It can be 'OFF' or 'ON'." ),
309
- "WFU_RESTRICT_FRONTEND_LOADING" => array( "Restrict Front-End Loading", "string", "false", "It defines whether the plugin will load on all pages or specific ones. If it is 'false' then it will load on all pages. To restrict loading only on specific pages set a comma-separated list of page or post IDs." ),
310
- "WFU_UPLOADPROGRESS_MODE" => array( "Upload Progress Mode", "string", "incremental", "Defines how the upload progress is calculated. It can be 'incremental' or 'absolute'. Default value is 'incremental'." ),
311
- "WFU_DOS_ATTACKS_CHECK" => array( "Check for Denial-Of-Service Attacks", "string", "true", "If it is true then then plugin will check if the number of files uploaded within a specific amount of time exceeds the limit, thus protecting from DOS attacks. It can be 'true' or 'false'." ),
312
- "WFU_DOS_ATTACKS_FILE_LIMIT" => array( "Denial-Of-Service File Limit", "integer", 10000, "Defines the maximum number of files that are allowed to be uploaded within a specific amount of time. It can be any positive integer." ),
313
- "WFU_DOS_ATTACKS_TIME_INTERVAL" => array( "Denial-Of-Service Time Interval", "integer", 3600, "Defines the time interval for DOS attacks check. The time interval is given in seconds." ),
314
- "WFU_DOS_ATTACKS_ADMIN_EMAIL_FREQUENCY" => array( "Denial-Of-Service Admin Email Frequency", "integer", 3600, "Defines how frequently an email will be sent to administrator notifying for Denial-Of-Service attacks. The time interval is given in seconds." ),
315
- "WFU_SANITIZE_FILENAME_MODE" => array( "Filename Sanitization Mode", "string", "strict", "The sanitization mode for filenames. It can be 'strict' or 'loose'." ),
316
- "WFU_SANITIZE_FILENAME_DOTS" => array( "Sanitize Filename Dots", "string", "true", "Convert dot symbols (.) in filename into dashes, in order to avoid double extensions. It can be 'true' or 'false'." ),
317
- "WFU_WILDCARD_ASTERISK_MODE" => array( "Wildcard Asterisk Mode", "string", "strict", "The mode of wildcard pattern asterisk symbol. If it is strict, then the asterisk will not match dot (.) characters. It can be 'strict' or 'loose'." ),
318
- "WFU_PHP_ARRAY_MAXLEN" => array( "Max PHP Array Length", "string", "10000", "The maximum allowable number of items of a PHP array." ),
319
- "WFU_ADMINBROWSER_TABLE_MAXROWS" => array( "Admin Browser Rows Per Page", "integer", 25, "The number of rows per page of the admin browser. A value equal to zero or less denotes no pagination." ),
320
- "WFU_HISTORYLOG_TABLE_MAXROWS" => array( "History Log Table Rows Per Page", "integer", 25, "The number of rows per page of the History Log table." ),
321
- "WFU_UPLOADEDFILES_TABLE_MAXROWS" => array( "Uploaded Files Table Rows Per Page", "integer", 25, "The number of rows per page of the Uploaded Files table." ),
322
- "WFU_ALTERNATIVE_RANDOMIZER" => array( "Use Alternative Randomizer", "string", "false", "On fast web servers the plugin's generator of random strings may not work properly causing various problems. If it is set to true, an alternative randomizer method is employed that works for fast web servers. It can be 'true' or 'false'." ),
323
- "WFU_FORCE_NOTIFICATIONS" => array( "Force Email Notifications", "string", "false", "Send email notifications (if they are activated) even if no file has been uploaded. It can be 'true' or 'false'." ),
324
- "WFU_UPDATE_MEDIA_ON_DELETE" => array( "Update Media on Delete", "string", "true", "When an uploaded file is deleted then delete also the corresponding Media Library item if exists. It can be 'true' or 'false'." ),
325
- "WFU_DASHBOARD_PROTECTED" => array( "Dashboard Is Protected", "string", "false", "If /wp-admin folder is password protected then this variable should be set to 'true' so that internal operations of the plugin can work. The username and password should also be set." ),
326
- "WFU_DASHBOARD_USERNAME" => array( "Protected Dashboard Username", "string", "", "Username entry for accessing protected /wp-admin folder." ),
327
- "WFU_DASHBOARD_PASSWORD" => array( "Protected Dashboard Password", "string", "", "Password entry for accessing protected /wp-admin folder." ),
328
- "WFU_EXPORT_DATA_SEPARATOR" => array( "Export Data Separator", "string", ",", "This is the delimiter of the exported file data columns. It can be any symbol. Default value is comma (,)." ),
329
- "WFU_EXPORT_USERDATA_SEPARATOR" => array( "Export User Data Separator", "string", ";", "This is the delimiter of the exported user data of each file. It can be any symbol. Default value is semicolon (;)." ),
330
- "WFU_DISABLE_VERSION_CHECK" => array( "Disable Version Check", "string", "false", "If it is set to 'true' then the plugin will not check if there are any new versions available. This is a temporary solution to problems having some users accessing Iptanus Services server causing the plugin to stall. It can be 'true' or 'false'." ),
331
- "WFU_RELAX_CURL_VERIFY_HOST" => array( "Relax cURL Host Verification", "string", "false", "If it is set to 'true' then CURLOPT_SSL_VERIFYHOST will be disabled when executing a cURL POST request. This is required in some cases so that the plugin can reach https://services2.iptanus.com, because on some servers it fails with a file_get_contents warning. It can be 'true' or 'false'." ),
332
- "WFU_USE_ALT_IPTANUS_SERVER" => array( "Use Alternative Iptanus Server", "string", "false", "If it is set to 'true' then the alternative Iptanus server will be used. This is a work-around in some cases where the website cannot reach https://services2.iptanus.com. It can be 'true' or 'false'." ),
333
- "WFU_ALT_IPTANUS_SERVER" => array( "Alternative Iptanus Server", "string", "https://iptanusservices.appspot.com", "If it is set then this is the URL of the alternative Iptanus server." ),
334
- "WFU_ALT_VERSION_SERVER" => array( "Alternative Version Server", "string", "https://iptanusservices.appspot.com/g79xo30q8s", "If the alternative Iptanus server is used and this variable is not empty, then it will be used as the alternative Version Server URL." ),
335
- "WFU_MINIFY_INLINE_CSS" => array( "Minify Inline CSS Code", "string", "true", "Defines whether the inline CSS code will be minified. It can be 'true' or 'false'." ),
336
- "WFU_MINIFY_INLINE_JS" => array( "Minify Inline JS Code", "string", "true", "Defines whether the inline Javascript code will be minified. It can be 'true' or 'false'." ),
337
- "WFU_US_DBOPTION_CHECK" => array( "DB Option User State Check Interval", "integer", 7200, "Defines how often (in seconds) the plugin will update user state list, when user state is saved in DB option table." ),
338
- "WFU_US_DBOPTION_LIFE" => array( "DB Option User State Life", "integer", 1800, "Defines the maximum time of inactivity of a user state, when user state is saved in DB option table." ),
339
- "WFU_PD_VISIBLE_OPLEVELS" => array( "Personal Data Visible Operation Levels", "integer", 3, "Defines how deep administrators can go into personal data operation details. A value of -1 denotes that there is no limit." ),
340
- "WFU_PD_VISIBLE_PERLEVELS" => array( "Personal Data Visible Permission Levels", "integer", 2, "Defines how deep administrators can go into personal data permission details. A value of -1 denotes that there is no limit." ),
341
- "WFU_PD_VISIBLE_LOGLEVELS" => array( "Personal Data Visible Log Action Levels", "integer", 2, "Defines how deep administrators can go into personal data log action details. A value of -1 denotes that there is no limit." ),
342
- "WFU_UPLOADEDFILES_MENU" => array( "Uploaded Files Menu State", "string", "true", "Defines whether the Uploaded Files Dashboard menu item will be shown or not. It can be 'true' or 'false'." ),
343
- "WFU_UPLOADEDFILES_DEFACTION" => array( "Uploaded Files Default Action", "string", "adminbrowser", "Defines the default action that will be executed when a file link is pressed in Uploaded Files page. It can be 'details', 'adminbrowser', 'historylog', 'link', 'download' and 'none'." ),
344
- "WFU_UPLOADEDFILES_COLUMNS" => array( "Uploaded Files Columns", "string", "#, file, upload_date, user, properties, remarks, actions", "Defines the visible columns of the Uploaded Files list as well as their order. It is noted that 'File' column is always visible and it is the second column if '#' column is visible, or the first one if '#' column is hidden." ),
345
- "WFU_UPLOADEDFILES_ACTIONS" => array( "Uploaded Files Actions", "string", "details, media, adminbrowser, historylog, link, download", "Defines the allowable actions and their order for each file in Uploaded Files list. It is noted that the actions shown for each file depend on its properties." ),
346
- "WFU_UPLOADEDFILES_HIDEINVALID" => array( "Hide Invalid Uploaded Files", "string", "false", "Defines whether all uploaded file records will be shown in Uploaded File menu or only the valid ones. Invalid are the records who are obsolete or their files do not exist anymore." ),
347
- "WFU_UPLOADEDFILES_RESET_TIME" => array( "Uploaded Files Reset Time", "integer", 5, "Defines the interval in seconds before the unread uploaded files can be marked as read. A value of -1 denotes that there is no interval." ),
348
- "WFU_UPLOADEDFILES_BARMENU" => array( "Uploaded Files Toolbar Menu State", "string", "true", "Defines whether the Uploaded Files Toolbar (Admin Bar) menu item will be shown or not. It can be 'true' or 'false'." ),
349
- "WFU_UPLOADEDFILES_BARAUTOHIDE" => array( "Uploaded Files Auto-Hide on Toolbar", "string", "false", "Defines whether the Uploaded Files Toolbar (Admin Bar) menu item will be hidden when there are no new uploads. It can be 'true' or 'false'." ),
350
- "WFU_SHORTCODECOMPOSER_NOADMIN" => array( "Show Shortcode Composer to Non-Admins", "string", "true", "Defines whether the shortcode composer will be visible to non-admin users who can edit posts or pages. It can be 'true' or 'false'." )
351
- );
352
- //color definitions
353
- $GLOBALS["WFU_GLOBALS"] += array(
354
- "WFU_TESTMESSAGECOLORS" => array( "Colors for Message in Test Mode", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message in Test mode of the uploader shortcode." ),
355
- "WFU_DEFAULTMESSAGECOLORS" => array( "Defaults Message Colors", "string", "#666666,#EEEEEE,#333333", "The default color triplet (text, background and border colors) of message of the uploader shortcode." ),
356
- "WFU_HEADERMESSAGECOLORS_STATE0" => array( "State 0 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 0 (upload in progress with no messages) of the uploader shortcode." ),
357
- "WFU_HEADERMESSAGECOLORS_STATE1" => array( "State 1 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 1 (upload in progress with messages) of the uploader shortcode." ),
358
- "WFU_HEADERMESSAGECOLORS_STATE2" => array( "State 2 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 2 (upload in progress with some files not uploaded) of the uploader shortcode." ),
359
- "WFU_HEADERMESSAGECOLORS_STATE3" => array( "State 3 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 3 (upload in progress with no files uploaded so far) of the uploader shortcode." ),
360
- "WFU_HEADERMESSAGECOLORS_STATE4" => array( "State 4 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 4 (all files uploaded) of the uploader shortcode." ),
361
- "WFU_HEADERMESSAGECOLORS_STATE5" => array( "State 5 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 5 (all files uploaded with messages) of the uploader shortcode." ),
362
- "WFU_HEADERMESSAGECOLORS_STATE6" => array( "State 6 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 6 (some files not uploaded) of the uploader shortcode." ),
363
- "WFU_HEADERMESSAGECOLORS_STATE7" => array( "State 7 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 7 (no files uploaded) of the uploader shortcode." ),
364
- "WFU_HEADERMESSAGECOLORS_STATE8" => array( "State 8 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 8 (there are no files to upload) of the uploader shortcode." ),
365
- "WFU_HEADERMESSAGECOLORS_STATE9" => array( "State 9 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 9 (test state) of the uploader shortcode." ),
366
- "WFU_HEADERMESSAGECOLORS_STATE10" => array( "State 10 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 10 (JSON parse error) of the uploader shortcode." ),
367
- "WFU_HEADERMESSAGECOLORS_STATE11" => array( "State 11 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 11 (redirecting) of the uploader shortcode." ),
368
- "WFU_HEADERMESSAGECOLORS_STATE12" => array( "State 12 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 12 (upload failed) of the uploader shortcode." ),
369
- "WFU_HEADERMESSAGECOLORS_STATE13" => array( "State 13 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 13 (sending data) of the uploader shortcode." ),
370
- "WFU_HEADERMESSAGECOLORS_STATE14" => array( "State 14 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 14 (data submit succeeded) of the uploader shortcode." ),
371
- "WFU_HEADERMESSAGECOLORS_STATE15" => array( "State 15 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 15 (data submit failed) of the uploader shortcode." ),
372
- "WFU_HEADERMESSAGECOLORS_STATE16" => array( "State 16 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 16 (cancelling upload) of the uploader shortcode." ),
373
- "WFU_HEADERMESSAGECOLORS_STATE17" => array( "State 17 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 17 (upload cancelled) of the uploader shortcode." ),
374
- "WFU_HEADERMESSAGECOLORS_STATE18" => array( "State 18 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 18 (upload succeeded) of the uploader shortcode." ),
375
- "WFU_HEADERMESSAGECOLORS_STATE19" => array( "State 19 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 19 (upload completed but no files were saved due to personal data policy) of the uploader shortcode." )
376
- );
377
- //insert saved values to array
378
- $envars = get_option("wfu_environment_variables", array());
379
- foreach ( $GLOBALS["WFU_GLOBALS"] as $ind => $envar ) {
380
- if ( isset($envars[$ind]) ) {
381
- if ( $envar[1] == "integer" ) $saved = (int)$envars[$ind];
382
- else $saved = (string)$envars[$ind];
383
- }
384
- else $saved = $envar[2];
385
- array_splice($GLOBALS["WFU_GLOBALS"][$ind], 3, 0, array( $saved ));
386
- //add visibility
387
- $GLOBALS["WFU_GLOBALS"][$ind][5] = true;
388
- }
389
-
390
- //hide unwanted environment variables
391
- $GLOBALS["WFU_GLOBALS"]["WFU_RELAX_CURL_VERIFY_HOST"][5] = false;
392
- $GLOBALS["WFU_GLOBALS"]["WFU_USE_ALT_IPTANUS_SERVER"][5] = false;
393
-
394
- /************** Constant Values ***************/
395
- //other plugin values
396
- DEFINE("WFU_SUCCESSMESSAGECOLOR", "green");
397
- DEFINE("WFU_MAX_TIME_LIMIT", ini_get("max_input_time"));
398
- DEFINE("WFU_RESPONSE_URL", WPFILEUPLOAD_DIR."wfu_response.php");
399
- DEFINE("WFU_AJAX_URL", $siteurl."/wp-admin/admin-ajax.php");
400
- DEFINE("WFU_SERVICES_SERVER_URL", 'https://services2.iptanus.com');
401
- DEFINE("WFU_VERSION_SERVER_URL", WFU_SERVICES_SERVER_URL.'/wp-admin/admin-ajax.php');
402
- DEFINE("WFU_VERSION_HASH", '9npWpXMhAQ5e6AGJ5zqbaPxLk9ePD3eSu3WKeN9p89E9wmgL2PHtrqXPzBVpStzh');
403
- DEFINE("WFU_DOWNLOADER_URL", WPFILEUPLOAD_DIR."wfu_file_downloader.php");
404
- DEFINE("WFU_IPTANUS_SERVER_UNREACHABLE_ARTICLE", 'https://www.iptanus.com/iptanus-services-server-unreachable-error-wfu-plugin/');
405
- //alternative insecure server
406
- DEFINE("WFU_SERVICES_SERVER_ALT_URL", 'http://services.iptanus.com');
407
- DEFINE("WFU_VERSION_SERVER_ALT_URL", WFU_SERVICES_SERVER_ALT_URL.'/wp-admin/admin-ajax.php');
408
- DEFINE("WFU_PRO_VERSION_URL", 'https://www.iptanus.com/product/wordpress-file-upload-pro/');
409
- //define images
410
- DEFINE("WFU_IMAGE_ADMIN_HELP", WPFILEUPLOAD_DIR.'images/help_16.png');
411
- DEFINE("WFU_IMAGE_ADMIN_RESTOREDEFAULT", WPFILEUPLOAD_DIR.'images/restore_16.png');
412
- DEFINE("WFU_IMAGE_ADMIN_USERDATA_ADD", WPFILEUPLOAD_DIR.'images/add_12.png');
413
- DEFINE("WFU_IMAGE_ADMIN_USERDATA_REMOVE", WPFILEUPLOAD_DIR.'images/remove_12.png');
414
- DEFINE("WFU_IMAGE_ADMIN_USERDATA_UP", WPFILEUPLOAD_DIR.'images/up_12.png');
415
- DEFINE("WFU_IMAGE_ADMIN_USERDATA_DOWN", WPFILEUPLOAD_DIR.'images/down_12.png');
416
- DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_BROWSE", WPFILEUPLOAD_DIR.'images/tree_16.gif');
417
- DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_OK", WPFILEUPLOAD_DIR.'images/ok_12.gif');
418
- DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_CANCEL", WPFILEUPLOAD_DIR.'images/cancel_12.gif');
419
- DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_LOADING", WPFILEUPLOAD_DIR.'images/refresh_16.gif');
420
- DEFINE("WFU_IMAGE_SIMPLE_PROGBAR", WPFILEUPLOAD_DIR.'images/progbar.gif');
421
- DEFINE("WFU_IMAGE_OVERLAY_EDITOR", WPFILEUPLOAD_DIR.'images/pencil.svg');
422
- DEFINE("WFU_IMAGE_OVERLAY_LOADING", WPFILEUPLOAD_DIR.'images/loading_icon.gif');
423
- DEFINE("WFU_IMAGE_FILE_CANCEL", WPFILEUPLOAD_DIR.'images/cancel_16.png');
424
- DEFINE("WFU_IMAGE_MEDIA_BUTTONS", WPFILEUPLOAD_DIR.'images/open-iconic.svg');
425
- DEFINE("WFU_IMAGE_VERSION_COMPARISON", WPFILEUPLOAD_DIR.'images/Version Comparison.png');
426
-
427
- function wfu_set_javascript_constants() {
428
- $consts = array(
429
- "notify_testmode" => WFU_NOTIFY_TESTMODE,
430
- "nofilemessage" => WFU_ERROR_UPLOAD_NOFILESELECTED,
431
- "enable_popups" => WFU_ERROR_ENABLE_POPUPS,
432
- "remoteserver_noresult" => WFU_ERROR_REMOTESERVER_NORESULT,
433
- "message_header" => WFU_ERRORMESSAGE,
434
- "message_failed" => WFU_ERROR_UPLOAD_FAILED_WHILE,
435
- "message_cancelled" => WFU_ERROR_UPLOAD_CANCELLED,
436
- "message_unknown" => WFU_ERROR_UNKNOWN,
437
- "adminmessage_unknown" => WFU_FAILMESSAGE_DETAILS,
438
- "message_timelimit" => WFU_ERROR_FILE_PHP_TIME,
439
- "message_admin_timelimit" => WFU_ERROR_ADMIN_FILE_PHP_TIME,
440
- "cancel_upload_prompt" => WFU_CANCEL_UPLOAD_PROMPT,
441
- "file_cancelled" => WFU_ERROR_FILE_CANCELLED,
442
- "jsonparse_filemessage" => WFU_ERROR_JSONPARSE_FILEMESSAGE,
443
- "jsonparse_message" => WFU_ERROR_JSONPARSE_MESSAGE,
444
- "jsonparse_adminmessage" => WFU_ERROR_JSONPARSE_ADMINMESSAGE,
445
- "jsonparse_headermessage" => WFU_ERROR_JSONPARSE_HEADERMESSAGE,
446
- "jsonparse_headeradminmessage" => WFU_ERROR_JSONPARSE_HEADERADMINMESSAGE,
447
- "same_pluginid" => WFU_ERROR_SAME_PLUGINID,
448
- "webcam_video_notsupported" => WFU_ERROR_WEBCAM_VIDEO_NOTSUPPORTED,
449
- "webcam_video_nothingrecorded" => WFU_ERROR_WEBCAM_VIDEO_NOTHINGRECORDED,
450
- "default_colors" => WFU_VAR("WFU_DEFAULTMESSAGECOLORS"),
451
- "fail_colors" => WFU_VAR("WFU_FAILMESSAGECOLORS"),
452
- "max_time_limit" => WFU_MAX_TIME_LIMIT,
453
- "response_url" => WFU_RESPONSE_URL,
454
- "ajax_url" => wfu_ajaxurl(),
455
- "wfu_pageexit_prompt" => WFU_PAGEEXIT_PROMPT,
456
- "wfu_subdir_typedir" => WFU_SUBDIR_TYPEDIR,
457
- "wfu_uploadprogress_mode" => WFU_VAR("WFU_UPLOADPROGRESS_MODE"),
458
- "wfu_consent_notcompleted" => WFU_WARNING_CONSENT_NOTCOMPLETED
459
- );
460
- $consts_txt = "";
461
- foreach ( $consts as $key => $val )
462
- $consts_txt .= ( $consts_txt == "" ? "" : ";" ).wfu_plugin_encode_string($key).":".wfu_plugin_encode_string($val);
463
-
464
- return $consts_txt;
465
- }
466
-
467
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Constants and Strings of Plugin
5
+ *
6
+ * This file initializes all constants and translatable strings of the plugin.
7
+ *
8
+ * @link /lib/wfu_constants.php
9
+ *
10
+ * @package WordPress File Upload Plugin
11
+ * @subpackage Core Components
12
+ * @since 2.1.2
13
+ */
14
+
15
+ $siteurl = site_url();
16
+
17
+ /**
18
+ * Translatable Strings Initialization.
19
+ *
20
+ * This function initializes all translatable strings of the plugin.
21
+ *
22
+ * @since 4.7.0
23
+ */
24
+ function wfu_initialize_i18n_strings() {
25
+ if ( defined("WFU_I18_LOADED") ) return;
26
+ DEFINE("WFU_I18_LOADED", 1);
27
+ //plugin default values
28
+ DEFINE("WFU_UPLOADTITLE", __('Upload files', 'wp-file-upload'));
29
+ DEFINE("WFU_SELECTBUTTON", __('Select File', 'wp-file-upload'));
30
+ DEFINE("WFU_UPLOADBUTTON", __('Upload File', 'wp-file-upload'));
31
+ DEFINE("WFU_NOTIFYSUBJECT", __('File Upload Notification', 'wp-file-upload'));
32
+ DEFINE("WFU_NOTIFYMESSAGE", __("Dear Recipient,%n%%n% This is an automatic delivery message to notify you that a new file has been uploaded.%n%%n%Best Regards", 'wp-file-upload'));
33
+ DEFINE("WFU_SUCCESSMESSAGE", __('File %filename% uploaded successfully', 'wp-file-upload'));
34
+ DEFINE("WFU_WARNINGMESSAGE", __('File %filename% uploaded successfully but with warnings', 'wp-file-upload'));
35
+ DEFINE("WFU_ERRORMESSAGE", __('File %filename% not uploaded', 'wp-file-upload'));
36
+ DEFINE("WFU_WAITMESSAGE", __('File %filename% is being uploaded', 'wp-file-upload'));
37
+ DEFINE("WFU_USERDATALABEL", __('Your message', 'wp-file-upload')."|t:text|s:left|r:0|a:0|p:inline|d:");
38
+ DEFINE("WFU_CAPTCHAPROMPT", __('Please fill in the above words: ', 'wp-file-upload'));
39
+ DEFINE("WFU_UPLOADMEDIABUTTON", __('Upload Media', 'wp-file-upload'));
40
+ DEFINE("WFU_VIDEONAME", __('videostream', 'wp-file-upload'));
41
+ DEFINE("WFU_IMAGENAME", __('screenshot', 'wp-file-upload'));
42
+ DEFINE("WFU_CONSENTQUESTION", __('By activating this option I agree to let the website keep my personal data', 'wp-file-upload'));
43
+ DEFINE("WFU_CONSENTREJECTMESSAGE", __('You have denied to let the website keep your personal data. Upload cannot continue!', 'wp-file-upload'));
44
+ //browser default values
45
+ DEFINE("WFU_FILETITLE", __('File', 'wp-file-upload'));
46
+ DEFINE("WFU_DATETITLE", __('Date', 'wp-file-upload'));
47
+ DEFINE("WFU_SIZETITLE", __('Size', 'wp-file-upload'));
48
+ DEFINE("WFU_USERTITLE", __('User', 'wp-file-upload'));
49
+ DEFINE("WFU_POSTTITLE", __('Page', 'wp-file-upload'));
50
+ DEFINE("WFU_FIELDSTITLE", __('User Fields', 'wp-file-upload'));
51
+ DEFINE("WFU_DOWNLOADLABEL", __('Download', 'wp-file-upload'));
52
+ DEFINE("WFU_DOWNLOADTITLE", __('Download this file', 'wp-file-upload'));
53
+ DEFINE("WFU_DELETELABEL", __('Delete', 'wp-file-upload'));
54
+ DEFINE("WFU_DELETETITLE", __('Delete this file', 'wp-file-upload'));
55
+ DEFINE("WFU_SORTTITLE", __('Sort list based on this column', 'wp-file-upload'));
56
+ DEFINE("WFU_GUESTTITLE", __('guest', 'wp-file-upload'));
57
+ DEFINE("WFU_UNKNOWNTITLE", __('unknown', 'wp-file-upload'));
58
+ //error messages
59
+ DEFINE("WFU_ERROR_ADMIN_FTPDIR_RESOLVE", __("Error. Could not resolve ftp target filedir. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
60
+ DEFINE("WFU_ERROR_ADMIN_FTPINFO_INVALID", __("Error. Invalid ftp information. Check 'ftpinfo' attribute.", "wp-file-upload"));
61
+ DEFINE("WFU_ERROR_ADMIN_FTPINFO_EXTRACT", __("Error. Could not extract ftp information from 'ftpinfo' attribute. Check its syntax.", "wp-file-upload"));
62
+ DEFINE("WFU_ERROR_ADMIN_FTPFILE_RESOLVE", __("Error. Could not resolve ftp target filename. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
63
+ DEFINE("WFU_ERROR_ADMIN_FTPSOURCE_FAIL", __("Error. Could not open source file for ftp upload. Check if file is accessible.", "wp-file-upload"));
64
+ DEFINE("WFU_ERROR_ADMIN_FTPTRANSFER_FAIL", __("Error. Could not send data to ftp target file.", "wp-file-upload"));
65
+ DEFINE("WFU_ERROR_ADMIN_FTPHOST_FAIL", __("Error. Could not connect to ftp host. Check the domain in 'ftpinfo' attribute.", "wp-file-upload"));
66
+ DEFINE("WFU_ERROR_ADMIN_FTPLOGIN_FAIL", __("Error. Could not authenticate to ftp host. Check username and password in 'ftpinfo' attribute.", "wp-file-upload"));
67
+ DEFINE("WFU_ERROR_ADMIN_SFTPINIT_FAIL", __("Error. Could not initialize sftp subsystem. Please check if the server supports sftp.", "wp-file-upload"));
68
+ DEFINE("WFU_ERROR_ADMIN_SFTP_UNSUPPORTED", __("Error. The web server does not support sftp.", "wp-file-upload"));
69
+ DEFINE("WFU_ERROR_ADMIN_FILE_PHP_SIZE", __("Error. The upload size limit of PHP directive upload_max_filesize is preventing the upload of big files.\nPHP directive upload_max_filesize limit is: ".ini_get("upload_max_filesize").".\nTo increase the limit change the value of the directive from php.ini.\nIf you don't have access to php.ini, then try adding the following line to your .htaccess file:\n\nphp_value upload_max_filesize 10M\n\n(adjust the size according to your needs)\n\nThe file .htaccess is found in your website root directory (where index.php is found).\nIf your don't have this file, then create it.\nIf this does not work either, then contact your domain provider.", "wp-file-upload"));
70
+ DEFINE("WFU_ERROR_ADMIN_FILE_PHP_TIME", __("The upload time limit of PHP directive max_input_time is preventing the upload of big files.\nPHP directive max_input_time limit is: ".ini_get("max_input_time")." seconds.\nTo increase the limit change the value of the directive from php.ini.\nIf you don't have access to php.ini, then add the following line to your .htaccess file:\n\nphp_value max_input_time 500\n\n(adjust the time according to your needs)\n\nThe file .htaccess is found in your website root directory (where index.php is found).\nIf your don't have this file, then create it.\nIf this does not work either, then contact your domain provider.", "wp-file-upload"));
71
+ DEFINE("WFU_ERROR_ADMIN_DIR_PERMISSION", __("Error. Permission denied to write to target folder.\nCheck and correct read/write permissions of target folder.", "wp-file-upload"));
72
+ DEFINE("WFU_ERROR_ADMIN_FILE_WRONGEXT", __("Error. This file was rejected because its extension is not correct. Its proper filename is: ", "wp-file-upload"));
73
+ DEFINE("WFU_ERROR_ADMIN_DOS_ATTACK", __("Too many files are uploaded in a short period of time. This may be a Denial-Of-Service attack, so file was rejected. Please check the upload log for suspicious behaviour.", "wp-file-upload"));
74
+ DEFINE("WFU_ERROR_DOS_ATTACK", __("File not uploaded in order to prevent overflow of the website. Please contact administrator.", "wp-file-upload"));
75
+ DEFINE("WFU_ERROR_DIR_EXIST", __("Target folder doesn't exist.", "wp-file-upload"));
76
+ DEFINE("WFU_ERROR_DIR_NOTEMP", __("Upload failed! Missing a temporary folder.", "wp-file-upload"));
77
+ DEFINE("WFU_ERROR_DIR_PERMISSION", __("Upload failed! Permission denied to write to target folder.", "wp-file-upload"));
78
+ DEFINE("WFU_ERROR_FILE_ALLOW", __("File not allowed.", "wp-file-upload"));
79
+ DEFINE("WFU_ERROR_FILE_REJECT", __("File is suspicious and was rejected.", "wp-file-upload"));
80
+ DEFINE("WFU_ERROR_FILE_PLUGIN_SIZE", __("The uploaded file exceeds the file size limit.", "wp-file-upload"));
81
+ DEFINE("WFU_ERROR_FILE_PLUGIN_2GBSIZE", __("The uploaded file exceeds 2GB and is not supported by this server.", "wp-file-upload"));
82
+ DEFINE("WFU_ERROR_FILE_PHP_SIZE", __("Upload failed! The uploaded file exceeds the file size limit of the server. Please contact the administrator.", "wp-file-upload"));
83
+ DEFINE("WFU_ERROR_FILE_PHP_TIME", __("Upload failed! The duration of the upload exceeded the time limit of the server. Please contact the administrator.", "wp-file-upload"));
84
+ DEFINE("WFU_ERROR_FILE_HTML_SIZE", __("Upload failed! The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.", "wp-file-upload"));
85
+ DEFINE("WFU_ERROR_FILE_PARTIAL", __("Upload failed! The uploaded file was only partially uploaded.", "wp-file-upload"));
86
+ DEFINE("WFU_ERROR_FILE_NOTHING", __("Upload failed! No file was uploaded.", "wp-file-upload"));
87
+ DEFINE("WFU_ERROR_FILE_WRITE", __("Upload failed! Failed to write file to disk.", "wp-file-upload"));
88
+ DEFINE("WFU_ERROR_FILE_MOVE", __("Upload failed! Error occured while moving temporary file. Please contact administrator.", "wp-file-upload"));
89
+ DEFINE("WFU_ERROR_FILE_CANCELLED", __("Upload cancelled!", "wp-file-upload"));
90
+ DEFINE("WFU_ERROR_UPLOAD_STOPPED", __("Upload failed! A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.", "wp-file-upload"));
91
+ DEFINE("WFU_ERROR_UPLOAD_FAILED_WHILE", __("Upload failed! Error occured while attemting to upload the file.", "wp-file-upload"));
92
+ DEFINE("WFU_ERROR_UPLOAD_FAILED", __("Upload failed!", "wp-file-upload"));
93
+ DEFINE("WFU_ERROR_UPLOAD_NOFILESELECTED", __("No file!", "wp-file-upload"));
94
+ DEFINE("WFU_ERROR_UPLOAD_CANCELLED", __("Upload failed! The upload has been canceled by the user or the browser dropped the connection.", "wp-file-upload"));
95
+ DEFINE("WFU_ERROR_UNKNOWN", __("Upload failed! Unknown error.", "wp-file-upload"));
96
+ DEFINE("WFU_ERROR_CONTACT_ADMIN", __("Please contact the administrator.", "wp-file-upload"));
97
+ DEFINE("WFU_ERROR_REMOTESERVER_NORESULT", __("No result from remote server!", "wp-file-upload"));
98
+ DEFINE("WFU_ERROR_JSONPARSE_FILEMESSAGE", __(" but with warnings", "wp-file-upload"));
99
+ DEFINE("WFU_ERROR_JSONPARSE_MESSAGE", __("Warning: JSON parse error.", "wp-file-upload"));
100
+ DEFINE("WFU_ERROR_JSONPARSE_ADMINMESSAGE", __("Upload parameters of this file, passed as JSON string to the handler, could not be parsed.", "wp-file-upload"));
101
+ DEFINE("WFU_ERROR_JSONPARSE_HEADERMESSAGE", __("Warning: JSON parse error.", "wp-file-upload"));
102
+ DEFINE("WFU_ERROR_JSONPARSE_HEADERADMINMESSAGE", __("UploadStates, passed as JSON string to the handler, could not be parsed.", "wp-file-upload"));
103
+ DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE0", __("Redirection to classic form functionality occurred due to unknown error.", "wp-file-upload"));
104
+ DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE1", __("Redirection to classic form functionality occurred because AJAX is not supported.", "wp-file-upload"));
105
+ DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE2", __("Redirection to classic form functionality occurred because HTML5 is not supported.", "wp-file-upload"));
106
+ DEFINE("WFU_ERROR_REDIRECTION_ERRORCODE3", __("Redirection to classic form functionality occurred due to JSON parse error.", "wp-file-upload"));
107
+ DEFINE("WFU_ERROR_ENABLE_POPUPS", __("Please enable popup windows from the browser's settings!", "wp-file-upload"));
108
+ DEFINE("WFU_ERROR_USERDATA_EMPTY", __("cannot be empty!", "wp-file-upload"));
109
+ DEFINE("WFU_ERROR_USERDATANUMBER_INVALID", __("number not valid!", "wp-file-upload"));
110
+ DEFINE("WFU_ERROR_USERDATAEMAIL_INVALID", __("email not valid!", "wp-file-upload"));
111
+ DEFINE("WFU_ERROR_USERDATACONFIRMEMAIL_NOMATCH", __("emails do not match!", "wp-file-upload"));
112
+ DEFINE("WFU_ERROR_USERDATACONFIRMEMAIL_NOBASE", __("no base email field in group!", "wp-file-upload"));
113
+ DEFINE("WFU_ERROR_USERDATACONFIRMPASSWORD_NOMATCH", __("passwords do not match!", "wp-file-upload"));
114
+ DEFINE("WFU_ERROR_USERDATACONFIRMPASSWORD_NOBASE", __("no base password field in group!", "wp-file-upload"));
115
+ DEFINE("WFU_ERROR_USERDATACHECKBOX_NOTCHECKED", __("checkbox unchecked!", "wp-file-upload"));
116
+ DEFINE("WFU_ERROR_USERDATARADIO_NOTSELECTED", __("no option selected!", "wp-file-upload"));
117
+ DEFINE("WFU_ERROR_USERDATALIST_NOITEMSELECTED", __("no item selected!", "wp-file-upload"));
118
+ DEFINE("WFU_ERROR_SAME_PLUGINID", __("There are more than one instances of the plugin in this page with the same id. Please change it.", "wp-file-upload"));
119
+ DEFINE("WFU_ERROR_PAGE_OBSOLETE", __("Cannot edit the shortcode because the page has been modified. Please reload the page.", "wp-file-upload"));
120
+ DEFINE("WFU_ERROR_WEBCAM_NOTSUPPORTED", __("Your browser does not support webcam capture!", "wp-file-upload"));
121
+ DEFINE("WFU_ERROR_WEBCAM_VIDEO_NOTSUPPORTED", __("Your browser does not support video recording from the webcam!", "wp-file-upload"));
122
+ DEFINE("WFU_ERROR_WEBCAM_VIDEO_NOTHINGRECORDED", __("No video was recorded!", "wp-file-upload"));
123
+ DEFINE("WFU_ERROR_CAPTCHA_OLDPHP", __("ERROR: Captcha not supported! You have an old PHP version. Upgrade your PHP or use RecaptchaV2 (no account).", "wp-file-upload"));
124
+ DEFINE("WFU_ERROR_CAPTCHA_MULTIPLE_NOTALLOWED", __("ERROR: Only one instance of RecaptchaV1 can exist on the same page. Please notify administrator.", "wp-file-upload"));
125
+ DEFINE("WFU_ERROR_CAPTCHA_MULTIPLE_NOTALLOWED_ADMIN", __("ERROR: Only one instance of RecaptchaV1 can exist on the same page. Please use RecaptchaV1 (no account).", "wp-file-upload"));
126
+ DEFINE("WFU_ERROR_CAPTCHA_NOSITEKEY", __("ERROR: No site key. Please contact administrator!", "wp-file-upload"));
127
+ DEFINE("WFU_ERROR_CAPTCHA_NOSITEKEY_ADMIN", __("ERROR: No site key defined! Please go to the plugin settings in Dashboard to define Google Recaptcha keys.", "wp-file-upload"));
128
+ DEFINE("WFU_ERROR_CAPTCHA_NOCHALLENGE", __("Bad captcha image!", "wp-file-upload"));
129
+ DEFINE("WFU_ERROR_CAPTCHA_NOINPUT", __("No input!", "wp-file-upload"));
130
+ DEFINE("WFU_ERROR_CAPTCHA_EMPTY", __("Captcha not completed!", "wp-file-upload"));
131
+ DEFINE("WFU_ERROR_CAPTCHA_WRONGCAPTCHA", __("Wrong captcha!", "wp-file-upload"));
132
+ DEFINE("WFU_ERROR_CAPTCHA_REFRESHING", __("Error refreshing captcha!", "wp-file-upload"));
133
+ DEFINE("WFU_ERROR_CAPTCHA_UNKNOWNERROR", __("Unknown captcha error!", "wp-file-upload"));
134
+ DEFINE("WFU_ERROR_CAPTCHA_NOTSUPPORTED", __("Captcha not supported by your browser!", "wp-file-upload"));
135
+ DEFINE("WFU_ERROR_CAPTCHA_MISSINGINPUTSECRET", __("the secret parameter is missing", "wp-file-upload"));
136
+ DEFINE("WFU_ERROR_CAPTCHA_INVALIDINPUTSECRET", __("the secret parameter is invalid or malformed", "wp-file-upload"));
137
+ DEFINE("WFU_ERROR_CAPTCHA_MISSINGINPUTRESPONSE", __("the response parameter is missing", "wp-file-upload"));
138
+ DEFINE("WFU_ERROR_CAPTCHA_INVALIDINPUTRESPONSE", __("the response parameter is invalid or malformed", "wp-file-upload"));
139
+ DEFINE("WFU_ERROR_REDIRECTION_NODRAGDROP", __("Please do not use drag drop due to an internal problem.", "wp-file-upload"));
140
+ DEFINE("WFU_ERROR_CHUNKEDUPLOAD_UNIQUEIDEMPTY", __("Error during chunked upload. Unique ID empty in chunk %d", "wp-file-upload"));
141
+ DEFINE("WFU_ERROR_CHUNKEDUPLOAD_NOTALLOWED", __("Chunked upload is not allowed!", "wp-file-upload"));
142
+ DEFINE("WFU_ERROR_CHUNKEDUPLOAD_ABORTED", __("Chunked upload aborted due to error in previous chunk!", "wp-file-upload"));
143
+ DEFINE("WFU_ERROR_CHUNKEDUPLOAD_CONCATFAILED", __("Chunked upload failed, final file could not be created!", "wp-file-upload"));
144
+ DEFINE("WFU_ERROR_ADMIN_CHUNKWRITEFAILED", __("Could not write file chuck to destination on chunk %d", "wp-file-upload"));
145
+ DEFINE("WFU_ERROR_ADMIN_CHUNKENLARGEFAILED", __("Could not enlarge destination file on chunk %d", "wp-file-upload"));
146
+ DEFINE("WFU_ERROR_ADMIN_CHUNKHANDLEFAILED", __("Could not open file handles on chunk %d", "wp-file-upload"));
147
+ DEFINE("WFU_BROWSER_DOWNLOADFILE_NOTALLOWED", __("You are not allowed to download this file!", "wp-file-upload"));
148
+ DEFINE("WFU_BROWSER_DOWNLOADFILE_NOTEXIST", __("File does not exist!", "wp-file-upload"));
149
+ DEFINE("WFU_BROWSER_DOWNLOADFILE_FAILED", __("Could not download file!", "wp-file-upload"));
150
+ DEFINE("WFU_BROWSER_DELETEFILE_NOTALLOWED", __("You are not allowed to delete this file!", "wp-file-upload"));
151
+ DEFINE("WFU_BROWSER_DELETEFILE_FAILED", __("File was not deleted!", "wp-file-upload"));
152
+ DEFINE("WFU_BROWSER_DELETEFILES_ALLFAILED", __("No file was deleted!", "wp-file-upload"));
153
+ DEFINE("WFU_BROWSER_DELETEFILES_SOMEFAILED", __("Some files were not deleted!", "wp-file-upload"));
154
+ //warning messages
155
+ DEFINE("WFU_WARNING_FILE_EXISTS", __("Upload skipped! File already exists.", "wp-file-upload"));
156
+ DEFINE("WFU_WARNING_FILE_SUSPICIOUS", __("The extension of the file does not match its contents.", "wp-file-upload"));
157
+ DEFINE("WFU_WARNING_ADMIN_FILE_SUSPICIOUS", __("Upload succeeded but the file is suspicious because its contents do not match its extension. Its proper filename is: ", "wp-file-upload"));
158
+ DEFINE("WFU_WARNING_NOFILES_SELECTED", __("No files have been selected!", "wp-file-upload"));
159
+ DEFINE("WFU_WARNING_CONSENT_NOTCOMPLETED", __("Please complete the consent question before continuing the upload!", "wp-file-upload"));
160
+ DEFINE("WFU_WARNING_WPFILEBASE_NOTUPDATED_NOFILES", __("WPFilebase Plugin not updated because there were no files uploaded.", "wp-file-upload"));
161
+ DEFINE("WFU_WARNING_NOTIFY_NOTSENT_NOFILES", __("Notification email was not sent because there were no files uploaded.", "wp-file-upload"));
162
+ DEFINE("WFU_WARNING_NOTIFY_NOTSENT_NORECIPIENTS", __("Notification email was not sent because no recipients were defined. Please check notifyrecipients attribute in the shortcode.", "wp-file-upload"));
163
+ DEFINE("WFU_WARNING_NOTIFY_NOTSENT_UNKNOWNERROR", __("Notification email was not sent due to an error. Please check notifyrecipients, notifysubject and notifymessage attributes for errors.", "wp-file-upload"));
164
+ DEFINE("WFU_WARNING_REDIRECT_NOTEXECUTED_EMPTY", __("Redirection not executed because redirection link is empty. Please check redirectlink attribute.", "wp-file-upload"));
165
+ DEFINE("WFU_WARNING_REDIRECT_NOTEXECUTED_FILESFAILED", __("Redirection not executed because not all files were successfully uploaded.", "wp-file-upload"));
166
+ DEFINE("WFU_WARNING_POTENTIAL_DOS_EMAIL_SUBJECT", __("Potential Denial-Of-Service Attack on {SITE}", "wp-file-upload"));
167
+ DEFINE("WFU_WARNING_POTENTIAL_DOS_EMAIL_MESSAGE", __("Hello admin\n\nThis is a message from Wordpress File Upload Plugin to notify you that a potential Denial-Of-Service attack has been detected on {SITE}.\n\nThe plugin detected more than {FILENUM} uploads within {INTERVAL} seconds.\n\nAll file uploads that exceed this limit are rejected to protect the website from overflowing.\n\nPlease check the upload history log in the plugin's area in Dashboard for any suspicious behaviour.\n\nA new message will follow if the situation remains.\n\nThanks", "wp-file-upload"));
168
+ DEFINE("WFU_WARNING_ALT_IPTANUS_SERVER_ACTIVATED", __("You have activated an alternative insecure Iptanus Services Server. For details please contact info@iptanus.com.", "wp-file-upload"));
169
+ DEFINE("WFU_WARNING_IPTANUS_SERVER_UNREACHABLE", __("Iptanus Services Server is unreachable. This may cause problems on some plugin functions. Please read this :article: for resolution.", "wp-file-upload"));
170
+ //admin area messages
171
+ DEFINE("WFU_DASHBOARD_ADD_SHORTCODE_REJECTED", __("Failed to add the shortcode to the page/post. Please try again. If the message persists, contact administrator.", "wp-file-upload"));
172
+ DEFINE("WFU_DASHBOARD_EDIT_SHORTCODE_REJECTED", __("Failed to edit the shortcode because the contents of the page changed. Try again to edit the shortcode.", "wp-file-upload"));
173
+ DEFINE("WFU_DASHBOARD_DELETE_SHORTCODE_REJECTED", __("Failed to delete the shortcode because the contents of the page changed. Try again to delete it.", "wp-file-upload"));
174
+ DEFINE("WFU_DASHBOARD_PAGE_OBSOLETE", __("The page containing the shortcode has been modified and it is no longer valid. Please go back to reload the shortcode.", "wp-file-upload"));
175
+ DEFINE("WFU_DASHBOARD_UPDATE_SHORTCODE_REJECTED", __("Failed to update the shortcode because the contents of the page changed. Go back to reload the shortcode.", "wp-file-upload"));
176
+ DEFINE("WFU_DASHBOARD_UPDATE_SHORTCODE_FAILED", __("Failed to update the shortcode. Please try again. If the problem persists, go back and reload the shortcode.", "wp-file-upload"));
177
+ //test messages
178
+ DEFINE("WFU_TESTMESSAGE_MESSAGE", __('This is a test message', 'wp-file-upload'));
179
+ DEFINE("WFU_TESTMESSAGE_ADMINMESSAGE", __('This is a test administrator message', 'wp-file-upload'));
180
+ DEFINE("WFU_TESTMESSAGE_FILE1_HEADER", __('File testfile 1 under test', 'wp-file-upload'));
181
+ DEFINE("WFU_TESTMESSAGE_FILE1_MESSAGE", __('File testfile 1 message', 'wp-file-upload'));
182
+ DEFINE("WFU_TESTMESSAGE_FILE1_ADMINMESSAGE", __('File testfile 1 administrator message', 'wp-file-upload'));
183
+ DEFINE("WFU_TESTMESSAGE_FILE2_HEADER", __('File testfile 2 under test', 'wp-file-upload'));
184
+ DEFINE("WFU_TESTMESSAGE_FILE2_MESSAGE", __('File testfile 2 message', 'wp-file-upload'));
185
+ DEFINE("WFU_TESTMESSAGE_FILE2_ADMINMESSAGE", __('File testfile 2 administrator message', 'wp-file-upload'));
186
+ //variables tool-tips
187
+ DEFINE("WFU_VARIABLE_TITLE_USERID", __("Insert variable %userid% inside text. It will be replaced by the id of the current user.", "wp-file-upload"));
188
+ DEFINE("WFU_VARIABLE_TITLE_USERNAME", __("Insert variable %username% inside text. It will be replaced by the username of the current user.", "wp-file-upload"));
189
+ DEFINE("WFU_VARIABLE_TITLE_USEREMAIL", __("Insert variable %useremail% inside text. It will be replaced by the email of the current user.", "wp-file-upload"));
190
+ DEFINE("WFU_VARIABLE_TITLE_FILENAME", __("Insert variable %filename% inside text. It will be replaced by the filename of the uploaded file.", "wp-file-upload"));
191
+ DEFINE("WFU_VARIABLE_TITLE_FILEPATH", __("Insert variable %filepath% inside text. It will be replaced by the full filepath of the uploaded file.", "wp-file-upload"));
192
+ DEFINE("WFU_VARIABLE_TITLE_BLOGID", __("Insert variable %blogid% inside text. It will be replaced by the blog id of the website.", "wp-file-upload"));
193
+ DEFINE("WFU_VARIABLE_TITLE_PAGEID", __("Insert variable %pageid% inside text. It will be replaced by the id of the current page.", "wp-file-upload"));
194
+ DEFINE("WFU_VARIABLE_TITLE_PAGETITLE", __("Insert variable %pagetitle% inside text. It will be replaced by the title of the current page.", "wp-file-upload"));
195
+ DEFINE("WFU_VARIABLE_TITLE_USERDATAXXX", __("Insert variable %userdataXXX% inside text. Select the user field from the drop-down list. It will be replaced by the value that the user entered in this field.", "wp-file-upload"));
196
+ DEFINE("WFU_VARIABLE_TITLE_N", __("Insert variable %n% inside text to denote a line change.", "wp-file-upload"));
197
+ //other plugin values
198
+ DEFINE("WFU_WARNINGMESSAGE_NOSAVE", __('File %filename% uploaded successfully but not saved', 'wp-file-upload'));
199
+ DEFINE("WFU_NOTIFY_TESTMODE", __("Test Mode", "wp-file-upload"));
200
+ DEFINE("WFU_SUBDIR_SELECTDIR", __("select dir...", "wp-file-upload"));
201
+ DEFINE("WFU_SUBDIR_TYPEDIR", __("type dir", "wp-file-upload"));
202
+ DEFINE("WFU_SUCCESSMESSAGE_DETAILS", __('Upload path: %filepath%', 'wp-file-upload'));
203
+ DEFINE("WFU_FAILMESSAGE_DETAILS", __('Failed upload path: %filepath%', 'wp-file-upload'));
204
+ DEFINE("WFU_USERDATA_REQUIREDLABEL", __(' (required)', 'wp-file-upload'));
205
+ DEFINE("WFU_PAGEEXIT_PROMPT", __('Files are being uploaded. Are you sure you want to exit the page?', 'wp-file-upload'));
206
+ DEFINE("WFU_MESSAGE_CAPTCHA_CHECKING", __("checking captcha...", "wp-file-upload"));
207
+ DEFINE("WFU_MESSAGE_CAPTCHA_REFRESHING", __("refreshing...", "wp-file-upload"));
208
+ DEFINE("WFU_MESSAGE_CAPTCHA_OK", __("correct captcha", "wp-file-upload"));
209
+ DEFINE("WFU_CONFIRMBOX_CAPTION", __("click to continue the upload", "wp-file-upload"));
210
+ DEFINE("WFU_BROWSER_DELETEFILE_PROMPT", __("Are you sure you want to delete this file?", "wp-file-upload"));
211
+ DEFINE("WFU_BROWSER_DELETEFILES_PROMPT", __("Are you sure you want to delete these files?", "wp-file-upload"));
212
+ DEFINE("WFU_BROWSER_BULKACTION_TITLE", __("Bulk Actions", "wp-file-upload"));
213
+ DEFINE("WFU_BROWSER_BULKACTION_LABEL", __("Apply", "wp-file-upload"));
214
+ DEFINE("WFU_PAGINATION_PAGE", __("Page", "wp-file-upload"));
215
+ DEFINE("WFU_PAGINATION_OF", __("of ", "wp-file-upload"));
216
+ DEFINE("WFU_CANCEL_UPLOAD_PROMPT", __("Are you sure that you want to cancel the upload?", "wp-file-upload"));
217
+ DEFINE("WFU_FILE_CANCEL_HINT", __("cancel upload of this file", "wp-file-upload"));
218
+ DEFINE("WFU_UPLOAD_STATE0", __("Upload in progress", "wp-file-upload"));
219
+ DEFINE("WFU_UPLOAD_STATE1", __("Upload in progress with warnings!", "wp-file-upload"));
220
+ DEFINE("WFU_UPLOAD_STATE2", __("Upload in progress but some files already failed!", "wp-file-upload"));
221
+ DEFINE("WFU_UPLOAD_STATE3", __("Upload in progress but no files uploaded so far!", "wp-file-upload"));
222
+ DEFINE("WFU_UPLOAD_STATE4", __("All files uploaded successfully", "wp-file-upload"));
223
+ DEFINE("WFU_UPLOAD_STATE5", __("All files uploaded successfully but there are warnings!", "wp-file-upload"));
224
+ DEFINE("WFU_UPLOAD_STATE5_SINGLEFILE", __("File uploaded successfully but there are warnings!", "wp-file-upload"));
225
+ DEFINE("WFU_UPLOAD_STATE6", __("Some files failed to upload!", "wp-file-upload"));
226
+ DEFINE("WFU_UPLOAD_STATE7", __("All files failed to upload", "wp-file-upload"));
227
+ DEFINE("WFU_UPLOAD_STATE7_SINGLEFILE", __("File failed to upload", "wp-file-upload"));
228
+ DEFINE("WFU_UPLOAD_STATE8", __("There are no files to upload!", "wp-file-upload"));
229
+ DEFINE("WFU_UPLOAD_STATE9", __("Test upload message", "wp-file-upload"));
230
+ DEFINE("WFU_UPLOAD_STATE10", __("JSON parse warning!", "wp-file-upload"));
231
+ DEFINE("WFU_UPLOAD_STATE11", __("please wait while redirecting...", "wp-file-upload"));
232
+ DEFINE("WFU_UPLOAD_STATE12", __("Upload failed!", "wp-file-upload"));
233
+ DEFINE("WFU_UPLOAD_STATE13", __("Submitting data", "wp-file-upload"));
234
+ DEFINE("WFU_UPLOAD_STATE14", __("Data submitted successfully!", "wp-file-upload"));
235
+ DEFINE("WFU_UPLOAD_STATE15", __("Data were not submitted!", "wp-file-upload"));
236
+ DEFINE("WFU_UPLOAD_STATE16", __("Cancelling upload", "wp-file-upload"));
237
+ DEFINE("WFU_UPLOAD_STATE17", __("Upload cancelled!", "wp-file-upload"));
238
+ DEFINE("WFU_UPLOAD_STATE18", __("Upload succeeded!", "wp-file-upload"));
239
+ DEFINE("WFU_UPLOAD_STATE19", __("Upload completed but no files were saved!", "wp-file-upload"));
240
+ DEFINE("WFU_UPLOAD_STATE19_SINGLEFILE", __("File was not saved due to personal data policy!", "wp-file-upload"));
241
+ DEFINE("WFU_PAGE_PLUGINEDITOR_BUTTONTITLE", __("Open visual shortcode editor in new window", "wp-file-upload"));
242
+ DEFINE("WFU_PAGE_PLUGINEDITOR_LOADING", __("loading visual editor", "wp-file-upload"));
243
+ DEFINE("WFU_CONFIRM_CLEARFILES", __("Clear file list?", "wp-file-upload"));
244
+ DEFINE("WFU_DROP_HERE_MESSAGE", __('DROP HERE', 'wp-file-upload'));
245
+ //webcam values
246
+ DEFINE("WFU_WEBCAM_RECVIDEO_BTN", __('record video', 'wp-file-upload'));
247
+ DEFINE("WFU_WEBCAM_TAKEPIC_BTN", __('take a picture', 'wp-file-upload'));
248
+ DEFINE("WFU_WEBCAM_TURNONOFF_BTN", __('turn webcam on/off', 'wp-file-upload'));
249
+ DEFINE("WFU_WEBCAM_GOLIVE_BTN", __('go live again', 'wp-file-upload'));
250
+ DEFINE("WFU_WEBCAM_STOPREC_BTN", __('end recording', 'wp-file-upload'));
251
+ DEFINE("WFU_WEBCAM_PLAY_BTN", __('play', 'wp-file-upload'));
252
+ DEFINE("WFU_WEBCAM_PAUSE_BTN", __('pause', 'wp-file-upload'));
253
+ DEFINE("WFU_WEBCAM_GOBACK_BTN", __('go to the beginning', 'wp-file-upload'));
254
+ DEFINE("WFU_WEBCAM_GOFWD_BTN", __('go to the end', 'wp-file-upload'));
255
+ //widget values
256
+ DEFINE("WFU_WIDGET_PLUGINFORM_TITLE", __('Wordpress File Upload Form', 'wp-file-upload'));
257
+ DEFINE("WFU_WIDGET_PLUGINFORM_DESCRIPTION", __('Wordpress File Upload plugin uploader for sidebars', 'wp-file-upload'));
258
+ DEFINE("WFU_WIDGET_SIDEBAR_DEFAULTTITLE", __('Upload Files', 'wp-file-upload'));
259
+ }
260
+
261
+ /*********** Environment Variables ************/
262
+ //plugin default values
263
+ $GLOBALS["WFU_GLOBALS"] = array(
264
+ "WFU_UPLOADID" => array( "Default Upload ID", "string", "1", "The default upload ID of the uploader shortcode. It can be any integer from 1 and above." ),
265
+ "WFU_SINGLEBUTTON" => array( "Default Single-Button Status", "string", "false", "The default single-button status of the uploader shortcode. It can be 'true' or 'false'." ),
266
+ "WFU_UPLOADROLE" => array( "Default Upload Role", "string", "all,guests", "The default upload role of the uploader shortcode. It can be a comma-separated list of role slugs, including keywords 'all' and 'guests'." ),
267
+ "WFU_UPLOADPATH" => array( "Default Upload Path", "string", "uploads", "The default upload path of the uploader shortcode. It must be a folder relative to wp-content dir." ),
268
+ "WFU_FITMODE" => array( "Default Fit Mode", "string", "fixed", "The default fit mode of the uploader shortcode. It can be 'fixed' or 'responsive'." ),
269
+ "WFU_ALLOWNOFILE" => array( "Default Allow No File Mode", "string", "false", "The default mode for allowing no file uploads. If it is set to 'true' then an upload form can be submitted even if a file has not been selected. It can be 'true' or 'false'." ),
270
+ "WFU_ALLOWNOFILE" => array( "Default Allow No File Mode", "string", "false", "The default mode for allowing no file uploads. If it is set to 'true' then an upload form can be submitted even if a file has not been selected. It can be 'true' or 'false'." ),
271
+ "WFU_RESETMODE" => array( "Default Reset Form Mode", "string", "always", "The default reset mode of the upload form. It can be 'always', 'onsuccess' or 'never'." ),
272
+ "WFU_FORCEFILENAME" => array( "Default Force Filename State", "string", "false", "The default force filename state (force plugin to leave filename unchanged) of the uploader shortcode. It can be 'true' or 'false'." ),
273
+ "WFU_UPLOADPATTERNS" => array( "Default Upload Extensions", "string", "*.*", "The default allowed file extensions of the uploader shortcode. It can be a comma-separated list of wildcard extensions." ),
274
+ "WFU_MAXSIZE" => array( "Default Maximum File Size", "string", "50", "The default maximum allowed file size of the uploader shortcode in Megabytes. It can be any positive number." ),
275
+ "WFU_ACCESSMETHOD" => array( "Default Access Method", "string", "normal", "The default access method (of the website filesystem) of the uploader shortcode. It can be 'normal' or 'ftp'." ),
276
+ "WFU_FTPINFO" => array( "Default FTP Access Information", "string", "", "The default FTP access parameters of the uploader shortcode. It's syntax is 'username:password@ftp_domain'." ),
277
+ "WFU_USEFTPDOMAIN" => array( "Default Use FTP Domain State", "string", "false", "The default use FTP domain state (use the FTP domain defined in ftpinfo to store the uploaded files) of the uploader shortcode. It can be 'true' or 'false'." ),
278
+ "WFU_FTPPASSIVEMODE" => array( "Default FTP Passive Mode State", "string", "false", "The default FTP passive mode (use passive mode or not for FTP access) of the uploader shortcode. It can be 'true' or 'false'." ),
279
+ "WFU_FTPFILEPERMISSIONS" => array( "Default FTP File Permissions", "string", "", "The default FTP passive mode (use passive mode or not for FTP access) of the uploader shortcode. It can be 'true' or 'false'." ),
280
+ "WFU_DUBLICATESPOLICY" => array( "Default Duplicate File Action", "string", "overwrite", "The default duplicate file action of the uploader shortcode. It can be 'overwrite', 'reject' or 'mantain both'." ),
281
+ "WFU_UNIQUEPATTERN" => array( "Default Duplicate File Pattern", "string", "index", "The default duplicate file pattern of the uploader shortcode. It can be 'index' or 'datetimestamp'." ),
282
+ "WFU_FILEBASELINK" => array( "Default WPFilebase Update State", "string", "false", "The default WPFilebase plugin update state of the uploader shortcode. It can be 'true' or 'false'." ),
283
+ "WFU_NOTIFY" => array( "Default Email Notification State", "string", "false", "The default email notification state of the uploader shortcode. It can be 'true' or 'false'." ),
284
+ "WFU_NOTIFYRECIPIENTS" => array( "Default Email Recipients", "string", "", "The default email recipients of the uploader shortcode. It can be a comma-separated list of email addresses." ),
285
+ "WFU_NOTIFYHEADERS" => array( "Default Email Headers", "string", "", "The default email headers of the uploader shortcode." ),
286
+ "WFU_ATTACHFILE" => array( "Default Attach File State", "string", "false", "The default attach file to email state of the uploader shortcode. It can be 'true' or 'false'." ),
287
+ "WFU_REDIRECT" => array( "Default Redirection State", "string", "false", "The default redirection state of the uploader shortcode. It can be 'true' or 'false'." ),
288
+ "WFU_REDIRECTLINK" => array( "Default Redirect URL", "string", "", "The default redirect URL of the uploader shortcode." ),
289
+ "WFU_ADMINMESSAGES" => array( "Default State for Admin Messages", "string", "false", "The default state of displaying or not admin messages of the uploader shortcode. It can be 'true' or 'false'." ),
290
+ "WFU_SUCCESSMESSAGECOLORS" => array( "Default Colors for Success Message", "string", "#006600,#EEFFEE,#006666", "The default color triplet (text, background and border colors) of success message of the uploader shortcode." ),
291
+ "WFU_WARNINGMESSAGECOLORS" => array( "Default Colors for Warning Message", "string", "#F88017,#FEF2E7,#633309", "The default color triplet (text, background and border colors) of warning message of the uploader shortcode." ),
292
+ "WFU_FAILMESSAGECOLORS" => array( "Default Colors for Fail Message", "string", "#660000,#FFEEEE,#666600", "The default color triplet (text, background and border colors) of fail message of the uploader shortcode." ),
293
+ "WFU_WAITMESSAGECOLORS" => array( "Default Colors for Wait Message", "string", "#666666,#EEEEEE,#333333", "The default color triplet (text, background and border colors) of wait message of the uploader shortcode." ),
294
+ "WFU_SHOWTARGETFOLDER" => array( "Default State for Target Folder", "string", "false", "The default state of displaying or not the target folder of the uploader shortcode. It can be 'true' or 'false'." ),
295
+ "WFU_TARGETFOLDERLABEL" => array( "Default Text for Target Folder Label", "string", "Upload Directory", "The default text of the target folder label of the uploader shortcode." ),
296
+ "WFU_ASKFORSUBFOLDERS" => array( "Default Subfolders State", "string", "false", "The default state of displaying or not a list of subfolders of the uploader shortcode. It can be 'true' or 'false'." ),
297
+ "WFU_SUBFOLDERLABEL" => array( "Default Text of Subfolders Label", "string", "Select Subfolder", "The default text of subfolders label of the uploader shortcode." ),
298
+ "WFU_SUBFOLDERTREE" => array( "Default Subfolders List", "string", "", "The default list of subfolders of the uploader shortcode. Check plugin's support page for syntax." ),
299
+ "WFU_FORCECLASSIC" => array( "Default Disable AJAX State", "string", "false", "The default state of disabling or not AJAX functionality of the uploader shortcode. It can be 'true' or 'false'." ),
300
+ "WFU_TESTMODE" => array( "Default Test Mode State", "string", "false", "The default state of test mode of the uploader shortcode. It can be 'true' or 'false'." ),
301
+ "WFU_DEBUGMODE" => array( "Default Debug Mode State", "string", "false", "The default state of debug mode of the uploader shortcode. It can be 'true' or 'false'." ),
302
+ "WFU_WIDTHS" => array( "Default Element Widths", "string", "", "The default widths of the elements of the uploader shortcode. It is a comma-separated list of element widths." ),
303
+ "WFU_HEIGHTS" => array( "Default Element Heights", "string", "", "The default heights of the elements of the uploader shortcode. It is a comma-separated list of element heights." ),
304
+ "WFU_PLACEMENTS" => array( "Default Element Placements", "string", "title/filename+selectbutton+uploadbutton/subfolders"."/userdata"."/message", "The default placements of the elements of the uploader shortcode. Check plugin's support page for syntax." ),
305
+ "WFU_USERDATA" => array( "Default User Fields State", "string", "false", "The default state of custom user fields of the uploader shortcode. It can be 'true' or 'false'." ),
306
+ "WFU_MEDIALINK" => array( "Default Add to Media State", "string", "false", "The default state for adding files to Media of the uploader shortcode. It can be 'true' or 'false'." ),
307
+ "WFU_POSTLINK" => array( "Default Attachment to Post State", "string", "false", "The default state for attaching files to current post of the uploader shortcode. It can be 'true' or 'false'." ),
308
+ "WFU_WEBCAM" => array( "Default Webcam State", "string", "false", "The default state for webcam capture. It can be 'true' or 'false'." ),
309
+ "WFU_AUDIOCAPTURE" => array( "Default Capture Audio State", "string", "false", "The default state of audio capture. If it is set to 'true' then audio will be captured, together with video from the webcam. It can be 'true' or 'false'." ),
310
+ "WFU_WEBCAMMODE" => array( "Default Webcam Mode", "string", "capture video", "The default webcam capture mode. It can be 'capture video', 'take photos' or 'both'." ),
311
+ "WFU_VIDEOWIDTH" => array( "Default Video Width", "string", "", "The default preferable video width for webcam capture. It can be any positive integer in pixels." ),
312
+ "WFU_VIDEOHEIGHT" => array( "Default Video Height", "string", "", "The default preferable video height for webcam capture. It can be any positive integer in pixels." ),
313
+ "WFU_VIDEOASPECTRATIO" => array( "Default Video Aspect Ratio", "string", "", "The default preferable video aspect ratio for webcam video capture. It can be any positive value." ),
314
+ "WFU_VIDEOFRAMERATE" => array( "Default Video Frame Rate", "string", "", "The default preferable video frame rate for webcam video capture. It can be any positive value in frames/sec." ),
315
+ "WFU_CAMERAFACING" => array( "Default Camera Facing Mode", "string", "any", "The default preferable camera to be used for video/screenshot capture. It can be 'any', 'front' or 'back'." ),
316
+ "WFU_MAXRECORDTIME" => array( "Default Maximum Record Time", "string", "10", "The default maximum video recording time in seconds. The default value is 10 seconds." ),
317
+ "WFU_ASKCONSENT" => array( "Default Ask Consent State", "string", "false", "The default state of personal data consent request. The default value is false." ),
318
+ "WFU_PERSONALDATATYPES" => array( "Default Personal Data Types", "string", "userdata", "The default personal data types. The default value is 'userdata'." ),
319
+ "WFU_NOTREMEMBERCONSENT" => array( "Default Do Not Remember Consent Answer State", "string", "false", "The default state about remembering or not user's answer on consent question. The default value is true." ),
320
+ "WFU_CONSENTREJECTUPLOAD" => array( "Default Reject Upload on Consent Denial State", "string", "false", "The default state of continuing or rejecting the upload depending on consent answer. The default value is true." ),
321
+ "WFU_CONSENTFORMAT" => array( "Default Consent Format", "string", "radio", "The default format of consent question. The default value is 'checkbox'." ),
322
+ "WFU_CONSENTPRESELECT" => array( "Default Consent Preselect State", "string", "none", "The default preselect state of consent question when checkbox format is active. The default value is false." )
323
+ );
324
+ //other plugin values
325
+ $GLOBALS["WFU_GLOBALS"] += array(
326
+ "WFU_DEBUG" => array( "Plugin Debug Mode", "string", "OFF", "If DEBUG mode is activated then advanced hook of plugin's function can be performed. This option may make the plugin slower, so use it very carefully. It can be 'OFF' or 'ON'." ),
327
+ "WFU_RESTRICT_FRONTEND_LOADING" => array( "Restrict Front-End Loading", "string", "false", "It defines whether the plugin will load on all pages or specific ones. If it is 'false' then it will load on all pages. To restrict loading only on specific pages set a comma-separated list of page or post IDs." ),
328
+ "WFU_UPLOADPROGRESS_MODE" => array( "Upload Progress Mode", "string", "incremental", "Defines how the upload progress is calculated. It can be 'incremental' or 'absolute'. Default value is 'incremental'." ),
329
+ "WFU_DOS_ATTACKS_CHECK" => array( "Check for Denial-Of-Service Attacks", "string", "true", "If it is true then then plugin will check if the number of files uploaded within a specific amount of time exceeds the limit, thus protecting from DOS attacks. It can be 'true' or 'false'." ),
330
+ "WFU_DOS_ATTACKS_FILE_LIMIT" => array( "Denial-Of-Service File Limit", "integer", 10000, "Defines the maximum number of files that are allowed to be uploaded within a specific amount of time. It can be any positive integer." ),
331
+ "WFU_DOS_ATTACKS_TIME_INTERVAL" => array( "Denial-Of-Service Time Interval", "integer", 3600, "Defines the time interval for DOS attacks check. The time interval is given in seconds." ),
332
+ "WFU_DOS_ATTACKS_ADMIN_EMAIL_FREQUENCY" => array( "Denial-Of-Service Admin Email Frequency", "integer", 3600, "Defines how frequently an email will be sent to administrator notifying for Denial-Of-Service attacks. The time interval is given in seconds." ),
333
+ "WFU_SANITIZE_FILENAME_MODE" => array( "Filename Sanitization Mode", "string", "strict", "The sanitization mode for filenames. It can be 'strict' or 'loose'." ),
334
+ "WFU_SANITIZE_FILENAME_DOTS" => array( "Sanitize Filename Dots", "string", "true", "Convert dot symbols (.) in filename into dashes, in order to avoid double extensions. It can be 'true' or 'false'." ),
335
+ "WFU_WILDCARD_ASTERISK_MODE" => array( "Wildcard Asterisk Mode", "string", "strict", "The mode of wildcard pattern asterisk symbol. If it is strict, then the asterisk will not match dot (.) characters. It can be 'strict' or 'loose'." ),
336
+ "WFU_PHP_ARRAY_MAXLEN" => array( "Max PHP Array Length", "string", "10000", "The maximum allowable number of items of a PHP array." ),
337
+ "WFU_ADMINBROWSER_TABLE_MAXROWS" => array( "Admin Browser Rows Per Page", "integer", 25, "The number of rows per page of the admin browser. A value equal to zero or less denotes no pagination." ),
338
+ "WFU_HISTORYLOG_TABLE_MAXROWS" => array( "History Log Table Rows Per Page", "integer", 25, "The number of rows per page of the History Log table." ),
339
+ "WFU_UPLOADEDFILES_TABLE_MAXROWS" => array( "Uploaded Files Table Rows Per Page", "integer", 25, "The number of rows per page of the Uploaded Files table." ),
340
+ "WFU_ALTERNATIVE_RANDOMIZER" => array( "Use Alternative Randomizer", "string", "false", "On fast web servers the plugin's generator of random strings may not work properly causing various problems. If it is set to true, an alternative randomizer method is employed that works for fast web servers. It can be 'true' or 'false'." ),
341
+ "WFU_FORCE_NOTIFICATIONS" => array( "Force Email Notifications", "string", "false", "Send email notifications (if they are activated) even if no file has been uploaded. It can be 'true' or 'false'." ),
342
+ "WFU_UPDATE_MEDIA_ON_DELETE" => array( "Update Media on Delete", "string", "true", "When an uploaded file is deleted then delete also the corresponding Media Library item if exists. It can be 'true' or 'false'." ),
343
+ "WFU_DASHBOARD_PROTECTED" => array( "Dashboard Is Protected", "string", "false", "If /wp-admin folder is password protected then this variable should be set to 'true' so that internal operations of the plugin can work. The username and password should also be set." ),
344
+ "WFU_DASHBOARD_USERNAME" => array( "Protected Dashboard Username", "string", "", "Username entry for accessing protected /wp-admin folder." ),
345
+ "WFU_DASHBOARD_PASSWORD" => array( "Protected Dashboard Password", "string", "", "Password entry for accessing protected /wp-admin folder." ),
346
+ "WFU_EXPORT_DATA_SEPARATOR" => array( "Export Data Separator", "string", ",", "This is the delimiter of the exported file data columns. It can be any symbol. Default value is comma (,)." ),
347
+ "WFU_EXPORT_USERDATA_SEPARATOR" => array( "Export User Data Separator", "string", ";", "This is the delimiter of the exported user data of each file. It can be any symbol. Default value is semicolon (;)." ),
348
+ "WFU_DISABLE_VERSION_CHECK" => array( "Disable Version Check", "string", "false", "If it is set to 'true' then the plugin will not check if there are any new versions available. This is a temporary solution to problems having some users accessing Iptanus Services server causing the plugin to stall. It can be 'true' or 'false'." ),
349
+ "WFU_RELAX_CURL_VERIFY_HOST" => array( "Relax cURL Host Verification", "string", "false", "If it is set to 'true' then CURLOPT_SSL_VERIFYHOST will be disabled when executing a cURL POST request. This is required in some cases so that the plugin can reach https://services2.iptanus.com, because on some servers it fails with a file_get_contents warning. It can be 'true' or 'false'." ),
350
+ "WFU_USE_ALT_IPTANUS_SERVER" => array( "Use Alternative Iptanus Server", "string", "false", "If it is set to 'true' then the alternative Iptanus server will be used. This is a work-around in some cases where the website cannot reach https://services2.iptanus.com. It can be 'true' or 'false'." ),
351
+ "WFU_ALT_IPTANUS_SERVER" => array( "Alternative Iptanus Server", "string", "https://iptanusservices.appspot.com", "If it is set then this is the URL of the alternative Iptanus server." ),
352
+ "WFU_ALT_VERSION_SERVER" => array( "Alternative Version Server", "string", "https://iptanusservices.appspot.com/g79xo30q8s", "If the alternative Iptanus server is used and this variable is not empty, then it will be used as the alternative Version Server URL." ),
353
+ "WFU_MINIFY_INLINE_CSS" => array( "Minify Inline CSS Code", "string", "true", "Defines whether the inline CSS code will be minified. It can be 'true' or 'false'." ),
354
+ "WFU_MINIFY_INLINE_JS" => array( "Minify Inline JS Code", "string", "true", "Defines whether the inline Javascript code will be minified. It can be 'true' or 'false'." ),
355
+ "WFU_US_SESSION_LEGACY" => array( "Session Legacy Option", "string", "true", "Defines whether the old (legacy) operation of reading and storing session data (using session_start in header) will be used. By default it is set to 'true' to maintain backward compatibility." ),
356
+ "WFU_US_COOKIE_LIFE" => array( "Session Cookie Life", "integer", 48, "Defines the life of session cookie, in hours." ),
357
+ "WFU_US_DBOPTION_BASE" => array( "DB Option User State Base", "string", "cookies", "Defines how DB option defines the unique user state key. It can take the values 'session' or 'cookies'." ),
358
+ "WFU_US_DBOPTION_CHECK" => array( "DB Option User State Check Interval", "integer", 7200, "Defines how often (in seconds) the plugin will update user state list, when user state is saved in DB option table." ),
359
+ "WFU_US_DBOPTION_LIFE" => array( "DB Option User State Life", "integer", 1800, "Defines the maximum time of inactivity of a user state, when user state is saved in DB option table." ),
360
+ "WFU_US_HANDLER_CHANGED" => array( "User State Handler Changed", "string", "false", "Defines whether the plugin changed automatically the user state handler during installation." ),
361
+ "WFU_US_DBOPTION_USEOLD" => array( "Use Old DB Option Handler", "string", "false", "Defines whether the old DBOption user state handlers will be used." ),
362
+ "WFU_US_DEADLOCK_TIMEOUT" => array( "Database Deadlock Timeout", "integer", 10, "Defines for how long a deadlocked database transaction will be repeated." ),
363
+ "WFU_US_LOG_DBERRORS" => array( "Log Database Errors", "string", "false", "Defines whether database errors will be logged." ),
364
+ "WFU_QUEUE_ACTIVE" => array( "Enable Queue Functionality", "string", "true", "Defines whether queue operation is active." ),
365
+ "WFU_QUEUE_THREAD_TIMEOUT" => array( "Queue Thread Timeout", "integer", 5, "Defines for how long, in seconds, a queue will wait for a thread to finish before aborting the operation." ),
366
+ "WFU_QUEUE_LOOP_DELAY" => array( "Queue Loop Delay", "integer", 100, "Defines the time, in milliseconds, a wait loop will sleep before continuing." ),
367
+ "WFU_PD_VISIBLE_OPLEVELS" => array( "Personal Data Visible Operation Levels", "integer", 3, "Defines how deep administrators can go into personal data operation details. A value of -1 denotes that there is no limit." ),
368
+ "WFU_PD_VISIBLE_PERLEVELS" => array( "Personal Data Visible Permission Levels", "integer", 2, "Defines how deep administrators can go into personal data permission details. A value of -1 denotes that there is no limit." ),
369
+ "WFU_PD_VISIBLE_LOGLEVELS" => array( "Personal Data Visible Log Action Levels", "integer", 2, "Defines how deep administrators can go into personal data log action details. A value of -1 denotes that there is no limit." ),
370
+ "WFU_UPLOADEDFILES_MENU" => array( "Uploaded Files Menu State", "string", "true", "Defines whether the Uploaded Files Dashboard menu item will be shown or not. It can be 'true' or 'false'." ),
371
+ "WFU_UPLOADEDFILES_DEFACTION" => array( "Uploaded Files Default Action", "string", "adminbrowser", "Defines the default action that will be executed when a file link is pressed in Uploaded Files page. It can be 'details', 'adminbrowser', 'historylog', 'link', 'download' and 'none'." ),
372
+ "WFU_UPLOADEDFILES_COLUMNS" => array( "Uploaded Files Columns", "string", "#, file, upload_date, user, properties, remarks, actions", "Defines the visible columns of the Uploaded Files list as well as their order. It is noted that 'File' column is always visible and it is the second column if '#' column is visible, or the first one if '#' column is hidden." ),
373
+ "WFU_UPLOADEDFILES_ACTIONS" => array( "Uploaded Files Actions", "string", "details, media, adminbrowser, historylog, link, download", "Defines the allowable actions and their order for each file in Uploaded Files list. It is noted that the actions shown for each file depend on its properties." ),
374
+ "WFU_UPLOADEDFILES_HIDEINVALID" => array( "Hide Invalid Uploaded Files", "string", "false", "Defines whether all uploaded file records will be shown in Uploaded File menu or only the valid ones. Invalid are the records who are obsolete or their files do not exist anymore." ),
375
+ "WFU_UPLOADEDFILES_RESET_TIME" => array( "Uploaded Files Reset Time", "integer", 5, "Defines the interval in seconds before the unread uploaded files can be marked as read. A value of -1 denotes that there is no interval." ),
376
+ "WFU_UPLOADEDFILES_BARMENU" => array( "Uploaded Files Toolbar Menu State", "string", "true", "Defines whether the Uploaded Files Toolbar (Admin Bar) menu item will be shown or not. It can be 'true' or 'false'." ),
377
+ "WFU_UPLOADEDFILES_BARAUTOHIDE" => array( "Uploaded Files Auto-Hide on Toolbar", "string", "false", "Defines whether the Uploaded Files Toolbar (Admin Bar) menu item will be hidden when there are no new uploads. It can be 'true' or 'false'." ),
378
+ "WFU_SHORTCODECOMPOSER_NOADMIN" => array( "Show Shortcode Composer to Non-Admins", "string", "true", "Defines whether the shortcode composer will be visible to non-admin users who can edit posts or pages. It can be 'true' or 'false'." )
379
+ );
380
+ //color definitions
381
+ $GLOBALS["WFU_GLOBALS"] += array(
382
+ "WFU_TESTMESSAGECOLORS" => array( "Colors for Message in Test Mode", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message in Test mode of the uploader shortcode." ),
383
+ "WFU_DEFAULTMESSAGECOLORS" => array( "Defaults Message Colors", "string", "#666666,#EEEEEE,#333333", "The default color triplet (text, background and border colors) of message of the uploader shortcode." ),
384
+ "WFU_HEADERMESSAGECOLORS_STATE0" => array( "State 0 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 0 (upload in progress with no messages) of the uploader shortcode." ),
385
+ "WFU_HEADERMESSAGECOLORS_STATE1" => array( "State 1 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 1 (upload in progress with messages) of the uploader shortcode." ),
386
+ "WFU_HEADERMESSAGECOLORS_STATE2" => array( "State 2 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 2 (upload in progress with some files not uploaded) of the uploader shortcode." ),
387
+ "WFU_HEADERMESSAGECOLORS_STATE3" => array( "State 3 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 3 (upload in progress with no files uploaded so far) of the uploader shortcode." ),
388
+ "WFU_HEADERMESSAGECOLORS_STATE4" => array( "State 4 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 4 (all files uploaded) of the uploader shortcode." ),
389
+ "WFU_HEADERMESSAGECOLORS_STATE5" => array( "State 5 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 5 (all files uploaded with messages) of the uploader shortcode." ),
390
+ "WFU_HEADERMESSAGECOLORS_STATE6" => array( "State 6 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 6 (some files not uploaded) of the uploader shortcode." ),
391
+ "WFU_HEADERMESSAGECOLORS_STATE7" => array( "State 7 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 7 (no files uploaded) of the uploader shortcode." ),
392
+ "WFU_HEADERMESSAGECOLORS_STATE8" => array( "State 8 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 8 (there are no files to upload) of the uploader shortcode." ),
393
+ "WFU_HEADERMESSAGECOLORS_STATE9" => array( "State 9 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 9 (test state) of the uploader shortcode." ),
394
+ "WFU_HEADERMESSAGECOLORS_STATE10" => array( "State 10 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 10 (JSON parse error) of the uploader shortcode." ),
395
+ "WFU_HEADERMESSAGECOLORS_STATE11" => array( "State 11 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 11 (redirecting) of the uploader shortcode." ),
396
+ "WFU_HEADERMESSAGECOLORS_STATE12" => array( "State 12 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 12 (upload failed) of the uploader shortcode." ),
397
+ "WFU_HEADERMESSAGECOLORS_STATE13" => array( "State 13 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 13 (sending data) of the uploader shortcode." ),
398
+ "WFU_HEADERMESSAGECOLORS_STATE14" => array( "State 14 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 14 (data submit succeeded) of the uploader shortcode." ),
399
+ "WFU_HEADERMESSAGECOLORS_STATE15" => array( "State 15 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 15 (data submit failed) of the uploader shortcode." ),
400
+ "WFU_HEADERMESSAGECOLORS_STATE16" => array( "State 16 Message Colors", "string", "#666666,#EEEEEE,#333333", "The color triplet (text, background and border colors) of message of upload state 16 (cancelling upload) of the uploader shortcode." ),
401
+ "WFU_HEADERMESSAGECOLORS_STATE17" => array( "State 17 Message Colors", "string", "#660000,#FFEEEE,#666600", "The color triplet (text, background and border colors) of message of upload state 17 (upload cancelled) of the uploader shortcode." ),
402
+ "WFU_HEADERMESSAGECOLORS_STATE18" => array( "State 18 Message Colors", "string", "#006600,#EEFFEE,#006666", "The color triplet (text, background and border colors) of message of upload state 18 (upload succeeded) of the uploader shortcode." ),
403
+ "WFU_HEADERMESSAGECOLORS_STATE19" => array( "State 19 Message Colors", "string", "#F88017,#FEF2E7,#633309", "The color triplet (text, background and border colors) of message of upload state 19 (upload completed but no files were saved due to personal data policy) of the uploader shortcode." )
404
+ );
405
+ //insert saved values to array
406
+ $envars = get_option("wfu_environment_variables", array());
407
+ foreach ( $GLOBALS["WFU_GLOBALS"] as $ind => $envar ) {
408
+ if ( isset($envars[$ind]) ) {
409
+ if ( $envar[1] == "integer" ) $saved = (int)$envars[$ind];
410
+ else $saved = (string)$envars[$ind];
411
+ }
412
+ else $saved = $envar[2];
413
+ array_splice($GLOBALS["WFU_GLOBALS"][$ind], 3, 0, array( $saved ));
414
+ //add visibility
415
+ $GLOBALS["WFU_GLOBALS"][$ind][5] = true;
416
+ }
417
+
418
+ //hide unwanted environment variables
419
+ $GLOBALS["WFU_GLOBALS"]["WFU_RELAX_CURL_VERIFY_HOST"][5] = false;
420
+ $GLOBALS["WFU_GLOBALS"]["WFU_USE_ALT_IPTANUS_SERVER"][5] = false;
421
+
422
+ /************** Constant Values ***************/
423
+ //other plugin values
424
+ DEFINE("WFU_SUCCESSMESSAGECOLOR", "green");
425
+ DEFINE("WFU_MAX_TIME_LIMIT", ini_get("max_input_time"));
426
+ DEFINE("WFU_RESPONSE_URL", WPFILEUPLOAD_DIR."wfu_response.php");
427
+ DEFINE("WFU_AJAX_URL", $siteurl."/wp-admin/admin-ajax.php");
428
+ DEFINE("WFU_SERVICES_SERVER_URL", 'https://services2.iptanus.com');
429
+ DEFINE("WFU_VERSION_SERVER_URL", WFU_SERVICES_SERVER_URL.'/wp-admin/admin-ajax.php');
430
+ DEFINE("WFU_VERSION_HASH", '9npWpXMhAQ5e6AGJ5zqbaPxLk9ePD3eSu3WKeN9p89E9wmgL2PHtrqXPzBVpStzh');
431
+ DEFINE("WFU_DOWNLOADER_URL", WPFILEUPLOAD_DIR."wfu_file_downloader.php");
432
+ DEFINE("WFU_IPTANUS_SERVER_UNREACHABLE_ARTICLE", 'https://www.iptanus.com/iptanus-services-server-unreachable-error-wfu-plugin/');
433
+ //alternative insecure server
434
+ DEFINE("WFU_SERVICES_SERVER_ALT_URL", 'http://services.iptanus.com');
435
+ DEFINE("WFU_VERSION_SERVER_ALT_URL", WFU_SERVICES_SERVER_ALT_URL.'/wp-admin/admin-ajax.php');
436
+ DEFINE("WFU_PRO_VERSION_URL", 'https://www.iptanus.com/product/wordpress-file-upload-pro/');
437
+ //define images
438
+ DEFINE("WFU_IMAGE_ADMIN_HELP", WPFILEUPLOAD_DIR.'images/help_16.png');
439
+ DEFINE("WFU_IMAGE_ADMIN_RESTOREDEFAULT", WPFILEUPLOAD_DIR.'images/restore_16.png');
440
+ DEFINE("WFU_IMAGE_ADMIN_USERDATA_ADD", WPFILEUPLOAD_DIR.'images/add_12.png');
441
+ DEFINE("WFU_IMAGE_ADMIN_USERDATA_REMOVE", WPFILEUPLOAD_DIR.'images/remove_12.png');
442
+ DEFINE("WFU_IMAGE_ADMIN_USERDATA_UP", WPFILEUPLOAD_DIR.'images/up_12.png');
443
+ DEFINE("WFU_IMAGE_ADMIN_USERDATA_DOWN", WPFILEUPLOAD_DIR.'images/down_12.png');
444
+ DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_BROWSE", WPFILEUPLOAD_DIR.'images/tree_16.gif');
445
+ DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_OK", WPFILEUPLOAD_DIR.'images/ok_12.gif');
446
+ DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_CANCEL", WPFILEUPLOAD_DIR.'images/cancel_12.gif');
447
+ DEFINE("WFU_IMAGE_ADMIN_SUBFOLDER_LOADING", WPFILEUPLOAD_DIR.'images/refresh_16.gif');
448
+ DEFINE("WFU_IMAGE_SIMPLE_PROGBAR", WPFILEUPLOAD_DIR.'images/progbar.gif');
449
+ DEFINE("WFU_IMAGE_OVERLAY_EDITOR", WPFILEUPLOAD_DIR.'images/pencil.svg');
450
+ DEFINE("WFU_IMAGE_OVERLAY_LOADING", WPFILEUPLOAD_DIR.'images/loading_icon.gif');
451
+ DEFINE("WFU_IMAGE_FILE_CANCEL", WPFILEUPLOAD_DIR.'images/cancel_16.png');
452
+ DEFINE("WFU_IMAGE_MEDIA_BUTTONS", WPFILEUPLOAD_DIR.'images/open-iconic.svg');
453
+ DEFINE("WFU_IMAGE_VERSION_COMPARISON", WPFILEUPLOAD_DIR.'images/Version Comparison.png');
454
+
455
+ /**
456
+ * Front-End Constants Initialization
457
+ *
458
+ * This function initializes all constants that need to be passed to the front-
459
+ * end scripts of the upload form.
460
+ *
461
+ * @since 2.1.2
462
+ */
463
+ function wfu_set_javascript_constants() {
464
+ $consts = array(
465
+ "notify_testmode" => WFU_NOTIFY_TESTMODE,
466
+ "nofilemessage" => WFU_ERROR_UPLOAD_NOFILESELECTED,
467
+ "enable_popups" => WFU_ERROR_ENABLE_POPUPS,
468
+ "remoteserver_noresult" => WFU_ERROR_REMOTESERVER_NORESULT,
469
+ "message_header" => WFU_ERRORMESSAGE,
470
+ "message_failed" => WFU_ERROR_UPLOAD_FAILED_WHILE,
471
+ "message_cancelled" => WFU_ERROR_UPLOAD_CANCELLED,
472
+ "message_unknown" => WFU_ERROR_UNKNOWN,
473
+ "adminmessage_unknown" => WFU_FAILMESSAGE_DETAILS,
474
+ "message_timelimit" => WFU_ERROR_FILE_PHP_TIME,
475
+ "message_admin_timelimit" => WFU_ERROR_ADMIN_FILE_PHP_TIME,
476
+ "cancel_upload_prompt" => WFU_CANCEL_UPLOAD_PROMPT,
477
+ "file_cancelled" => WFU_ERROR_FILE_CANCELLED,
478
+ "jsonparse_filemessage" => WFU_ERROR_JSONPARSE_FILEMESSAGE,
479
+ "jsonparse_message" => WFU_ERROR_JSONPARSE_MESSAGE,
480
+ "jsonparse_adminmessage" => WFU_ERROR_JSONPARSE_ADMINMESSAGE,
481
+ "jsonparse_headermessage" => WFU_ERROR_JSONPARSE_HEADERMESSAGE,
482
+ "jsonparse_headeradminmessage" => WFU_ERROR_JSONPARSE_HEADERADMINMESSAGE,
483
+ "same_pluginid" => WFU_ERROR_SAME_PLUGINID,
484
+ "webcam_video_notsupported" => WFU_ERROR_WEBCAM_VIDEO_NOTSUPPORTED,
485
+ "webcam_video_nothingrecorded" => WFU_ERROR_WEBCAM_VIDEO_NOTHINGRECORDED,
486
+ "default_colors" => WFU_VAR("WFU_DEFAULTMESSAGECOLORS"),
487
+ "fail_colors" => WFU_VAR("WFU_FAILMESSAGECOLORS"),
488
+ "max_time_limit" => WFU_MAX_TIME_LIMIT,
489
+ "response_url" => WFU_RESPONSE_URL,
490
+ "ajax_url" => wfu_ajaxurl(),
491
+ "wfu_pageexit_prompt" => WFU_PAGEEXIT_PROMPT,
492
+ "wfu_subdir_typedir" => WFU_SUBDIR_TYPEDIR,
493
+ "wfu_uploadprogress_mode" => WFU_VAR("WFU_UPLOADPROGRESS_MODE"),
494
+ "wfu_consent_notcompleted" => WFU_WARNING_CONSENT_NOTCOMPLETED
495
+ );
496
+ $consts_txt = "";
497
+ foreach ( $consts as $key => $val )
498
+ $consts_txt .= ( $consts_txt == "" ? "" : ";" ).wfu_plugin_encode_string($key).":".wfu_plugin_encode_string($val);
499
+
500
+ return $consts_txt;
501
+ }
502
+
503
+ ?>
lib/wfu_functions.php CHANGED
@@ -1,3404 +1,6443 @@
1
- <?php
2
-
3
- //********************* Debug Functions ***************************************************************************************************
4
-
5
- /**
6
- * Hook on plugin's functions
7
- *
8
- * This is a very powerful function that enables almost all plugin functions to
9
- * be redeclared, either in whole or partially. Here is what it can do:
10
- *
11
- * - It can execute a hook, based on the function parameters and then
12
- * execute the original function.
13
- * - It can execute a hook, based on the function's parameters and then
14
- * return without executing the original function. This mode is like
15
- * entirely redeclaring the original function.
16
- * - It can execute a hook after execution of the original function.
17
- * - It can redeclare the function parameters or pass new variables to the
18
- * original function.
19
- *
20
- * In order to make a function redeclarable we just need to put the
21
- * following 'magic' code at the top of its function block:
22
- *
23
- * $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out);
24
- * if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v;
25
- * switch($a) { case 'R': return $out['output']; break; case 'D':
26
- * die($out['output']); }
27
- *
28
- * Then the function can be hooked through the filter wfu_debug-{__FUNCTION__}.
29
- *
30
- * The hook function takes the same parameters as the original function, plus
31
- * one, which comes first and determines the behaviour of the hook function.
32
- *
33
- * This parameter is an array having three items as follows:
34
- *
35
- * - item 'output' contains the output of the original function (if exists)
36
- * - item 'result' has no meaning as input parameter but as returning one
37
- * - item 'vars' has no meaning as input parameter but as returning one
38
- *
39
- * The hook function must return the same array as follows:
40
- *
41
- * - item 'output' must contain the hook's output
42
- * - item 'result' must be either 'X', 'R', or 'D' when the hook is executed
43
- * at the beginning of the function, as explained below. It determines how
44
- * the hook will be handled, as follows:
45
- * - If 'result' is 'X' then the result of the hook function will be
46
- * ignored and the original function will be executed afterwards.
47
- * - If 'result' is 'R' then the original function will terminate
48
- * returning the output of the hook function. So it is like having been
49
- * entirely substituted by the hook function.
50
- * - If 'result' is 'D' then the original function will die returning the
51
- * output of the hook function. This applies to ajax handlers.
52
- * In the case that the hook is executed at the end of the function, then
53
- * item 'result' must always be 'R'.
54
- * - item 'vars' is an associative array that contains any variables that the
55
- * hook wants to pass to the original function like this:
56
- * $res['output'] = array('varname1' => value1, 'varname2' => value2);
57
- * Item 'vars' can be used to redeclare the function arguments and it is a
58
- * workaround to handling arguments passed by reference.
59
- *
60
- * It is noted that the hook can be executed either before or after execution
61
- * of the original function, despite the fact that the 'magic' code is added
62
- * to the beginning of the function.
63
- *
64
- * - To execute the hook before the function a global variable with name
65
- * wfu_debug-{__FUNCTION__} must be declared.
66
- * - To execute the hook after the function a global variable with name
67
- * wfu_debug_end-{__FUNCTION__} must be declared.
68
- *
69
- * It is noted that if both of these global variables are declared, or none of
70
- * them then the hook will not work.
71
- *
72
- * Arguments passed by reference: When declaring the hook filter, all arguments
73
- * are passed by value, even if some of the original function's arguments pass
74
- * by reference. However no PHP warnings and errors will be generated due to
75
- * this difference. If the hook wants to change the value of an argument and
76
- * reflect this change to the original function, it is possible through item
77
- * 'vars' explained above. For example, if the original function passes
78
- * argument $var1 by reference (it is declared as &$var1 in the function
79
- * parameters), we cannot use the syntax $var1 = ...; inside the hook filter
80
- * but we can use the syntax $res['vars']['var1'] = ...; and this will result
81
- * $var1 in the original function to get the new value!
82
- *
83
- * @param string $function the function name of the original function
84
- * @param array $args an array of parameters of the original function
85
- * @param string $out it stores the output of the hook function
86
-
87
- * @return string returns how the hook function will be handled ('X': hook
88
- * output must be ignored, 'R': the original function must return the
89
- * hook's output, 'D': the original function must die returning the
90
- * hook's output)
91
- */
92
- function WFU_FUNCTION_HOOK($function, $args, &$out) {
93
- // exit if plugin's debug mode is off or the hook has not been declared in
94
- // global variables;
95
- if ( WFU_VAR("WFU_DEBUG") != "ON" || !( isset($GLOBALS["wfu_debug-".$function]) xor isset($GLOBALS["wfu_debug_end-".$function]) ) ) return 'X';
96
- // exit if function name is empty or invalid
97
- if ( $function == "" || preg_replace("/[^0-9a-zA-Z_]/", "", $function) != $function ) return 'X';
98
- //if the hook has been declared in global variables with wfu_debug_end-
99
- //prefix then it will run at the end of the function
100
- if ( isset($GLOBALS["wfu_debug_end-".$function]) ) {
101
- $args_count = count($args);
102
- //if a flag (specific string) is contained in the last position of the
103
- //arguments list then do not re-execute the hook as this is the second
104
- //pass
105
- if ( $args_count > 0 && $args[$args_count - 1] === "wfu_debug_end-".$function."-second_pass" ) return 'X';
106
- else {
107
- //create an array of references to the function arguments and pass
108
- //this to call_user_func_array instead of $args; this is a
109
- //workaround to avoid PHP warnings when the original function passes
110
- //arguments by reference
111
- $args_byref = array();
112
- foreach ( $args as $key => &$arg ) $args_byref[$key] = &$arg;
113
- //add a flag (specific string) as the last argument in order to
114
- //denote that the next execution of the hook is the second pass
115
- array_push($args_byref, "wfu_debug_end-".$function."-second_pass");
116
- //call the original function and get the returned value; it will
117
- //contain the flag in the arguments, so the hook will not be
118
- //executed again and the whole script will not be put in an infinite
119
- //loop
120
- $ret = call_user_func_array($function, $args_byref);
121
- //pass the original function's output to the hook
122
- array_splice($args, 0, 0, array( array( "output" => $ret, "result" => "X", "vars" => array() ) ));
123
- //execute the hook
124
- $res = apply_filters_ref_array("wfu_debug-".$function, $args);
125
- if ( !is_array($res) || !isset($res["output"]) || !isset($res["result"]) ) $res = array( "output" => $ret, "result" => "R" );
126
- if ( $res["result"] != 'R' ) $res["result"] = 'R';
127
- if ( isset($res["vars"]) && !is_array($res["vars"]) ) $res["vars"] = array();
128
- $out = $res;
129
- return $res["result"];
130
- }
131
- }
132
- else {
133
- // prepare the arguments for the hook
134
- array_splice($args, 0, 0, array( array( "output" => "", "result" => "X", "vars" => array() ) ));
135
- // run the hook
136
- $res = apply_filters_ref_array("wfu_debug-".$function, $args);
137
- // exit if $res is invalid
138
- if ( !is_array($res) || !isset($res["output"]) || !isset($res["result"]) ) $res = array( "output" => "", "result" => "X" );
139
- if ( $res["result"] != 'X' && $res["result"] != 'R' && $res["result"] != 'D' ) $res["result"] = 'X';
140
- if ( isset($res["vars"]) && !is_array($res["vars"]) ) $res["vars"] = array();
141
- $out = $res;
142
- // if result is 'X' then the caller must ignore the hook
143
- // if result is 'R' then the caller must return the hook's output
144
- // if result is 'D' then the caller must die returning the hook's output
145
- return $res["result"];
146
- }
147
- }
148
-
149
- //********************* String Functions ***************************************************************************************************
150
-
151
- function wfu_upload_plugin_clean($filename) {
152
- $clean = sanitize_file_name($filename);
153
- if ( WFU_VAR("WFU_SANITIZE_FILENAME_MODE") != "loose" ) {
154
- $name = wfu_filename($clean);
155
- $ext = wfu_fileext($clean);
156
- if ( WFU_VAR("WFU_SANITIZE_FILENAME_DOTS") == "true" ) $name_search = array ( '@[^a-zA-Z0-9_]@' );
157
- else $name_search = array ( '@[^a-zA-Z0-9._]@' );
158
- $ext_search = array ( '@[^a-zA-Z0-9._]@' );
159
- $replace = array ( '-' );
160
- $clean_name = preg_replace($name_search, $replace, remove_accents($name));
161
- $clean_ext = preg_replace($ext_search, $replace, remove_accents($ext));
162
- $clean = $clean_name.".".$clean_ext;
163
- }
164
-
165
- return $clean;
166
- }
167
-
168
- function _wildcard_to_preg_preg_replace_callback($matches) {
169
- global $wfu_preg_replace_callback_var;
170
- array_push($wfu_preg_replace_callback_var, $matches[0]);
171
- $key = count($wfu_preg_replace_callback_var) - 1;
172
- return "[".$key."]";
173
- }
174
-
175
- function wfu_upload_plugin_wildcard_to_preg($pattern, $strict = false) {
176
- global $wfu_preg_replace_callback_var;
177
- $wfu_preg_replace_callback_var = array();
178
- $pattern = preg_replace_callback("/\[(.*?)\]/", "_wildcard_to_preg_preg_replace_callback", $pattern);
179
- if ( !$strict ) $pattern = '/^' . str_replace(array('\*', '\?', '\[', '\]'), array('.*', '.', '[', ']'), preg_quote($pattern)) . '$/is';
180
- else $pattern = '/^' . str_replace(array('\*', '\?', '\[', '\]'), array('[^.]*', '.', '[', ']'), preg_quote($pattern)) . '$/is';
181
- foreach ($wfu_preg_replace_callback_var as $key => $match)
182
- $pattern = str_replace("[".$key."]", $match, $pattern);
183
- return $pattern;
184
- }
185
-
186
- function wfu_upload_plugin_wildcard_to_mysqlregexp($pattern) {
187
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
188
- if ( substr($pattern, 0, 6) == "regex:" ) return str_replace("\\", "\\\\", substr($pattern, 6));
189
- else return str_replace("\\", "\\\\", '^'.str_replace(array('\*', '\?', '\[', '\]'), array('.*', '.', '[', ']'), preg_quote($pattern)).'$');
190
- }
191
-
192
- function wfu_upload_plugin_wildcard_match($pattern, $str, $strict = false) {
193
- $pattern = wfu_upload_plugin_wildcard_to_preg($pattern, $strict);
194
- return preg_match($pattern, $str);
195
- }
196
-
197
- function wfu_plugin_encode_string($string) {
198
- $array = unpack('H*', $string);
199
- return $array[1];
200
-
201
- $array = unpack('C*', $string);
202
- $new_string = "";
203
- for ($i = 1; $i <= count($array); $i ++) {
204
- $new_string .= sprintf("%02X", $array[$i]);
205
- }
206
- return $new_string;
207
- }
208
-
209
- function wfu_plugin_decode_string($string) {
210
- return pack('H*', $string);
211
-
212
- $new_string = "";
213
- for ($i = 0; $i < strlen($string); $i += 2 ) {
214
- $new_string .= sprintf("%c", hexdec(substr($string, $i ,2)));
215
- }
216
- return $new_string;
217
- }
218
-
219
- function wfu_create_random_string($len) {
220
- $base = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
221
- $max = strlen($base) - 1;
222
- $activatecode = '';
223
- if ( WFU_VAR("WFU_ALTERNATIVE_RANDOMIZER") != "true" )
224
- mt_srand((double)microtime()*1000000);
225
- else mt_srand((double)substr(uniqid("", true), 15));
226
- while (strlen($activatecode) < $len)
227
- $activatecode .= $base{mt_rand(0, $max)};
228
- return $activatecode;
229
- }
230
-
231
- function wfu_join_strings($delimeter) {
232
- $arr = func_get_args();
233
- unset($arr[0]);
234
- foreach ($arr as $key => $item)
235
- if ( $item == "" ) unset($arr[$key]);
236
- return join($delimeter, $arr);
237
- }
238
-
239
- function wfu_create_string($size) {
240
- $piece = str_repeat("0", 1024);
241
- $str = "";
242
- $reps = $size / 1024;
243
- $rem = $size - 1024 * $reps;
244
- for ( $i = 0; $i < $reps; $i++ ) $str .= $piece;
245
- $str .= substr($piece, 0, $rem);
246
- return $str;
247
- }
248
-
249
- function wfu_html_output($output) {
250
- $output = str_replace(array("\r\n", "\r", "\n"), "<br/>", $output);
251
- return str_replace(array("\t", " "), "&nbsp;", $output);
252
- }
253
-
254
- function wfu_sanitize_code($code) {
255
- return preg_replace("/[^A-Za-z0-9]/", "", $code);
256
- }
257
-
258
- function wfu_sanitize_int($code) {
259
- return preg_replace("/[^0-9+\-]/", "", $code);
260
- }
261
-
262
- function wfu_sanitize_float($code) {
263
- return preg_replace("/[^0-9+\-\.,]/", "", $code);
264
- }
265
-
266
- function wfu_sanitize_colors($code) {
267
- return preg_replace("/[^A-Fa-f0-9#,]/", "", $code);
268
- }
269
-
270
- function wfu_sanitize_tag($code) {
271
- return preg_replace("/[^A-Za-z0-9_]/", "", $code);
272
- }
273
-
274
- function wfu_sanitize_url($url) {
275
- return filter_var(strip_tags($url), FILTER_SANITIZE_URL);
276
- }
277
-
278
- function wfu_sanitize_urls($urls, $separator) {
279
- $urls_arr = explode($separator, $urls);
280
- foreach( $urls_arr as &$url ) $url = wfu_sanitize_url($url);
281
- return implode($separator, $urls_arr);
282
- }
283
-
284
- function wfu_sanitize_shortcode($shortcode, $shortcode_tag) {
285
- $attrs = wfu_shortcode_string_to_array($shortcode);
286
- $sanitized_attrs = wfu_sanitize_shortcode_array($attrs, $shortcode_tag);
287
- //reconstruct sanitized shortcode string from array
288
- $sanitized_shortcode = "";
289
- foreach ( $sanitized_attrs as $attr => $value )
290
- $sanitized_shortcode .= ( $sanitized_shortcode == "" ? "" : " " ).$attr.'="'.$value.'"';
291
-
292
- return $sanitized_shortcode;
293
- }
294
-
295
- function wfu_sanitize_shortcode_array($attrs, $shortcode_tag) {
296
- $sanitized_attrs = array();
297
- if ( $shortcode_tag == 'wordpress_file_upload' ) $defs = wfu_attribute_definitions();
298
- else $defs = wfu_browser_attribute_definitions();
299
- // get validator types for defs
300
- $def_validators = array();
301
- foreach ( $defs as $def ) $def_validators[$def['attribute']] = $def['validator'];
302
- // sanitize each attribute
303
- foreach ( $attrs as $attr => $value ) {
304
- //first sanitize the attribute name
305
- $sanitized = sanitize_text_field($attr);
306
- //continue only for attributes that sanitization did not crop any
307
- //characters
308
- if ( $sanitized == $attr && $attr != "" ) {
309
- //flatten attributes that have many occurencies
310
- $flat = preg_replace("/^(.*?)[0-9]*$/", "$1", $attr);
311
- //get validator type
312
- $validator = "text";
313
- if ( isset($def_validators[$flat]) ) $validator = $def_validators[$flat];
314
- //sanitize value based on validator type
315
- $new_value = $value;
316
- switch( $validator ) {
317
- case "text":
318
- $new_value = wp_strip_all_tags($value);
319
- break;
320
- case "integer":
321
- $new_value = wfu_sanitize_int($value);
322
- break;
323
- case "float":
324
- $new_value = wfu_sanitize_float($value);
325
- break;
326
- case "path":
327
- $new_value = wp_strip_all_tags($value);
328
- break;
329
- case "link":
330
- $new_value = wp_strip_all_tags($value);
331
- break;
332
- case "emailheaders":
333
- if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
334
- break;
335
- case "emailsubject":
336
- if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
337
- break;
338
- case "emailbody":
339
- if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
340
- break;
341
- case "colors":
342
- $new_value = wfu_sanitize_colors($value);
343
- break;
344
- case "css":
345
- $new_value = wp_strip_all_tags($value);
346
- break;
347
- case "datetime":
348
- $new_value = wp_strip_all_tags($value);
349
- break;
350
- case "pattern":
351
- if ( substr_count($value, "'") > 0 && substr_count($value, "'") > substr_count($value, "\\'") ) $new_value = "";
352
- break;
353
- default:
354
- $new_value = wp_strip_all_tags($value);
355
- }
356
- //allow custom filters to change the sanitization result
357
- $new_value = apply_filters("_wfu_sanitize_shortcode", $new_value, $attr, $validator, $value);
358
- $sanitized_attrs[$attr] = $new_value;
359
- }
360
- }
361
-
362
- return $sanitized_attrs;
363
- }
364
-
365
- function wfu_slash( $value ) {
366
- if ( is_array( $value ) ) {
367
- foreach ( $value as $k => $v ) {
368
- if ( is_array( $v ) ) {
369
- $value[$k] = wfu_slash( $v );
370
- }
371
- else {
372
- $value[$k] = addslashes( $v );
373
- }
374
- }
375
- }
376
- else {
377
- $value = addslashes( $value );
378
- }
379
-
380
- return $value;
381
- }
382
-
383
- function wfu_generate_global_short_token($timeout) {
384
- $token = wfu_create_random_string(16);
385
- $expire = time() + (int)$timeout;
386
- update_option('wfu_gst_'.$token, $expire);
387
- return $token;
388
- }
389
-
390
- function wfu_verify_global_short_token($token) {
391
- $timeout = get_option('wfu_gst_'.$token);
392
- if ( $timeout === false ) return false;
393
- delete_option('wfu_gst_'.$token);
394
- return ( $timeout > time() );
395
- }
396
-
397
- function wfu_generate_user_short_token($timeout) {
398
- $token = wfu_create_random_string(16);
399
- $expire = time() + (int)$timeout;
400
- WFU_USVAR_store('wfu_ust_'.$token, $expire);
401
- return $token;
402
- }
403
-
404
- function wfu_verify_user_short_token($token) {
405
- if ( !WFU_USVAR_exists('wfu_ust_'.$token) ) return false;
406
- $timeout = WFU_USVAR('wfu_ust_'.$token);
407
- WFU_USVAR_unset('wfu_ust_'.$token);
408
- return ( $timeout > time() );
409
- }
410
-
411
- //********************* Array Functions ****************************************************************************************************
412
-
413
- function wfu_encode_array_to_string($arr) {
414
- $arr_str = json_encode($arr);
415
- $arr_str = wfu_plugin_encode_string($arr_str);
416
- return $arr_str;
417
- }
418
-
419
- function wfu_decode_array_from_string($arr_str) {
420
- $arr_str = wfu_plugin_decode_string($arr_str);
421
- $arr = json_decode($arr_str, true);
422
- return $arr;
423
- }
424
-
425
- function wfu_plugin_parse_array($source) {
426
- $keys = array_keys($source);
427
- $new_arr = array();
428
- for ($i = 0; $i < count($keys); $i ++)
429
- $new_arr[$keys[$i]] = wp_specialchars_decode($source[$keys[$i]]);
430
- return $new_arr;
431
- }
432
-
433
- function wfu_array_remove_nulls(&$arr) {
434
- foreach ( $arr as $key => $arri )
435
- if ( $arri == null )
436
- array_splice($arr, $key, 1);
437
- }
438
-
439
- function wfu_safe_array($arr) {
440
- return array_map("htmlspecialchars", $arr);
441
- }
442
-
443
- function wfu_sanitize($var) {
444
- $typ = gettype($var);
445
- if ( $typ == "boolean" || $typ == "integer" || $typ == "double" || $typ == "resource" || $typ == "NULL" )
446
- return $var;
447
- elseif ( $typ == "string" )
448
- return htmlspecialchars($var);
449
- elseif ( $typ == "array" || $typ == "object" ) {
450
- foreach ( $var as &$item ) $item = wfu_sanitize($item);
451
- return $var;
452
- }
453
- else
454
- return $typ;
455
- }
456
-
457
- function _wfu_preg_replace_callback_alt($contents, $token) {
458
- $in_block = false;
459
- $prev_pos = 0;
460
- $new_contents = '';
461
- $ret['items'] = array();
462
- $ret['tokens'] = array();
463
- $ii = 0;
464
- while ( ($pos = strpos($contents, '"', $prev_pos)) !== false ) {
465
- if ( !$in_block ) {
466
- $new_contents .= substr($contents, $prev_pos, $pos - $prev_pos + 1);
467
- $in_block = true;
468
- }
469
- else {
470
- $ret['items'][$ii] = substr($contents, $prev_pos, $pos - $prev_pos);
471
- $ret['tokens'][$ii] = $token.sprintf('%03d', $ii);
472
- $new_contents .= $token.sprintf('%03d', $ii).'"';
473
- $ii ++;
474
- $in_block = false;
475
- }
476
- $prev_pos = $pos + 1;
477
- }
478
- if ( $in_block ) {
479
- $ret['items'][$ii] = substr($contents, $prev_pos);
480
- $ret['tokens'][$ii] = $token.sprintf('%03d', $ii);
481
- $new_contents .= $token.sprintf('%03d', $ii).'"';
482
- }
483
- else
484
- $new_contents .= substr($contents, $prev_pos);
485
- $ret['contents'] = $new_contents;
486
- return $ret;
487
- }
488
-
489
- function wfu_shortcode_string_to_array($shortcode) {
490
- $i = 0;
491
- $m1 = array();
492
- $m2 = array();
493
- //for some reason preg_replace_callback does not work in all cases, so it has been replaced by a similar custom inline routine
494
- // $mm = preg_replace_callback('/"([^"]*)"/', function ($matches) use(&$i, &$m1, &$m2) {array_push($m1, $matches[1]); array_push($m2, "attr".$i); return "attr".$i++;}, $shortcode);
495
- $ret = _wfu_preg_replace_callback_alt($shortcode, "attr");
496
- $mm = $ret['contents'];
497
- $m1 = $ret['items'];
498
- $m2 = $ret['tokens'];
499
- $arr = explode(" ", $mm);
500
- $attrs = array();
501
- foreach ( $arr as $attr ) {
502
- if ( trim($attr) != "" ) {
503
- $attr_arr = explode("=", $attr, 2);
504
- $key = "";
505
- if ( count($attr_arr) > 0 ) $key = $attr_arr[0];
506
- $val = "";
507
- if ( count($attr_arr) > 1 ) $val = $attr_arr[1];
508
- if ( trim($key) != "" ) $attrs[trim($key)] = str_replace('"', '', $val);
509
- }
510
- }
511
- $attrs2 = str_replace($m2, $m1, $attrs);
512
- return $attrs2;
513
- }
514
-
515
- function wfu_array_sort_function_string_asc($a, $b) {
516
- return strcmp(strtolower($a), strtolower($b));
517
- }
518
-
519
- function wfu_array_sort_function_string_asc_with_id0($a, $b) {
520
- $cmp = strcmp(strtolower($a["value"]), strtolower($b["value"]));
521
- if ( $cmp == 0 ) $cmp = ( (int)$a["id0"] < (int)$b["id0"] ? -1 : 1 );
522
- return $cmp;
523
- }
524
-
525
- function wfu_array_sort_function_string_desc($a, $b) {
526
- return -strcmp(strtolower($a), strtolower($b));
527
- }
528
-
529
- function wfu_array_sort_function_string_desc_with_id0($a, $b) {
530
- $cmp = strcmp(strtolower($a["value"]), strtolower($b["value"]));
531
- if ( $cmp == 0 ) $cmp = ( (int)$a["id0"] < (int)$b["id0"] ? -1 : 1 );
532
- return -$cmp;
533
- }
534
-
535
- function wfu_array_sort_function_numeric_asc($a, $b) {
536
- $aa = (double)$a;
537
- $bb = (double)$b;
538
- if ( $aa < $bb ) return -1;
539
- elseif ( $aa > $bb ) return 1;
540
- else return 0;
541
- }
542
-
543
- function wfu_array_sort_function_numeric_asc_with_id0($a, $b) {
544
- $aa = (double)$a["value"];
545
- $bb = (double)$b["value"];
546
- if ( $aa < $bb ) return -1;
547
- elseif ( $aa > $bb ) return 1;
548
- elseif ( (int)$a["id0"] < (int)$b["id0"] ) return -1;
549
- else return 1;
550
- }
551
-
552
- function wfu_array_sort_function_numeric_desc($a, $b) {
553
- $aa = (double)$a;
554
- $bb = (double)$b;
555
- if ( $aa > $bb ) return -1;
556
- elseif ( $aa < $bb ) return 1;
557
- else return 0;
558
- }
559
-
560
- function wfu_array_sort_function_numeric_desc_with_id0($a, $b) {
561
- $aa = (double)$a["value"];
562
- $bb = (double)$b["value"];
563
- if ( $aa > $bb ) return -1;
564
- elseif ( $aa < $bb ) return 1;
565
- elseif ( (int)$a["id0"] > (int)$b["id0"] ) return -1;
566
- else return 1;
567
- }
568
-
569
- function wfu_array_sort($array, $on, $order = SORT_ASC, $with_id0 = false) {
570
- $new_array = array();
571
- $sortable_array = array();
572
-
573
- $pos = strpos($on, ":");
574
- if ( $pos !== false ) {
575
- $sorttype = substr($on, $pos + 1);
576
- if ( $sorttype == "" ) $sorttype = "s";
577
- $on = substr($on, 0, $pos);
578
- }
579
- else $sorttype = "s";
580
-
581
- if (count($array) > 0) {
582
- foreach ($array as $k => $v) {
583
- if (is_array($v)) {
584
- foreach ($v as $k2 => $v2) {
585
- if ($k2 == $on) {
586
- $sortable_array[$k] = ( $with_id0 ? array( "id0" => $v["id0"], "value" => $v2 ) : $v2 );
587
- }
588
- }
589
- } else {
590
- $sortable_array[$k] = $v;
591
- $with_id0 = false;
592
- }
593
- }
594
-
595
- uasort($sortable_array, "wfu_array_sort_function_".( $sorttype == "n" ? "numeric" : "string" )."_".( $order == SORT_ASC ? "asc" : "desc" ).( $with_id0 ? "_with_id0" : "" ));
596
-
597
- foreach ($sortable_array as $k => $v) {
598
- $new_array[$k] = $array[$k];
599
- }
600
- }
601
-
602
- return $new_array;
603
- }
604
-
605
- function wfu_echo_array($arr) {
606
- if ( !is_array($arr) ) return;
607
- echo '<pre>'.print_r($arr, true).'</pre>';
608
- }
609
-
610
- function wfu_minify_code($lang, $code) {
611
- $ret = array( "result" => false, "minified_code" => "" );
612
- $php_version = preg_replace("/-.*/", "", phpversion());
613
- $unsupported = false;
614
- $ret = wfu_compare_versions($php_version, '5.3.0');
615
- $unsupported = ( $ret['status'] && $ret['result'] == 'lower' );
616
- if ( !$unsupported ) {
617
- $path = ABSWPFILEUPLOAD_DIR;
618
- if ( !class_exists('MatthiasMullie\Minify\Minify') ) {
619
- include_once $path.'vendor/minifier/minify/src/Minify.php';
620
- include_once $path.'vendor/minifier/minify/src/CSS.php';
621
- include_once $path.'vendor/minifier/minify/src/JS.php';
622
- include_once $path.'vendor/minifier/minify/src/Exception.php';
623
- include_once $path.'vendor/minifier/minify/src/Exceptions/BasicException.php';
624
- include_once $path.'vendor/minifier/minify/src/Exceptions/FileImportException.php';
625
- include_once $path.'vendor/minifier/minify/src/Exceptions/IOException.php';
626
- }
627
- if ( !class_exists('MatthiasMullie\PathConverter\Converter') ) {
628
- include_once $path.'vendor/minifier/path-converter/src/ConverterInterface.php';
629
- include_once $path.'vendor/minifier/path-converter/src/Converter.php';
630
- }
631
- $minifier = null;
632
- eval('$minifier = new MatthiasMullie\Minify\\'.strtoupper($lang).'($code);');
633
- if ( $minifier !== null ) {
634
- $ret["result"] = true;
635
- $ret["minified_code"] = $minifier->minify();
636
- }
637
- }
638
-
639
- return $ret;
640
- }
641
-
642
- function wfu_css_to_HTML($css) {
643
- if ( WFU_VAR("WFU_MINIFY_INLINE_CSS") == "true" ) {
644
- $ret = wfu_minify_code("CSS", $css);
645
- if ( $ret["result"] ) $css = $ret["minified_code"];
646
- }
647
- $echo_str = "\n\t".'<style>';
648
- $echo_str .= "\n".$css;
649
- $echo_str .= "\n\t".'</style>';
650
-
651
- return $echo_str;
652
- }
653
-
654
- function wfu_js_to_HTML($js) {
655
- if ( WFU_VAR("WFU_MINIFY_INLINE_JS") == "true" ) {
656
- $ret = wfu_minify_code("JS", $js);
657
- if ( $ret["result"] ) $js = $ret["minified_code"];
658
- }
659
- $echo_str = '<script type="text/javascript">';
660
- $echo_str .= "\n".$js;
661
- $echo_str .= "\n".'</script>';
662
-
663
- return $echo_str;
664
- }
665
-
666
- function wfu_init_run_js_script() {
667
- // $script = 'if (typeof wfu_js_decode_obj == "undefined") function wfu_js_decode_obj(obj_str) { var obj = null; if (obj_str == "window") obj = window; else { var match = obj_str.match(new RegExp(\'GlobalData(\\\\.(WFU|WFUB)\\\\[(.*?)\\\\](\\\\.(.*))?)?$\')); if (match) { obj = GlobalData; if (match[3]) obj = obj[match[2]][match[3]]; if (match[5]) obj = obj[match[5]]; } } return obj; }';
668
- $script = 'if (typeof wfu_js_decode_obj == "undefined") function wfu_js_decode_obj(obj_str) { var obj = null; if (obj_str == "window") obj = window; else { var dbs = String.fromCharCode(92); var match = obj_str.match(new RegExp(\'GlobalData(\' + dbs + \'.(WFU|WFUB)\' + dbs + \'[(.*?)\' + dbs + \'](\' + dbs + \'.(.*))?)?$\')); if (match) { obj = GlobalData; if (match[3]) obj = obj[match[2]][match[3]]; if (match[5]) obj = obj[match[5]]; } } return obj; }';
669
- $script .= "\n".'if (typeof wfu_run_js == "undefined") function wfu_run_js(obj_str, func) { if (typeof GlobalData == "undefined") { if (typeof window.WFU_JS_BANK == "undefined") WFU_JS_BANK = []; WFU_JS_BANK.push({obj_str: obj_str, func: func}) } else { var obj = wfu_js_decode_obj(obj_str); if (obj) obj[func].call(obj); } }';
670
- return wfu_js_to_HTML($script);
671
- }
672
-
673
- function wfu_PHP_array_to_JS_object($arr) {
674
- $ret = "";
675
- foreach ( $arr as $prop => $value ) {
676
- if ( is_string($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: \"$value\"";
677
- elseif ( is_numeric($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: $value";
678
- elseif ( is_bool($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: ".( $value ? "true" : "false" );
679
- }
680
- return ( $ret == "" ? "{ }" : "{ $ret }" );
681
- }
682
-
683
- function wfu_array_to_GET_params($arr) {
684
- $str = "";
685
- foreach ( $arr as $key => $var )
686
- $str .= ( $str == "" ? "" : "&" ).$key."=".$var;
687
-
688
- return $str;
689
- }
690
-
691
- //********************* Shortcode Attribute Functions **************************************************************************************
692
-
693
- function wfu_insert_category($categories, $before_category, $new_category) {
694
- if ( $before_category == "" ) $index = count($categories);
695
- else {
696
- $index = array_search($before_category, array_keys($categories));
697
- if ( $index === false ) $index = count($categories);
698
- }
699
-
700
- return array_merge(array_slice($categories, 0, $index), $new_category, array_slice($categories, $index));
701
- }
702
-
703
- function wfu_insert_attributes($attributes, $in_category, $in_subcategory, $position, $new_attributes) {
704
- $index = -1;
705
- if ( $in_category == "" ) {
706
- if ( $position == "first" ) $index = 0;
707
- elseif ( $position == "last" ) $index = count($attributes);
708
- }
709
- else {
710
- foreach ( $attributes as $pos => $attribute ) {
711
- $match = ( $attribute["category"] == $in_category );
712
- if ( $in_subcategory != "" ) $match = $match && ( $attribute["subcategory"] == $in_subcategory );
713
- if ( $match ) {
714
- if ( $position == "first" ) {
715
- $index = $pos;
716
- break;
717
- }
718
- elseif ( $position == "last" ) {
719
- $index = $pos + 1;
720
- }
721
- }
722
- }
723
- }
724
- if ( $index > -1 ) array_splice($attributes, $index, 0, $new_attributes);
725
-
726
- return $attributes;
727
- }
728
-
729
- //********************* Plugin Options Functions *******************************************************************************************
730
-
731
- function wfu_get_server_environment() {
732
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
733
- $php_env = '';
734
- if ( PHP_INT_SIZE == 4 ) $php_env = '32bit';
735
- elseif ( PHP_INT_SIZE == 8 ) $php_env = '64bit';
736
- else {
737
- $int = "9223372036854775807";
738
- $int = intval($int);
739
- if ($int == 9223372036854775807) $php_env = '64bit';
740
- elseif ($int == 2147483647) $php_env = '32bit';
741
- }
742
-
743
- return $php_env;
744
- }
745
-
746
- function wfu_ajaxurl() {
747
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
748
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
749
- return ( $plugin_options['admindomain'] == 'siteurl' || $plugin_options['admindomain'] == '' ? site_url("wp-admin/admin-ajax.php") : ( $plugin_options['admindomain'] == 'adminurl' ? admin_url("admin-ajax.php") : home_url("wp-admin/admin-ajax.php") ) );
750
- }
751
-
752
- function WFU_VAR($varname) {
753
- if ( !isset($GLOBALS["WFU_GLOBALS"][$varname]) ) return false;
754
- if ( $GLOBALS["WFU_GLOBALS"][$varname][5] ) return $GLOBALS["WFU_GLOBALS"][$varname][3];
755
- //in case the environment variable is hidden then return the default value
756
- else return $GLOBALS["WFU_GLOBALS"][$varname][2];
757
- }
758
-
759
- function wfu_get_plugin_version() {
760
- $plugin_data = get_plugin_data(WPFILEUPLOAD_PLUGINFILE);
761
- return $plugin_data['Version'];
762
- }
763
-
764
- function wfu_get_latest_version() {
765
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
766
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
767
- $postfields = array();
768
- $postfields['action'] = 'wfuca_check_latest_version_free';
769
- $postfields['version_hash'] = WFU_VERSION_HASH;
770
- $url = ( $plugin_options["altserver"] == "1" && trim(WFU_VAR("WFU_ALT_IPTANUS_SERVER")) != "" ? ( trim(WFU_VAR("WFU_ALT_VERSION_SERVER")) != "" ? trim(WFU_VAR("WFU_ALT_VERSION_SERVER")) : trim(WFU_VAR("WFU_ALT_IPTANUS_SERVER")).'/wp-admin/admin-ajax.php' ) : WFU_VERSION_SERVER_URL );
771
- $result = null;
772
- if ( WFU_VAR("WFU_DISABLE_VERSION_CHECK") != "true" )
773
- $result = wfu_post_request($url, $postfields, false, false, 10);
774
- return $result;
775
- }
776
-
777
- function wfu_compare_versions($current, $latest) {
778
- $ret['status'] = true;
779
- $ret['custom'] = false;
780
- $ret['result'] = 'equal';
781
- $res = preg_match('/^([0-9]*)\.([0-9]*)\.([0-9]*)(.*)/', $current, $cur_data);
782
- if ( !$res || count($cur_data) < 5 )
783
- return array( 'status' => false, 'custom' => false, 'result' => 'current version invalid' );
784
- if ( $cur_data[1] == '' || $cur_data[2] == '' || $cur_data[3] == '' )
785
- return array( 'status' => false, 'custom' => false, 'result' => 'current version invalid' );
786
- $custom = ( $cur_data[4] != '' );
787
- $res = preg_match('/^([0-9]*)\.([0-9]*)\.([0-9]*)/', $latest, $lat_data);
788
- if ( !$res || count($lat_data) < 4 )
789
- return array( 'status' => false, 'custom' => $custom, 'result' => 'latest version invalid' );
790
- if ( $lat_data[1] == '' || $lat_data[2] == '' || $lat_data[3] == '' )
791
- return array( 'status' => false, 'custom' => $custom, 'result' => 'latest version invalid' );
792
- if ( intval($cur_data[1]) < intval($lat_data[1]) )
793
- return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
794
- elseif ( intval($cur_data[1]) > intval($lat_data[1]) )
795
- return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
796
- if ( intval($cur_data[2]) < intval($lat_data[2]) )
797
- return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
798
- elseif ( intval($cur_data[2]) > intval($lat_data[2]) )
799
- return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
800
- if ( intval($cur_data[3]) < intval($lat_data[3]) )
801
- return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
802
- elseif ( intval($cur_data[3]) > intval($lat_data[3]) )
803
- return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
804
- return array( 'status' => true, 'custom' => $custom, 'result' => 'equal' );
805
- }
806
-
807
- //********************* File / Directory Functions ************************************************************************************************
808
-
809
- function wfu_abspath() {
810
- $path = WP_CONTENT_DIR;
811
- //remove trailing slash if exists
812
- if ( substr($path, -1) == '/' ) $path = substr($path, 0, -1);
813
- $pos = strrpos($path, '/');
814
- //to find abspath we go one dir up from content path
815
- if ( $pos !== false ) $path = substr($path, 0, $pos + 1);
816
- //else if we cannot go up we stay at content path adding a trailing slash
817
- else $path .= '/';
818
-
819
- return $path;
820
- }
821
-
822
- function wfu_fileext($basename, $with_dot = false) {
823
- if ( $with_dot ) return preg_replace("/^.*?(\.[^.]*)?$/", "$1", $basename);
824
- else return preg_replace("/^.*?(\.([^.]*))?$/", "$2", $basename);
825
- }
826
-
827
- function wfu_filename($basename) {
828
- return preg_replace("/^(.*?)(\.[^.]*)?$/", "$1", $basename);
829
- }
830
-
831
- function wfu_basename($path) {
832
- if ( !$path || $path == "" ) return "";
833
- return preg_replace('/.*(\\\\|\\/)/', '', $path);
834
- }
835
-
836
- function wfu_basedir($path) {
837
- if ( !$path || $path == "" ) return "";
838
- return substr($path, 0, strlen($path) - strlen(wfu_basename($path)));
839
- }
840
-
841
- function wfu_path_abs2rel($path) {
842
- $abspath_notrailing_slash = substr(wfu_abspath(), 0, -1);
843
- if ( substr($path, 0, 6) == 'ftp://' || substr($path, 0, 7) == 'ftps://' || substr($path, 0, 7) == 'sftp://' ) return $path;
844
- else {
845
- $is_outside_root = ( substr($path, 0, strlen($abspath_notrailing_slash)) != $abspath_notrailing_slash );
846
- if ( $is_outside_root ) return 'abs:'.$path;
847
- // else return str_replace($abspath_notrailing_slash, "", $path);
848
- else return substr($path, strlen($abspath_notrailing_slash));
849
- }
850
- }
851
-
852
- function wfu_path_rel2abs($path) {
853
- if ( substr($path, 0, 1) == "/" ) $path = substr($path, 1);
854
- if ( substr($path, 0, 6) == 'ftp://' || substr($path, 0, 7) == 'ftps://' || substr($path, 0, 7) == 'sftp://' ) return $path;
855
- elseif ( substr($path, 0, 4) == 'abs:' ) return substr($path, 4);
856
- else return wfu_abspath().$path;
857
- }
858
-
859
- function wfu_delete_file_execute($filepath, $userid) {
860
- $filedata = wfu_get_filedata($filepath);
861
- $retid = wfu_log_action('delete', $filepath, $userid, '', 0, 0, '', null);
862
- $result = unlink($filepath);
863
- if ( !$result ) wfu_revert_log_action($retid);
864
- else {
865
- //delete linked attachment if exists and it is allowed to be deleted
866
- if ( $filedata != null && isset($filedata["media"]) && WFU_VAR("WFU_UPDATE_MEDIA_ON_DELETE") == "true" )
867
- wp_delete_attachment( $filedata["media"]["attach_id"] );
868
- }
869
-
870
- return $result;
871
- }
872
-
873
- function wfu_decode_ftpinfo($ftpdata) {
874
- $ret = array(
875
- "error" => true,
876
- "data" => array(
877
- "username" => "",
878
- "password" => "",
879
- "ftpdomain" => "",
880
- "port" => "",
881
- "sftp" => false
882
- )
883
- );
884
- $ftpdata_flat = str_replace(array('\:', '\@'), array('\_', '\_'), $ftpdata);
885
- $pos1 = strpos($ftpdata_flat, ":");
886
- $pos2 = strpos($ftpdata_flat, "@");
887
- if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
888
- $ret["error"] = false;
889
- $ret["data"]["username"] = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
890
- $ret["data"]["password"] = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, $pos1 + 1, $pos2 - $pos1 - 1));
891
- $ftp_host = substr($ftpdata, $pos2 + 1);
892
- $ret["data"]["ftpdomain"] = preg_replace("/:.*/", "", $ftp_host);
893
- if ( trim($ret["data"]["ftpdomain"]) == "" ) $ret["error"] = true;
894
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
895
- if ( substr($ftp_port, 0, 1) == "s" ) {
896
- $ret["data"]["sftp"] = true;
897
- $ftp_port = substr($ftp_port, 1);
898
- }
899
- $ret["data"]["port"] = $ftp_port;
900
- }
901
- elseif ( $pos2 ) {
902
- $ret["error"] = false;
903
- $ret["data"]["username"] = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos2));
904
- $ftp_host = substr($ftpdata, $pos2 + 1);
905
- $ret["data"]["ftpdomain"] = preg_replace("/:.*/", "", $ftp_host);
906
- if ( trim($ret["data"]["ftpdomain"]) == "" ) $ret["error"] = true;
907
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
908
- if ( substr($ftp_port, 0, 1) == "s" ) {
909
- $ret["data"]["sftp"] = true;
910
- $ftp_port = substr($ftp_port, 1);
911
- }
912
- $ret["data"]["port"] = $ftp_port;
913
- }
914
- elseif ( $pos1 ) {
915
- $ret["error"] = true;
916
- $ret["data"]["username"] = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
917
- $ret["data"]["password"] = str_replace(array('\:', '\@'), array(':', '@'),substr($ftpdata, $pos1 + 1));
918
- }
919
- else {
920
- $ret["error"] = true;
921
- $ret["data"]["username"] = str_replace(array('\:', '\@'), array(':', '@'), $ftpdata);
922
- }
923
-
924
- return $ret;
925
- }
926
-
927
- function wfu_upload_plugin_full_path( $params ) {
928
- $path = $params["uploadpath"];
929
- if ( $params["accessmethod"] == 'ftp' && $params["ftpinfo"] != '' && $params["useftpdomain"] == "true" ) {
930
- $ftpdata_flat = str_replace(array('\:', '\@'), array('\_', '\_'), $params["ftpinfo"]);
931
- //remove parent folder symbol (..) in path so that the path does not go outside host
932
- $ftpdata_flat = str_replace('..', '', $ftpdata_flat);
933
- $pos1 = strpos($ftpdata_flat, ":");
934
- $pos2 = strpos($ftpdata_flat, "@");
935
- if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
936
- $ftp_username = str_replace(array('\:', '\@'), array(':', '@'), substr($params["ftpinfo"], 0, $pos1));
937
- $ftp_password = str_replace(array('\:', '\@'), array(':', '@'), substr($params["ftpinfo"], $pos1 + 1, $pos2 - $pos1 - 1));
938
- $ftp_host = substr($params["ftpinfo"], $pos2 + 1);
939
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
940
- $ftp_host_clean = preg_replace("/:.*/", "", $ftp_host);
941
- $is_sftp = false;
942
- if ( substr($ftp_port, 0, 1) == "s" ) {
943
- $is_sftp = true;
944
- $ftp_port = substr($ftp_port, 1);
945
- if ( $ftp_port == "" ) $ftp_port = "22";
946
- }
947
- if ( $ftp_port != "" ) $ftp_host = $ftp_host_clean.":".$ftp_port;
948
- $ftp_username = str_replace('@', '%40', $ftp_username); //if username contains @ character then convert it to %40
949
- $ftp_password = str_replace('@', '%40', $ftp_password); //if password contains @ character then convert it to %40
950
- $start_folder = ( $is_sftp ? 's' : '' ).'ftp://'.$ftp_username.':'.$ftp_password."@".$ftp_host.'/';
951
- }
952
- else $start_folder = 'ftp://'.$params["ftpinfo"].'/';
953
- }
954
- else $start_folder = WP_CONTENT_DIR.'/';
955
- if ($path) {
956
- if ( $path == ".." || substr($path, 0, 3) == "../" ) {
957
- $start_folder = wfu_abspath();
958
- $path = substr($path, 2, strlen($path) - 2);
959
- }
960
- //remove additional parent folder symbols (..) in path so that the path does not go outside the $start_folder
961
- $path = str_replace('..', '', $path);
962
- if ( substr($path, 0, 1) == "/" ) $path = substr($path, 1, strlen($path) - 1);
963
- if ( substr($path, -1, 1) == "/" ) $path = substr($path, 0, strlen($path) - 1);
964
- $full_upload_path = $start_folder;
965
- if ( $path != "" ) $full_upload_path .= $path.'/';
966
- }
967
- else {
968
- $full_upload_path = $start_folder;
969
- }
970
- return $full_upload_path;
971
- }
972
-
973
- function wfu_upload_plugin_directory( $path ) {
974
- $dirparts = explode("/", $path);
975
- return $dirparts[count($dirparts) - 1];
976
- }
977
-
978
- //function to extract sort, filename or filter information from path, which are
979
- //stored as [[-sort]], {{filename}} or ((filter)) inside the path
980
- function wfu_extract_sortdata_from_path($path) {
981
- $ret['path'] = $path;
982
- $ret['sort'] = "";
983
- $ret['file'] = "";
984
- $ret['filter'] = "";
985
- //extract sort info
986
- $pos1 = strpos($path, '[[');
987
- $pos2 = strpos($path, ']]');
988
- if ( $pos1 !== false && $pos2 !== false )
989
- if ( $pos2 > $pos1 ) {
990
- $ret['sort'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
991
- $ret['path'] = str_replace('[['.$ret['sort'].']]', '', $path);
992
- }
993
- //extract filename info
994
- $pos1 = strpos($path, '{{');
995
- $pos2 = strpos($path, '}}');
996
- if ( $pos1 !== false && $pos2 !== false )
997
- if ( $pos2 > $pos1 ) {
998
- $ret['file'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
999
- $ret['path'] = str_replace('{{'.$ret['file'].'}}', '', $path);
1000
- }
1001
- //extract filter info
1002
- $pos1 = strpos($path, '((');
1003
- $pos2 = strpos($path, '))');
1004
- if ( $pos1 !== false && $pos2 !== false )
1005
- if ( $pos2 > $pos1 ) {
1006
- $ret['filter'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
1007
- $ret['path'] = str_replace('(('.$ret['filter'].'))', '', $path);
1008
- }
1009
- return $ret;
1010
- }
1011
-
1012
- //extract sort information from path and return the flatten path
1013
- function wfu_flatten_path($path) {
1014
- $ret = wfu_extract_sortdata_from_path($path);
1015
- return $ret['path'];
1016
- }
1017
-
1018
- function wfu_delTree($dir) {
1019
- $files = array_diff(scandir($dir), array('.','..'));
1020
- foreach ($files as $file) {
1021
- is_dir("$dir/$file") ? wfu_delTree("$dir/$file") : unlink("$dir/$file");
1022
- }
1023
- return rmdir($dir);
1024
- }
1025
-
1026
- function wfu_getTree($dir) {
1027
- $tree = array();
1028
- $files = @scandir($dir);
1029
- if ( !is_array($files) ) $files = array();
1030
- $files = array_diff($files, array('.','..'));
1031
- foreach ($files as $file) {
1032
- if ( is_dir("$dir/$file") ) array_push($tree, $file);
1033
- }
1034
- return $tree;
1035
- }
1036
- function wfu_parse_folderlist($subfoldertree) {
1037
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1038
- $ret['path'] = array();
1039
- $ret['label'] = array();
1040
- $ret['level'] = array();
1041
- $ret['default'] = array();
1042
-
1043
- if ( substr($subfoldertree, 0, 4) == "auto" ) return $ret;
1044
- $subfolders = explode(",", $subfoldertree);
1045
- if ( count($subfolders) == 0 ) return $ret;
1046
- if ( count($subfolders) == 1 && trim($subfolders[0]) == "" ) return $ret;
1047
- $dir_levels = array ( "root" );
1048
- $prev_level = 0;
1049
- $level0_count = 0;
1050
- $default = -1;
1051
- foreach ($subfolders as $subfolder) {
1052
- $subfolder = trim($subfolder);
1053
- $star_count = 0;
1054
- $start_spaces = "";
1055
- $is_default = false;
1056
- //check for folder level
1057
- while ( $star_count < strlen($subfolder) ) {
1058
- if ( substr($subfolder, $star_count, 1) == "*" ) {
1059
- $star_count ++;
1060
- $start_spaces .= "&nbsp;&nbsp;&nbsp;";
1061
- }
1062
- else break;
1063
- }
1064
- if ( $star_count - $prev_level <= 1 && ( $star_count > 0 || $level0_count == 0 ) ) {
1065
- $subfolder = substr($subfolder, $star_count, strlen($subfolder) - $star_count);
1066
- // check for default value
1067
- if ( substr($subfolder, 0, 1) == '&' ) {
1068
- $subfolder = substr($subfolder, 1);
1069
- $is_default = true;
1070
- }
1071
- //split item in folder path and folder name
1072
- $subfolder_items = explode('/', $subfolder);
1073
- if ( count($subfolder_items) > 1 && $subfolder_items[1] != "" ) {
1074
- $subfolder_dir = $subfolder_items[0];
1075
- $subfolder_label = $subfolder_items[1];
1076
- }
1077
- else {
1078
- $subfolder_dir = $subfolder;
1079
- $subfolder_label = $subfolder;
1080
- }
1081
- if ( $subfolder_dir != "" ) {
1082
- // set is_default flag to true only for the first default item
1083
- if ( $is_default && $default == -1 ) $default = count($ret['path']);
1084
- else $is_default = false;
1085
- // set flag that root folder has been included (so that it is not included it again)
1086
- if ( $star_count == 0 ) $level0_count = 1;
1087
- if ( count($dir_levels) > $star_count ) $dir_levels[$star_count] = $subfolder_dir;
1088
- else array_push($dir_levels, $subfolder_dir);
1089
- $subfolder_path = "";
1090
- for ( $i_count = 1; $i_count <= $star_count; $i_count++) {
1091
- $subfolder_path .= $dir_levels[$i_count].'/';
1092
- }
1093
- array_push($ret['path'], $subfolder_path);
1094
- array_push($ret['label'], $subfolder_label);
1095
- array_push($ret['level'], $star_count);
1096
- array_push($ret['default'], $is_default);
1097
- $prev_level = $star_count;
1098
- }
1099
- }
1100
- }
1101
-
1102
- return $ret;
1103
- }
1104
-
1105
- function wfu_filesize($filepath) {
1106
- $fp = fopen($filepath, 'r');
1107
- $pos = 0;
1108
- if ($fp) {
1109
- $size = 1073741824;
1110
- fseek($fp, 0, SEEK_SET);
1111
- while ($size > 1) {
1112
- fseek($fp, $size, SEEK_CUR);
1113
- if (fgetc($fp) === false) {
1114
- fseek($fp, -$size, SEEK_CUR);
1115
- $size = (int)($size / 2);
1116
- }
1117
- else {
1118
- fseek($fp, -1, SEEK_CUR);
1119
- $pos += $size;
1120
- }
1121
- }
1122
- while (fgetc($fp) !== false) $pos++;
1123
- fclose($fp);
1124
- }
1125
-
1126
- return $pos;
1127
- }
1128
-
1129
- function wfu_filesize2($filepath) {
1130
- $fp = fopen($filepath, 'r');
1131
- $return = false;
1132
- if (is_resource($fp)) {
1133
- if (PHP_INT_SIZE < 8) {
1134
- // 32bit
1135
- if (0 === fseek($fp, 0, SEEK_END)) {
1136
- $return = 0.0;
1137
- $step = 0x7FFFFFFF;
1138
- while ($step > 0) {
1139
- if (0 === fseek($fp, - $step, SEEK_CUR)) {
1140
- $return += floatval($step);
1141
- } else {
1142
- $step >>= 1;
1143
- }
1144
- }
1145
- }
1146
- } elseif (0 === fseek($fp, 0, SEEK_END)) {
1147
- // 64bit
1148
- $return = ftell($fp);
1149
- }
1150
- fclose($fp);
1151
- }
1152
- return $return;
1153
- }
1154
-
1155
- function wfu_fseek($fp, $pos, $first = 1) {
1156
- // set to 0 pos initially, one-time
1157
- if ( $first ) fseek($fp, 0, SEEK_SET);
1158
-
1159
- // get pos float value
1160
- $pos = floatval($pos);
1161
-
1162
- // within limits, use normal fseek
1163
- if ( $pos <= PHP_INT_MAX )
1164
- fseek($fp, $pos, SEEK_CUR);
1165
- // out of limits, use recursive fseek
1166
- else {
1167
- fseek($fp, PHP_INT_MAX, SEEK_CUR);
1168
- $pos -= PHP_INT_MAX;
1169
- wfu_fseek($fp, $pos, 0);
1170
- }
1171
- }
1172
-
1173
- function wfu_fseek2($fp, $pos) {
1174
- $pos = floatval($pos);
1175
- if ( $pos <= PHP_INT_MAX ) {
1176
- return fseek($fp, $pos, SEEK_SET);
1177
- }
1178
- else {
1179
- $fsize = wfu_filesize2($filepath);
1180
- $opp = $fsize - $pos;
1181
- if ( 0 === ($ans = fseek($fp, 0, SEEK_END)) ) {
1182
- $maxstep = 0x7FFFFFFF;
1183
- $step = $opp;
1184
- if ( $step > $maxstep ) $step = $maxstep;
1185
- while ($step > 0) {
1186
- if ( 0 === ($ans = fseek($fp, - $step, SEEK_CUR)) ) {
1187
- $opp -= floatval($step);
1188
- }
1189
- else {
1190
- $maxstep >>= 1;
1191
- }
1192
- $step = $opp;
1193
- if ( $step > $maxstep ) $step = $maxstep;
1194
- }
1195
- }
1196
- }
1197
- return $ans;
1198
- }
1199
-
1200
- function wfu_debug_log($message) {
1201
- $logpath = WP_CONTENT_DIR.'/debug_log.txt';
1202
- file_put_contents($logpath, $message, FILE_APPEND);
1203
- }
1204
-
1205
- function wfu_debug_log_obj($obj) {
1206
- wfu_debug_log(print_r($obj, true));
1207
- }
1208
-
1209
- function wfu_safe_store_filepath($path) {
1210
- $code = wfu_create_random_string(16);
1211
- $safe_storage = ( WFU_USVAR_exists('wfu_filepath_safe_storage') ? WFU_USVAR('wfu_filepath_safe_storage') : array() );
1212
- $safe_storage[$code] = $path;
1213
- WFU_USVAR_store('wfu_filepath_safe_storage', $safe_storage);
1214
- return $code;
1215
- }
1216
-
1217
- function wfu_get_filepath_from_safe($code) {
1218
- //sanitize $code
1219
- $code = wfu_sanitize_code($code);
1220
- if ( $code == "" ) return false;
1221
- //return filepath from session variable, if exists
1222
- if ( !WFU_USVAR_exists('wfu_filepath_safe_storage') ) return false;
1223
- $safe_storage = WFU_USVAR('wfu_filepath_safe_storage');
1224
- if ( !isset($safe_storage[$code]) ) return false;
1225
- return $safe_storage[$code];
1226
- }
1227
-
1228
- function wfu_file_extension_restricted($filename) {
1229
- return (
1230
- substr($filename, -4) == ".php" ||
1231
- substr($filename, -3) == ".js" ||
1232
- substr($filename, -4) == ".pht" ||
1233
- substr($filename, -5) == ".php3" ||
1234
- substr($filename, -5) == ".php4" ||
1235
- substr($filename, -5) == ".php5" ||
1236
- substr($filename, -6) == ".phtml" ||
1237
- substr($filename, -4) == ".htm" ||
1238
- substr($filename, -5) == ".html" ||
1239
- substr($filename, -9) == ".htaccess" ||
1240
- strpos($filename, ".php.") !== false ||
1241
- strpos($filename, ".js.") !== false ||
1242
- strpos($filename, ".pht.") !== false ||
1243
- strpos($filename, ".php3.") !== false ||
1244
- strpos($filename, ".php4.") !== false ||
1245
- strpos($filename, ".php5.") !== false ||
1246
- strpos($filename, ".phtml.") !== false ||
1247
- strpos($filename, ".htm.") !== false ||
1248
- strpos($filename, ".html.") !== false ||
1249
- strpos($filename, ".htaccess.") !== false
1250
- );
1251
- }
1252
-
1253
- function wfu_human_time($time) {
1254
- $time = (int)$time;
1255
- $days = (int)($time/86400);
1256
- $time -= $days * 86400;
1257
- $hours = (int)($time/3600);
1258
- $time -= $hours * 3600;
1259
- $minutes = (int)($time/60);
1260
- $secs = $time - $minutes * 60;
1261
- $human_time = ( $days > 0 ? $days."d" : "" ).( $hours > 0 ? $hours."h" : "" ).( $minutes > 0 ? $minutes."m" : "" ).( $secs > 0 ? $secs."s" : "" );
1262
- if ( $human_time == "" ) $human_time == "0s";
1263
- return $human_time;
1264
- }
1265
-
1266
- function wfu_human_filesize($size, $unit = "") {
1267
- if ( ( !$unit && $size >= 1<<30 ) || $unit == "GB" )
1268
- return number_format($size / (1<<30), 2)."GB";
1269
- if( ( !$unit && $size >= 1<<20 ) || $unit == "MB" )
1270
- return number_format($size / (1<<20), 2)."MB";
1271
- if( ( !$unit && $size >= 1<<10 ) || $unit == "KB" )
1272
- return number_format($size / (1<<10), 2)."KB";
1273
- return number_format($size)." bytes";
1274
- }
1275
-
1276
- function wfu_file_exists($path) {
1277
- if ( file_exists($path) ) return true;
1278
-
1279
- return false;
1280
- }
1281
-
1282
- //********************* User Functions *****************************************************************************************************
1283
-
1284
- function wfu_get_user_role($user, $param_roles) {
1285
- $result_role = 'nomatch';
1286
- if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
1287
- /* Go through the array of the roles of the current user */
1288
- foreach ( $user->roles as $user_role ) {
1289
- $user_role = strtolower($user_role);
1290
- /* if this role matches to the roles in $param_roles or it is administrator or $param_roles allow all roles then it is approved */
1291
- if ( in_array($user_role, $param_roles) || $user_role == 'administrator' || in_array('all', $param_roles) ) {
1292
- /* We approve this role of the user and exit */
1293
- $result_role = $user_role;
1294
- break;
1295
- }
1296
- }
1297
- }
1298
- /* if the user has no roles (guest) and guests are allowed, then it is approved */
1299
- elseif ( in_array('guests', $param_roles) ) {
1300
- $result_role = 'guest';
1301
- }
1302
- return $result_role;
1303
- }
1304
-
1305
- function wfu_get_user_valid_role_names($user) {
1306
- global $wp_roles;
1307
-
1308
- $result_roles = array();
1309
- if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
1310
- /* get all valid roles */
1311
- $roles = $wp_roles->get_names();
1312
- /* Go through the array of the roles of the current user */
1313
- foreach ( $user->roles as $user_role ) {
1314
- $user_role = strtolower($user_role);
1315
- /* If one role of the current user matches to the roles allowed to upload */
1316
- if ( in_array($user_role, array_keys($roles)) ) array_push($result_roles, $user_role);
1317
- }
1318
- }
1319
-
1320
- return $result_roles;
1321
- }
1322
-
1323
- //*********************** DB Functions *****************************************************************************************************
1324
-
1325
- //log action to database
1326
- function wfu_log_action($action, $filepath, $userid, $uploadid, $pageid, $blogid, $sid, $userdata) {
1327
- global $wpdb;
1328
- $table_name1 = $wpdb->prefix . "wfu_log";
1329
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1330
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1331
-
1332
- if ( !file_exists($filepath) && $action != 'datasubmit' && substr($action, 0, 5) != 'other' ) return;
1333
- $parts = pathinfo($filepath);
1334
- $relativepath = wfu_path_abs2rel($filepath);
1335
- // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
1336
-
1337
- $retid = 0;
1338
- if ( $action == 'upload' || $action == 'include' || $action == 'datasubmit' ) {
1339
- if ( $action == 'upload' || $action == 'include' ) {
1340
- // calculate and store file hash if this setting is enabled from Settings
1341
- $filehash = '';
1342
- if ( $plugin_options['hashfiles'] == '1' ) $filehash = md5_file($filepath);
1343
- // calculate file size
1344
- $filesize = filesize($filepath);
1345
- // first make obsolete records having the same file path because the old file has been replaced
1346
- $oldrecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND date_to = 0');
1347
- if ( $oldrecs ) {
1348
- foreach ( $oldrecs as $oldrec ) wfu_make_rec_obsolete($oldrec);
1349
- }
1350
- }
1351
- // attempt to create new log record
1352
- $now_date = date('Y-m-d H:i:s');
1353
- if ( $wpdb->insert($table_name1,
1354
- array(
1355
- 'userid' => $userid,
1356
- 'uploaduserid' => $userid,
1357
- 'uploadtime' => time(),
1358
- 'sessionid' => session_id(),
1359
- 'filepath' => ( $action == 'datasubmit' ? '' : $relativepath ),
1360
- 'filehash' => ( $action == 'datasubmit' ? '' : $filehash ),
1361
- 'filesize' => ( $action == 'datasubmit' ? 0 : $filesize ),
1362
- 'uploadid' => $uploadid,
1363
- 'pageid' => $pageid,
1364
- 'blogid' => $blogid,
1365
- 'sid' => $sid,
1366
- 'date_from' => $now_date,
1367
- 'date_to' => 0,
1368
- 'action' => $action
1369
- ),
1370
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s' )) !== false ) {
1371
- $retid = $wpdb->insert_id;
1372
- // if new log record has been created, also create user data records
1373
- if ( $userdata != null && $uploadid != '' ) {
1374
- foreach ( $userdata as $userdata_key => $userdata_field ) {
1375
- $existing = $wpdb->get_row('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$uploadid.'\' AND property = \''.esc_sql($userdata_field['label']).'\' AND date_to = 0');
1376
- if ($existing == null)
1377
- $wpdb->insert($table_name2,
1378
- array(
1379
- 'uploadid' => $uploadid,
1380
- 'property' => $userdata_field['label'],
1381
- 'propkey' => $userdata_key,
1382
- 'propvalue' => $userdata_field['value'],
1383
- 'date_from' => $now_date,
1384
- 'date_to' => 0
1385
- ),
1386
- array( '%s', '%s', '%d', '%s', '%s', '%s' ));
1387
- }
1388
- }
1389
- }
1390
- }
1391
- //for rename or move action the $action variable is of the form:
1392
- // $action = 'rename:'.$newfilepath; (for rename action)
1393
- // $action = 'move:'.$newfilepath; (for move action)
1394
- //in order to pass the new file path
1395
- elseif ( substr($action, 0, 6) == 'rename' || substr($action, 0, 4) == 'move' ) {
1396
- $cleanaction = ( substr($action, 0, 6) == 'rename' ? 'rename' : 'move' );
1397
- //get new filepath
1398
- $newfilepath = substr($action, strlen($cleanaction) + 1);
1399
- $relativepath = wfu_path_abs2rel($newfilepath);
1400
- // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
1401
- //get stored file data from database without user data
1402
- $filerec = wfu_get_file_rec($filepath, false);
1403
- //log action only if there are previous stored file data
1404
- if ( $filerec != null ) {
1405
- $now_date = date('Y-m-d H:i:s');
1406
- //make previous record obsolete
1407
- $wpdb->update($table_name1,
1408
- array( 'date_to' => $now_date ),
1409
- array( 'idlog' => $filerec->idlog ),
1410
- array( '%s' ),
1411
- array( '%d' )
1412
- );
1413
- //insert new rename record
1414
- if ( $wpdb->insert($table_name1,
1415
- array(
1416
- 'userid' => $userid,
1417
- 'uploaduserid' => $filerec->uploaduserid,
1418
- 'uploadtime' => $filerec->uploadtime,
1419
- 'sessionid' => $filerec->sessionid,
1420
- 'filepath' => $relativepath,
1421
- 'filehash' => $filerec->filehash,
1422
- 'filesize' => $filerec->filesize,
1423
- 'uploadid' => $filerec->uploadid,
1424
- 'pageid' => $filerec->pageid,
1425
- 'blogid' => $filerec->blogid,
1426
- 'sid' => $filerec->sid,
1427
- 'date_from' => $now_date,
1428
- 'date_to' => 0,
1429
- 'action' => $cleanaction,
1430
- 'linkedto' => $filerec->idlog,
1431
- 'filedata' => $filerec->filedata
1432
- ),
1433
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' ) ) !== false )
1434
- $retid = $wpdb->insert_id;
1435
- }
1436
- }
1437
- elseif ( $action == 'delete' ) {
1438
- //get stored file data from database without user data
1439
- $filerec = wfu_get_file_rec($filepath, false);
1440
- //log action only if there are previous stored file data
1441
- if ( $filerec != null ) {
1442
- $now_date = date('Y-m-d H:i:s');
1443
- //make previous record obsolete
1444
- $wpdb->update($table_name1,
1445
- array( 'date_to' => $now_date ),
1446
- array( 'idlog' => $filerec->idlog ),
1447
- array( '%s' ),
1448
- array( '%d' )
1449
- );
1450
- //insert new delete record
1451
- if ( $wpdb->insert($table_name1,
1452
- array(
1453
- 'userid' => $userid,
1454
- 'uploaduserid' => $filerec->uploaduserid,
1455
- 'uploadtime' => $filerec->uploadtime,
1456
- 'sessionid' => $filerec->sessionid,
1457
- 'filepath' => $filerec->filepath,
1458
- 'filehash' => $filerec->filehash,
1459
- 'filesize' => $filerec->filesize,
1460
- 'uploadid' => $filerec->uploadid,
1461
- 'pageid' => $filerec->pageid,
1462
- 'blogid' => $filerec->blogid,
1463
- 'sid' => $filerec->sid,
1464
- 'date_from' => $now_date,
1465
- 'date_to' => $now_date,
1466
- 'action' => 'delete',
1467
- 'linkedto' => $filerec->idlog,
1468
- 'filedata' => $filerec->filedata
1469
- ),
1470
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
1471
- $retid = $wpdb->insert_id;
1472
- }
1473
- }
1474
- elseif ( $action == 'download' ) {
1475
- //get stored file data from database without user data
1476
- $filerec = wfu_get_file_rec($filepath, false);
1477
- //log action only if there are previous stored file data
1478
- if ( $filerec != null ) {
1479
- $now_date = date('Y-m-d H:i:s');
1480
- //make previous record obsolete
1481
- $wpdb->update($table_name1,
1482
- array( 'date_to' => $now_date ),
1483
- array( 'idlog' => $filerec->idlog ),
1484
- array( '%s' ),
1485
- array( '%d' )
1486
- );
1487
- //insert new download record
1488
- if ( $wpdb->insert($table_name1,
1489
- array(
1490
- 'userid' => $userid,
1491
- 'uploaduserid' => $filerec->uploaduserid,
1492
- 'uploadtime' => $filerec->uploadtime,
1493
- 'sessionid' => $filerec->sessionid,
1494
- 'filepath' => $filerec->filepath,
1495
- 'filehash' => $filerec->filehash,
1496
- 'filesize' => $filerec->filesize,
1497
- 'uploadid' => $filerec->uploadid,
1498
- 'pageid' => $filerec->pageid,
1499
- 'blogid' => $filerec->blogid,
1500
- 'sid' => $filerec->sid,
1501
- 'date_from' => $now_date,
1502
- 'date_to' => 0,
1503
- 'action' => 'download',
1504
- 'linkedto' => $filerec->idlog,
1505
- 'filedata' => $filerec->filedata
1506
- ),
1507
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
1508
- $retid = $wpdb->insert_id;
1509
- }
1510
- }
1511
- //for modify action the $action variable is of the form: $action = 'modify:'.$now_date; in order to pass the exact modify date
1512
- elseif ( substr($action, 0, 6) == 'modify' ) {
1513
- $now_date = substr($action, 7);
1514
- //get stored file data from database without user data
1515
- $filerec = wfu_get_file_rec($filepath, false);
1516
- //log action only if there are previous stored file data
1517
- if ( $filerec != null ) {
1518
- //make previous record obsolete
1519
- $wpdb->update($table_name1,
1520
- array( 'date_to' => $now_date ),
1521
- array( 'idlog' => $filerec->idlog ),
1522
- array( '%s' ),
1523
- array( '%d' )
1524
- );
1525
- //insert new modify record
1526
- if ( $wpdb->insert($table_name1,
1527
- array(
1528
- 'userid' => $userid,
1529
- 'uploaduserid' => $filerec->uploaduserid,
1530
- 'uploadtime' => $filerec->uploadtime,
1531
- 'sessionid' => $filerec->sessionid,
1532
- 'filepath' => $filerec->filepath,
1533
- 'filehash' => $filerec->filehash,
1534
- 'filesize' => $filerec->filesize,
1535
- 'uploadid' => $filerec->uploadid,
1536
- 'pageid' => $filerec->pageid,
1537
- 'blogid' => $filerec->blogid,
1538
- 'sid' => $filerec->sid,
1539
- 'date_from' => $now_date,
1540
- 'date_to' => 0,
1541
- 'action' => 'modify',
1542
- 'linkedto' => $filerec->idlog,
1543
- 'filedata' => $filerec->filedata
1544
- ),
1545
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
1546
- $retid = $wpdb->insert_id;
1547
- }
1548
- }
1549
- elseif ( substr($action, 0, 10) == 'changeuser' ) {
1550
- $new_user = substr($action, 11);
1551
- //get stored file data from database without user data
1552
- $filerec = wfu_get_file_rec($filepath, false);
1553
- //log action only if there are previous stored file data
1554
- if ( $filerec != null ) {
1555
- $now_date = date('Y-m-d H:i:s');
1556
- //make previous record obsolete
1557
- $wpdb->update($table_name1,
1558
- array( 'date_to' => $now_date ),
1559
- array( 'idlog' => $filerec->idlog ),
1560
- array( '%s' ),
1561
- array( '%d' )
1562
- );
1563
- //insert new modify record
1564
- if ( $wpdb->insert($table_name1,
1565
- array(
1566
- 'userid' => $userid,
1567
- 'uploaduserid' => $new_user,
1568
- 'uploadtime' => $filerec->uploadtime,
1569
- 'sessionid' => $filerec->sessionid,
1570
- 'filepath' => $filerec->filepath,
1571
- 'filehash' => $filerec->filehash,
1572
- 'filesize' => $filerec->filesize,
1573
- 'uploadid' => $filerec->uploadid,
1574
- 'pageid' => $filerec->pageid,
1575
- 'blogid' => $filerec->blogid,
1576
- 'sid' => $filerec->sid,
1577
- 'date_from' => $now_date,
1578
- 'date_to' => 0,
1579
- 'action' => 'changeuser',
1580
- 'linkedto' => $filerec->idlog,
1581
- 'filedata' => $filerec->filedata
1582
- ),
1583
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
1584
- $retid = $wpdb->insert_id;
1585
- }
1586
- }
1587
- elseif ( substr($action, 0, 5) == 'other' ) {
1588
- $info = substr($action, 6);
1589
- $now_date = date('Y-m-d H:i:s');
1590
- //insert new other type record
1591
- if ( $wpdb->insert($table_name1,
1592
- array(
1593
- 'userid' => $userid,
1594
- 'uploaduserid' => -1,
1595
- 'uploadtime' => 0,
1596
- 'sessionid' => '',
1597
- 'filepath' => $info,
1598
- 'filehash' => '',
1599
- 'filesize' => 0,
1600
- 'uploadid' => '',
1601
- 'pageid' => 0,
1602
- 'blogid' => 0,
1603
- 'sid' => '',
1604
- 'date_from' => $now_date,
1605
- 'date_to' => $now_date,
1606
- 'action' => 'other',
1607
- 'linkedto' => -1
1608
- ),
1609
- array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d' )) != false )
1610
- $retid = $wpdb->insert_id;
1611
- }
1612
- return $retid;
1613
- }
1614
-
1615
- //revert previously saved action
1616
- function wfu_revert_log_action($idlog) {
1617
- global $wpdb;
1618
- $table_name1 = $wpdb->prefix . "wfu_log";
1619
-
1620
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
1621
- if ( $filerec != null ) {
1622
- $prevfilerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$filerec->linkedto);
1623
- if ( $prevfilerec != null ) {
1624
- $wpdb->delete($table_name1,
1625
- array( 'idlog' => $filerec->idlog ),
1626
- array( '%d' )
1627
- );
1628
- $wpdb->update($table_name1,
1629
- array( 'date_to' => 0 ),
1630
- array( 'idlog' => $prevfilerec->idlog ),
1631
- array( '%s' ),
1632
- array( '%d' )
1633
- );
1634
- }
1635
- }
1636
- }
1637
-
1638
- //find user by its id and return a non-empty username
1639
- function wfu_get_username_by_id($id) {
1640
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1641
- $user = get_user_by('id', $id);
1642
- if ( $user == false && $id > 0 ) $username = 'unknown';
1643
- elseif ( $user == false && $id == -999 ) $username = 'system';
1644
- elseif ( $user == false ) $username = 'guest';
1645
- else $username = $user->user_login;
1646
- return $username;
1647
- }
1648
-
1649
- function wfu_get_unread_files_count() {
1650
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1651
- global $wpdb;
1652
- $table_name1 = $wpdb->prefix . "wfu_log";
1653
-
1654
- //get the last idlog read from options; create the option if it does not
1655
- //exist pointing to the currently last idlog
1656
- $last_idlog = get_option( "wordpress_file_upload_last_idlog" );
1657
- if ( $last_idlog === false ) {
1658
- $latest_idlog = $wpdb->get_var('SELECT MAX(idlog) FROM '.$table_name1);
1659
- $last_idlog = array( 'pre' => $latest_idlog, 'post' => $latest_idlog, 'time' => time() );
1660
- update_option( "wordpress_file_upload_last_idlog", $last_idlog );
1661
- }
1662
- $limit = (int)WFU_VAR("WFU_UPLOADEDFILES_RESET_TIME");
1663
- $unread_files_count = 0;
1664
- if ( $limit == -1 || time() > $last_idlog["time"] + $limit ) $unread_files_count = wfu_get_new_files_count($last_idlog["post"]);
1665
- else $unread_files_count = wfu_get_new_files_count($last_idlog["pre"]);
1666
-
1667
- return $unread_files_count;
1668
- }
1669
-
1670
- function wfu_get_new_files_count($last_idlog) {
1671
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1672
- global $wpdb;
1673
- $table_name1 = $wpdb->prefix . "wfu_log";
1674
- return $wpdb->get_var('SELECT COUNT(idlog) FROM '.$table_name1.' WHERE action = \'upload\' AND idlog > '.(int)$last_idlog);
1675
- }
1676
-
1677
- function wfu_read_log_data($data) {
1678
- $ret['service'] = "";
1679
- $ret['transferred'] = "";
1680
- $ret['error'] = "";
1681
- $ret['destination'] = "";
1682
- $ret['new_filename'] = "";
1683
- if ( substr($data, 0, 5) == "json:" ) {
1684
- $logdata = json_decode(substr($data, 5), true);
1685
- $ret['service'] = $logdata["service"];
1686
- $ret['transferred'] = $logdata["transferred"];
1687
- $ret['error'] = $logdata["error"];
1688
- $ret['destination'] = $logdata["destination"];
1689
- $ret['new_filename'] = $logdata["new_filename"];
1690
- }
1691
- else list($ret['service'], $ret['destination']) = explode("|", $data);
1692
-
1693
- return $ret;
1694
- }
1695
-
1696
- //get the most current database record for file $filepath and also include any userdata if $include_userdata is true
1697
- function wfu_get_file_rec($filepath, $include_userdata) {
1698
- global $wpdb;
1699
- $table_name1 = $wpdb->prefix . "wfu_log";
1700
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1701
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1702
-
1703
- if ( !file_exists($filepath) ) return null;
1704
-
1705
- $relativepath = wfu_path_abs2rel($filepath);
1706
- // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
1707
- //if file hash is enabled, then search file based on its path and hash, otherwise find file based on its path and size
1708
- if ( isset($plugin_options['hashfiles']) && $plugin_options['hashfiles'] == '1' ) {
1709
- $filehash = md5_file($filepath);
1710
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND filehash = \''.$filehash.'\' AND date_to = 0 ORDER BY date_from DESC');
1711
- }
1712
- else {
1713
- $stat = stat($filepath);
1714
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND filesize = '.$stat['size'].' AND date_to = 0 ORDER BY date_from DESC');
1715
- }
1716
- //get user data
1717
- if ( $filerec != null && $include_userdata ) {
1718
- $filerec->userdata = null;
1719
- if ( $filerec->uploadid != '' ) {
1720
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
1721
- }
1722
- }
1723
- return $filerec;
1724
- }
1725
-
1726
- function wfu_get_valid_affected_files($recs) {
1727
- $valid_affected_files = array();
1728
- $files_checked = array();
1729
- foreach ($recs as $rec)
1730
- if ( $latestrec = wfu_get_latest_rec_from_id($rec->idlog) ) {
1731
- $file = wfu_path_rel2abs($latestrec->filepath);
1732
- if ( !in_array($file, $files_checked) ) {
1733
- if ( file_exists($file) ) array_push($valid_affected_files, $file);
1734
- array_push($files_checked, $file);
1735
- }
1736
- }
1737
-
1738
- return $valid_affected_files;
1739
- }
1740
-
1741
- //get database record for id
1742
- function wfu_get_file_rec_from_id($idlog, $include_userdata = false) {
1743
- global $wpdb;
1744
- $table_name1 = $wpdb->prefix . "wfu_log";
1745
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1746
-
1747
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
1748
- if ( $filerec != null && $include_userdata ) {
1749
- $filerec->userdata = null;
1750
- if ( $filerec->uploadid != '' ) {
1751
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
1752
- }
1753
- }
1754
-
1755
- return $filerec;
1756
- }
1757
-
1758
- function wfu_get_userdata_from_id($idlog) {
1759
- $userdata = array();
1760
- $filerec = wfu_get_file_rec_from_id($idlog, true);
1761
- if ( $filerec != null && $filerec->userdata != null )
1762
- foreach ( $filerec->userdata as $item ) {
1763
- $arrayitem = array(
1764
- "property" => $item->property,
1765
- "value" => $item->propvalue
1766
- );
1767
- array_push($userdata, $arrayitem);
1768
- }
1769
-
1770
- return $userdata;
1771
- }
1772
-
1773
- function wfu_get_userdata_from_rec($filerec) {
1774
- global $wpdb;
1775
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1776
-
1777
- $userdata = array();
1778
- if ( $filerec->uploadid != '' ) {
1779
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
1780
- if ( $filerec->userdata != null )
1781
- foreach ( $filerec->userdata as $item ) {
1782
- $arrayitem = array(
1783
- "property" => $item->property,
1784
- "value" => $item->propvalue
1785
- );
1786
- array_push($userdata, $arrayitem);
1787
- }
1788
- }
1789
-
1790
- return $userdata;
1791
- }
1792
-
1793
- function wfu_get_oldestrec_from_uniqueid($uniqueid) {
1794
- global $wpdb;
1795
- $table_name1 = $wpdb->prefix . "wfu_log";
1796
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE idlog IN (SELECT MIN(idlog) FROM '.$table_name1.' WHERE uploadid = \''.$uniqueid.'\')');
1797
- if ( $filerecs == null ) return null;
1798
- if ( count($filerecs) > 0 ) return $filerecs[0];
1799
- else return null;
1800
- }
1801
-
1802
- function wfu_get_latest_rec_from_id($idlog) {
1803
- global $wpdb;
1804
- $table_name1 = $wpdb->prefix . "wfu_log";
1805
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
1806
- while ( $filerec != null && $filerec->date_to != "0000-00-00 00:00:00" )
1807
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE linkedto = '.$filerec->idlog);
1808
-
1809
- return $filerec;
1810
- }
1811
-
1812
- function wfu_get_rec_new_history($idlog) {
1813
- global $wpdb;
1814
- $table_name1 = $wpdb->prefix . "wfu_log";
1815
- $filerecs = array();
1816
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
1817
- while ( $filerec != null ) {
1818
- array_push($filerecs, $filerec);
1819
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE linkedto = '.$filerec->idlog);
1820
- }
1821
-
1822
- return $filerecs;
1823
- }
1824
-
1825
- function wfu_get_rec_old_history($idlog) {
1826
- global $wpdb;
1827
- $table_name1 = $wpdb->prefix . "wfu_log";
1828
- $filerecs = array();
1829
- $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
1830
- while ( $filerec != null ) {
1831
- array_push($filerecs, $filerec);
1832
- $filerec = ( $filerec->linkedto > 0 ? $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$filerec->linkedto) : null );
1833
- }
1834
-
1835
- return $filerecs;
1836
- }
1837
-
1838
- /**
1839
- * gets the filedata property from file record in database
1840
- *
1841
- * This function returns the filedata property of the corresponding record of
1842
- * the file in the database holding data about its transfer to a service
1843
- * account like Dropbox, provided that this record is still valid. If the
1844
- * record does not exist or exists but it is absolete, then the function
1845
- * returns null, otherwise it returns an array.
1846
- *
1847
- * The [$service]["filepath"] item of the array is set to the final $filepath
1848
- * of the file, in case that the original filename was renamed.
1849
- *
1850
- * @param int $idlog file id of the file
1851
- * @param bool $is_new it is true if the function is called during addition of
1852
- * a new file
1853
- * @return mixed
1854
- */
1855
- function wfu_get_latest_filedata_from_id($idlog, $is_new = false) {
1856
- //get latest database record of file, if it is still valid
1857
- $filerec = wfu_get_latest_rec_from_id($idlog);
1858
- //return null if the record does not exist or it is obsolete
1859
- if ( $filerec == null ) return null;
1860
-
1861
- return wfu_get_filedata_from_rec($filerec, $is_new, true, false);
1862
- }
1863
-
1864
- function wfu_get_filedata($filepath, $include_general_data = false) {
1865
- $filerec = wfu_get_file_rec($filepath, false);
1866
- if ( $filerec == null ) return null;
1867
-
1868
- return wfu_get_filedata_from_rec($filerec, true, false, $include_general_data);
1869
- }
1870
-
1871
- function wfu_get_filedata_from_rec($filerec, $is_new = false, $update_transfer = false, $include_general_data = false) {
1872
- //return filedata, if it does not exist and we do not want to create a new
1873
- //filedata structure return null, otherwise return an empty array
1874
- if ( !isset($filerec->filedata) || is_null($filerec->filedata) ) $filedata = ( $is_new ? array() : null );
1875
- else {
1876
- $filedata = wfu_decode_array_from_string($filerec->filedata);
1877
- if ( !is_array($filedata) ) $filedata = ( $is_new ? array() : null );
1878
- }
1879
- if ( !is_null($filedata) ) {
1880
- //update filepath property in filedata of "transfer" type, if service
1881
- //records exist
1882
- if ( $update_transfer ) {
1883
- foreach ( $filedata as $key => $data )
1884
- if ( !isset($data["type"]) || $data["type"] == "transfer" )
1885
- $filedata[$key]["filepath"] = $filerec->filepath;
1886
- }
1887
- //add idlog in filedata if $include_general_data is true
1888
- if ( $include_general_data )
1889
- $filedata["general"] = array(
1890
- "type" => "data",
1891
- "idlog" => $filerec->idlog
1892
- );
1893
- }
1894
-
1895
- return $filedata;
1896
- }
1897
-
1898
- function wfu_save_filedata_from_id($idlog, $filedata, $store_in_latest_rec = true) {
1899
- global $wpdb;
1900
- $table_name1 = $wpdb->prefix . "wfu_log";
1901
- if ( $store_in_latest_rec ) {
1902
- $latestrec = wfu_get_latest_rec_from_id($idlog);
1903
- $idlog = $latestrec->idlog;
1904
- }
1905
- return $wpdb->update($table_name1, array( 'filedata' => wfu_encode_array_to_string($filedata) ), array( 'idlog' => $idlog ), array( '%s' ), array( '%d' ));
1906
- }
1907
-
1908
- //get userdata from uploadid
1909
- function wfu_get_userdata_from_uploadid($uploadid) {
1910
- global $wpdb;
1911
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1912
- $userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$uploadid.'\' AND date_to = 0 ORDER BY propkey');
1913
-
1914
- return $userdata;
1915
- }
1916
-
1917
- //reassign file hashes for all valid files in the database
1918
- function wfu_reassign_hashes() {
1919
- global $wpdb;
1920
- $table_name1 = $wpdb->prefix . "wfu_log";
1921
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1922
- if ( $plugin_options['hashfiles'] == '1' ) {
1923
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE filehash = \'\' AND date_to = 0');
1924
- foreach( $filerecs as $filerec ) {
1925
- //calculate full file path
1926
- $filepath = wfu_path_rel2abs($filerec->filepath);
1927
- if ( file_exists($filepath) ) {
1928
- $filehash = md5_file($filepath);
1929
- $wpdb->update($table_name1,
1930
- array( 'filehash' => $filehash ),
1931
- array( 'idlog' => $filerec->idlog ),
1932
- array( '%s' ),
1933
- array( '%d' )
1934
- );
1935
- }
1936
- }
1937
- }
1938
- }
1939
-
1940
- function wfu_make_rec_obsolete($filerec) {
1941
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1942
- global $wpdb;
1943
- $table_name1 = $wpdb->prefix . "wfu_log";
1944
- $filedata = wfu_get_filedata_from_rec($filerec, true);
1945
- //update db record accordingly
1946
- $wpdb->update($table_name1,
1947
- array( 'date_to' => date('Y-m-d H:i:s'), 'filedata' => wfu_encode_array_to_string($filedata) ),
1948
- array( 'idlog' => $filerec->idlog ),
1949
- array( '%s', '%s' ),
1950
- array( '%d' )
1951
- );
1952
- }
1953
-
1954
- //update database to reflect the current status of files
1955
- function wfu_sync_database() {
1956
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1957
- global $wpdb;
1958
- $table_name1 = $wpdb->prefix . "wfu_log";
1959
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1960
-
1961
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND date_to = 0');
1962
- $obsolete_count = 0;
1963
- foreach( $filerecs as $filerec ) {
1964
- $obsolete = true;
1965
- //calculate full file path
1966
- $filepath = wfu_path_rel2abs($filerec->filepath);
1967
- if ( file_exists($filepath) ) {
1968
- if ( $plugin_options['hashfiles'] == '1' ) {
1969
- $filehash = md5_file($filepath);
1970
- if ( $filehash == $filerec->filehash ) $obsolete = false;
1971
- }
1972
- else {
1973
- $filesize = filesize($filepath);
1974
- if ( $filesize == $filerec->filesize ) $obsolete = false;
1975
- }
1976
- }
1977
- if ( $obsolete ) {
1978
- wfu_make_rec_obsolete($filerec);
1979
- $obsolete_count ++;
1980
- }
1981
- }
1982
- return $obsolete_count;
1983
- }
1984
-
1985
- function wfu_get_recs_of_user($userid) {
1986
- global $wpdb;
1987
- $table_name1 = $wpdb->prefix . "wfu_log";
1988
- $table_name2 = $wpdb->prefix . "wfu_userdata";
1989
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1990
-
1991
- //if $userid starts with 'guest' then retrieval of records is done using sessionid and uploaduserid is zero (for guests)
1992
- if ( substr($userid, 0, 5) == 'guest' )
1993
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND uploaduserid = 0 AND sessionid = \''.substr($userid, 5).'\' AND date_to = 0');
1994
- else
1995
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND uploaduserid = '.$userid.' AND date_to = 0');
1996
- $out = array();
1997
- foreach( $filerecs as $filerec ) {
1998
- $obsolete = true;
1999
- //calculate full file path
2000
- $filepath = wfu_path_rel2abs($filerec->filepath);
2001
- if ( file_exists($filepath) ) {
2002
- if ( $plugin_options['hashfiles'] == '1' ) {
2003
- $filehash = md5_file($filepath);
2004
- if ( $filehash == $filerec->filehash ) $obsolete = false;
2005
- }
2006
- else {
2007
- $filesize = filesize($filepath);
2008
- if ( $filesize == $filerec->filesize ) $obsolete = false;
2009
- }
2010
- }
2011
- if ( $obsolete ) {
2012
- wfu_make_rec_obsolete($filerec);
2013
- }
2014
- else {
2015
- $filerec->userdata = null;
2016
- if ( $filerec->uploadid != '' )
2017
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
2018
- array_push($out, $filerec);
2019
- }
2020
- }
2021
-
2022
- return $out;
2023
- }
2024
-
2025
- function wfu_get_filtered_recs($filter) {
2026
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2027
- global $wpdb;
2028
- $table_name1 = $wpdb->prefix . "wfu_log";
2029
- $table_name2 = $wpdb->prefix . "wfu_userdata";
2030
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
2031
-
2032
- $queries = array();
2033
- // add default filters
2034
- array_push($queries, 'action <> \'other\' AND action <> \'datasubmit\'');
2035
- array_push($queries, 'date_to = 0');
2036
- // construct user filter
2037
- if ( isset($filter['user']) ) {
2038
- if ( $filter['user']['all'] ) {
2039
- if ( $filter['user']['guests'] ) $query = 'uploaduserid >= 0';
2040
- else $query = 'uploaduserid > 0';
2041
- }
2042
- elseif ( count($filter['user']['ids']) == 1 && substr($filter['user']['ids'][0], 0, 5) == 'guest' )
2043
- $query = 'uploaduserid = 0 AND sessionid = \''.substr($filter['user']['ids'][0], 5).'\'';
2044
- else {
2045
- if ( $filter['user']['guests'] ) array_push($filter['user']['ids'], '0');
2046
- if ( count($filter['user']['ids']) == 1 ) $query = 'uploaduserid = '.$filter['user']['ids'][0];
2047
- else $query = 'uploaduserid in ('.implode(",",$filter['user']['ids']).')';
2048
- }
2049
- array_push($queries, $query);
2050
- }
2051
- // construct size filter
2052
- if ( isset($filter['size']) ) {
2053
- if ( isset($filter['size']['lower']) && isset($filter['size']['upper']) )
2054
- $query = 'filesize > '.$filter['size']['lower'].' AND filesize < '.$filter['size']['upper'];
2055
- elseif ( isset($filter['size']['lower']) ) $query = 'filesize > '.$filter['size']['lower'];
2056
- else $query = 'filesize < '.$filter['size']['upper'];
2057
- array_push($queries, $query);
2058
- }
2059
- // construct date filter
2060
- if ( isset($filter['date']) ) {
2061
- if ( isset($filter['date']['lower']) && isset($filter['date']['upper']) )
2062
- $query = 'uploadtime > '.$filter['date']['lower'].' AND uploadtime < '.$filter['date']['upper'];
2063
- elseif ( isset($filter['date']['lower']) ) $query = 'uploadtime > '.$filter['date']['lower'];
2064
- else $query = 'uploadtime < '.$filter['date']['upper'];
2065
- array_push($queries, $query);
2066
- }
2067
- // construct file pattern filter
2068
- if ( isset($filter['pattern']) ) {
2069
- $query = 'filepath REGEXP \''.wfu_upload_plugin_wildcard_to_mysqlregexp($filter['pattern']).'\'';
2070
- array_push($queries, $query);
2071
- }
2072
- // construct page/post filter
2073
- if ( isset($filter['post']) ) {
2074
- if ( count($filter['post']['ids']) == 1 ) $query = 'pageid = '.$filter['post']['ids'][0];
2075
- else $query = 'pageid in ('.implode(",",$filter['post']['ids']).')';
2076
- array_push($queries, $query);
2077
- }
2078
- // construct blog filter
2079
- if ( isset($filter['blog']) ) {
2080
- if ( count($filter['blog']['ids']) == 1 ) $query = 'blogid = '.$filter['blog']['ids'][0];
2081
- else $query = 'blogid in ('.implode(",",$filter['blog']['ids']).')';
2082
- array_push($queries, $query);
2083
- }
2084
- // construct userdata filter
2085
- if ( isset($filter['userdata']) ) {
2086
- if ( $filter['userdata']['criterion'] == "equal to" ) $valuecriterion = 'propvalue = \''.esc_sql($filter['userdata']['value']).'\'';
2087
- elseif ( $filter['userdata']['criterion'] == "starts with" ) $valuecriterion = 'propvalue LIKE \''.esc_sql($filter['userdata']['value']).'%\'';
2088
- elseif ( $filter['userdata']['criterion'] == "ends with" ) $valuecriterion = 'propvalue LIKE \'%'.esc_sql($filter['userdata']['value']).'\'';
2089
- elseif ( $filter['userdata']['criterion'] == "contains" ) $valuecriterion = 'propvalue LIKE \'%'.esc_sql($filter['userdata']['value']).'%\'';
2090
- elseif ( $filter['userdata']['criterion'] == "not equal to" ) $valuecriterion = 'propvalue <> \''.esc_sql($filter['userdata']['value']).'\'';
2091
- elseif ( $filter['userdata']['criterion'] == "does not start with" ) $valuecriterion = 'propvalue NOT LIKE \''.esc_sql($filter['userdata']['value']).'%\'';
2092
- elseif ( $filter['userdata']['criterion'] == "does not end with" ) $valuecriterion = 'propvalue NOT LIKE \'%'.esc_sql($filter['userdata']['value']).'\'';
2093
- elseif ( $filter['userdata']['criterion'] == "does not contain" ) $valuecriterion = 'propvalue NOT LIKE \'%'.esc_sql($filter['userdata']['value']).'%\'';
2094
- else $valuecriterion = 'propvalue = \''.esc_sql($filter['userdata']['value']).'\'';
2095
- $query = 'uploadid in (SELECT DISTINCT uploadid FROM '.$table_name2.' WHERE date_to = 0 AND property = \''.esc_sql($filter['userdata']['field']).'\' AND '.$valuecriterion.')';
2096
- array_push($queries, $query);
2097
- }
2098
-
2099
- //allow filters to modify the queries
2100
- $queries = apply_filters("_wfu_filtered_recs_queries", $queries, $filter);
2101
-
2102
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE '.implode(' AND ', $queries));
2103
- $out = array();
2104
- foreach( $filerecs as $filerec ) {
2105
- $obsolete = true;
2106
- //calculate full file path
2107
- $filepath = wfu_path_rel2abs($filerec->filepath);
2108
- if ( file_exists($filepath) ) {
2109
- if ( $plugin_options['hashfiles'] == '1' ) {
2110
- $filehash = md5_file($filepath);
2111
- if ( $filehash == $filerec->filehash ) $obsolete = false;
2112
- }
2113
- else {
2114
- $filesize = filesize($filepath);
2115
- if ( $filesize == $filerec->filesize ) $obsolete = false;
2116
- }
2117
- }
2118
- if ( $obsolete ) {
2119
- wfu_make_rec_obsolete($filerec);
2120
- }
2121
- else {
2122
- $filerec->userdata = null;
2123
- if ( $filerec->uploadid != '' )
2124
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
2125
- array_push($out, $filerec);
2126
- }
2127
- }
2128
-
2129
- return $out;
2130
- }
2131
-
2132
- function wfu_get_uncached_option($option, $default = false) {
2133
- $GLOBALS['wp_object_cache']->delete( 'your_option_name', 'options' );
2134
- return get_option($option, $default);
2135
- }
2136
-
2137
- function wfu_get_option($option, $default) {
2138
- global $wpdb;
2139
- $table_name1 = $wpdb->prefix . "options";
2140
- $val = $wpdb->get_var($wpdb->prepare("SELECT option_value FROM $table_name1 WHERE option_name = %s", $option));
2141
- if ( $val === null && $default !== false ) $val = $default;
2142
- elseif ( $val !== null ) $val = wfu_decode_array_from_string($val);
2143
- return $val;
2144
- }
2145
-
2146
- function wfu_update_option($option, $value) {
2147
- global $wpdb;
2148
- $table_name1 = $wpdb->prefix . "options";
2149
- $value = wfu_encode_array_to_string($value);
2150
- $wpdb->query($wpdb->prepare("INSERT INTO $table_name1 (option_name, option_value) VALUES (%s, %s) ON DUPLICATE KEY UPDATE option_value = VALUES(option_value)", $option, $value));
2151
- }
2152
-
2153
- function wfu_delete_option($option) {
2154
- global $wpdb;
2155
- $table_name1 = $wpdb->prefix . "options";
2156
- $val = $wpdb->get_var($wpdb->prepare("SELECT option_value FROM $table_name1 WHERE option_name = %s", $option));
2157
- $wpdb->query($wpdb->prepare("DELETE FROM $table_name1 WHERE option_name = %s", $option));
2158
- }
2159
-
2160
- function wfu_export_uploaded_files($params) {
2161
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2162
- global $wpdb;
2163
- $table_name1 = $wpdb->prefix . "wfu_log";
2164
- $table_name2 = $wpdb->prefix . "wfu_userdata";
2165
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
2166
- $sep = WFU_VAR("WFU_EXPORT_DATA_SEPARATOR");
2167
- $sep2 = WFU_VAR("WFU_EXPORT_USERDATA_SEPARATOR");
2168
- $includeall = isset($params["username"]);
2169
-
2170
- $contents = "";
2171
- $header = 'Name'.$sep.'Path'.$sep.'Upload User'.$sep.'Upload Time'.$sep.'Size'.$sep.'Page ID'.$sep.'Blog ID'.$sep.'Shortcode ID'.$sep.'Upload ID'.$sep.'User Data';
2172
- $contents = $header;
2173
- if ( $includeall ) {
2174
- $user = get_user_by('login', $params["username"]);
2175
- $userid = $user->ID;
2176
- $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE uploaduserid = '.$userid);
2177
- }
2178
- else $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND date_to = 0');
2179
- foreach( $filerecs as $filerec ) {
2180
- if ( $filerec->action == 'datasubmit' ) $obsolete = false;
2181
- else {
2182
- $obsolete = true;
2183
- //calculate full file path
2184
- $filepath = wfu_path_rel2abs($filerec->filepath);
2185
- if ( file_exists($filepath) ) {
2186
- if ( $plugin_options['hashfiles'] == '1' ) {
2187
- $filehash = md5_file($filepath);
2188
- if ( $filehash == $filerec->filehash ) $obsolete = false;
2189
- }
2190
- else {
2191
- $filesize = filesize($filepath);
2192
- if ( $filesize == $filerec->filesize ) $obsolete = false;
2193
- }
2194
- }
2195
- }
2196
- //export file data if file is not obsolete
2197
- if ( !$obsolete || $includeall ) {
2198
- $username = wfu_get_username_by_id($filerec->uploaduserid);
2199
- $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
2200
- $line = ( $filerec->action == 'datasubmit' ? 'datasubmit' : wfu_basename($filerec->filepath) );
2201
- $line .= $sep.( $filerec->action == 'datasubmit' ? '' : wfu_basedir($filerec->filepath) );
2202
- $line .= $sep.$username;
2203
- $line .= $sep.( $filerec->uploadtime == null ? "" : date("Y-m-d H:i:s", $filerec->uploadtime) );
2204
- $line .= $sep.( $filerec->action == 'datasubmit' ? '0' : $filerec->filesize );
2205
- $line .= $sep.( $filerec->pageid == null ? "" : $filerec->pageid );
2206
- $line .= $sep.( $filerec->blogid == null ? "" : $filerec->blogid );
2207
- $line .= $sep.( $filerec->sid == null ? "" : $filerec->sid );
2208
- $line .= $sep.$filerec->uploadid;
2209
- $line2 = "";
2210
- foreach ( $filerec->userdata as $userdata ) {
2211
- if ( $line2 != "" ) $line2 .= $sep2;
2212
- $line2 .= $userdata->property.":".str_replace(array("\n", "\r", "\r\n"), " ", $userdata->propvalue);
2213
- }
2214
- $line .= $sep.$line2;
2215
- $contents .= "\n".$line;
2216
- }
2217
- }
2218
- //create file
2219
- $path = tempnam(sys_get_temp_dir(), 'wfu');
2220
- file_put_contents($path, $contents);
2221
-
2222
- return $path;
2223
- }
2224
-
2225
- function wfu_get_all_plugin_options() {
2226
- //structure of $options array; every item has the following properties:
2227
- // 0: name of option, an asterisk (*) denotes many occurencies
2228
- // 1: location of option, "db" or "session"
2229
- // 2: delete this option when purging all plugin data
2230
- // 3: store this option when extracting plugin data
2231
- $options = array(
2232
- //stored plugin's Settings
2233
- array( "wordpress_file_upload_options", "db", true, true ),
2234
- //wfu_log table version
2235
- array( "wordpress_file_upload_table_log_version", "db", true, true ),
2236
- //wfu_userdata version
2237
- array( "wordpress_file_upload_table_userdata_version", "db", true, true ),
2238
- //wfu_dbxqueue version
2239
- array( "wordpress_file_upload_table_dbxqueue_version", "db", true, true ),
2240
- //stored hooks
2241
- array( "wordpress_file_upload_hooks", "db", true, true ),
2242
- //transfer manager properties
2243
- array( "wfu_transfermanager_props", "db", true, true ),
2244
- //last file record that was read
2245
- array( "wordpress_file_upload_last_idlog", "db", true, false ),
2246
- //indices of stored shortcode parameters
2247
- array( "wfu_params_index", "db", true, false ),
2248
- //stored shortcode parameters
2249
- array( "wfu_params_*", "db", true, false ),
2250
- //stored advanced environment variables
2251
- array( "wfu_environment_variables", "db", true, true ),
2252
- //stored global tokens
2253
- array( "wfu_gst_*", "db", true, false ),
2254
- //data of unfinished uploaded files
2255
- array( "wordpress_file_upload_unfinished_data", "db", true, false ),
2256
- //list of stored variables in dboption user state
2257
- array( "wfu_userstate_list", "db", true, false ),
2258
- //stored variable value in dboption user state
2259
- array( "wfu_userstate_*", "db", true, false ),
2260
- //last time dboption user state was checked
2261
- array( "wfu_userstate_list_last_check", "db", true, false ),
2262
- //stored personal data policies
2263
- array( "wordpress_file_upload_pd_policies", "db", true, true ),
2264
- //last time admin was notified about DOS attack
2265
- array( "wfu_admin_notification_about_DOS", "db", true, false ),
2266
- //stored token for adding uploader shortcode
2267
- array( "wfu_add_shortcode_ticket_for_wordpress_file_upload", "session", true, false ),
2268
- //stored token for adding file viewer shortcode
2269
- array( "wfu_add_shortcode_ticket_for_wordpress_file_upload_browser", "session", true, false ),
2270
- //session array holding dir and file paths
2271
- array( "wfu_filepath_safe_storage", "session", true, false ),
2272
- //stored rename file flag when renaming file
2273
- array( "wfu_rename_file", "session", true, false ),
2274
- //stored rename file error when renaming file
2275
- array( "wfu_rename_file_error", "session", true, false ),
2276
- //stored create dir flag when creating dir
2277
- array( "wfu_create_dir", "session", true, false ),
2278
- //stored create dir error when creating dir
2279
- array( "wfu_create_dir_error", "session", true, false ),
2280
- //stored file details error when updating file details
2281
- array( "wfu_filedetails_error", "session", true, false ),
2282
- //stored hook data key when updating a hook
2283
- array( "wfu_hook_data_key", "session", true, false ),
2284
- //stored hook data title when updating a hook
2285
- array( "wfu_hook_data_title", "session", true, false ),
2286
- //stored hook data description when updating a hook
2287
- array( "wfu_hook_data_description", "session", true, false ),
2288
- //stored hook data code when updating a hook
2289
- array( "wfu_hook_data_code", "session", true, false ),
2290
- //stored hook data status when updating a hook
2291
- array( "wfu_hook_data_status", "session", true, false ),
2292
- //stored hook data scope when updating a hook
2293
- array( "wfu_hook_data_scope", "session", true, false ),
2294
- //stored hook data error message when updating a hook
2295
- array( "wfu_hook_data_message", "session", true, false ),
2296
- //stored data of file transfers tab
2297
- array( "wfu_transfers_data", "session", true, false ),
2298
- //stored token of upload form
2299
- array( "wfu_token_*", "session", true, false ),
2300
- //stored data of uploaded files
2301
- array( "filedata_*", "session", true, false ),
2302
- //stored status of upload
2303
- array( "wfu_uploadstatus_*", "session", true, false ),
2304
- //flag determining if this is the first pass of an upload
2305
- array( "wfu_upload_first_pass_*", "session", true, false ),
2306
- //stored approved captcha verification code
2307
- array( "wfu_approvedcaptcha_*", "session", true, false ),
2308
- //stored short tokens
2309
- array( "wfu_ust_*", "session", true, false ),
2310
- //stored shortcode data
2311
- array( "wfu_shortcode_data_safe_storage", "session", true, false ),
2312
- //stored number of deleted thumbnails
2313
- array( "wfu_deleted_thumbnails_counter", "session", true, false ),
2314
- //stored number of added thumbnails
2315
- array( "wfu_added_thumbnails_counter", "session", true, false ),
2316
- //stored consent data
2317
- array( "WFU_Consent_Data", "session", true, false ),
2318
- //stored browser actions
2319
- array( "wfu_browser_actions_safe_storage", "session", true, false ),
2320
- //stored data of chunked uploads
2321
- array( "chunkdata_*", "session", true, false ),
2322
- //stored flag of uploader form refresh status
2323
- array( "wfu_check_refresh_*", "session", true, false ),
2324
- //stored upload start time
2325
- array( "wfu_start_time_*", "session", true, false ),
2326
- //stored upload start time
2327
- array( "wfu_start_time_*", "session", true, false )
2328
- );
2329
-
2330
-
2331
- return $options;
2332
- }
2333
-
2334
- //********************* Widget Functions ****************************************************************************************
2335
-
2336
- function wfu_get_widget_obj_from_id($widgetid) {
2337
- global $wp_registered_widgets;
2338
-
2339
- if ( !isset($wp_registered_widgets[$widgetid]) ) return false;
2340
- if ( !isset($wp_registered_widgets[$widgetid]['callback']) ) return false;
2341
- if ( !isset($wp_registered_widgets[$widgetid]['callback'][0]) ) return false;
2342
- $obj = $wp_registered_widgets[$widgetid]['callback'][0];
2343
- if ( !($obj instanceof WP_Widget) ) return false;
2344
-
2345
- return $obj;
2346
- }
2347
-
2348
- //********************* Shortcode Options Functions ****************************************************************************************
2349
-
2350
- function wfu_shortcode_attribute_definitions_adjusted($shortcode_atts) {
2351
- //get attribute definitions
2352
- $defs = wfu_attribute_definitions();
2353
- $defs_indexed = array();
2354
- $defs_indexed_flat = array();
2355
- foreach ( $defs as $def ) {
2356
- $defs_indexed[$def["attribute"]] = $def;
2357
- $defs_indexed_flat[$def["attribute"]] = $def["value"];
2358
- }
2359
- //get placement attribute from shortcode
2360
- $placements = "";
2361
- if ( isset($shortcode_atts["placements"]) ) $placements = $shortcode_atts["placements"];
2362
- else $placements = $defs_indexed_flat["placements"];
2363
- //get component definitions
2364
- $components = wfu_component_definitions();
2365
- //analyse components that can appear more than once in placements
2366
- foreach ( $components as $component ) {
2367
- if ( $component["multiplacements"] ) {
2368
- $componentid = $component["id"];
2369
- //count component occurrences in placements
2370
- $component_occurrences = substr_count($placements, $componentid);
2371
- if ( $component_occurrences > 1 && isset($defs_indexed[$componentid]) ) {
2372
- //add incremented attribute definitions in $defs_indexed_flat array if occurrences are more than one
2373
- for ( $i = 2; $i <= $component_occurrences; $i++ ) {
2374
- foreach ( $defs_indexed[$componentid]["dependencies"] as $attribute )
2375
- $defs_indexed_flat[$attribute.$i] = $defs_indexed_flat[$attribute];
2376
- }
2377
- }
2378
- }
2379
- }
2380
-
2381
- return $defs_indexed_flat;
2382
- }
2383
-
2384
- function wfu_generate_current_params_index($shortcode_id, $user_login) {
2385
- global $post;
2386
- $cur_index_str = '||'.$post->ID.'||'.$shortcode_id.'||'.$user_login;
2387
- $cur_index_str_search = '\|\|'.$post->ID.'\|\|'.$shortcode_id.'\|\|'.$user_login;
2388
- $index_str = get_option('wfu_params_index');
2389
- $index = explode("&&", $index_str);
2390
- foreach ($index as $key => $value) if ($value == "") unset($index[$key]);
2391
- $index_match = preg_grep("/".$cur_index_str_search."$/", $index);
2392
- if ( count($index_match) == 1 )
2393
- foreach ( $index_match as $key => $value )
2394
- if ( $value == "" ) unset($index_match[$key]);
2395
- if ( count($index_match) <= 0 ) {
2396
- $cur_index_rand = wfu_create_random_string(16);
2397
- array_push($index, $cur_index_rand.$cur_index_str);
2398
- }
2399
- else {
2400
- reset($index_match);
2401
- $cur_index_rand = substr(current($index_match), 0, 16);
2402
- if ( count($index_match) > 1 ) {
2403
- $index_match_keys = array_keys($index_match);
2404
- for ($i = 1; $i < count($index_match); $i++) {
2405
- $ii = $index_match_keys[$i];
2406
- unset($index[array_search($index_match[$ii], $index, true)]);
2407
- }
2408
- }
2409
- }
2410
- if ( count($index_match) != 1 ) {
2411
- $index_str = implode("&&", $index);
2412
- update_option('wfu_params_index', $index_str);
2413
- }
2414
- return $cur_index_rand;
2415
- }
2416
-
2417
- function wfu_get_params_fields_from_index($params_index, $session_token = "") {
2418
- $fields = array();
2419
- $index_str = get_option('wfu_params_index');
2420
- $index = explode("&&", $index_str);
2421
- $index_match = preg_grep("/^".$params_index."/", $index);
2422
- if ( count($index_match) >= 1 )
2423
- foreach ( $index_match as $key => $value )
2424
- if ( $value == "" ) unset($index_match[$key]);
2425
- if ( count($index_match) > 0 ) {
2426
- if ( $session_token == "" ) {
2427
- reset($index_match);
2428
- list($fields['unique_id'], $fields['page_id'], $fields['shortcode_id'], $fields['user_login']) = explode("||", current($index_match));
2429
- }
2430
- //some times $params_index corresponds to 2 or more sets of params, so
2431
- //we need to check session token in order to find the correct one
2432
- else {
2433
- $found = false;
2434
- foreach ( $index_match as $value ) {
2435
- list($fields['unique_id'], $fields['page_id'], $fields['shortcode_id'], $fields['user_login']) = explode("||", $value);
2436
- $sid = $fields['shortcode_id'];
2437
- if ( WFU_USVAR_exists("wfu_token_".$sid) && WFU_USVAR("wfu_token_".$sid) == $session_token ) {
2438
- $found = true;
2439
- break;
2440
- }
2441
- }
2442
- if ( !$found ) $fields = array();
2443
- }
2444
- }
2445
- return $fields;
2446
- }
2447
-
2448
- function wfu_safe_store_shortcode_data($data) {
2449
- $code = wfu_create_random_string(16);
2450
- $safe_storage = ( WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ? WFU_USVAR('wfu_shortcode_data_safe_storage') : array() );
2451
- $safe_storage[$code] = $data;
2452
- WFU_USVAR_store('wfu_shortcode_data_safe_storage', $safe_storage);
2453
- return $code;
2454
- }
2455
-
2456
- function wfu_get_shortcode_data_from_safe($code) {
2457
- //sanitize $code
2458
- $code = wfu_sanitize_code($code);
2459
- if ( $code == "" ) return '';
2460
- //return shortcode data from session variable, if exists
2461
- if ( !WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ) return '';
2462
- $safe_storage = WFU_USVAR('wfu_shortcode_data_safe_storage');
2463
- if ( !isset($safe_storage[$code]) ) return '';
2464
- return $safe_storage[$code];
2465
- }
2466
-
2467
- function wfu_clear_shortcode_data_from_safe($code) {
2468
- //sanitize $code
2469
- $code = wfu_sanitize_code($code);
2470
- if ( $code == "" ) return;
2471
- //clear shortcode data from session variable, if exists
2472
- if ( !WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ) return;
2473
- $safe_storage = WFU_USVAR('wfu_shortcode_data_safe_storage');
2474
- if ( !isset($safe_storage[$code]) ) return;
2475
- unset($safe_storage[$code]);
2476
- WFU_USVAR_store('wfu_shortcode_data_safe_storage', $safe_storage);
2477
- }
2478
-
2479
- function wfu_decode_dimensions($dimensions_str) {
2480
- $components = wfu_component_definitions();
2481
- $dimensions = array();
2482
-
2483
- foreach ( $components as $comp ) {
2484
- if ( $comp['dimensions'] == null ) $dimensions[$comp['id']] = "";
2485
- else foreach ( $comp['dimensions'] as $dimraw ) {
2486
- list($dim_id, $dim_name) = explode("/", $dimraw);
2487
- $dimensions[$dim_id] = "";
2488
- }
2489
- }
2490
- $dimensions_raw = explode(",", $dimensions_str);
2491
- foreach ( $dimensions_raw as $dimension_str ) {
2492
- $dimension_raw = explode(":", $dimension_str);
2493
- $item = strtolower(trim($dimension_raw[0]));
2494
- foreach ( array_keys($dimensions) as $key ) {
2495
- if ( $item == $key ) $dimensions[$key] = trim($dimension_raw[1]);
2496
- }
2497
- }
2498
- return $dimensions;
2499
- }
2500
-
2501
- function wfu_placements_remove_item($placements, $item) {
2502
- $itemplaces = explode("/", $placements);
2503
- $newplacements = array();
2504
- foreach ( $itemplaces as $section ) {
2505
- $items_in_section = explode("+", trim($section));
2506
- $newsection = array();
2507
- foreach ( $items_in_section as $item_in_section ) {
2508
- $item_in_section = strtolower(trim($item_in_section));
2509
- if ( $item_in_section != "" && $item_in_section != $item ) array_push($newsection, $item_in_section);
2510
- }
2511
- if ( count($newsection) > 0 ) array_push($newplacements, implode("+", $newsection));
2512
- }
2513
- if ( count($newplacements) > 0 ) return implode("/", $newplacements);
2514
- else return "";
2515
- }
2516
-
2517
- //********************* Plugin Design Functions ********************************************************************************************
2518
-
2519
- function wfu_get_uploader_template($templatename = "") {
2520
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2521
- if ($templatename != "") {
2522
- $classname = "WFU_UploaderTemplate_$templatename";
2523
- if ( class_exists($classname) )
2524
- return call_user_func(array($classname, 'get_instance'));
2525
- $filepath = ABSWPFILEUPLOAD_DIR."templates/uploader-$templatename.php";
2526
- if ( file_exists($filepath) ) {
2527
- include_once $filepath;
2528
- $classname = "WFU_UploaderTemplate_$templatename";
2529
- if ( class_exists($classname) )
2530
- return call_user_func(array($classname, 'get_instance'));
2531
- }
2532
- }
2533
- return WFU_Original_Template::get_instance();
2534
- }
2535
-
2536
- function wfu_get_browser_template($templatename = "") {
2537
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2538
- if ($templatename != "") {
2539
- $classname = "WFU_BrowserTemplate_$templatename";
2540
- if ( class_exists($classname) )
2541
- return call_user_func(array($classname, 'get_instance'));
2542
- $filepath = ABSWPFILEUPLOAD_DIR."templates/browser-$templatename.php";
2543
- if ( file_exists($filepath) ) {
2544
- include_once $filepath;
2545
- $classname = "WFU_BrowserTemplate_$templatename";
2546
- if ( class_exists($classname) )
2547
- return call_user_func(array($classname, 'get_instance'));
2548
- }
2549
- }
2550
- return WFU_Original_Template::get_instance();
2551
- }
2552
-
2553
- function wfu_add_div() {
2554
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2555
- $items_count = func_num_args();
2556
- if ( $items_count == 0 ) return "";
2557
- $items_raw = func_get_args();
2558
- $params = $items_raw[0];
2559
- unset($items_raw[0]);
2560
- $items = array( );
2561
- foreach ( $items_raw as $item_raw ) {
2562
- if ( is_array($item_raw) ) array_push($items, $item_raw);
2563
- }
2564
- $items_count = count($items);
2565
- if ( $items_count == 0 ) return "";
2566
-
2567
- $template = wfu_get_uploader_template($params["uploadertemplate"]);
2568
- $data["ID"] = $params["uploadid"];
2569
- $data["responsive"] = ( $params["fitmode"] == "responsive" );
2570
- $data["items"] = $items;
2571
- $data["params"] = $params;
2572
-
2573
- ob_start();
2574
- $template->wfu_row_container_template($data);
2575
- $str_output = ob_get_clean();
2576
- return $str_output;
2577
- }
2578
-
2579
- function wfu_read_template_output($blockname, $data) {
2580
- $output = array();
2581
- if ( isset($data["params"]["uploadertemplate"]) ) $template = wfu_get_uploader_template($data["params"]["uploadertemplate"]);
2582
- else $template = wfu_get_browser_template($data["params"]["browsertemplate"]);
2583
- $func = "wfu_".$blockname."_template";
2584
- $sid = $data["ID"];
2585
- ob_start();
2586
- call_user_func(array($template, $func), $data);
2587
- $str_output = ob_get_clean();
2588
-
2589
- $str_output = str_replace('$ID', $sid, $str_output);
2590
- //extract css, javascript and HTML from output
2591
- $match = array();
2592
- preg_match("/<style>(.*)<\/style><script.*?>(.*)<\/script>(.*)/s", $str_output, $match);
2593
- if ( count($match) == 4 ) {
2594
- $output["css"] = trim($match[1]);
2595
- $output["js"] = trim($match[2]);
2596
- $html = trim($match[3]);
2597
- $i = 1;
2598
- foreach( preg_split("/((\r?\n)|(\r\n?))/", $html) as $line )
2599
- $output["line".$i++] = $line;
2600
- }
2601
-
2602
- return $output;
2603
- }
2604
-
2605
- function wfu_template_to_HTML($blockname, $params, $additional_params, $occurrence_index) {
2606
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
2607
- $block = call_user_func("wfu_prepare_".$blockname."_block", $params, $additional_params, $occurrence_index);
2608
- if ( isset($params["uploadid"]) ) {
2609
- $ID = $params["uploadid"];
2610
- $WF = "WFU";
2611
- }
2612
- else {
2613
- $ID = $params["browserid"];
2614
- $WF = "WFUB";
2615
- }
2616
- $css = $block["css"];
2617
- if ( $block["js"] != "" ) {
2618
- $js = 'var '.$WF.'_JS_'.$ID.'_'.$blockname.' = function() {';
2619
- $js .= "\n".$block["js"];
2620
- $js .= "\n".'}';
2621
- $js .= "\n".'wfu_run_js("window", "'.$WF.'_JS_'.$ID.'_'.$blockname.'");';
2622
- }
2623
- //relax css rules if this option is enabled
2624
- if ( $plugin_options['relaxcss'] == '1' ) $css = preg_replace('#.*?/\*relax\*/\s*#', '', $css);
2625
- $echo_str = wfu_css_to_HTML($css);
2626
- $echo_str .= "\n".wfu_js_to_HTML($js);
2627
- $k = 1;
2628
- while ( isset($block["line".$k]) ) {
2629
- if ( $block["line".$k] != "" ) $echo_str .= "\n".$block["line".$k];
2630
- $k++;
2631
- }
2632
-
2633
- return $echo_str;
2634
- }
2635
-
2636
- function wfu_extract_css_js_from_components($section_array, &$css, &$js) {
2637
- for ( $i = 1; $i < count($section_array); $i++ ) {
2638
- if ( isset($section_array[$i]["css"]) ) $css .= ( $css == "" ? "" : "\n" ).$section_array[$i]["css"];
2639
- if ( isset($section_array[$i]["js"]) ) $js .= ( $js == "" ? "" : "\n" ).$section_array[$i]["js"];
2640
- }
2641
- return;
2642
- }
2643
-
2644
- function wfu_add_loading_overlay($dlp, $code) {
2645
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2646
- $echo_str = $dlp.'<div id="wfu_'.$code.'_overlay" style="margin:0; padding: 0; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background:none; display:none;">';
2647
- $echo_str .= $dlp."\t".'<div style="margin:0; padding: 0; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background-color:rgba(255,255,255,0.8); z-index:1;""></div>';
2648
- $echo_str .= $dlp."\t".'<table style="margin:0; padding: 0; table-layout:fixed; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background:none; z-index:2;"><tbody><tr><td align="center" style="border:none;">';
2649
- $echo_str .= $dlp."\t\t".'<img src="'.WFU_IMAGE_OVERLAY_LOADING.'" /><br /><span>loading...</span>';
2650
- $echo_str .= $dlp."\t".'</td></tr></tbody></table>';
2651
- $echo_str .= $dlp.'</div>';
2652
-
2653
- return $echo_str;
2654
- }
2655
-
2656
- function wfu_add_pagination_header($dlp, $code, $curpage, $pages, $nonce = false) {
2657
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2658
- if ($nonce === false) $nonce = wp_create_nonce( 'wfu-'.$code.'-page' );
2659
- $echo_str = $dlp.'<div style="float:right;">';
2660
- $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_first_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == 1 ? 'inline' : 'none' ).';">&#60;&#60;</label>';
2661
- $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_prev_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == 1 ? 'inline' : 'none' ).';">&#60;</label>';
2662
- $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_first" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'first\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == 1 ? 'none' : 'inline' ).';">&#60;&#60;</a>';
2663
- $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_prev" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'prev\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == 1 ? 'none' : 'inline' ).';">&#60;</a>';
2664
- $echo_str .= $dlp."\t".'<label style="margin:0 0 0 4px; cursor:default;">'.WFU_PAGINATION_PAGE.'</label>';
2665
- $echo_str .= $dlp."\t".'<select id="wfu_'.$code.'_pages" style="margin:0 4px;" onchange="wfu_goto_'.$code.'_page(\''.$nonce.'\', \'sel\');">';
2666
- for ( $i = 1; $i <= $pages; $i++ )
2667
- $echo_str .= $dlp."\t\t".'<option value="'.$i.'"'.( $i == $curpage ? ' selected="selected"' : '' ).'>'.$i.'</option>';
2668
- $echo_str .= $dlp."\t".'</select>';
2669
- $echo_str .= $dlp."\t".'<label style="margin:0 4px 0 0; cursor:default;">'.WFU_PAGINATION_OF.$pages.'</label>';
2670
- $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_next_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == $pages ? 'inline' : 'none' ).';">&#62;</label>';
2671
- $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_last_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == $pages ? 'inline' : 'none' ).';">&#62;&#62;</label>';
2672
- $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_next" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'next\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == $pages ? 'none' : 'inline' ).';">&#62;</a>';
2673
- $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_last" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'last\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == $pages ? 'none' : 'inline' ).';">&#62;&#62;</a>';
2674
- $echo_str .= $dlp.'</div>';
2675
-
2676
- return $echo_str;
2677
- }
2678
-
2679
- function wfu_add_bulkactions_header($dlp, $code, $actions) {
2680
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2681
- $echo_str = $dlp.'<div style="float:left;">';
2682
- $echo_str .= $dlp."\t".'<select id="wfu_'.$code.'_bulkactions">';
2683
- $echo_str .= $dlp."\t\t".'<option value="" selected="selected">'.( substr($code, 0, 8) == "browser_" ? WFU_BROWSER_BULKACTION_TITLE : "Bulk Actions").'</option>';
2684
- foreach ( $actions as $action )
2685
- $echo_str .= $dlp."\t\t".'<option value="'.$action["name"].'">'.$action["title"].'</option>';
2686
- $echo_str .= $dlp."\t".'</select>';
2687
- $echo_str .= $dlp."\t".'<input type="button" class="button action" value="'.( substr($code, 0, 8) == "browser_" ? WFU_BROWSER_BULKACTION_LABEL : "Apply").'" onclick="wfu_apply_'.$code.'_bulkaction();" />';
2688
- $echo_str .= $dlp."\t".'<img src="'.WFU_IMAGE_OVERLAY_LOADING.'" style="display:none;" />';
2689
- $echo_str .= $dlp.'</div>';
2690
-
2691
- return $echo_str;
2692
- }
2693
-
2694
- function wfu_prepare_message_colors($template) {
2695
- $color_array = explode(",", $template);
2696
- $colors['color'] = $color_array[0];
2697
- $colors['bgcolor'] = $color_array[1];
2698
- $colors['borcolor'] = $color_array[2];
2699
- return $colors;
2700
- }
2701
-
2702
- //********************* Email Functions ****************************************************************************************************
2703
-
2704
- function wfu_send_notification_email($user, $uploaded_file_paths, $userdata_fields, $params) {
2705
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2706
- global $blog_id;
2707
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
2708
-
2709
- //get consent status
2710
- $consent_revoked = ( $plugin_options["personaldata"] == "1" && $params["consent_result"] == "0" );
2711
- $not_store_files = ( $params["personaldatatypes"] == "userdata and files" );
2712
- //create necessary variables
2713
- $only_filename_list = "";
2714
- $target_path_list = "";
2715
- foreach ( $uploaded_file_paths as $filepath ) {
2716
- $only_filename_list .= ( $only_filename_list == "" ? "" : ", " ).wfu_basename($filepath);
2717
- $target_path_list .= ( $target_path_list == "" ? "" : ", " ).$filepath;
2718
- }
2719
-
2720
- //apply wfu_before_email_notification filter
2721
- $changable_data['recipients'] = $params["notifyrecipients"];
2722
- $changable_data['subject'] = $params["notifysubject"];
2723
- $changable_data['message'] = $params["notifymessage"];
2724
- $changable_data['headers'] = $params["notifyheaders"];
2725
- $changable_data['user_data'] = $userdata_fields;
2726
- $changable_data['filename'] = $only_filename_list;
2727
- $changable_data['filepath'] = $target_path_list;
2728
- $changable_data['error_message'] = '';
2729
- $additional_data['shortcode_id'] = $params["uploadid"];
2730
- $ret_data = apply_filters('wfu_before_email_notification', $changable_data, $additional_data);
2731
-
2732
- if ( $ret_data['error_message'] == '' ) {
2733
- $notifyrecipients = $ret_data['recipients'];
2734
- $notifysubject = $ret_data['subject'];
2735
- $notifymessage = $ret_data['message'];
2736
- $notifyheaders = $ret_data['headers'];
2737
- $userdata_fields = $ret_data['user_data'];
2738
- $only_filename_list = $ret_data['filename'];
2739
- $target_path_list = $ret_data['filepath'];
2740
-
2741
- if ( 0 == $user->ID ) {
2742
- $user_login = "guest";
2743
- $user_email = "";
2744
- }
2745
- else {
2746
- $user_login = $user->user_login;
2747
- $user_email = $user->user_email;
2748
- }
2749
- $search = array ('/%useremail%/', '/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
2750
- $replace = array ($user_email, "\n", "\"", "[", "]");
2751
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
2752
- $ind = 1 + $userdata_key;
2753
- array_push($search, '/%userdata'.$ind.'%/');
2754
- array_push($replace, $userdata_field["value"]);
2755
- }
2756
- // $notifyrecipients = trim(preg_replace('/%useremail%/', $user_email, $params["notifyrecipients"]));
2757
- $notifyrecipients = preg_replace($search, $replace, $notifyrecipients);
2758
- $search = array ('/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
2759
- $replace = array ("\n", "\"", "[", "]");
2760
- $notifyheaders = preg_replace($search, $replace, $notifyheaders);
2761
- $search = array ('/%username%/', '/%useremail%/', '/%filename%/', '/%filepath%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/', '/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
2762
- $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename_list, $target_path_list, $blog_id, $params["pageid"], get_the_title($params["pageid"]), "\n", "\"", "[", "]");
2763
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
2764
- $ind = 1 + $userdata_key;
2765
- array_push($search, '/%userdata'.$ind.'%/');
2766
- array_push($replace, $userdata_field["value"]);
2767
- }
2768
- $notifysubject = preg_replace($search, $replace, $notifysubject);
2769
- $notifymessage = preg_replace($search, $replace, $notifymessage);
2770
-
2771
- if ( $params["attachfile"] == "true" ) {
2772
- $notify_sent = wp_mail($notifyrecipients, $notifysubject, $notifymessage, $notifyheaders, $uploaded_file_paths);
2773
- }
2774
- else {
2775
- $notify_sent = wp_mail($notifyrecipients, $notifysubject, $notifymessage, $notifyheaders);
2776
- }
2777
- //delete files if it is required by consent policy
2778
- if ( $consent_revoked && $not_store_files ) {
2779
- foreach ( $uploaded_file_paths as $file ) unlink($file);
2780
- }
2781
- return ( $notify_sent ? "" : WFU_WARNING_NOTIFY_NOTSENT_UNKNOWNERROR );
2782
- }
2783
- else return $ret_data['error_message'];
2784
- }
2785
-
2786
- function wfu_notify_admin($subject, $message) {
2787
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2788
- $admin_email = get_option("admin_email");
2789
- if ( $admin_email === false ) return;
2790
- wp_mail($admin_email, $subject, $message);
2791
- }
2792
-
2793
- //********************* Media Functions ****************************************************************************************************
2794
-
2795
- // function wfu_process_media_insert contribution from Aaron Olin with some corrections regarding the upload path
2796
- function wfu_process_media_insert($file_path, $userdata_fields, $page_id){
2797
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2798
- $wp_upload_dir = wp_upload_dir();
2799
- $filetype = wp_check_filetype( wfu_basename( $file_path ), null );
2800
-
2801
- $attachment = array(
2802
- 'guid' => $wp_upload_dir['url'] . '/' . wfu_basename( $file_path ),
2803
- 'post_mime_type' => $filetype['type'],
2804
- 'post_title' => preg_replace( '/\.[^.]+$/', '', wfu_basename( $file_path ) ),
2805
- 'post_content' => '',
2806
- 'post_status' => 'inherit'
2807
- );
2808
-
2809
- $attach_id = wp_insert_attachment( $attachment, $file_path, $page_id );
2810
-
2811
- // If file is an image, process the default thumbnails for previews
2812
- require_once(ABSPATH . 'wp-admin/includes/image.php');
2813
- $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
2814
- // Add userdata as attachment metadata
2815
- foreach ( $userdata_fields as $userdata_field )
2816
- $attach_data["WFU User Data"][$userdata_field["label"]] = $userdata_field["value"];
2817
- $update_attach = wp_update_attachment_metadata( $attach_id, $attach_data );
2818
- // link attachment with file in plugin's database
2819
- $filedata = wfu_get_filedata($file_path, true);
2820
- if ( $filedata != null ) {
2821
- $filedata["media"] = array(
2822
- "type" => "data",
2823
- "attach_id" => $attach_id
2824
- );
2825
- wfu_save_filedata_from_id($filedata["general"]["idlog"], $filedata);
2826
- }
2827
-
2828
- return $attach_id;
2829
- }
2830
-
2831
- //********************* Form Fields Functions ****************************************************************************************************
2832
-
2833
- function wfu_preg_replace_callback_func($matches) {
2834
- return str_replace("[/]", "/", $matches[0]);
2835
- }
2836
-
2837
- // function wfu_parse_userdata_attribute parses the shortcode attribute to a form field array
2838
- function wfu_parse_userdata_attribute($value){
2839
- $fields = array();
2840
- //read defaults
2841
- $definitions_unindexed = wfu_formfield_definitions();
2842
- $defaults = array();
2843
- foreach ( $definitions_unindexed as $def ) {
2844
- $default = array();
2845
- $default["type"] = $def["type"];
2846
- $default["label"] = $def["label"];
2847
- $default["labelposition"] = "".substr($def["labelposition"], 5);
2848
- $default["required"] = ( substr($def["required"], 5) == "true" );
2849
- $default["donotautocomplete"] = ( substr($def["donotautocomplete"], 5) == "true" );
2850
- $default["validate"] = ( substr($def["validate"], 5) == "true" );
2851
- $default["typehook"] = ( substr($def["typehook"], 5) == "true" );
2852
- $default["hintposition"] = "".substr($def["hintposition"], 5);
2853
- $default["default"] = "".substr($def["default"], 5);
2854
- $default["data"] = "".substr($def["data"], 5);
2855
- $default["group"] = "".substr($def["group"], 5);
2856
- $default["format"] = "".substr($def["format"], 5);
2857
- $defaults[$def["type"]] = $default;
2858
- }
2859
- // $fields_arr = explode("/", $value);
2860
- $value = str_replace("/", "[/]", $value);
2861
- $value = preg_replace_callback("/\(.*\)/", "wfu_preg_replace_callback_func", $value);
2862
- $fields_arr = explode("[/]", $value);
2863
- //parse shortcode attribute to $fields
2864
- foreach ( $fields_arr as $field_raw ) {
2865
- $field_raw = trim($field_raw);
2866
- $fieldprops = $defaults["text"];
2867
- //read old default attribute
2868
- if ( substr($field_raw, 0, 1) == "*" ) {
2869
- $fieldprops["required"] = true;
2870
- $field_raw = substr($field_raw, 1);
2871
- }
2872
- $field_parts = explode("|", $field_raw);
2873
- //proceed if the first part, which is the label, is non-empty
2874
- if ( trim($field_parts[0]) != "" ) {
2875
- //get type, if exists, in order to adjust defaults
2876
- $type_key = -1;
2877
- $new_type = "";
2878
- foreach ( $field_parts as $key => $part ) {
2879
- $part = ltrim($part);
2880
- $flag = substr($part, 0, 2);
2881
- $val = substr($part, 2);
2882
- if ( $flag == "t:" && $key > 0 && array_key_exists($val, $defaults) ) {
2883
- $new_type = $val;
2884
- $type_key = $key;
2885
- break;
2886
- }
2887
- }
2888
- if ( $new_type != "" ) {
2889
- $fieldprops = $defaults[$new_type];
2890
- unset($field_parts[$type_key]);
2891
- }
2892
- //store label
2893
- $fieldprops["label"] = trim($field_parts[0]);
2894
- unset($field_parts[0]);
2895
- //get other properties
2896
- foreach ( $field_parts as $part ) {
2897
- $part = ltrim($part);
2898
- $flag = substr($part, 0, 2);
2899
- $val = "".substr($part, 2);
2900
- if ( $flag == "s:" ) $fieldprops["labelposition"] = $val;
2901
- elseif ( $flag == "r:" ) $fieldprops["required"] = ( $val == "1" );
2902
- elseif ( $flag == "a:" ) $fieldprops["donotautocomplete"] = ( $val == "1" );
2903
- elseif ( $flag == "v:" ) $fieldprops["validate"] = ( $val == "1" );
2904
- elseif ( $flag == "d:" ) $fieldprops["default"] = $val;
2905
- elseif ( $flag == "l:" ) $fieldprops["data"] = $val;
2906
- elseif ( $flag == "g:" ) $fieldprops["group"] = $val;
2907
- elseif ( $flag == "f:" ) $fieldprops["format"] = $val;
2908
- elseif ( $flag == "p:" ) $fieldprops["hintposition"] = $val;
2909
- elseif ( $flag == "h:" ) $fieldprops["typehook"] = ( $val == "1" );
2910
- }
2911
- array_push($fields, $fieldprops);
2912
- }
2913
- }
2914
-
2915
- return $fields;
2916
- }
2917
-
2918
- function wfu_check_remove_honeypot_fields(&$userdata_fields, $post_key) {
2919
- //check if honeypot userdata fields have been added to the form and if they
2920
- //contain any data
2921
- $honeypot_filled = false;
2922
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
2923
- if ( $userdata_field["type"] == "honeypot" ) {
2924
- $val = ( isset($_POST[$post_key.$userdata_key]) ? $_POST[$post_key.$userdata_key] : "" );
2925
- //if a non-zero value has been passed to the server, this means
2926
- //that it has been filled by a bot
2927
- if ( $val != "" ) {
2928
- $honeypot_filled = true;
2929
- break;
2930
- }
2931
- //if the honeypot field is empty then remove it from
2932
- //userdata_fields array because we do not want to be stored
2933
- else unset($userdata_fields[$userdata_key]);
2934
- }
2935
- }
2936
-
2937
- //if any honeypot field has been filled then return true to denote that
2938
- //the upload must be aborted
2939
- return $honeypot_filled;
2940
- }
2941
-
2942
- //********************* User State Functions ****************************************************************************************************
2943
-
2944
- function WFU_USVAR_exists($var) {
2945
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2946
- global $wfu_user_state_handler;
2947
- if ( $wfu_user_state_handler == "dboption" ) return WFU_USVAR_exists_dboption($var);
2948
- else return WFU_USVAR_exists_session($var);
2949
- }
2950
-
2951
- function WFU_USVAR($var) {
2952
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2953
- global $wfu_user_state_handler;
2954
- if ( $wfu_user_state_handler == "dboption" ) return WFU_USVAR_dboption($var);
2955
- else return WFU_USVAR_session($var);
2956
- }
2957
-
2958
- function WFU_USALL() {
2959
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2960
- global $wfu_user_state_handler;
2961
- if ( $wfu_user_state_handler == "dboption" ) return WFU_USALL_dboption();
2962
- else return WFU_USALL_session();
2963
- }
2964
-
2965
- function WFU_USVAR_store($var, $value) {
2966
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2967
- global $wfu_user_state_handler;
2968
- if ( $wfu_user_state_handler == "dboption" ) WFU_USVAR_store_dboption($var, $value);
2969
- else WFU_USVAR_store_session($var, $value);
2970
- }
2971
-
2972
- function WFU_USVAR_unset($var) {
2973
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2974
- global $wfu_user_state_handler;
2975
- if ( $wfu_user_state_handler == "dboption" ) WFU_USVAR_unset_dboption($var);
2976
- else WFU_USVAR_unset_session($var);
2977
- }
2978
-
2979
- function WFU_USVAR_exists_session($var) {
2980
- return isset($_SESSION[$var]);
2981
- }
2982
-
2983
- function WFU_USVAR_session($var) {
2984
- return $_SESSION[$var];
2985
- }
2986
-
2987
- function WFU_USALL_session() {
2988
- return $_SESSION;
2989
- }
2990
-
2991
- function WFU_USVAR_store_session($var, $value) {
2992
- $_SESSION[$var] = $value;
2993
- }
2994
-
2995
- function WFU_USVAR_unset_session($var) {
2996
- unset($_SESSION[$var]);
2997
- }
2998
-
2999
- function wfu_get_safe_session_id() {
3000
- return preg_replace("/[^a-z0-9_]/", "", strtolower(session_id()));
3001
- }
3002
-
3003
- function wfu_get_US_dboption_data($id, $default = false) {
3004
- if ( $id == "" ) return false;
3005
- return wfu_get_option("wfu_userstate_".$id, $default);
3006
- }
3007
-
3008
- function wfu_update_US_dboption_time($id) {
3009
- $list = wfu_get_option("wfu_userstate_list", array());
3010
- $list[$id] = time();
3011
- wfu_update_option("wfu_userstate_list", $list);
3012
- }
3013
-
3014
- function WFU_USVAR_exists_dboption($var) {
3015
- $id = wfu_get_safe_session_id();
3016
- $data = wfu_get_US_dboption_data($id);
3017
- if ( $data === false ) return false;
3018
- wfu_update_US_dboption_time($id);
3019
- return isset($data[$var]);
3020
- }
3021
-
3022
- function WFU_USVAR_dboption($var) {
3023
- $id = wfu_get_safe_session_id();
3024
- $data = wfu_get_US_dboption_data($id);
3025
- if ( $data === false ) return "";
3026
- wfu_update_US_dboption_time($id);
3027
- return $data[$var];
3028
- }
3029
-
3030
- function WFU_USALL_dboption() {
3031
- $id = wfu_get_safe_session_id();
3032
- $data = wfu_get_US_dboption_data($id);
3033
- if ( $data === false ) return array();
3034
- wfu_update_US_dboption_time($id);
3035
- return $data;
3036
- }
3037
-
3038
- function WFU_USVAR_store_dboption($var, $value) {
3039
- $id = wfu_get_safe_session_id();
3040
- $data = wfu_get_US_dboption_data($id, array());
3041
- if ( $data === false ) return;
3042
- $data[$var] = $value;
3043
- wfu_update_option("wfu_userstate_".$id, $data);
3044
- wfu_update_US_dboption_time($id);
3045
- wfu_update_US_dboption_list();
3046
- }
3047
-
3048
- function WFU_USVAR_unset_dboption($var) {
3049
- $id = wfu_get_safe_session_id();
3050
- $data = wfu_get_US_dboption_data($id);
3051
- if ( $data === false ) return;
3052
- unset($data[$var]);
3053
- wfu_update_option("wfu_userstate_".$id, $data);
3054
- wfu_update_US_dboption_time($id);
3055
- }
3056
-
3057
- function wfu_update_US_dboption_list() {
3058
- $last_check_interval = time() - wfu_get_option("wfu_userstate_list_last_check", 0);
3059
- $limit = WFU_VAR("WFU_US_DBOPTION_CHECK");
3060
- if ( $last_check_interval < $limit ) return;
3061
-
3062
- $list = wfu_get_option("wfu_userstate_list", array());
3063
- $changed = false;
3064
- $limit = WFU_VAR("WFU_US_DBOPTION_LIFE");
3065
- foreach ( $list as $id => $time ) {
3066
- $interval = time() - $time;
3067
- if ( $interval > $limit ) {
3068
- $changed = true;
3069
- unset($list[$id]);
3070
- wfu_delete_option("wfu_userstate_".$id);
3071
- }
3072
- }
3073
- if ( $changed ) wfu_update_option("wfu_userstate_list", $list);
3074
- wfu_update_option("wfu_userstate_list_last_check", time());
3075
- }
3076
-
3077
- //********************* Javascript Related Functions ****************************************************************************************************
3078
-
3079
- // function wfu_inject_js_code generates html code for injecting js code and then erase the trace
3080
- function wfu_inject_js_code($code){
3081
- $id = 'code_'.wfu_create_random_string(8);
3082
- $html = '<div id="'.$id.'" style="display:none;"><script type="text/javascript">'.$code.'</script><script type="text/javascript">var div = document.getElementById("'.$id.'"); div.parentNode.removeChild(div);</script></div>';
3083
-
3084
- return $html;
3085
- }
3086
-
3087
- //********************* Consent Functions ****************************************************************************************************
3088
-
3089
- function wfu_check_user_consent($user) {
3090
- //returns empty string if user has not completed consent question yet, "1"
3091
- //if user has given consent, "0" otherwise
3092
- $result = "";
3093
- if ( $user->ID > 0 ) {
3094
- //check in user meta for consent
3095
- $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
3096
- if ( $data && isset($data["consent_status"]) )
3097
- $result = $data["consent_status"];
3098
- }
3099
- else {
3100
- //check in user state for consent
3101
- if ( WFU_USVAR_exists('WFU_Consent_Data') ) {
3102
- $data = WFU_USVAR('WFU_Consent_Data');
3103
- if ( isset($data["consent_status"]) )
3104
- $result = $data["consent_status"];
3105
- }
3106
- }
3107
-
3108
- return $result;
3109
- }
3110
-
3111
- function wfu_update_user_consent($user, $consent_result) {
3112
- if ( $user->ID > 0 ) {
3113
- //check in user meta for consent
3114
- $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
3115
- if ( !$data ) $data = array();
3116
- $data["consent_status"] = ( $consent_result == "yes" ? "1" : ( $consent_result == "no" ? "0" : "" ) );
3117
- update_user_meta( $user->ID, 'WFU_Consent_Data', $data );
3118
- }
3119
- else {
3120
- //check in user state for consent
3121
- if ( WFU_USVAR_exists('WFU_Consent_Data') ) $data = WFU_USVAR('WFU_Consent_Data');
3122
- else $data = array();
3123
- $data["consent_status"] = ( $consent_result == "yes" ? "1" : ( $consent_result == "no" ? "0" : "" ) );
3124
- WFU_USVAR_store( 'WFU_Consent_Data', $data );
3125
- }
3126
- }
3127
-
3128
- function wfu_show_consent_profile_fields($user) {
3129
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3130
- if ( $plugin_options["personaldata"] != "1" ) return;
3131
-
3132
- $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
3133
- if ( !$data ) $data = array();
3134
- if ( !isset($data["consent_status"]) ) $data["consent_status"] = "";
3135
- $status = $data["consent_status"];
3136
-
3137
- $echo_str = "\n\t".'<h3>'.esc_html__( 'Wordpress File Upload Consent Status', 'wp-file-upload' ).'</h3>';
3138
- $echo_str .= "\n\t".'<table class="form-table">';
3139
- $echo_str .= "\n\t\t".'<tr>';
3140
- $echo_str .= "\n\t\t\t".'<th><label>'.esc_html__( 'Consent Status', 'wp-file-upload' ).'</label></th>';
3141
- $echo_str .= "\n\t\t\t".'<td>';
3142
- $echo_str .= "\n\t\t\t\t".'<label style="font-weight: bold;">'.( $status == "1" ? esc_html__( 'You have given your consent to store personal data.', 'wp-file-upload' ) : ( $status == "0" ? esc_html__( 'You have denied to store personal data.', 'wp-file-upload' ) : esc_html__( 'You have not answered to consent yet.', 'wp-file-upload' ) ) ).'</label>';
3143
- $echo_str .= "\n\t\t\t".'</td>';
3144
- $echo_str .= "\n\t\t".'</tr>';
3145
- $echo_str .= "\n\t\t".'<tr>';
3146
- $echo_str .= "\n\t\t\t".'<th></th>';
3147
- $echo_str .= "\n\t\t\t".'<td>';
3148
- $echo_str .= "\n\t\t\t\t".'<label>'.esc_html__( 'Change status to', 'wp-file-upload' ).'</label>';
3149
- $echo_str .= "\n\t\t\t\t".'<select name="consent_status">';
3150
- $echo_str .= "\n\t\t\t\t\t".'<option value="-1" selected="selected">'.esc_html__( 'No change', 'wp-file-upload' ).'</option>';
3151
- if ( $status == "1" ) {
3152
- $echo_str .= "\n\t\t\t\t\t".'<option value="0">'.esc_html__( 'Revoke Consent', 'wp-file-upload' ).'</option>';
3153
- $echo_str .= "\n\t\t\t\t\t".'<option value="">'.esc_html__( 'Clear Consent', 'wp-file-upload' ).'</option>';
3154
- }
3155
- elseif ( $status == "0" ) {
3156
- $echo_str .= "\n\t\t\t\t\t".'<option value="1">'.esc_html__( 'Give Consent', 'wp-file-upload' ).'</option>';
3157
- $echo_str .= "\n\t\t\t\t\t".'<option value="">'.esc_html__( 'Clear Consent', 'wp-file-upload' ).'</option>';
3158
- }
3159
- if ( $status == "" ) {
3160
- $echo_str .= "\n\t\t\t\t\t".'<option value="0">'.esc_html__( 'Revoke Consent', 'wp-file-upload' ).'</option>';
3161
- $echo_str .= "\n\t\t\t\t\t".'<option value="1">'.esc_html__( 'Give Consent', 'wp-file-upload' ).'</option>';
3162
- }
3163
- $echo_str .= "\n\t\t\t\t".'</select>';
3164
- $echo_str .= "\n\t\t\t".'</td>';
3165
- $echo_str .= "\n\t\t".'</tr>';
3166
- /*
3167
- if ( current_user_can( 'manage_options' ) ) {
3168
- $echo_str .= "\n\t\t".'<tr>';
3169
- $echo_str .= "\n\t\t\t".'<th><label>'.esc_html__( 'Personal Data Operations', 'wp-file-upload' ).'</label></th>';
3170
- $echo_str .= "\n\t\t\t".'<td>';
3171
- $echo_str .= "\n\t\t\t\t".'<input id="wfu_download_file_nonce" type="hidden" value="'.wp_create_nonce('wfu_download_file_invoker').'" />';
3172
- $echo_str .= "\n\t\t\t\t".'<button type="button" class="button" onclick="wfu_download_file(\'exportdata\', 1);">'.esc_html__( 'Export User Data', 'wp-file-upload' ).'</button>';
3173
- $echo_str .= "\n\t\t\t".'</td>';
3174
- $echo_str .= "\n\t\t".'</tr>';
3175
- }*/
3176
- $echo_str .= "\n\t".'</table>';
3177
-
3178
- echo $echo_str;
3179
- }
3180
-
3181
- function wfu_update_consent_profile_fields( $user_id ) {
3182
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3183
- if ( $plugin_options["personaldata"] != "1" ) return false;
3184
-
3185
- if ( ! current_user_can( 'edit_user', $user_id ) ) {
3186
- return false;
3187
- }
3188
-
3189
- $status = $_POST['consent_status'];
3190
- if ( $status == '1' || $status == '0' || $status == '' ) {
3191
- $data = get_the_author_meta( 'WFU_Consent_Data', $user_id );
3192
- if ( !$data ) $data = array();
3193
- $data["consent_status"] = $status;
3194
- update_user_meta( $user_id, 'WFU_Consent_Data', $data );
3195
- }
3196
- }
3197
-
3198
- //********************* Browser Functions ****************************************************************************************************
3199
-
3200
- function wfu_safe_store_browser_params($params) {
3201
- $code = wfu_create_random_string(16);
3202
- $safe_storage = ( WFU_USVAR_exists('wfu_browser_actions_safe_storage') ? WFU_USVAR('wfu_browser_actions_safe_storage') : array() );
3203
- $safe_storage[$code] = $params;
3204
- WFU_USVAR_store('wfu_browser_actions_safe_storage', $safe_storage);
3205
- return $code;
3206
- }
3207
-
3208
- function wfu_get_browser_params_from_safe($code) {
3209
- //sanitize $code
3210
- $code = wfu_sanitize_code($code);
3211
- if ( $code == "" ) return false;
3212
- //return params from session variable, if exists
3213
- if ( !WFU_USVAR_exists('wfu_browser_actions_safe_storage') ) return false;
3214
- $safe_storage = WFU_USVAR('wfu_browser_actions_safe_storage');
3215
- if ( !isset($safe_storage[$code]) ) return false;
3216
- return $safe_storage[$code];
3217
- }
3218
-
3219
- //********************* POST/GET Requests Functions ****************************************************************************************************
3220
-
3221
- function wfu_add_proxy_param(&$config) {
3222
- //include proxy support
3223
- $proxy = new \WP_HTTP_Proxy();
3224
- $proxy_enabled = $proxy->is_enabled();
3225
- if ( $proxy_enabled ) {
3226
- $config['proxy']['http'] = 'http://'.( $proxy->use_authentication() ? $proxy->authentication().'@' : '' ).$proxy->host().":".$proxy->port();
3227
- $config['proxy']['https'] = 'http://'.( $proxy->use_authentication() ? $proxy->authentication().'@' : '' ).$proxy->host().":".$proxy->port();
3228
- //make sure that wildcard asterisks (*) are removed from bypass hosts
3229
- //to make it compatible with Guzzle format
3230
- if ( defined('WP_PROXY_BYPASS_HOSTS') ) $config['proxy']['no'] = preg_split('|,\s*|', str_replace('*', '', WP_PROXY_BYPASS_HOSTS));
3231
- }
3232
-
3233
- return $proxy_enabled;
3234
- }
3235
-
3236
- function wfu_decode_socket_response($response) {
3237
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
3238
- $ret = "";
3239
- if (0 === strpos($response, 'HTTP/1.1 200 OK')) {
3240
- $parts = preg_split("#\n\s*\n#Uis", $response);
3241
- if ( count($parts) > 1 ) {
3242
- $rawheader = strtolower(preg_replace("/\s/", "", $parts[0]));
3243
- if ( strpos($rawheader, 'transfer-encoding:chunked') !== false ) {
3244
- $ret = "";
3245
- $pos = 0;
3246
- while ( $pos < strlen($parts[1]) ) {
3247
- $next = strpos($parts[1], "\r\n", $pos);
3248
- $len = ( $next === false || $next == $pos ? 0 : hexdec(substr($parts[1], $pos, $next - $pos)) );
3249
- if ( $len <= 0 ) break;
3250
- $ret .= substr($parts[1], $next + 2, $len);
3251
- $pos = $next + $len + 4;
3252
- }
3253
- }
3254
- else $ret = $parts[1];
3255
- }
3256
- }
3257
- return $ret;
3258
- }
3259
-
3260
- function wfu_post_request($url, $params, $verifypeer = true, $internal_request = false, $timeout = 0) {
3261
- $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
3262
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3263
- $default_args = array(
3264
- 'url' => $url,
3265
- 'params' => $params,
3266
- 'verifypeer' => $verifypeer,
3267
- 'internal_request' => $internal_request,
3268
- 'timeout' => $timeout
3269
- );
3270
- //check proxy
3271
- $proxy = new WP_HTTP_Proxy();
3272
- if ( isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'curl' ) {
3273
- // POST request using CURL
3274
- $ch = curl_init($url);
3275
- $options = array(
3276
- CURLOPT_POST => true,
3277
- CURLOPT_POSTFIELDS => http_build_query($params),
3278
- CURLOPT_HTTPHEADER => array(
3279
- 'Content-Type: application/x-www-form-urlencoded'
3280
- ),
3281
- CURLINFO_HEADER_OUT => false,
3282
- CURLOPT_HEADER => false,
3283
- CURLOPT_RETURNTRANSFER => true,
3284
- CURLOPT_SSL_VERIFYPEER => $verifypeer,
3285
- CURLOPT_SSL_VERIFYHOST => ( $verifypeer ? CURLOPT_SSL_VERIFYHOST : false )
3286
- );
3287
- if ( $timeout > 0 ) $options[CURLOPT_TIMEOUT] = $timeout;
3288
- //for internal requests to /wp-admin area that is password protected
3289
- //authorization is required
3290
- if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
3291
- $options[CURLOPT_HTTPAUTH] = CURLAUTH_ANY;
3292
- $options[CURLOPT_USERPWD] = WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD");
3293
- }
3294
- if ( WFU_VAR("WFU_RELAX_CURL_VERIFY_HOST") == "true" ) $options[CURLOPT_SSL_VERIFYHOST] = false;
3295
- //configure cURL request for proxy
3296
- if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
3297
- $options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
3298
- $options[CURLOPT_PROXY] = $proxy->host().":".$proxy->port();
3299
- if ( $proxy->use_authentication() ) {
3300
- $options[CURLOPT_PROXYAUTH] = CURLAUTH_ANY;
3301
- $options[CURLOPT_PROXYUSERPWD] = $proxy->authentication();
3302
- }
3303
- }
3304
- //customize request options before dispatching to destination
3305
- $options = apply_filters("_wfu_post_request_options", $options, "curl", $default_args);
3306
- curl_setopt_array($ch, $options);
3307
- $result = curl_exec($ch);
3308
- curl_close ($ch);
3309
- return $result;
3310
- }
3311
- elseif ( isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'socket' ) {
3312
- // POST request using sockets
3313
- $scheme = "";
3314
- $port = 80;
3315
- $errno = 0;
3316
- $errstr = '';
3317
- $ret = '';
3318
- $url_parts = parse_url($url);
3319
- $host = $url_parts['host'];
3320
- $socket_host = $host;
3321
- $path = $url_parts['path'];
3322
- if ( $url_parts['scheme'] == 'https' ) {
3323
- $scheme = "ssl://";
3324
- $port = 443;
3325
- if ( $timeout == 0 ) $timeout = 30;
3326
- }
3327
- elseif ( $url['scheme'] != 'http' ) return '';
3328
- //configure sockets request for proxy
3329
- if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
3330
- $scheme = "";
3331
- $socket_host = $proxy->host();
3332
- $port = $proxy->port();
3333
- $path = $url;
3334
- }
3335
- if ( $verifypeer ) $handle = fsockopen($scheme.$socket_host, $port, $errno, $errstr, ($timeout == 0 ? ini_get("default_socket_timeout") : $timeout));
3336
- else {
3337
- $context = stream_context_create(array(
3338
- 'ssl' => array(
3339
- 'verify_peer' => false,
3340
- 'verify_peer_name' => false
3341
- )));
3342
- $handle = stream_socket_client($scheme.$socket_host.":".$port, $errno, $errstr, ($timeout == 0 ? ini_get("default_socket_timeout") : $timeout), STREAM_CLIENT_CONNECT, $context);
3343
- }
3344
- if ( $errno !== 0 || $errstr !== '' ) $handle = false;
3345
- if ( $handle !== false ) {
3346
- $content = http_build_query($params);
3347
- $request = "POST " . $path . " HTTP/1.1\r\n";
3348
- $request .= "Host: " . $host . "\r\n";
3349
- $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
3350
- //for internal requests to /wp-admin area that is password protected
3351
- //authorization is required
3352
- if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" )
3353
- $request .= "Authorization: Basic ".base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD"))."\r\n";
3354
- //add proxy authentication if exists and is required
3355
- if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) && $proxy->use_authentication() )
3356
- $request .= $proxy->authentication_header()."\r\n";
3357
- $request .= "Content-length: " . strlen($content) . "\r\n";
3358
- $request .= "Connection: close\r\n\r\n";
3359
- $request .= $content . "\r\n\r\n";
3360
- //customize request options before dispatching to destination
3361
- $request = apply_filters("_wfu_post_request_options", $request, "socket", $default_args);
3362
- fwrite($handle, $request, strlen($request));
3363
- $response = '';
3364
- while ( !feof($handle) ) {
3365
- $response .= fgets($handle, 4096);
3366
- }
3367
- fclose($handle);
3368
- $ret = wfu_decode_socket_response($response);
3369
- }
3370
- return $ret;
3371
- }
3372
- else {
3373
- // POST request using file_get_contents
3374
- if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
3375
- $url = preg_replace("/^(http|https):\/\//", "$1://".WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD")."@", $url);
3376
- }
3377
- $peer_key = version_compare(PHP_VERSION, '5.6.0', '<') ? 'CN_name' : 'peer_name';
3378
- $http_array = array(
3379
- 'method' => 'POST',
3380
- 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
3381
- 'content' => http_build_query($params)
3382
- );
3383
- //configure fopen request for proxy
3384
- if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
3385
- $http_array['proxy'] = 'tcp://'.$proxy->host().":".$proxy->port();
3386
- if ( $proxy->use_authentication() )
3387
- $http_array['header'] .= $proxy->authentication_header()."\r\n";
3388
- }
3389
- if ( $timeout > 0 ) $http_array['timeout'] = $timeout;
3390
- //for internal requests to /wp-admin area that is password protected
3391
- //authorization is required
3392
- if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
3393
- $http_array['header'] .= "Authorization: Basic ".base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD"))."\r\n";
3394
- }
3395
- $context_params = array( 'http' => $http_array );
3396
- if ( !$verifypeer ) $context_params['ssl'] = array( 'verify_peer' => false, 'allow_self_signed' => true, 'verify_peer_name' => false );
3397
- //customize request options before dispatching to destination
3398
- $context_params = apply_filters("_wfu_post_request_options", $context_params, "fopen", $default_args);
3399
- $context = stream_context_create($context_params);
3400
- return file_get_contents($url, false, $context);
3401
- }
3402
- }
3403
-
3404
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * General Use Functions of Plugin
5
+ *
6
+ * This file contains general use functions of the plugin.
7
+ *
8
+ * @link /lib/wfu_functions.php
9
+ *
10
+ * @package WordPress File Upload Plugin
11
+ * @subpackage Core Components
12
+ * @since 2.1.2
13
+ */
14
+
15
+ //********************* Debug Functions ****************************************
16
+
17
+ /**
18
+ * Hook on plugin's functions.
19
+ *
20
+ * This is a very powerful function that enables almost all plugin functions to
21
+ * be redeclared, either in whole or partially. Here is what it can do:
22
+ *
23
+ * - It can execute a hook, based on the function parameters and then
24
+ * execute the original function.
25
+ * - It can execute a hook, based on the function's parameters and then
26
+ * return without executing the original function. This mode is like
27
+ * entirely redeclaring the original function.
28
+ * - It can execute a hook after execution of the original function.
29
+ * - It can redeclare the function parameters or pass new variables to the
30
+ * original function.
31
+ *
32
+ * In order to make a function redeclarable we just need to put the
33
+ * following 'magic' code at the top of its function block:
34
+ *
35
+ * $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out);
36
+ * if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v;
37
+ * switch($a) { case 'R': return $out['output']; break; case 'D':
38
+ * die($out['output']); }
39
+ *
40
+ * Then the function can be hooked through the filter wfu_debug-{__FUNCTION__}.
41
+ *
42
+ * The hook function takes the same parameters as the original function, plus
43
+ * one, which comes first and determines the behaviour of the hook function.
44
+ *
45
+ * This parameter is an array having three items as follows:
46
+ *
47
+ * - item 'output' contains the output of the original function (if exists)
48
+ * - item 'result' has no meaning as input parameter but as returning one
49
+ * - item 'vars' has no meaning as input parameter but as returning one
50
+ *
51
+ * The hook function must return the same array as follows:
52
+ *
53
+ * - item 'output' must contain the hook's output
54
+ * - item 'result' must be either 'X', 'R', or 'D' when the hook is executed
55
+ * at the beginning of the function, as explained below. It determines how
56
+ * the hook will be handled, as follows:
57
+ * - If 'result' is 'X' then the result of the hook function will be
58
+ * ignored and the original function will be executed afterwards.
59
+ * - If 'result' is 'R' then the original function will terminate
60
+ * returning the output of the hook function. So it is like having been
61
+ * entirely substituted by the hook function.
62
+ * - If 'result' is 'D' then the original function will die returning the
63
+ * output of the hook function. This applies to ajax handlers.
64
+ * In the case that the hook is executed at the end of the function, then
65
+ * item 'result' must always be 'R'.
66
+ * - item 'vars' is an associative array that contains any variables that the
67
+ * hook wants to pass to the original function like this:
68
+ * $res['output'] = array('varname1' => value1, 'varname2' => value2);
69
+ * Item 'vars' can be used to redeclare the function arguments and it is a
70
+ * workaround to handling arguments passed by reference.
71
+ *
72
+ * It is noted that the hook can be executed either before or after execution
73
+ * of the original function, despite the fact that the 'magic' code is added
74
+ * to the beginning of the function.
75
+ *
76
+ * - To execute the hook before the function a global variable with name
77
+ * wfu_debug-{__FUNCTION__} must be declared.
78
+ * - To execute the hook after the function a global variable with name
79
+ * wfu_debug_end-{__FUNCTION__} must be declared.
80
+ *
81
+ * It is noted that if both of these global variables are declared, or none of
82
+ * them then the hook will not work.
83
+ *
84
+ * Arguments passed by reference: When declaring the hook filter, all arguments
85
+ * are passed by value, even if some of the original function's arguments pass
86
+ * by reference. However no PHP warnings and errors will be generated due to
87
+ * this difference. If the hook wants to change the value of an argument and
88
+ * reflect this change to the original function, it is possible through item
89
+ * 'vars' explained above. For example, if the original function passes
90
+ * argument $var1 by reference (it is declared as &$var1 in the function
91
+ * parameters), we cannot use the syntax $var1 = ...; inside the hook filter
92
+ * but we can use the syntax $res['vars']['var1'] = ...; and this will result
93
+ * $var1 in the original function to get the new value!
94
+ *
95
+ * @since 3.11.0
96
+ *
97
+ * @param string $function The function name of the original function.
98
+ * @param array $args An array of parameters of the original function.
99
+ * @param string $out Tt stores the output of the hook function.
100
+ *
101
+ * @return string Returns how the hook function will be handled ('X': hook
102
+ * output must be ignored, 'R': the original function must return the
103
+ * hook's output, 'D': the original function must die returning the
104
+ * hook's output).
105
+ */
106
+ function WFU_FUNCTION_HOOK($function, $args, &$out) {
107
+ // exit if plugin's debug mode is off or the hook has not been declared in
108
+ // global variables;
109
+ if ( WFU_VAR("WFU_DEBUG") != "ON" || !( isset($GLOBALS["wfu_debug-".$function]) xor isset($GLOBALS["wfu_debug_end-".$function]) ) ) return 'X';
110
+ // exit if function name is empty or invalid
111
+ if ( $function == "" || preg_replace("/[^0-9a-zA-Z_]/", "", $function) != $function ) return 'X';
112
+ //if the hook has been declared in global variables with wfu_debug_end-
113
+ //prefix then it will run at the end of the function
114
+ if ( isset($GLOBALS["wfu_debug_end-".$function]) ) {
115
+ $args_count = count($args);
116
+ //if a flag (specific string) is contained in the last position of the
117
+ //arguments list then do not re-execute the hook as this is the second
118
+ //pass
119
+ if ( $args_count > 0 && $args[$args_count - 1] === "wfu_debug_end-".$function."-second_pass" ) return 'X';
120
+ else {
121
+ //create an array of references to the function arguments and pass
122
+ //this to call_user_func_array instead of $args; this is a
123
+ //workaround to avoid PHP warnings when the original function passes
124
+ //arguments by reference
125
+ $args_byref = array();
126
+ foreach ( $args as $key => &$arg ) $args_byref[$key] = &$arg;
127
+ //add a flag (specific string) as the last argument in order to
128
+ //denote that the next execution of the hook is the second pass
129
+ array_push($args_byref, "wfu_debug_end-".$function."-second_pass");
130
+ //call the original function and get the returned value; it will
131
+ //contain the flag in the arguments, so the hook will not be
132
+ //executed again and the whole script will not be put in an infinite
133
+ //loop
134
+ $ret = call_user_func_array($function, $args_byref);
135
+ //pass the original function's output to the hook
136
+ array_splice($args, 0, 0, array( array( "output" => $ret, "result" => "X", "vars" => array() ) ));
137
+ /**
138
+ * Hook on a Specific Function.
139
+ *
140
+ * This filter allows to redeclare, or change the behaviour, of the
141
+ * original function $function.
142
+ *
143
+ * @since 3.11.0
144
+ *
145
+ * @param array $args Array of parameters of the original function.
146
+ */
147
+ $res = apply_filters_ref_array("wfu_debug-".$function, $args);
148
+ if ( !is_array($res) || !isset($res["output"]) || !isset($res["result"]) ) $res = array( "output" => $ret, "result" => "R" );
149
+ if ( $res["result"] != 'R' ) $res["result"] = 'R';
150
+ if ( isset($res["vars"]) && !is_array($res["vars"]) ) $res["vars"] = array();
151
+ $out = $res;
152
+ return $res["result"];
153
+ }
154
+ }
155
+ else {
156
+ // prepare the arguments for the hook
157
+ array_splice($args, 0, 0, array( array( "output" => "", "result" => "X", "vars" => array() ) ));
158
+ /** This hook is decribed above. */
159
+ $res = apply_filters_ref_array("wfu_debug-".$function, $args);
160
+ // exit if $res is invalid
161
+ if ( !is_array($res) || !isset($res["output"]) || !isset($res["result"]) ) $res = array( "output" => "", "result" => "X" );
162
+ if ( $res["result"] != 'X' && $res["result"] != 'R' && $res["result"] != 'D' ) $res["result"] = 'X';
163
+ if ( isset($res["vars"]) && !is_array($res["vars"]) ) $res["vars"] = array();
164
+ $out = $res;
165
+ // if result is 'X' then the caller must ignore the hook
166
+ // if result is 'R' then the caller must return the hook's output
167
+ // if result is 'D' then the caller must die returning the hook's output
168
+ return $res["result"];
169
+ }
170
+ }
171
+
172
+ //********************* String Functions ***************************************
173
+
174
+ /**
175
+ * Sanitize Filename.
176
+ *
177
+ * This function sanitizes filename so that it is compatible with most file
178
+ * systems. Invalid non-latin characters will be converted into dashes.
179
+ *
180
+ * @since 2.1.2
181
+ *
182
+ * @param string $filename The file name.
183
+ *
184
+ * @return string The sanitized file name.
185
+ */
186
+ function wfu_upload_plugin_clean($filename) {
187
+ $clean = sanitize_file_name($filename);
188
+ if ( WFU_VAR("WFU_SANITIZE_FILENAME_MODE") != "loose" ) {
189
+ $name = wfu_filename($clean);
190
+ $ext = wfu_fileext($clean);
191
+ if ( WFU_VAR("WFU_SANITIZE_FILENAME_DOTS") == "true" ) $name_search = array ( '@[^a-zA-Z0-9_]@' );
192
+ else $name_search = array ( '@[^a-zA-Z0-9._]@' );
193
+ $ext_search = array ( '@[^a-zA-Z0-9._]@' );
194
+ $replace = array ( '-' );
195
+ $clean_name = preg_replace($name_search, $replace, remove_accents($name));
196
+ $clean_ext = preg_replace($ext_search, $replace, remove_accents($ext));
197
+ $clean = $clean_name.".".$clean_ext;
198
+ }
199
+
200
+ return $clean;
201
+ }
202
+
203
+ /**
204
+ * Wildcard Conversion Callback.
205
+ *
206
+ * This function is a callback used in a preg_replace_callback() function to
207
+ * convert wildcard syntax to natural expression.
208
+ *
209
+ * @since 3.9.0
210
+ *
211
+ * @global array $wfu_preg_replace_callback_var An array with matches.
212
+ *
213
+ * @param array $matches An array of matches of preg_replace_callback().
214
+ *
215
+ * @return string The result of the callback processing the matches.
216
+ */
217
+ function _wildcard_to_preg_preg_replace_callback($matches) {
218
+ global $wfu_preg_replace_callback_var;
219
+ array_push($wfu_preg_replace_callback_var, $matches[0]);
220
+ $key = count($wfu_preg_replace_callback_var) - 1;
221
+ return "[".$key."]";
222
+ }
223
+
224
+ /**
225
+ * Wildcard To Natural Expression Conversion.
226
+ *
227
+ * This function converts wildcard syntax of a pattern to natural expression.
228
+ *
229
+ * @since 2.1.2
230
+ *
231
+ * @global array $wfu_preg_replace_callback_var An array with matches.
232
+ *
233
+ * @param string $pattern The pattern to convert.
234
+ * @param bool $strict Optional. Strict matching. If true, dot symbols (.) will
235
+ * not be matched.
236
+ *
237
+ * @return The converted natural expression pattern.
238
+ */
239
+ function wfu_upload_plugin_wildcard_to_preg($pattern, $strict = false) {
240
+ global $wfu_preg_replace_callback_var;
241
+ $wfu_preg_replace_callback_var = array();
242
+ $pattern = preg_replace_callback("/\[(.*?)\]/", "_wildcard_to_preg_preg_replace_callback", $pattern);
243
+ if ( !$strict ) $pattern = '/^' . str_replace(array('\*', '\?', '\[', '\]'), array('.*', '.', '[', ']'), preg_quote($pattern)) . '$/is';
244
+ else $pattern = '/^' . str_replace(array('\*', '\?', '\[', '\]'), array('[^.]*', '.', '[', ']'), preg_quote($pattern)) . '$/is';
245
+ foreach ($wfu_preg_replace_callback_var as $key => $match)
246
+ $pattern = str_replace("[".$key."]", $match, $pattern);
247
+ return $pattern;
248
+ }
249
+
250
+ /**
251
+ * Wildcard To MySQL Natural Expression Conversion.
252
+ *
253
+ * This function converts wildcard syntax of a pattern to MySQL natural
254
+ * expression.
255
+ *
256
+ * @since 3.2.1
257
+ *
258
+ * @redeclarable
259
+ *
260
+ * @param string $pattern The pattern to convert.
261
+ *
262
+ * @return The converted MySQL natural expression pattern.
263
+ */
264
+ function wfu_upload_plugin_wildcard_to_mysqlregexp($pattern) {
265
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
266
+ if ( substr($pattern, 0, 6) == "regex:" ) return str_replace("\\", "\\\\", substr($pattern, 6));
267
+ else return str_replace("\\", "\\\\", '^'.str_replace(array('\*', '\?', '\[', '\]'), array('.*', '.', '[', ']'), preg_quote($pattern)).'$');
268
+ }
269
+
270
+ /**
271
+ * Match String With Pattern.
272
+ *
273
+ * This function checks if a specific string matches with a pattern.
274
+ *
275
+ * @since 2.1.2
276
+ *
277
+ * @param string $pattern The pattern to match.
278
+ * @param string $str The string to match.
279
+ * @param bool $strict Defines whether strict mode will be used. In strict mode
280
+ * dot symbols (.) are not considered as normal characters and are not
281
+ * matched with preg * symbol.
282
+ *
283
+ * @return bool True if there is a match, false otherwise.
284
+ */
285
+ function wfu_upload_plugin_wildcard_match($pattern, $str, $strict = false) {
286
+ $pattern = wfu_upload_plugin_wildcard_to_preg($pattern, $strict);
287
+ return preg_match($pattern, $str);
288
+ }
289
+
290
+ /**
291
+ * Convert String to Hex.
292
+ *
293
+ * This function converts every character of a string into a 2-byte hex
294
+ * representation.
295
+ *
296
+ * @since 2.1.2
297
+ *
298
+ * @param string $string The string to convert.
299
+ *
300
+ * @return string The converted hex string.
301
+ */
302
+ function wfu_plugin_encode_string($string) {
303
+ $array = unpack('H*', $string);
304
+ return $array[1];
305
+
306
+ $array = unpack('C*', $string);
307
+ $new_string = "";
308
+ for ($i = 1; $i <= count($array); $i ++) {
309
+ $new_string .= sprintf("%02X", $array[$i]);
310
+ }
311
+ return $new_string;
312
+ }
313
+
314
+ /**
315
+ * Convert Hex to String.
316
+ *
317
+ * This function converts a hex string into a normal ASCII string.
318
+ *
319
+ * @since 2.1.2
320
+ *
321
+ * @param string $string The hex string to convert.
322
+ *
323
+ * @return string The converted ASCII string.
324
+ */
325
+ function wfu_plugin_decode_string($string) {
326
+ return pack('H*', $string);
327
+
328
+ $new_string = "";
329
+ for ($i = 0; $i < strlen($string); $i += 2 ) {
330
+ $new_string .= sprintf("%c", hexdec(substr($string, $i ,2)));
331
+ }
332
+ return $new_string;
333
+ }
334
+
335
+ /**
336
+ * Create a Random String.
337
+ *
338
+ * This function creates a random string composing of latin letters and numbers.
339
+ *
340
+ * @since 2.1.2
341
+ *
342
+ * @param integer $len The length of the string.
343
+ *
344
+ * @return string The random string.
345
+ */
346
+ function wfu_create_random_string($len) {
347
+ $base = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
348
+ $max = strlen($base) - 1;
349
+ $activatecode = '';
350
+ if ( WFU_VAR("WFU_ALTERNATIVE_RANDOMIZER") != "true" )
351
+ mt_srand((double)microtime()*1000000);
352
+ else mt_srand((double)substr(uniqid("", true), 15));
353
+ while (strlen($activatecode) < $len)
354
+ $activatecode .= $base{mt_rand(0, $max)};
355
+ return $activatecode;
356
+ }
357
+
358
+ /**
359
+ * Join Two or More Strings.
360
+ *
361
+ * This function joins one or more strings. The strings are passed in the
362
+ * function as 2nd, 3rd, 4rth and so on parameters.
363
+ *
364
+ * @since 2.1.2
365
+ *
366
+ * @param string $delimeter The delimeter to use to join the strings.
367
+ *
368
+ * @return string The resulted joined string.
369
+ */
370
+ function wfu_join_strings($delimeter) {
371
+ $arr = func_get_args();
372
+ unset($arr[0]);
373
+ foreach ($arr as $key => $item)
374
+ if ( $item == "" ) unset($arr[$key]);
375
+ return join($delimeter, $arr);
376
+ }
377
+
378
+ /**
379
+ * Create a String of Zeros.
380
+ *
381
+ * This function creates a string filled with zeros. It is designed to be fast
382
+ * even when the length of the string is large.
383
+ *
384
+ * @since 2.1.2
385
+ *
386
+ * @param integer $size The size of the string.
387
+ *
388
+ * @return string The resulted string.
389
+ */
390
+ function wfu_create_string($size) {
391
+ $piece = str_repeat("0", 1024);
392
+ $str = "";
393
+ $reps = $size / 1024;
394
+ $rem = $size - 1024 * $reps;
395
+ for ( $i = 0; $i < $reps; $i++ ) $str .= $piece;
396
+ $str .= substr($piece, 0, $rem);
397
+ return $str;
398
+ }
399
+
400
+ /**
401
+ * Prepare String for HTML Output.
402
+ *
403
+ * This function converts newline characters into <br> tags and tabs/spaces into
404
+ * &nbsp; entities, so that they can be property shown in HTML output.
405
+ *
406
+ * @since 2.7.1
407
+ *
408
+ * @param string $output The string to be sent to output.
409
+ *
410
+ * @return string The converted HTML ready string.
411
+ */
412
+ function wfu_html_output($output) {
413
+ $output = str_replace(array("\r\n", "\r", "\n"), "<br/>", $output);
414
+ return str_replace(array("\t", " "), "&nbsp;", $output);
415
+ }
416
+
417
+ /**
418
+ * Sanitize a Code.
419
+ *
420
+ * This function sanitizes a code. A code must only contain latin letters and
421
+ * numbers.
422
+ *
423
+ * @since 3.0.0
424
+ *
425
+ * @param string $code The code to sanitize.
426
+ *
427
+ * @return string The sanitized code.
428
+ */
429
+ function wfu_sanitize_code($code) {
430
+ return preg_replace("/[^A-Za-z0-9]/", "", $code);
431
+ }
432
+
433
+ /**
434
+ * Sanitize an Integer.
435
+ *
436
+ * This function sanitizes an integer (passed as string). An integer must only
437
+ * contain numbers, plus (+) and minus (-) symbols.
438
+ *
439
+ * @since 3.1.0
440
+ *
441
+ * @param string $code The integer to sanitize passed as string.
442
+ *
443
+ * @return string The sanitized integer returned as string.
444
+ */
445
+ function wfu_sanitize_int($code) {
446
+ return preg_replace("/[^0-9+\-]/", "", $code);
447
+ }
448
+
449
+ /**
450
+ * Sanitize a Float.
451
+ *
452
+ * This function sanitizes a float (passed as string). A float must only contain
453
+ * numbers, plus (+), minus (-), dot (.) and comma (,) symbols.
454
+ *
455
+ * @since 4.3.3
456
+ *
457
+ * @param string $code The float to sanitize passed as string.
458
+ *
459
+ * @return string The sanitized float returned as string.
460
+ */
461
+ function wfu_sanitize_float($code) {
462
+ return preg_replace("/[^0-9+\-\.,]/", "", $code);
463
+ }
464
+
465
+ /**
466
+ * Sanitize a Color Value.
467
+ *
468
+ * This function sanitizes a color value. A color value must only contain
469
+ * characters a-f or A-F, numbers, number sign (#) and comma (,) symbols.
470
+ *
471
+ * @since 4.3.3
472
+ *
473
+ * @param string $code The color value to sanitize.
474
+ *
475
+ * @return string The sanitized color value.
476
+ */
477
+ function wfu_sanitize_colors($code) {
478
+ return preg_replace("/[^A-Fa-f0-9#,]/", "", $code);
479
+ }
480
+
481
+ /**
482
+ * Sanitize a Tag.
483
+ *
484
+ * This function sanitizes a tag. A tag must only contain latin characters,
485
+ * numbers and underscore (_) symbols.
486
+ *
487
+ * @since 3.1.0
488
+ *
489
+ * @param string $code The tag to sanitize.
490
+ *
491
+ * @return string The sanitized tag.
492
+ */
493
+ function wfu_sanitize_tag($code) {
494
+ return preg_replace("/[^A-Za-z0-9_]/", "", $code);
495
+ }
496
+
497
+ /**
498
+ * Sanitize a URL.
499
+ *
500
+ * This function sanitizes a URL.
501
+ *
502
+ * @since 3.11.0
503
+ *
504
+ * @param string $url The URL to sanitize.
505
+ *
506
+ * @return string The sanitized URL.
507
+ */
508
+ function wfu_sanitize_url($url) {
509
+ return filter_var(strip_tags($url), FILTER_SANITIZE_URL);
510
+ }
511
+
512
+ /**
513
+ * Sanitize a List of URL.
514
+ *
515
+ * This function sanitizes a list of URLs.
516
+ *
517
+ * @since 3.11.0
518
+ *
519
+ * @param string $urls The URLs to sanitize.
520
+ * @param string $separator The delimeter character of the URLs.
521
+ *
522
+ * @return string The sanitized URLs.
523
+ */
524
+ function wfu_sanitize_urls($urls, $separator) {
525
+ $urls_arr = explode($separator, $urls);
526
+ foreach( $urls_arr as &$url ) $url = wfu_sanitize_url($url);
527
+ return implode($separator, $urls_arr);
528
+ }
529
+
530
+ /**
531
+ * Sanitize a Shortcode.
532
+ *
533
+ * This function sanitizes a shortcode, that is sanitizes all its attributes.
534
+ *
535
+ * @since 4.3.3
536
+ *
537
+ * @param string $shortcode The shortcode to sanitize.
538
+ * @param string $shortcode_tag The shortcode tag.
539
+ *
540
+ * @return string The sanitized shortcode.
541
+ */
542
+ function wfu_sanitize_shortcode($shortcode, $shortcode_tag) {
543
+ $attrs = wfu_shortcode_string_to_array($shortcode);
544
+ $sanitized_attrs = wfu_sanitize_shortcode_array($attrs, $shortcode_tag);
545
+ //reconstruct sanitized shortcode string from array
546
+ $sanitized_shortcode = "";
547
+ foreach ( $sanitized_attrs as $attr => $value )
548
+ $sanitized_shortcode .= ( $sanitized_shortcode == "" ? "" : " " ).$attr.'="'.$value.'"';
549
+
550
+ return $sanitized_shortcode;
551
+ }
552
+
553
+ /**
554
+ * Sanitize Shortcode Attributes.
555
+ *
556
+ * This function sanitizes an array of shortcode attributes.
557
+ *
558
+ * @since 4.5.1
559
+ *
560
+ * @param array $attrs An array of shortcode attributes to sanitize.
561
+ * @param string $shortcode_tag The shortcode tag.
562
+ *
563
+ * @return array The sanitized array of shortcode attributes.
564
+ */
565
+ function wfu_sanitize_shortcode_array($attrs, $shortcode_tag) {
566
+ $sanitized_attrs = array();
567
+ if ( $shortcode_tag == 'wordpress_file_upload' ) $defs = wfu_attribute_definitions();
568
+ else $defs = wfu_browser_attribute_definitions();
569
+ // get validator types for defs
570
+ $def_validators = array();
571
+ foreach ( $defs as $def ) $def_validators[$def['attribute']] = $def['validator'];
572
+ // sanitize each attribute
573
+ foreach ( $attrs as $attr => $value ) {
574
+ //first sanitize the attribute name
575
+ $sanitized = sanitize_text_field($attr);
576
+ //continue only for attributes that sanitization did not crop any
577
+ //characters
578
+ if ( $sanitized == $attr && $attr != "" ) {
579
+ //flatten attributes that have many occurencies
580
+ $flat = preg_replace("/^(.*?)[0-9]*$/", "$1", $attr);
581
+ //get validator type
582
+ $validator = "text";
583
+ if ( isset($def_validators[$flat]) ) $validator = $def_validators[$flat];
584
+ //sanitize value based on validator type
585
+ $new_value = $value;
586
+ switch( $validator ) {
587
+ case "text":
588
+ $new_value = wp_strip_all_tags($value);
589
+ break;
590
+ case "integer":
591
+ $new_value = wfu_sanitize_int($value);
592
+ break;
593
+ case "float":
594
+ $new_value = wfu_sanitize_float($value);
595
+ break;
596
+ case "path":
597
+ $new_value = wp_strip_all_tags($value);
598
+ break;
599
+ case "link":
600
+ $new_value = wp_strip_all_tags($value);
601
+ break;
602
+ case "emailheaders":
603
+ if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
604
+ break;
605
+ case "emailsubject":
606
+ if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
607
+ break;
608
+ case "emailbody":
609
+ if ( strpos(strtolower($value), "<script") !== false ) $new_value = "";
610
+ break;
611
+ case "colors":
612
+ $new_value = wfu_sanitize_colors($value);
613
+ break;
614
+ case "css":
615
+ $new_value = wp_strip_all_tags($value);
616
+ break;
617
+ case "datetime":
618
+ $new_value = wp_strip_all_tags($value);
619
+ break;
620
+ case "pattern":
621
+ if ( substr_count($value, "'") > 0 && substr_count($value, "'") > substr_count($value, "\\'") ) $new_value = "";
622
+ break;
623
+ default:
624
+ $new_value = wp_strip_all_tags($value);
625
+ }
626
+ /**
627
+ * Custom Shortcode Sanitization.
628
+ *
629
+ * This filter allows custom actions to change the sanitization
630
+ * result of shortcode attributes.
631
+ *
632
+ * @since 4.3.3
633
+ *
634
+ * @param string $new_value New sanitized value of the attribute.
635
+ * @param string $attr The attribute name.
636
+ * @param string $validator The type of attribute used to determine
637
+ * the type of validator to use.
638
+ * @param string $value The initial value of the attribute.
639
+ */
640
+ $new_value = apply_filters("_wfu_sanitize_shortcode", $new_value, $attr, $validator, $value);
641
+ $sanitized_attrs[$attr] = $new_value;
642
+ }
643
+ }
644
+
645
+ return $sanitized_attrs;
646
+ }
647
+
648
+ /**
649
+ * Escape a Variable.
650
+ *
651
+ * This function escapes (adds backslashes before characters that need to be
652
+ * escaped) a variable, even if it is an array of unlimited depth.
653
+ *
654
+ * @since 3.3.0
655
+ *
656
+ * @param mixed $value The variable to be escaped.
657
+ *
658
+ * @return mixed The escaped variable.
659
+ */
660
+ function wfu_slash( $value ) {
661
+ if ( is_array( $value ) ) {
662
+ foreach ( $value as $k => $v ) {
663
+ if ( is_array( $v ) ) {
664
+ $value[$k] = wfu_slash( $v );
665
+ }
666
+ else {
667
+ $value[$k] = addslashes( $v );
668
+ }
669
+ }
670
+ }
671
+ else {
672
+ $value = addslashes( $value );
673
+ }
674
+
675
+ return $value;
676
+ }
677
+
678
+ /**
679
+ * Generate a Global Short-Life Token.
680
+ *
681
+ * This function generates a short-life token that is stored in Wordpress
682
+ * Options and has a global scope (is accessible by all users).
683
+ *
684
+ * @since 3.5.0
685
+ *
686
+ * @param integer $timeout The life of the token in seconds.
687
+ *
688
+ * @return string The token.
689
+ */
690
+ function wfu_generate_global_short_token($timeout) {
691
+ $token = wfu_create_random_string(16);
692
+ $expire = time() + (int)$timeout;
693
+ update_option('wfu_gst_'.$token, $expire);
694
+ return $token;
695
+ }
696
+
697
+ /**
698
+ * Verify a Global Short-Life Token.
699
+ *
700
+ * This function verifies that a global short-life token exists and it not
701
+ * expired. After verification the token is removed.
702
+ *
703
+ * @since 3.5.0
704
+ *
705
+ * @param string $token The token to verify.
706
+ *
707
+ * @return bool True if verification was successful, false otherwise.
708
+ */
709
+ function wfu_verify_global_short_token($token) {
710
+ $timeout = get_option('wfu_gst_'.$token);
711
+ if ( $timeout === false ) return false;
712
+ delete_option('wfu_gst_'.$token);
713
+ return ( $timeout > time() );
714
+ }
715
+
716
+ /**
717
+ * Generate a User Short-Life Token.
718
+ *
719
+ * This function generates a short-life token that is stored in a user's User
720
+ * Space and has a user scope (is accessible only by this user).
721
+ *
722
+ * @since 4.9.0
723
+ *
724
+ * @param integer $timeout The life of the token in seconds.
725
+ *
726
+ * @return string The token.
727
+ */
728
+ function wfu_generate_user_short_token($timeout) {
729
+ $token = wfu_create_random_string(16);
730
+ $expire = time() + (int)$timeout;
731
+ WFU_USVAR_store('wfu_ust_'.$token, $expire);
732
+ return $token;
733
+ }
734
+
735
+ /**
736
+ * Verify a User Short-Life Token.
737
+ *
738
+ * This function verifies that a user short-life token exists and it not
739
+ * expired. After verification the token is removed.
740
+ *
741
+ * @since 4.9.0
742
+ *
743
+ * @param string $token The token to verify.
744
+ *
745
+ * @return bool True if verification was successful, false otherwise.
746
+ */
747
+ function wfu_verify_user_short_token($token) {
748
+ if ( !WFU_USVAR_exists('wfu_ust_'.$token) ) return false;
749
+ $timeout = WFU_USVAR('wfu_ust_'.$token);
750
+ WFU_USVAR_unset('wfu_ust_'.$token);
751
+ return ( $timeout > time() );
752
+ }
753
+
754
+ //********************* Array Functions ****************************************
755
+
756
+ /**
757
+ * Encode Array to String.
758
+ *
759
+ * This function converts an array to a JSON string and then encodes it to its
760
+ * hex representation.
761
+ *
762
+ * @since 2.1.2
763
+ *
764
+ * @param array $arr The array to encode.
765
+ *
766
+ * @return string The encoded hex string.
767
+ */
768
+ function wfu_encode_array_to_string($arr) {
769
+ $arr_str = json_encode($arr);
770
+ $arr_str = wfu_plugin_encode_string($arr_str);
771
+ return $arr_str;
772
+ }
773
+
774
+ /**
775
+ * Decode Array from String.
776
+ *
777
+ * This function converts a hex string to its ASCII representation, which is a
778
+ * JSON string and then decodes it to an array.
779
+ *
780
+ * @since 2.1.2
781
+ *
782
+ * @param string $arr_str The encoded hex string to decode.
783
+ *
784
+ * @return array The decoded array.
785
+ */
786
+ function wfu_decode_array_from_string($arr_str) {
787
+ $arr_str = wfu_plugin_decode_string($arr_str);
788
+ $arr = json_decode($arr_str, true);
789
+ return $arr;
790
+ }
791
+
792
+ /**
793
+ * Decode HTML Entities in Array.
794
+ *
795
+ * This function decodes HTML entities found in array values into their special
796
+ * characters. It is useful when reading a shortcode array.
797
+ *
798
+ * @since 2.1.2
799
+ *
800
+ * @param array $source The source array.
801
+ *
802
+ * @return array The decoded array.
803
+ */
804
+ function wfu_plugin_parse_array($source) {
805
+ $keys = array_keys($source);
806
+ $new_arr = array();
807
+ for ($i = 0; $i < count($keys); $i ++)
808
+ $new_arr[$keys[$i]] = wp_specialchars_decode($source[$keys[$i]]);
809
+ return $new_arr;
810
+ }
811
+
812
+ /**
813
+ * Encode Special Characters in Array.
814
+ *
815
+ * This function converts special characters found in array values into HTML
816
+ * entities.
817
+ *
818
+ * @since 2.1.2
819
+ *
820
+ * @param array $arr The source array.
821
+ *
822
+ * @return array The encoded array.
823
+ */
824
+ function wfu_safe_array($arr) {
825
+ return array_map("htmlspecialchars", $arr);
826
+ }
827
+
828
+ /**
829
+ * Remove Nulls from Array.
830
+ *
831
+ * This function removes null items from array.
832
+ *
833
+ * @since 2.1.2
834
+ *
835
+ * @param array $arr The source array.
836
+ *
837
+ * @return array The cleaned array.
838
+ */
839
+ function wfu_array_remove_nulls(&$arr) {
840
+ foreach ( $arr as $key => $arri )
841
+ if ( $arri == null )
842
+ array_splice($arr, $key, 1);
843
+ }
844
+
845
+ /**
846
+ * Sanitize a Variable.
847
+ *
848
+ * This function sanitizes (converts special characters into HTML entities) a
849
+ * variable. If the variable is an array it will sanitize all elements
850
+ * recursively regardless of array depth. If the variable is not of an accepted
851
+ * type then its type will be returned.
852
+ *
853
+ * @since 2.4.4
854
+ *
855
+ * @param mixed $var The variable to sanitize.
856
+ *
857
+ * @return mixed The sanitized variable.
858
+ */
859
+ function wfu_sanitize($var) {
860
+ $typ = gettype($var);
861
+ if ( $typ == "boolean" || $typ == "integer" || $typ == "double" || $typ == "resource" || $typ == "NULL" )
862
+ return $var;
863
+ elseif ( $typ == "string" )
864
+ return htmlspecialchars($var);
865
+ elseif ( $typ == "array" || $typ == "object" ) {
866
+ foreach ( $var as &$item ) $item = wfu_sanitize($item);
867
+ return $var;
868
+ }
869
+ else
870
+ return $typ;
871
+ }
872
+
873
+ /**
874
+ * Mask a Shortcode.
875
+ *
876
+ * This function is part of a process to safely parse a shortcode string into an
877
+ * associative array. It replaces all attribute values by tokens, so that it is
878
+ * easier and safer for the process to separate the attributes.
879
+ *
880
+ * @since 2.2.1
881
+ *
882
+ * @param string $contents The shortcode.
883
+ * @param string $token The token that replaces the shortcode attribute values.
884
+ *
885
+ * @return array An array of converted attributes.
886
+ */
887
+ function _wfu_preg_replace_callback_alt($contents, $token) {
888
+ $in_block = false;
889
+ $prev_pos = 0;
890
+ $new_contents = '';
891
+ $ret['items'] = array();
892
+ $ret['tokens'] = array();
893
+ $ii = 0;
894
+ while ( ($pos = strpos($contents, '"', $prev_pos)) !== false ) {
895
+ if ( !$in_block ) {
896
+ $new_contents .= substr($contents, $prev_pos, $pos - $prev_pos + 1);
897
+ $in_block = true;
898
+ }
899
+ else {
900
+ $ret['items'][$ii] = substr($contents, $prev_pos, $pos - $prev_pos);
901
+ $ret['tokens'][$ii] = $token.sprintf('%03d', $ii);
902
+ $new_contents .= $token.sprintf('%03d', $ii).'"';
903
+ $ii ++;
904
+ $in_block = false;
905
+ }
906
+ $prev_pos = $pos + 1;
907
+ }
908
+ if ( $in_block ) {
909
+ $ret['items'][$ii] = substr($contents, $prev_pos);
910
+ $ret['tokens'][$ii] = $token.sprintf('%03d', $ii);
911
+ $new_contents .= $token.sprintf('%03d', $ii).'"';
912
+ }
913
+ else
914
+ $new_contents .= substr($contents, $prev_pos);
915
+ $ret['contents'] = $new_contents;
916
+ return $ret;
917
+ }
918
+
919
+ /**
920
+ * Parse a Shortcode.
921
+ *
922
+ * This function safely parses a shortcode string into an associative array.
923
+ *
924
+ * @since 2.1.3
925
+ *
926
+ * @param string $shortcode The shortcode.
927
+ *
928
+ * @return array The parsed shortcode as an associative array of attributes.
929
+ */
930
+ function wfu_shortcode_string_to_array($shortcode) {
931
+ $i = 0;
932
+ $m1 = array();
933
+ $m2 = array();
934
+ //for some reason preg_replace_callback does not work in all cases, so it has been replaced by a similar custom inline routine
935
+ // $mm = preg_replace_callback('/"([^"]*)"/', function ($matches) use(&$i, &$m1, &$m2) {array_push($m1, $matches[1]); array_push($m2, "attr".$i); return "attr".$i++;}, $shortcode);
936
+ $ret = _wfu_preg_replace_callback_alt($shortcode, "attr");
937
+ $mm = $ret['contents'];
938
+ $m1 = $ret['items'];
939
+ $m2 = $ret['tokens'];
940
+ $arr = explode(" ", $mm);
941
+ $attrs = array();
942
+ foreach ( $arr as $attr ) {
943
+ if ( trim($attr) != "" ) {
944
+ $attr_arr = explode("=", $attr, 2);
945
+ $key = "";
946
+ if ( count($attr_arr) > 0 ) $key = $attr_arr[0];
947
+ $val = "";
948
+ if ( count($attr_arr) > 1 ) $val = $attr_arr[1];
949
+ if ( trim($key) != "" ) $attrs[trim($key)] = str_replace('"', '', $val);
950
+ }
951
+ }
952
+ $attrs2 = str_replace($m2, $m1, $attrs);
953
+ return $attrs2;
954
+ }
955
+
956
+ /**
957
+ * Compare Two Strings in Ascending Order.
958
+ *
959
+ * This function returns the comparison result of two strings. It is part of an
960
+ * array sorting mechanism.
961
+ *
962
+ * @since 3.8.5
963
+ *
964
+ * @param string $a The first string.
965
+ * @param string $b The second string.
966
+ *
967
+ * @return int Returns < 0 if a is less than b; > 0 if a is greater than b
968
+ * and 0 if they are equal.
969
+ */
970
+ function wfu_array_sort_function_string_asc($a, $b) {
971
+ return strcmp(strtolower($a), strtolower($b));
972
+ }
973
+
974
+ /**
975
+ * Compare Two Strings Having a Second Property in Ascending Order.
976
+ *
977
+ * This function returns the comparison result of two strings. If the strings
978
+ * are equal then comparison will be done based on a second property (id0) of
979
+ * the strings, so that 0 is never returned. It is part of an array sorting
980
+ * mechanism.
981
+ *
982
+ * @since 3.8.5
983
+ *
984
+ * @param array $a The first string. It is passed as an array. 'value' item of
985
+ * the array is the string. 'id0' item is the second property.
986
+ * @param array $b The second string. It is passed as an array. 'value' item of
987
+ * the array is the string. 'id0' item is the second property.
988
+ *
989
+ * @return int Returns < 0 if a is less than b; > 0 if a is greater.
990
+ */
991
+ function wfu_array_sort_function_string_asc_with_id0($a, $b) {
992
+ $cmp = strcmp(strtolower($a["value"]), strtolower($b["value"]));
993
+ if ( $cmp == 0 ) $cmp = ( (int)$a["id0"] < (int)$b["id0"] ? -1 : 1 );
994
+ return $cmp;
995
+ }
996
+
997
+ /**
998
+ * Compare Two Strings in Descending Order.
999
+ *
1000
+ * This function returns the negstive of the comparison result of two strings.
1001
+ * It is part of an array sorting mechanism.
1002
+ *
1003
+ * @since 3.8.5
1004
+ *
1005
+ * @param string $a The first string.
1006
+ * @param string $b The second string.
1007
+ *
1008
+ * @return int Returns > 0 if a is less than b; < 0 if a is greater than b
1009
+ * and 0 if they are equal.
1010
+ */
1011
+ function wfu_array_sort_function_string_desc($a, $b) {
1012
+ return -strcmp(strtolower($a), strtolower($b));
1013
+ }
1014
+
1015
+ /**
1016
+ * Compare Two Strings Having a Second Property in Descending Order.
1017
+ *
1018
+ * This function returns the negative of the comparison result of two strings.
1019
+ * If the strings are equal then comparison will be done based on a second
1020
+ * property (id0) of the strings, so that 0 is never returned. It is part of an
1021
+ * array sorting mechanism.
1022
+ *
1023
+ * @since 3.8.5
1024
+ *
1025
+ * @param array $a The first string. It is passed as an array. 'value' item of
1026
+ * the array is the string. 'id0' item is the second property.
1027
+ * @param array $b The second string. It is passed as an array. 'value' item of
1028
+ * the array is the string. 'id0' item is the second property.
1029
+ *
1030
+ * @return int Returns > 0 if a is less than b; < 0 if a is greater.
1031
+ */
1032
+ function wfu_array_sort_function_string_desc_with_id0($a, $b) {
1033
+ $cmp = strcmp(strtolower($a["value"]), strtolower($b["value"]));
1034
+ if ( $cmp == 0 ) $cmp = ( (int)$a["id0"] < (int)$b["id0"] ? -1 : 1 );
1035
+ return -$cmp;
1036
+ }
1037
+
1038
+ /**
1039
+ * Compare Two Numbers in Ascending Order.
1040
+ *
1041
+ * This function returns the comparison result of two numbers. It is part of an
1042
+ * array sorting mechanism.
1043
+ *
1044
+ * @since 3.8.5
1045
+ *
1046
+ * @param int|float|double $a The first number.
1047
+ * @param int|float|double $b The second number.
1048
+ *
1049
+ * @return int Returns -1 if a is less than b; 1 if a is greater than b
1050
+ * and 0 if they are equal.
1051
+ */
1052
+ function wfu_array_sort_function_numeric_asc($a, $b) {
1053
+ $aa = (double)$a;
1054
+ $bb = (double)$b;
1055
+ if ( $aa < $bb ) return -1;
1056
+ elseif ( $aa > $bb ) return 1;
1057
+ else return 0;
1058
+ }
1059
+
1060
+ /**
1061
+ * Compare Two Numbers Having a Second Property in Ascending Order.
1062
+ *
1063
+ * This function returns the comparison result of two numbers. If the numbers
1064
+ * are equal then comparison will be done based on a second property (id0) of
1065
+ * the numbers, so that 0 is never returned. It is part of an array sorting
1066
+ * mechanism.
1067
+ *
1068
+ * @since 3.8.5
1069
+ *
1070
+ * @param array $a The first number. It is passed as an array. 'value' item of
1071
+ * the array is the number. 'id0' item is the second property.
1072
+ * @param array $b The second number. It is passed as an array. 'value' item of
1073
+ * the array is the number. 'id0' item is the second property.
1074
+ *
1075
+ * @return int Returns -1 if a is less than b; 1 if a is greater.
1076
+ */
1077
+ function wfu_array_sort_function_numeric_asc_with_id0($a, $b) {
1078
+ $aa = (double)$a["value"];
1079
+ $bb = (double)$b["value"];
1080
+ if ( $aa < $bb ) return -1;
1081
+ elseif ( $aa > $bb ) return 1;
1082
+ elseif ( (int)$a["id0"] < (int)$b["id0"] ) return -1;
1083
+ else return 1;
1084
+ }
1085
+
1086
+ /**
1087
+ * Compare Two Numbers in Descending Order.
1088
+ *
1089
+ * This function returns the negstive of the comparison result of two numbers.
1090
+ * It is part of an array sorting mechanism.
1091
+ *
1092
+ * @since 3.8.5
1093
+ *
1094
+ * @param int|float|number $a The first number.
1095
+ * @param int|float|number $b The second number.
1096
+ *
1097
+ * @return int Returns 1 if a is less than b; -1 if a is greater than b
1098
+ * and 0 if they are equal.
1099
+ */
1100
+ function wfu_array_sort_function_numeric_desc($a, $b) {
1101
+ $aa = (double)$a;
1102
+ $bb = (double)$b;
1103
+ if ( $aa > $bb ) return -1;
1104
+ elseif ( $aa < $bb ) return 1;
1105
+ else return 0;
1106
+ }
1107
+
1108
+ /**
1109
+ * Compare Two Numbers Having a Second Property in Descending Order.
1110
+ *
1111
+ * This function returns the negative of the comparison result of two numbers.
1112
+ * If the numbers are equal then comparison will be done based on a second
1113
+ * property (id0) of the numbers, so that 0 is never returned. It is part of an
1114
+ * array sorting mechanism.
1115
+ *
1116
+ * @since 3.8.5
1117
+ *
1118
+ * @param array $a The first number. It is passed as an array. 'value' item of
1119
+ * the array is the number. 'id0' item is the second property.
1120
+ * @param array $b The second number. It is passed as an array. 'value' item of
1121
+ * the array is the number. 'id0' item is the second property.
1122
+ *
1123
+ * @return int Returns 1 if a is less than b; -1 if a is greater.
1124
+ */
1125
+ function wfu_array_sort_function_numeric_desc_with_id0($a, $b) {
1126
+ $aa = (double)$a["value"];
1127
+ $bb = (double)$b["value"];
1128
+ if ( $aa > $bb ) return -1;
1129
+ elseif ( $aa < $bb ) return 1;
1130
+ elseif ( (int)$a["id0"] > (int)$b["id0"] ) return -1;
1131
+ else return 1;
1132
+ }
1133
+
1134
+ /**
1135
+ * Sort an Array Based on Key.
1136
+ *
1137
+ * This function sorts an array based on a key. It is used to sort a tabular
1138
+ * list based on a column. Every item of the array is another associative array
1139
+ * representing a row of the table. The key of every item is the column of the
1140
+ * table.
1141
+ *
1142
+ * @since 2.2.1
1143
+ *
1144
+ * @param array $array. The array to sort.
1145
+ * @param string $on. The sorting column name. If it is preceeded by 's:' it
1146
+ * will be sorted as string. If it is preceeded by 'n:' it will be sorted
1147
+ * as numeric.
1148
+ * @param int $order Optional. The sorting order. It can be SORT_ASC or
1149
+ * SORT_DESC.
1150
+ * @param bool $with_id0 Optional. A secord property will be used for sorting.
1151
+ *
1152
+ * @return array The sorted array.
1153
+ */
1154
+ function wfu_array_sort($array, $on, $order = SORT_ASC, $with_id0 = false) {
1155
+ $new_array = array();
1156
+ $sortable_array = array();
1157
+
1158
+ $pos = strpos($on, ":");
1159
+ if ( $pos !== false ) {
1160
+ $sorttype = substr($on, $pos + 1);
1161
+ if ( $sorttype == "" ) $sorttype = "s";
1162
+ $on = substr($on, 0, $pos);
1163
+ }
1164
+ else $sorttype = "s";
1165
+
1166
+ if (count($array) > 0) {
1167
+ foreach ($array as $k => $v) {
1168
+ if (is_array($v)) {
1169
+ foreach ($v as $k2 => $v2) {
1170
+ if ($k2 == $on) {
1171
+ $sortable_array[$k] = ( $with_id0 ? array( "id0" => $v["id0"], "value" => $v2 ) : $v2 );
1172
+ }
1173
+ }
1174
+ } else {
1175
+ $sortable_array[$k] = $v;
1176
+ $with_id0 = false;
1177
+ }
1178
+ }
1179
+
1180
+ uasort($sortable_array, "wfu_array_sort_function_".( $sorttype == "n" ? "numeric" : "string" )."_".( $order == SORT_ASC ? "asc" : "desc" ).( $with_id0 ? "_with_id0" : "" ));
1181
+
1182
+ foreach ($sortable_array as $k => $v) {
1183
+ $new_array[$k] = $array[$k];
1184
+ }
1185
+ }
1186
+
1187
+ return $new_array;
1188
+ }
1189
+
1190
+ /**
1191
+ * Output Array Contents.
1192
+ *
1193
+ * This function echoes array contents to show properly in a front-end page.
1194
+ *
1195
+ * @since 3.4.0
1196
+ *
1197
+ * @param array $arr. The array to echo.
1198
+ */
1199
+ function wfu_echo_array($arr) {
1200
+ if ( !is_array($arr) ) return;
1201
+ echo '<pre>'.print_r($arr, true).'</pre>';
1202
+ }
1203
+
1204
+ /**
1205
+ * Minify Code.
1206
+ *
1207
+ * This function minifies a piece of code. It is used to minify inline code of
1208
+ * the plugin. It supports minification of Javascript or CSS code.
1209
+ *
1210
+ * @since 4.2.0
1211
+ *
1212
+ * @param string $lang. The code language. It can be 'JS' or 'CSS'.
1213
+ * @param string $code. The code to minify.
1214
+ *
1215
+ * @return array An array holding minification result. Item 'result' is true if
1216
+ * minification was successful and false otherwise. Item 'minified_code'
1217
+ * holds the minified code.
1218
+ */
1219
+ function wfu_minify_code($lang, $code) {
1220
+ $ret = array( "result" => false, "minified_code" => "" );
1221
+ $php_version = preg_replace("/-.*/", "", phpversion());
1222
+ $unsupported = false;
1223
+ $ret = wfu_compare_versions($php_version, '5.3.0');
1224
+ $unsupported = ( $ret['status'] && $ret['result'] == 'lower' );
1225
+ if ( !$unsupported ) {
1226
+ $path = ABSWPFILEUPLOAD_DIR;
1227
+ if ( !class_exists('MatthiasMullie\Minify\Minify') ) {
1228
+ include_once $path.'vendor/minifier/minify/src/Minify.php';
1229
+ include_once $path.'vendor/minifier/minify/src/CSS.php';
1230
+ include_once $path.'vendor/minifier/minify/src/JS.php';
1231
+ include_once $path.'vendor/minifier/minify/src/Exception.php';
1232
+ include_once $path.'vendor/minifier/minify/src/Exceptions/BasicException.php';
1233
+ include_once $path.'vendor/minifier/minify/src/Exceptions/FileImportException.php';
1234
+ include_once $path.'vendor/minifier/minify/src/Exceptions/IOException.php';
1235
+ }
1236
+ if ( !class_exists('MatthiasMullie\PathConverter\Converter') ) {
1237
+ include_once $path.'vendor/minifier/path-converter/src/ConverterInterface.php';
1238
+ include_once $path.'vendor/minifier/path-converter/src/Converter.php';
1239
+ }
1240
+ $minifier = null;
1241
+ eval('$minifier = new MatthiasMullie\Minify\\'.strtoupper($lang).'($code);');
1242
+ if ( $minifier !== null ) {
1243
+ $ret["result"] = true;
1244
+ $ret["minified_code"] = $minifier->minify();
1245
+ }
1246
+ }
1247
+
1248
+ return $ret;
1249
+ }
1250
+
1251
+ /**
1252
+ * Prepare CSS Code for Output.
1253
+ *
1254
+ * This function prepares CSS code for HTML output. It minifies the code if
1255
+ * necessary and encloses it in <style> tags.
1256
+ *
1257
+ * @since 4.0.0
1258
+ *
1259
+ * @param string $css. The CSS code to output.
1260
+ *
1261
+ * @return string The resulted HTML code.
1262
+ */
1263
+ function wfu_css_to_HTML($css) {
1264
+ if ( WFU_VAR("WFU_MINIFY_INLINE_CSS") == "true" ) {
1265
+ $ret = wfu_minify_code("CSS", $css);
1266
+ if ( $ret["result"] ) $css = $ret["minified_code"];
1267
+ }
1268
+ $echo_str = "\n\t".'<style>';
1269
+ $echo_str .= "\n".$css;
1270
+ $echo_str .= "\n\t".'</style>';
1271
+
1272
+ return $echo_str;
1273
+ }
1274
+
1275
+ /**
1276
+ * Prepare Javascript Code for Output.
1277
+ *
1278
+ * This function prepares Javascript code for HTML output. It minifies the code
1279
+ * if necessary and encloses it in <script> tags.
1280
+ *
1281
+ * @since 4.0.0
1282
+ *
1283
+ * @param string $js. The Javascript code to output.
1284
+ *
1285
+ * @return string The resulted HTML code.
1286
+ */
1287
+ function wfu_js_to_HTML($js) {
1288
+ if ( WFU_VAR("WFU_MINIFY_INLINE_JS") == "true" ) {
1289
+ $ret = wfu_minify_code("JS", $js);
1290
+ if ( $ret["result"] ) $js = $ret["minified_code"];
1291
+ }
1292
+ $echo_str = '<script type="text/javascript">';
1293
+ $echo_str .= "\n".$js;
1294
+ $echo_str .= "\n".'</script>';
1295
+
1296
+ return $echo_str;
1297
+ }
1298
+
1299
+ /**
1300
+ * Generate Basic Inline Javascript Loader Functions.
1301
+ *
1302
+ * This function returns the initialization code of the basic inline JS loader
1303
+ * functions:
1304
+ *
1305
+ * wfu_js_decode_obj: This JS function generates an object from its string
1306
+ * representation.
1307
+ *
1308
+ * wfu_run_js: This JS function calls other JS functions. It is used to run
1309
+ * inline functions safely. Inline functions use objects, like GlobalData,
1310
+ * which initialize after Javascript files of the plugin have been loaded.
1311
+ * Usually these files are declared at the header of a page and load before
1312
+ * the inline code. So objects like GlobalData have been initialized and
1313
+ * inline functions can run without errors. However sometimes Javascript files
1314
+ * are declared at the footer, or handled by cache plugins and load after the
1315
+ * inline code. In these cases wfu_run_js will not run the inline functions
1316
+ * immediately. It will put them in a JS Bank, so that they run safely after
1317
+ * the Javascript files have been loaded.
1318
+ *
1319
+ * @since 4.2.0
1320
+ *
1321
+ * @return string The HTML code of the inline Javascript loader functions.
1322
+ */
1323
+ function wfu_init_run_js_script() {
1324
+ // $script = 'if (typeof wfu_js_decode_obj == "undefined") function wfu_js_decode_obj(obj_str) { var obj = null; if (obj_str == "window") obj = window; else { var match = obj_str.match(new RegExp(\'GlobalData(\\\\.(WFU|WFUB)\\\\[(.*?)\\\\](\\\\.(.*))?)?$\')); if (match) { obj = GlobalData; if (match[3]) obj = obj[match[2]][match[3]]; if (match[5]) obj = obj[match[5]]; } } return obj; }';
1325
+ $script = 'if (typeof wfu_js_decode_obj == "undefined") function wfu_js_decode_obj(obj_str) { var obj = null; if (obj_str == "window") obj = window; else { var dbs = String.fromCharCode(92); var match = obj_str.match(new RegExp(\'GlobalData(\' + dbs + \'.(WFU|WFUB)\' + dbs + \'[(.*?)\' + dbs + \'](\' + dbs + \'.(.*))?)?$\')); if (match) { obj = GlobalData; if (match[3]) obj = obj[match[2]][match[3]]; if (match[5]) obj = obj[match[5]]; } } return obj; }';
1326
+ $script .= "\n".'if (typeof wfu_run_js == "undefined") function wfu_run_js(obj_str, func) { if (typeof GlobalData == "undefined") { if (typeof window.WFU_JS_BANK == "undefined") WFU_JS_BANK = []; WFU_JS_BANK.push({obj_str: obj_str, func: func}) } else { var obj = wfu_js_decode_obj(obj_str); if (obj) obj[func].call(obj); } }';
1327
+ return wfu_js_to_HTML($script);
1328
+ }
1329
+
1330
+ /**
1331
+ * Convert PHP Array to JS Object.
1332
+ *
1333
+ * This function converts an associative PHP array into a Javascript object.
1334
+ *
1335
+ * @since 4.0.0
1336
+ *
1337
+ * @param array $arr. The associative PHP array to convert.
1338
+ *
1339
+ * @return string The converted Javascript object as a string.
1340
+ */
1341
+ function wfu_PHP_array_to_JS_object($arr) {
1342
+ $ret = "";
1343
+ foreach ( $arr as $prop => $value ) {
1344
+ if ( is_string($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: \"$value\"";
1345
+ elseif ( is_numeric($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: $value";
1346
+ elseif ( is_bool($value) ) $ret .= ( $ret == "" ? "" : ", " )."$prop: ".( $value ? "true" : "false" );
1347
+ }
1348
+ return ( $ret == "" ? "{ }" : "{ $ret }" );
1349
+ }
1350
+
1351
+ /**
1352
+ * Convert PHP Array to URL GET Params.
1353
+ *
1354
+ * This function converts an associative PHP array into GET parameters to add in
1355
+ * a URL.
1356
+ *
1357
+ * @since 4.9.0
1358
+ *
1359
+ * @param array $arr. The associative PHP array to convert.
1360
+ *
1361
+ * @return string The converted GET parameters.
1362
+ */
1363
+ function wfu_array_to_GET_params($arr) {
1364
+ $str = "";
1365
+ foreach ( $arr as $key => $var )
1366
+ $str .= ( $str == "" ? "" : "&" ).$key."=".$var;
1367
+
1368
+ return $str;
1369
+ }
1370
+
1371
+ //********************* Shortcode Attribute Functions **************************
1372
+
1373
+ /**
1374
+ * Insert a Category in a List of Categories.
1375
+ *
1376
+ * This function inserts a new category in a list of categories.
1377
+ *
1378
+ * @since 4.1.0
1379
+ *
1380
+ * @param array $categories. The list of categories.
1381
+ * @param string $before_category. Insert the new category before this one.
1382
+ * @param string $new_category. The new category to insert.
1383
+ *
1384
+ * @return array The updated list of categories.
1385
+ */
1386
+ function wfu_insert_category($categories, $before_category, $new_category) {
1387
+ if ( $before_category == "" ) $index = count($categories);
1388
+ else {
1389
+ $index = array_search($before_category, array_keys($categories));
1390
+ if ( $index === false ) $index = count($categories);
1391
+ }
1392
+
1393
+ return array_merge(array_slice($categories, 0, $index), $new_category, array_slice($categories, $index));
1394
+ }
1395
+
1396
+ /**
1397
+ * Insert new Attributes in a List of Attributes.
1398
+ *
1399
+ * This function inserts one or more attributes in a list of attributes.
1400
+ *
1401
+ * @since 4.1.0
1402
+ *
1403
+ * @param array $attributes. The list of attributes.
1404
+ * @param string $in_category. Insert the new attribute in this category.
1405
+ * @param string $in_subcategory. Insert the new attribute in this subcategory.
1406
+ * @param string $position. Position of the new attribute. It can be 'first' or
1407
+ * 'last'.
1408
+ * @param array $new_attributes. The new attributes to insert.
1409
+ *
1410
+ * @return array The updated list of attributes.
1411
+ */
1412
+ function wfu_insert_attributes($attributes, $in_category, $in_subcategory, $position, $new_attributes) {
1413
+ $index = -1;
1414
+ if ( $in_category == "" ) {
1415
+ if ( $position == "first" ) $index = 0;
1416
+ elseif ( $position == "last" ) $index = count($attributes);
1417
+ }
1418
+ else {
1419
+ foreach ( $attributes as $pos => $attribute ) {
1420
+ $match = ( $attribute["category"] == $in_category );
1421
+ if ( $in_subcategory != "" ) $match = $match && ( $attribute["subcategory"] == $in_subcategory );
1422
+ if ( $match ) {
1423
+ if ( $position == "first" ) {
1424
+ $index = $pos;
1425
+ break;
1426
+ }
1427
+ elseif ( $position == "last" ) {
1428
+ $index = $pos + 1;
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+ if ( $index > -1 ) array_splice($attributes, $index, 0, $new_attributes);
1434
+
1435
+ return $attributes;
1436
+ }
1437
+
1438
+ //********************* Plugin Options Functions *******************************
1439
+
1440
+ /**
1441
+ * Get Server Environment.
1442
+ *
1443
+ * This function gets the server environment, whether it is 32 or 64 bit.
1444
+ *
1445
+ * @since 2.6.0
1446
+ *
1447
+ * @redeclarable
1448
+ *
1449
+ * @return string The server environment, '32bit' or '64bit'.
1450
+ */
1451
+ function wfu_get_server_environment() {
1452
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1453
+ $php_env = '';
1454
+ if ( PHP_INT_SIZE == 4 ) $php_env = '32bit';
1455
+ elseif ( PHP_INT_SIZE == 8 ) $php_env = '64bit';
1456
+ else {
1457
+ $int = "9223372036854775807";
1458
+ $int = intval($int);
1459
+ if ($int == 9223372036854775807) $php_env = '64bit';
1460
+ elseif ($int == 2147483647) $php_env = '32bit';
1461
+ }
1462
+
1463
+ return $php_env;
1464
+ }
1465
+
1466
+ /**
1467
+ * Get AJAX URL.
1468
+ *
1469
+ * This function gets the URL of admin-ajax.php for AJAX requests.
1470
+ *
1471
+ * @since 3.7.2
1472
+ *
1473
+ * @redeclarable
1474
+ *
1475
+ * @return string The full URL for AJAX requests.
1476
+ */
1477
+ function wfu_ajaxurl() {
1478
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1479
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1480
+ return ( $plugin_options['admindomain'] == 'siteurl' || $plugin_options['admindomain'] == '' ? site_url("wp-admin/admin-ajax.php") : ( $plugin_options['admindomain'] == 'adminurl' ? admin_url("admin-ajax.php") : home_url("wp-admin/admin-ajax.php") ) );
1481
+ }
1482
+
1483
+ /**
1484
+ * Get Plugin Environment Variable Value.
1485
+ *
1486
+ * This function gets the value of a plugin's environment variable.
1487
+ *
1488
+ * @since 3.7.1
1489
+ *
1490
+ * @param string $varname The name of the environment variable.
1491
+ *
1492
+ * @return mixed The value of the environment variable.
1493
+ */
1494
+ function WFU_VAR($varname) {
1495
+ if ( !isset($GLOBALS["WFU_GLOBALS"][$varname]) ) return false;
1496
+ if ( $GLOBALS["WFU_GLOBALS"][$varname][5] ) return $GLOBALS["WFU_GLOBALS"][$varname][3];
1497
+ //in case the environment variable is hidden then return the default value
1498
+ else return $GLOBALS["WFU_GLOBALS"][$varname][2];
1499
+ }
1500
+
1501
+ /**
1502
+ * Get Plugin Version.
1503
+ *
1504
+ * This function gets the plugin's version.
1505
+ *
1506
+ * @since 2.4.6
1507
+ *
1508
+ * @return string The plugin's version.
1509
+ */
1510
+ function wfu_get_plugin_version() {
1511
+ $plugin_data = get_plugin_data(WPFILEUPLOAD_PLUGINFILE);
1512
+ return $plugin_data['Version'];
1513
+ }
1514
+
1515
+ /**
1516
+ * Get Plugin's Latest Version.
1517
+ *
1518
+ * This function gets the plugin's latest version from Iptanus Services Server.
1519
+ *
1520
+ * @since 2.4.6
1521
+ *
1522
+ * @redeclarable
1523
+ *
1524
+ * @return string The plugin's latest version.
1525
+ */
1526
+ function wfu_get_latest_version() {
1527
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1528
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
1529
+ $postfields = array();
1530
+ $postfields['action'] = 'wfuca_check_latest_version_free';
1531
+ $postfields['version_hash'] = WFU_VERSION_HASH;
1532
+ $url = ( $plugin_options["altserver"] == "1" && trim(WFU_VAR("WFU_ALT_IPTANUS_SERVER")) != "" ? ( trim(WFU_VAR("WFU_ALT_VERSION_SERVER")) != "" ? trim(WFU_VAR("WFU_ALT_VERSION_SERVER")) : trim(WFU_VAR("WFU_ALT_IPTANUS_SERVER")).'/wp-admin/admin-ajax.php' ) : WFU_VERSION_SERVER_URL );
1533
+ $result = null;
1534
+ if ( WFU_VAR("WFU_DISABLE_VERSION_CHECK") != "true" )
1535
+ $result = wfu_post_request($url, $postfields, false, false, 10);
1536
+ return $result;
1537
+ }
1538
+
1539
+ /**
1540
+ * Compare Current and Latest Version.
1541
+ *
1542
+ * This function compares curent version with latest one.
1543
+ *
1544
+ * @since 2.4.6
1545
+ *
1546
+ * @param string $current The curent plugin version.
1547
+ * @param string $latest The latest plugin version.
1548
+ *
1549
+ * @return string The comparison result. It can have the following values:
1550
+ * 'equal': both versions are equal.
1551
+ * 'lower': current version is lower than latest.
1552
+ * 'current version invalid' current version is invalid.
1553
+ * 'latest version invalid' latest version is invalid.
1554
+ */
1555
+ function wfu_compare_versions($current, $latest) {
1556
+ $ret['status'] = true;
1557
+ $ret['custom'] = false;
1558
+ $ret['result'] = 'equal';
1559
+ $res = preg_match('/^([0-9]*)\.([0-9]*)\.([0-9]*)(.*)/', $current, $cur_data);
1560
+ if ( !$res || count($cur_data) < 5 )
1561
+ return array( 'status' => false, 'custom' => false, 'result' => 'current version invalid' );
1562
+ if ( $cur_data[1] == '' || $cur_data[2] == '' || $cur_data[3] == '' )
1563
+ return array( 'status' => false, 'custom' => false, 'result' => 'current version invalid' );
1564
+ $custom = ( $cur_data[4] != '' );
1565
+ $res = preg_match('/^([0-9]*)\.([0-9]*)\.([0-9]*)/', $latest, $lat_data);
1566
+ if ( !$res || count($lat_data) < 4 )
1567
+ return array( 'status' => false, 'custom' => $custom, 'result' => 'latest version invalid' );
1568
+ if ( $lat_data[1] == '' || $lat_data[2] == '' || $lat_data[3] == '' )
1569
+ return array( 'status' => false, 'custom' => $custom, 'result' => 'latest version invalid' );
1570
+ if ( intval($cur_data[1]) < intval($lat_data[1]) )
1571
+ return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
1572
+ elseif ( intval($cur_data[1]) > intval($lat_data[1]) )
1573
+ return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
1574
+ if ( intval($cur_data[2]) < intval($lat_data[2]) )
1575
+ return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
1576
+ elseif ( intval($cur_data[2]) > intval($lat_data[2]) )
1577
+ return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
1578
+ if ( intval($cur_data[3]) < intval($lat_data[3]) )
1579
+ return array( 'status' => true, 'custom' => $custom, 'result' => 'lower' );
1580
+ elseif ( intval($cur_data[3]) > intval($lat_data[3]) )
1581
+ return array( 'status' => false, 'custom' => $custom, 'result' => 'current version invalid' );
1582
+ return array( 'status' => true, 'custom' => $custom, 'result' => 'equal' );
1583
+ }
1584
+
1585
+ //********************* File / Directory Functions *****************************
1586
+
1587
+ /**
1588
+ * Get Root Path of Website.
1589
+ *
1590
+ * This function gets the root (absolute) path of the website. If it cannot be
1591
+ * retrieved then content path is returned.
1592
+ *
1593
+ * @since 4.0.0
1594
+ *
1595
+ * @return string The absolute path of the website.
1596
+ */
1597
+ function wfu_abspath() {
1598
+ $path = WP_CONTENT_DIR;
1599
+ //remove trailing slash if exists
1600
+ if ( substr($path, -1) == '/' ) $path = substr($path, 0, -1);
1601
+ $pos = strrpos($path, '/');
1602
+ //to find abspath we go one dir up from content path
1603
+ if ( $pos !== false ) $path = substr($path, 0, $pos + 1);
1604
+ //else if we cannot go up we stay at content path adding a trailing slash
1605
+ else $path .= '/';
1606
+
1607
+ return $path;
1608
+ }
1609
+
1610
+ /**
1611
+ * Extract Extension from Filename.
1612
+ *
1613
+ * This function extracts the extension part from filename.
1614
+ *
1615
+ * @since 3.8.0
1616
+ *
1617
+ * @param string $basename The filename to extract the extension from.
1618
+ * @param bool $with_dot Optional. If true the dot symbol will be included in
1619
+ * the extension.
1620
+ *
1621
+ * @return string The extracted extension.
1622
+ */
1623
+ function wfu_fileext($basename, $with_dot = false) {
1624
+ if ( $with_dot ) return preg_replace("/^.*?(\.[^.]*)?$/", "$1", $basename);
1625
+ else return preg_replace("/^.*?(\.([^.]*))?$/", "$2", $basename);
1626
+ }
1627
+
1628
+ /**
1629
+ * Extract Name Part from Filename.
1630
+ *
1631
+ * This function extracts the name part from filename without the extension.
1632
+ *
1633
+ * @since 3.8.0
1634
+ *
1635
+ * @param string $basename The filename to extract the name part from.
1636
+ *
1637
+ * @return string The extracted name part.
1638
+ */
1639
+ function wfu_filename($basename) {
1640
+ return preg_replace("/^(.*?)(\.[^.]*)?$/", "$1", $basename);
1641
+ }
1642
+
1643
+ /**
1644
+ * Extract Filename From Path.
1645
+ *
1646
+ * This function extracts the filename from path.
1647
+ *
1648
+ * @since 2.6.0
1649
+ *
1650
+ * @param string $path The path to extract the filename from.
1651
+ *
1652
+ * @return string The extracted filename.
1653
+ */
1654
+ function wfu_basename($path) {
1655
+ if ( !$path || $path == "" ) return "";
1656
+ return preg_replace('/.*(\\\\|\\/)/', '', $path);
1657
+ }
1658
+
1659
+ /**
1660
+ * Extract Dir From Path.
1661
+ *
1662
+ * This function extracts the dir part from path without the filename.
1663
+ *
1664
+ * @since 2.7.1
1665
+ *
1666
+ * @param string $path The path to extract the dir part from.
1667
+ *
1668
+ * @return string The extracted dir part.
1669
+ */
1670
+ function wfu_basedir($path) {
1671
+ if ( !$path || $path == "" ) return "";
1672
+ return substr($path, 0, strlen($path) - strlen(wfu_basename($path)));
1673
+ }
1674
+
1675
+ /**
1676
+ * Convert Absolute Path to Relative.
1677
+ *
1678
+ * This function converts an absolute path to relative one by removing the
1679
+ * root path of the website. If the path points to an FTP location then no
1680
+ * conversion happens. If the path is outside the root, then 'abs:' is appended
1681
+ * to the path.
1682
+ *
1683
+ * @since 3.1.0
1684
+ *
1685
+ * @param string $path The absolute path.
1686
+ *
1687
+ * @return string The relative path.
1688
+ */
1689
+ function wfu_path_abs2rel($path) {
1690
+ $abspath_notrailing_slash = substr(wfu_abspath(), 0, -1);
1691
+ if ( substr($path, 0, 6) == 'ftp://' || substr($path, 0, 7) == 'ftps://' || substr($path, 0, 7) == 'sftp://' ) return $path;
1692
+ else {
1693
+ $is_outside_root = ( substr($path, 0, strlen($abspath_notrailing_slash)) != $abspath_notrailing_slash );
1694
+ if ( $is_outside_root ) return 'abs:'.$path;
1695
+ // else return str_replace($abspath_notrailing_slash, "", $path);
1696
+ else return substr($path, strlen($abspath_notrailing_slash));
1697
+ }
1698
+ }
1699
+
1700
+ /**
1701
+ * Convert Relative Path to Absolute.
1702
+ *
1703
+ * This function converts a relative path to absolute one by prepending the root
1704
+ * path of the website.
1705
+ *
1706
+ * @since 3.1.0
1707
+ *
1708
+ * @param string $path The relative path.
1709
+ *
1710
+ * @return string The absolute path.
1711
+ */
1712
+ function wfu_path_rel2abs($path) {
1713
+ if ( substr($path, 0, 1) == "/" ) $path = substr($path, 1);
1714
+ if ( substr($path, 0, 6) == 'ftp://' || substr($path, 0, 7) == 'ftps://' || substr($path, 0, 7) == 'sftp://' ) return $path;
1715
+ elseif ( substr($path, 0, 4) == 'abs:' ) return substr($path, 4);
1716
+ else return wfu_abspath().$path;
1717
+ }
1718
+
1719
+ /**
1720
+ * Delete an Uploaded File.
1721
+ *
1722
+ * This function deletes an uploaded file from the website. It marks the file as
1723
+ * deleted in the database. It also deletes any linked attachments or
1724
+ * thumbnails.
1725
+ *
1726
+ * @since 4.2.0
1727
+ *
1728
+ * @redeclarable
1729
+ *
1730
+ * @param string $filepath The path of the file to delete.
1731
+ * @param int $userid The ID of the user who performs the deletion.
1732
+ *
1733
+ * @return bool True if the deletion succeeded, false otherwise.
1734
+ */
1735
+ function wfu_delete_file_execute($filepath, $userid) {
1736
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
1737
+ $filedata = wfu_get_filedata($filepath);
1738
+ $retid = wfu_log_action('delete', $filepath, $userid, '', 0, 0, '', null);
1739
+ $result = unlink($filepath);
1740
+ if ( !$result ) wfu_revert_log_action($retid);
1741
+ else {
1742
+ //delete linked attachment if exists and it is allowed to be deleted
1743
+ if ( $filedata != null && isset($filedata["media"]) && WFU_VAR("WFU_UPDATE_MEDIA_ON_DELETE") == "true" )
1744
+ wp_delete_attachment( $filedata["media"]["attach_id"] );
1745
+ }
1746
+
1747
+ return $result;
1748
+ }
1749
+
1750
+ /**
1751
+ * Extract FTP Information From ftpinfo Attribute.
1752
+ *
1753
+ * This function extracts FTP information from ftpinfo attribute of the uploader
1754
+ * shortcode.
1755
+ *
1756
+ * @since 4.11.2
1757
+ *
1758
+ * @param string $ftpdata The ftpinfo attribute.
1759
+ *
1760
+ * @return array {
1761
+ * An array of extracted FTP information.
1762
+ *
1763
+ * @type bool $error Defines whether there was an error during
1764
+ * extraction of FTP information.
1765
+ * @type array $data {
1766
+ * The extracted FTP information.
1767
+ *
1768
+ * @type string $username The FTP login username.
1769
+ * @type string $password The FTP login password.
1770
+ * @type string $ftpdomain The FTP domain.
1771
+ * @type string $port The FTP port.
1772
+ * @type bool $sftp Defines whether sFTP connection will be used.
1773
+ * }
1774
+ * }
1775
+ */
1776
+ function wfu_decode_ftpinfo($ftpdata) {
1777
+ $ret = array(
1778
+ "error" => true,
1779
+ "data" => array(
1780
+ "username" => "",
1781
+ "password" => "",
1782
+ "ftpdomain" => "",
1783
+ "port" => "",
1784
+ "sftp" => false
1785
+ )
1786
+ );
1787
+ $ftpdata_flat = str_replace(array('\\:', '\\@'), array('\\_', '\\_'), $ftpdata);
1788
+ $pos1 = strpos($ftpdata_flat, ":");
1789
+ $pos2 = strpos($ftpdata_flat, "@");
1790
+ if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
1791
+ $ret["error"] = false;
1792
+ $ret["data"]["username"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
1793
+ $ret["data"]["password"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'), substr($ftpdata, $pos1 + 1, $pos2 - $pos1 - 1));
1794
+ $ftp_host = substr($ftpdata, $pos2 + 1);
1795
+ $ret["data"]["ftpdomain"] = preg_replace("/:.*/", "", $ftp_host);
1796
+ if ( trim($ret["data"]["ftpdomain"]) == "" ) $ret["error"] = true;
1797
+ $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
1798
+ if ( substr($ftp_port, 0, 1) == "s" ) {
1799
+ $ret["data"]["sftp"] = true;
1800
+ $ftp_port = substr($ftp_port, 1);
1801
+ }
1802
+ $ret["data"]["port"] = $ftp_port;
1803
+ }
1804
+ elseif ( $pos2 ) {
1805
+ $ret["error"] = false;
1806
+ $ret["data"]["username"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'), substr($ftpdata, 0, $pos2));
1807
+ $ftp_host = substr($ftpdata, $pos2 + 1);
1808
+ $ret["data"]["ftpdomain"] = preg_replace("/:.*/", "", $ftp_host);
1809
+ if ( trim($ret["data"]["ftpdomain"]) == "" ) $ret["error"] = true;
1810
+ $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
1811
+ if ( substr($ftp_port, 0, 1) == "s" ) {
1812
+ $ret["data"]["sftp"] = true;
1813
+ $ftp_port = substr($ftp_port, 1);
1814
+ }
1815
+ $ret["data"]["port"] = $ftp_port;
1816
+ }
1817
+ elseif ( $pos1 ) {
1818
+ $ret["error"] = true;
1819
+ $ret["data"]["username"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
1820
+ $ret["data"]["password"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'),substr($ftpdata, $pos1 + 1));
1821
+ }
1822
+ else {
1823
+ $ret["error"] = true;
1824
+ $ret["data"]["username"] = str_replace(array('\\\\:', '\\\\@'), array(':', '@'), $ftpdata);
1825
+ }
1826
+
1827
+ return $ret;
1828
+ }
1829
+
1830
+ /**
1831
+ * Get Full Upload Path.
1832
+ *
1833
+ * This function calculates the full upload path of an uploader shortcode from
1834
+ * its attributes.
1835
+ *
1836
+ * @since 2.1.2
1837
+ *
1838
+ * @param array $params The shortcode attributes.
1839
+ *
1840
+ * @return string The full uplod path.
1841
+ */
1842
+ function wfu_upload_plugin_full_path( $params ) {
1843
+ $path = $params["uploadpath"];
1844
+ if ( $params["accessmethod"] == 'ftp' && $params["ftpinfo"] != '' && $params["useftpdomain"] == "true" ) {
1845
+ //remove parent folder symbol (..) in path so that the path does not go outside host
1846
+ $ftpdata = str_replace('..', '', $params["ftpinfo"]);
1847
+ $ftpinfo = wfu_decode_ftpinfo($ftpdata);
1848
+ if ( !$ftpinfo["error"] ) {
1849
+ $data = $ftpinfo["data"];
1850
+ //extract relative FTP path
1851
+ $ftp_port = $data["port"];
1852
+ if ( $data["sftp"] && $ftp_port == "" ) $ftp_port = "22";
1853
+ $ftp_host = $data["ftpdomain"].( $ftp_port != "" ? ":".$ftp_port : "" );
1854
+ $ftp_username = str_replace('@', '%40', $data["username"]); //if username contains @ character then convert it to %40
1855
+ $ftp_password = str_replace('@', '%40', $data["password"]); //if password contains @ character then convert it to %40
1856
+ $start_folder = ( $data["sftp"] ? 's' : '' ).'ftp://'.$ftp_username.':'.$ftp_password."@".$ftp_host.'/';
1857
+ }
1858
+ else $start_folder = 'ftp://'.$params["ftpinfo"].'/';
1859
+ }
1860
+ else $start_folder = WP_CONTENT_DIR.'/';
1861
+ if ($path) {
1862
+ if ( $path == ".." || substr($path, 0, 3) == "../" ) {
1863
+ $start_folder = wfu_abspath();
1864
+ $path = substr($path, 2, strlen($path) - 2);
1865
+ }
1866
+ //remove additional parent folder symbols (..) in path so that the path does not go outside the $start_folder
1867
+ $path = str_replace('..', '', $path);
1868
+ if ( substr($path, 0, 1) == "/" ) $path = substr($path, 1, strlen($path) - 1);
1869
+ if ( substr($path, -1, 1) == "/" ) $path = substr($path, 0, strlen($path) - 1);
1870
+ $full_upload_path = $start_folder;
1871
+ if ( $path != "" ) $full_upload_path .= $path.'/';
1872
+ }
1873
+ else {
1874
+ $full_upload_path = $start_folder;
1875
+ }
1876
+ return $full_upload_path;
1877
+ }
1878
+
1879
+ /**
1880
+ * Get Full Upload Path.
1881
+ *
1882
+ * This function calculates the full upload path of an uploader shortcode from
1883
+ * its attributes.
1884
+ *
1885
+ * @since 2.1.2
1886
+ *
1887
+ * @param array $params The shortcode attributes.
1888
+ *
1889
+ * @return string The full upload path.
1890
+ */
1891
+ function wfu_upload_plugin_directory( $path ) {
1892
+ $dirparts = explode("/", $path);
1893
+ return $dirparts[count($dirparts) - 1];
1894
+ }
1895
+
1896
+ /**
1897
+ * Extract Additional Data From Complex Path.
1898
+ *
1899
+ * This function is used to extract sort, filename or filter information from
1900
+ * a complex path. A complex path is used by the plugin to pass additional
1901
+ * information between requests. In a complex path sort, filename and filter
1902
+ * information are stored as [[-sort]], {{filename}} and ((filter)).
1903
+ *
1904
+ * @since 2.2.1
1905
+ *
1906
+ * @param string $path The complex path.
1907
+ *
1908
+ * @return array {
1909
+ * Additional data extracted from path.
1910
+ *
1911
+ * @type string $path The clean path.
1912
+ * @type string $sort Sort information of a file list.
1913
+ * @type string $file Filename of a specific file.
1914
+ * @type string $filter Filter information of a file list.
1915
+ * }
1916
+ */
1917
+ function wfu_extract_sortdata_from_path($path) {
1918
+ $ret['path'] = $path;
1919
+ $ret['sort'] = "";
1920
+ $ret['file'] = "";
1921
+ $ret['filter'] = "";
1922
+ //extract sort info
1923
+ $pos1 = strpos($path, '[[');
1924
+ $pos2 = strpos($path, ']]');
1925
+ if ( $pos1 !== false && $pos2 !== false )
1926
+ if ( $pos2 > $pos1 ) {
1927
+ $ret['sort'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
1928
+ $ret['path'] = str_replace('[['.$ret['sort'].']]', '', $path);
1929
+ }
1930
+ //extract filename info
1931
+ $pos1 = strpos($path, '{{');
1932
+ $pos2 = strpos($path, '}}');
1933
+ if ( $pos1 !== false && $pos2 !== false )
1934
+ if ( $pos2 > $pos1 ) {
1935
+ $ret['file'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
1936
+ $ret['path'] = str_replace('{{'.$ret['file'].'}}', '', $path);
1937
+ }
1938
+ //extract filter info
1939
+ $pos1 = strpos($path, '((');
1940
+ $pos2 = strpos($path, '))');
1941
+ if ( $pos1 !== false && $pos2 !== false )
1942
+ if ( $pos2 > $pos1 ) {
1943
+ $ret['filter'] = substr($path, $pos1 + 2, $pos2 - $pos1 - 2);
1944
+ $ret['path'] = str_replace('(('.$ret['filter'].'))', '', $path);
1945
+ }
1946
+ return $ret;
1947
+ }
1948
+
1949
+ /**
1950
+ * Flatten A Complex Path.
1951
+ *
1952
+ * This function returns only the clean path from a complex path.
1953
+ *
1954
+ * @since 2.2.1
1955
+ *
1956
+ * @param string $path The complex path.
1957
+ *
1958
+ * @return string The clean path.
1959
+ */
1960
+ function wfu_flatten_path($path) {
1961
+ $ret = wfu_extract_sortdata_from_path($path);
1962
+ return $ret['path'];
1963
+ }
1964
+
1965
+ /**
1966
+ * Delete a Directory Recursively.
1967
+ *
1968
+ * This function deletes a directory recursively.
1969
+ *
1970
+ * @since 2.2.1
1971
+ *
1972
+ * @param string $dir The directory to delete.
1973
+ *
1974
+ * @return bool True if the deletion suceeded, false otherwise.
1975
+ */
1976
+ function wfu_delTree($dir) {
1977
+ $files = array_diff(scandir($dir), array('.','..'));
1978
+ foreach ($files as $file) {
1979
+ is_dir("$dir/$file") ? wfu_delTree("$dir/$file") : unlink("$dir/$file");
1980
+ }
1981
+ return rmdir($dir);
1982
+ }
1983
+
1984
+ /**
1985
+ * Get Top-Level Subdirectory Tree of a Directory.
1986
+ *
1987
+ * This function retrieves the first-level subdirectories of a directory.
1988
+ *
1989
+ * @since 2.7.1
1990
+ *
1991
+ * @param string $dir The directory to scan.
1992
+ *
1993
+ * @return array An array of subdirectories.
1994
+ */
1995
+ function wfu_getTree($dir) {
1996
+ $tree = array();
1997
+ $files = @scandir($dir);
1998
+ if ( !is_array($files) ) $files = array();
1999
+ $files = array_diff($files, array('.','..'));
2000
+ foreach ($files as $file) {
2001
+ if ( is_dir("$dir/$file") ) array_push($tree, $file);
2002
+ }
2003
+ return $tree;
2004
+ }
2005
+ /**
2006
+ * Parse List of Folders From subfoldertree Attribute.
2007
+ *
2008
+ * This function calculates the list of subfolders of a subfoldertree attribute
2009
+ * of an uploader shortcode.
2010
+ *
2011
+ * @since 2.4.1
2012
+ *
2013
+ * @redeclarable
2014
+ *
2015
+ * @param string $subfoldertree The subfoldertree attribute of the shortcode.
2016
+ *
2017
+ * @return array {
2018
+ * An array of folders.
2019
+ *
2020
+ * @type array $path An array of folder paths.
2021
+ * @type array $label An array of folder labels.
2022
+ * @type array $level An array of folder levels.
2023
+ * @type array $default An array defining which item is default.
2024
+ * }
2025
+ */
2026
+ function wfu_parse_folderlist($subfoldertree) {
2027
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2028
+ $ret['path'] = array();
2029
+ $ret['label'] = array();
2030
+ $ret['level'] = array();
2031
+ $ret['default'] = array();
2032
+
2033
+ if ( substr($subfoldertree, 0, 4) == "auto" ) return $ret;
2034
+ $subfolders = explode(",", $subfoldertree);
2035
+ if ( count($subfolders) == 0 ) return $ret;
2036
+ if ( count($subfolders) == 1 && trim($subfolders[0]) == "" ) return $ret;
2037
+ $dir_levels = array ( "root" );
2038
+ $prev_level = 0;
2039
+ $level0_count = 0;
2040
+ $default = -1;
2041
+ foreach ($subfolders as $subfolder) {
2042
+ $subfolder = trim($subfolder);
2043
+ $star_count = 0;
2044
+ $start_spaces = "";
2045
+ $is_default = false;
2046
+ //check for folder level
2047
+ while ( $star_count < strlen($subfolder) ) {
2048
+ if ( substr($subfolder, $star_count, 1) == "*" ) {
2049
+ $star_count ++;
2050
+ $start_spaces .= "&nbsp;&nbsp;&nbsp;";
2051
+ }
2052
+ else break;
2053
+ }
2054
+ if ( $star_count - $prev_level <= 1 && ( $star_count > 0 || $level0_count == 0 ) ) {
2055
+ $subfolder = substr($subfolder, $star_count, strlen($subfolder) - $star_count);
2056
+ // check for default value
2057
+ if ( substr($subfolder, 0, 1) == '&' ) {
2058
+ $subfolder = substr($subfolder, 1);
2059
+ $is_default = true;
2060
+ }
2061
+ //split item in folder path and folder name
2062
+ $subfolder_items = explode('/', $subfolder);
2063
+ if ( count($subfolder_items) > 1 && $subfolder_items[1] != "" ) {
2064
+ $subfolder_dir = $subfolder_items[0];
2065
+ $subfolder_label = $subfolder_items[1];
2066
+ }
2067
+ else {
2068
+ $subfolder_dir = $subfolder;
2069
+ $subfolder_label = $subfolder;
2070
+ }
2071
+ if ( $subfolder_dir != "" ) {
2072
+ // set is_default flag to true only for the first default item
2073
+ if ( $is_default && $default == -1 ) $default = count($ret['path']);
2074
+ else $is_default = false;
2075
+ // set flag that root folder has been included (so that it is not included it again)
2076
+ if ( $star_count == 0 ) $level0_count = 1;
2077
+ if ( count($dir_levels) > $star_count ) $dir_levels[$star_count] = $subfolder_dir;
2078
+ else array_push($dir_levels, $subfolder_dir);
2079
+ $subfolder_path = "";
2080
+ for ( $i_count = 1; $i_count <= $star_count; $i_count++) {
2081
+ $subfolder_path .= $dir_levels[$i_count].'/';
2082
+ }
2083
+ array_push($ret['path'], $subfolder_path);
2084
+ array_push($ret['label'], $subfolder_label);
2085
+ array_push($ret['level'], $star_count);
2086
+ array_push($ret['default'], $is_default);
2087
+ $prev_level = $star_count;
2088
+ }
2089
+ }
2090
+ }
2091
+
2092
+ return $ret;
2093
+ }
2094
+
2095
+ /**
2096
+ * Calculate Size of File.
2097
+ *
2098
+ * This function calculates the size of a file. It uses a complex approach for
2099
+ * calculating very big files (over 2GB) even in 32bit server environments.
2100
+ *
2101
+ * @since 2.6.0
2102
+ *
2103
+ * @param string $filepath The file path.
2104
+ *
2105
+ * @return The file size.
2106
+ */
2107
+ function wfu_filesize($filepath) {
2108
+ $fp = fopen($filepath, 'r');
2109
+ $pos = 0;
2110
+ if ($fp) {
2111
+ $size = 1073741824;
2112
+ fseek($fp, 0, SEEK_SET);
2113
+ while ($size > 1) {
2114
+ fseek($fp, $size, SEEK_CUR);
2115
+ if (fgetc($fp) === false) {
2116
+ fseek($fp, -$size, SEEK_CUR);
2117
+ $size = (int)($size / 2);
2118
+ }
2119
+ else {
2120
+ fseek($fp, -1, SEEK_CUR);
2121
+ $pos += $size;
2122
+ }
2123
+ }
2124
+ while (fgetc($fp) !== false) $pos++;
2125
+ fclose($fp);
2126
+ }
2127
+
2128
+ return $pos;
2129
+ }
2130
+
2131
+ /**
2132
+ * Alternative Calculate Size of File.
2133
+ *
2134
+ * This function calculates the size of a file following an alternative method.
2135
+ * Again, it uses a complex approach for calculating very big files (over 2GB)
2136
+ * even in 32bit server environments.
2137
+ *
2138
+ * @since 2.6.0
2139
+ *
2140
+ * @param string $filepath The file path.
2141
+ *
2142
+ * @return The file size.
2143
+ */
2144
+ function wfu_filesize2($filepath) {
2145
+ $fp = fopen($filepath, 'r');
2146
+ $return = false;
2147
+ if (is_resource($fp)) {
2148
+ if (PHP_INT_SIZE < 8) {
2149
+ // 32bit
2150
+ if (0 === fseek($fp, 0, SEEK_END)) {
2151
+ $return = 0.0;
2152
+ $step = 0x7FFFFFFF;
2153
+ while ($step > 0) {
2154
+ if (0 === fseek($fp, - $step, SEEK_CUR)) {
2155
+ $return += floatval($step);
2156
+ } else {
2157
+ $step >>= 1;
2158
+ }
2159
+ }
2160
+ }
2161
+ } elseif (0 === fseek($fp, 0, SEEK_END)) {
2162
+ // 64bit
2163
+ $return = ftell($fp);
2164
+ }
2165
+ fclose($fp);
2166
+ }
2167
+ return $return;
2168
+ }
2169
+
2170
+ /**
2171
+ * Set Read Position on File.
2172
+ *
2173
+ * This function sets read position on a file. It uses a complex approach for
2174
+ * allowing correct positioning of very big files (over 2GB) even in 32bit
2175
+ * server environments.
2176
+ *
2177
+ * @since 2.6.0
2178
+ *
2179
+ * @param string $fp The file handle of the file.
2180
+ * @param int $pos The read position to set.
2181
+ * @param int $first Optional. If non-zero then position will start from
2182
+ * beginning of file.
2183
+ */
2184
+ function wfu_fseek($fp, $pos, $first = 1) {
2185
+ // set to 0 pos initially, one-time
2186
+ if ( $first ) fseek($fp, 0, SEEK_SET);
2187
+
2188
+ // get pos float value
2189
+ $pos = floatval($pos);
2190
+
2191
+ // within limits, use normal fseek
2192
+ if ( $pos <= PHP_INT_MAX )
2193
+ fseek($fp, $pos, SEEK_CUR);
2194
+ // out of limits, use recursive fseek
2195
+ else {
2196
+ fseek($fp, PHP_INT_MAX, SEEK_CUR);
2197
+ $pos -= PHP_INT_MAX;
2198
+ wfu_fseek($fp, $pos, 0);
2199
+ }
2200
+ }
2201
+
2202
+ /**
2203
+ * Alternative Set Read Position on File.
2204
+ *
2205
+ * This function sets read position on a file following an alternative method.
2206
+ * Again, tt uses a complex approach for allowing correct positioning of very
2207
+ * big files (over 2GB) even in 32bit server environments.
2208
+ *
2209
+ * @since 2.6.0
2210
+ *
2211
+ * @param string $fp The file handle of the file.
2212
+ * @param int $pos The read position to set.
2213
+ *
2214
+ * @return int Upon success, returns 0 otherwise returns -1.
2215
+ */
2216
+ function wfu_fseek2($fp, $pos) {
2217
+ $pos = floatval($pos);
2218
+ if ( $pos <= PHP_INT_MAX ) {
2219
+ return fseek($fp, $pos, SEEK_SET);
2220
+ }
2221
+ else {
2222
+ $fsize = wfu_filesize2($filepath);
2223
+ $opp = $fsize - $pos;
2224
+ if ( 0 === ($ans = fseek($fp, 0, SEEK_END)) ) {
2225
+ $maxstep = 0x7FFFFFFF;
2226
+ $step = $opp;
2227
+ if ( $step > $maxstep ) $step = $maxstep;
2228
+ while ($step > 0) {
2229
+ if ( 0 === ($ans = fseek($fp, - $step, SEEK_CUR)) ) {
2230
+ $opp -= floatval($step);
2231
+ }
2232
+ else {
2233
+ $maxstep >>= 1;
2234
+ }
2235
+ $step = $opp;
2236
+ if ( $step > $maxstep ) $step = $maxstep;
2237
+ }
2238
+ }
2239
+ }
2240
+ return $ans;
2241
+ }
2242
+
2243
+ /**
2244
+ * Write Message to Debug Log.
2245
+ *
2246
+ * This function appends a message to the plugin's debug log file. This file is
2247
+ * located at /wp-content/debug_log.txt.
2248
+ *
2249
+ * @since 2.5.5
2250
+ *
2251
+ * @param string $message The message to log.
2252
+ */
2253
+ function wfu_debug_log($message) {
2254
+ $logpath = WP_CONTENT_DIR.'/debug_log.txt';
2255
+ file_put_contents($logpath, $message, FILE_APPEND);
2256
+ }
2257
+
2258
+ /**
2259
+ * Write Object Contents to Debug Log.
2260
+ *
2261
+ * This function appends the contents of an object to the plugin's debug log
2262
+ * file.
2263
+ *
2264
+ * @since 4.10.0
2265
+ *
2266
+ * @param mixed $obj The object to log.
2267
+ */
2268
+ function wfu_debug_log_obj($obj) {
2269
+ wfu_debug_log(print_r($obj, true));
2270
+ }
2271
+
2272
+ /**
2273
+ * Store Filepath to Safe.
2274
+ *
2275
+ * This function stores a file path into the current user's User Space and
2276
+ * returns a unique code corresponding to the file path. This process is used to
2277
+ * protect file paths from being exposed when needing to pass them as HTTP
2278
+ * request parameters.
2279
+ *
2280
+ * @since 3.0.0
2281
+ *
2282
+ * @param string $path The file path.
2283
+ *
2284
+ * @return The unique code coresponding to the file path.
2285
+ */
2286
+ function wfu_safe_store_filepath($path) {
2287
+ $code = wfu_create_random_string(16);
2288
+ $safe_storage = ( WFU_USVAR_exists('wfu_filepath_safe_storage') ? WFU_USVAR('wfu_filepath_safe_storage') : array() );
2289
+ $safe_storage[$code] = $path;
2290
+ WFU_USVAR_store('wfu_filepath_safe_storage', $safe_storage);
2291
+ return $code;
2292
+ }
2293
+
2294
+ /**
2295
+ * Retrieve Filepath from Safe.
2296
+ *
2297
+ * This function retrieves a file path, previously stored in current user's User
2298
+ * Space, based on its corresponding unique code.
2299
+ *
2300
+ * @since 3.0.0
2301
+ *
2302
+ * @param string $code The unique code.
2303
+ *
2304
+ * @return The file path coresponding to the code.
2305
+ */
2306
+ function wfu_get_filepath_from_safe($code) {
2307
+ //sanitize $code
2308
+ $code = wfu_sanitize_code($code);
2309
+ if ( $code == "" ) return false;
2310
+ //return filepath from session variable, if exists
2311
+ if ( !WFU_USVAR_exists('wfu_filepath_safe_storage') ) return false;
2312
+ $safe_storage = WFU_USVAR('wfu_filepath_safe_storage');
2313
+ if ( !isset($safe_storage[$code]) ) return false;
2314
+ return $safe_storage[$code];
2315
+ }
2316
+
2317
+ /**
2318
+ * Check if File Extension is Restricted.
2319
+ *
2320
+ * This function checks if the extension of a file name is restricted. It also
2321
+ * checks for double extensions. This function is not used anymore.
2322
+ *
2323
+ * @since 3.0.0
2324
+ * @deprecated 3.9.0 Use wfu_file_extension_blacklisted()
2325
+ * @see wfu_file_extension_blacklisted()
2326
+ *
2327
+ * @param string $filename The file name to check.
2328
+ *
2329
+ * @return bool True if extension is restricted, false otherwise.
2330
+ */
2331
+ function wfu_file_extension_restricted($filename) {
2332
+ return (
2333
+ substr($filename, -4) == ".php" ||
2334
+ substr($filename, -3) == ".js" ||
2335
+ substr($filename, -4) == ".pht" ||
2336
+ substr($filename, -5) == ".php3" ||
2337
+ substr($filename, -5) == ".php4" ||
2338
+ substr($filename, -5) == ".php5" ||
2339
+ substr($filename, -6) == ".phtml" ||
2340
+ substr($filename, -4) == ".htm" ||
2341
+ substr($filename, -5) == ".html" ||
2342
+ substr($filename, -9) == ".htaccess" ||
2343
+ strpos($filename, ".php.") !== false ||
2344
+ strpos($filename, ".js.") !== false ||
2345
+ strpos($filename, ".pht.") !== false ||
2346
+ strpos($filename, ".php3.") !== false ||
2347
+ strpos($filename, ".php4.") !== false ||
2348
+ strpos($filename, ".php5.") !== false ||
2349
+ strpos($filename, ".phtml.") !== false ||
2350
+ strpos($filename, ".htm.") !== false ||
2351
+ strpos($filename, ".html.") !== false ||
2352
+ strpos($filename, ".htaccess.") !== false
2353
+ );
2354
+ }
2355
+
2356
+ /**
2357
+ * Convert Time to Human-Readable Format.
2358
+ *
2359
+ * This function converts a time, given in integer format, into a human-readable
2360
+ * one providing number of days, hours, minutes and seconds.
2361
+ *
2362
+ * @since 4.0.0
2363
+ *
2364
+ * @param int $time The time to convert.
2365
+ *
2366
+ * @return string The time in human-readable format.
2367
+ */
2368
+ function wfu_human_time($time) {
2369
+ $time = (int)$time;
2370
+ $days = (int)($time/86400);
2371
+ $time -= $days * 86400;
2372
+ $hours = (int)($time/3600);
2373
+ $time -= $hours * 3600;
2374
+ $minutes = (int)($time/60);
2375
+ $secs = $time - $minutes * 60;
2376
+ $human_time = ( $days > 0 ? $days."d" : "" ).( $hours > 0 ? $hours."h" : "" ).( $minutes > 0 ? $minutes."m" : "" ).( $secs > 0 ? $secs."s" : "" );
2377
+ if ( $human_time == "" ) $human_time == "0s";
2378
+ return $human_time;
2379
+ }
2380
+
2381
+ /**
2382
+ * Convert File Size to Human-Readable Format.
2383
+ *
2384
+ * This function converts a file size, given in bytes, into a human-readable
2385
+ * format providing number of GBs, MBs, KBs and bytes.
2386
+ *
2387
+ * @since 3.1.0
2388
+ *
2389
+ * @param int $size The file size in bytes.
2390
+ * @param string $unit Optional. The size unit to use. It can be GB, MB, KB. If
2391
+ * it is omitted then it will be calculated automatically.
2392
+ *
2393
+ * @return string The file size in human-readable format.
2394
+ */
2395
+ function wfu_human_filesize($size, $unit = "") {
2396
+ if ( ( !$unit && $size >= 1<<30 ) || $unit == "GB" )
2397
+ return number_format($size / (1<<30), 2)."GB";
2398
+ if( ( !$unit && $size >= 1<<20 ) || $unit == "MB" )
2399
+ return number_format($size / (1<<20), 2)."MB";
2400
+ if( ( !$unit && $size >= 1<<10 ) || $unit == "KB" )
2401
+ return number_format($size / (1<<10), 2)."KB";
2402
+ return number_format($size)." bytes";
2403
+ }
2404
+
2405
+ /**
2406
+ * Check if File Exists Including Chunks.
2407
+ *
2408
+ * This function checks if a file exists. It will also return true if chunks of
2409
+ * a file still uploading exist.
2410
+ *
2411
+ * @since 4.12.0
2412
+ *
2413
+ * @param int $path The file path to check.
2414
+ *
2415
+ * @return bool True if file exists, false otherwise.
2416
+ */
2417
+ function wfu_file_exists_extended($path) {
2418
+ if ( wfu_file_exists($path) ) return true;
2419
+
2420
+ return false;
2421
+ }
2422
+
2423
+ /**
2424
+ * Check if File Exists.
2425
+ *
2426
+ * This function checks if a file exists. It is an extension to the original
2427
+ * PHP file_exists() function to take special actions in cases where the file
2428
+ * is stored in an sFTP location or perhaps in other external locations (cloud
2429
+ * services, WebDAV etc.).
2430
+ *
2431
+ * For the moment this functions will return false for a file stored in sFTP. In
2432
+ * a future release file_exists will be implemented for sFTP connections,
2433
+ * together with other relevant file functions, like filesize, fileperms, stat,
2434
+ * md5_file, mime_content_type, is_dir, pathinfo, unlink, getimagesize, unset.
2435
+ *
2436
+ * @since 3.9.3
2437
+ *
2438
+ * @param int $path The file path to check.
2439
+ *
2440
+ * @return bool True if file exists, false otherwise.
2441
+ */
2442
+ function wfu_file_exists($path) {
2443
+ //sftp will return false; in a future release file_exists will be
2444
+ //implemented for sftp connections, together with other relevant file
2445
+ //functions, like filesize, fileperms, stat, md5_file, mime_content_type,
2446
+ //is_dir, pathinfo, unlink, getimagesize, unset.
2447
+ if ( substr($path, 0, 7) == "sftp://" ) {
2448
+ return false;
2449
+ }
2450
+ elseif ( file_exists($path) ) return true;
2451
+
2452
+ return false;
2453
+ }
2454
+
2455
+ //********************* User Functions *****************************************
2456
+
2457
+ /**
2458
+ * Get Matching User Role.
2459
+ *
2460
+ * This function checks if any of the user's roles are included in a list of
2461
+ * roles. If the user is administrator it will match. If 'all' is included in
2462
+ * the list of roles then it will also match. The function returns the matched
2463
+ * role.
2464
+ *
2465
+ * @since 2.1.2
2466
+ *
2467
+ * @param object $user The user to check.
2468
+ * @param array $param_roles A list of roles to match the user.
2469
+ *
2470
+ * @return string The matching role, or 'nomatch'.
2471
+ */
2472
+ function wfu_get_user_role($user, $param_roles) {
2473
+ $result_role = 'nomatch';
2474
+ if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
2475
+ /* Go through the array of the roles of the current user */
2476
+ foreach ( $user->roles as $user_role ) {
2477
+ $user_role = strtolower($user_role);
2478
+ /* if this role matches to the roles in $param_roles or it is
2479
+ administrator or $param_roles allow all roles then it is
2480
+ approved */
2481
+ if ( in_array($user_role, $param_roles) || $user_role == 'administrator' || in_array('all', $param_roles) ) {
2482
+ /* We approve this role of the user and exit */
2483
+ $result_role = $user_role;
2484
+ break;
2485
+ }
2486
+ }
2487
+ }
2488
+ /* if the user has no roles (guest) and guests are allowed, then it is
2489
+ approved */
2490
+ elseif ( in_array('guests', $param_roles) ) {
2491
+ $result_role = 'guest';
2492
+ }
2493
+ return $result_role;
2494
+ }
2495
+
2496
+ /**
2497
+ * Get Valid User Roles.
2498
+ *
2499
+ * This function gets all user's valid roles by checking which of them are
2500
+ * included in $wp_roles global variable.
2501
+ *
2502
+ * @since 3.0.0
2503
+ *
2504
+ * @global array $wp_roles An array of Wordpress roles.
2505
+ *
2506
+ * @param object $user The user to check.
2507
+ *
2508
+ * @return array The list of user's valid roles.
2509
+ */
2510
+ function wfu_get_user_valid_role_names($user) {
2511
+ global $wp_roles;
2512
+
2513
+ $result_roles = array();
2514
+ if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
2515
+ /* get all valid roles */
2516
+ $roles = $wp_roles->get_names();
2517
+ /* Go through the array of the roles of the current user */
2518
+ foreach ( $user->roles as $user_role ) {
2519
+ $user_role = strtolower($user_role);
2520
+ /* If one role of the current user matches to the roles allowed to upload */
2521
+ if ( in_array($user_role, array_keys($roles)) ) array_push($result_roles, $user_role);
2522
+ }
2523
+ }
2524
+
2525
+ return $result_roles;
2526
+ }
2527
+
2528
+ //*********************** DB Functions *****************************************************************************************************
2529
+
2530
+ /**
2531
+ * Log Action to Database.
2532
+ *
2533
+ * This function logs plugin's actions (uploads, renames, deletions etc.) in the
2534
+ * plugin's database tables. This function stores upload information about all
2535
+ * uploaded files.
2536
+ *
2537
+ * @since 2.4.1
2538
+ *
2539
+ * @global object $wpdb The Wordpress database object.
2540
+ *
2541
+ * @param string $action The action to log.
2542
+ * @param string $filepath The file path of the involved file.
2543
+ * @param int $userid The ID of the user who performs the action.
2544
+ * @param string $uploadid The unique ID of the upload, if this is an upload
2545
+ * action.
2546
+ * @param int $pageid The ID of the upload page, if this is an upload action.
2547
+ * @param int $blogid The ID of the blog (in case this is a multisite
2548
+ * installation).
2549
+ * @param int $sid The plugin ID of the upload form, if this is an upload
2550
+ * action.
2551
+ * @param array $userdata {
2552
+ * Any additional user data to store with the uploaded files.
2553
+ *
2554
+ * @type array $userdata_field {
2555
+ * Individual user data field.
2556
+ *
2557
+ * @type string $label The title of the userdata field.
2558
+ * @type string $value The value entered by the user in the field.
2559
+ * }
2560
+ * }
2561
+ *
2562
+ * @return int The ID of the new record that was added in the database, or 0 if
2563
+ * no record was added.
2564
+ */
2565
+ function wfu_log_action($action, $filepath, $userid, $uploadid, $pageid, $blogid, $sid, $userdata) {
2566
+ global $wpdb;
2567
+ $table_name1 = $wpdb->prefix . "wfu_log";
2568
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
2569
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
2570
+
2571
+ if ( !file_exists($filepath) && $action != 'datasubmit' && substr($action, 0, 5) != 'other' ) return;
2572
+ $parts = pathinfo($filepath);
2573
+ $relativepath = wfu_path_abs2rel($filepath);
2574
+ // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
2575
+
2576
+ $retid = 0;
2577
+ if ( $action == 'upload' || $action == 'include' || $action == 'datasubmit' ) {
2578
+ if ( $action == 'upload' || $action == 'include' ) {
2579
+ // calculate and store file hash if this setting is enabled from Settings
2580
+ $filehash = '';
2581
+ if ( $plugin_options['hashfiles'] == '1' ) $filehash = md5_file($filepath);
2582
+ // calculate file size
2583
+ $filesize = filesize($filepath);
2584
+ // first make obsolete records having the same file path because the old file has been replaced
2585
+ $oldrecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND date_to = 0');
2586
+ if ( $oldrecs ) {
2587
+ foreach ( $oldrecs as $oldrec ) wfu_make_rec_obsolete($oldrec);
2588
+ }
2589
+ }
2590
+ // attempt to create new log record
2591
+ $now_date = date('Y-m-d H:i:s');
2592
+ if ( $wpdb->insert($table_name1,
2593
+ array(
2594
+ 'userid' => $userid,
2595
+ 'uploaduserid' => $userid,
2596
+ 'uploadtime' => time(),
2597
+ 'sessionid' => wfu_get_session_id(),
2598
+ 'filepath' => ( $action == 'datasubmit' ? '' : $relativepath ),
2599
+ 'filehash' => ( $action == 'datasubmit' ? '' : $filehash ),
2600
+ 'filesize' => ( $action == 'datasubmit' ? 0 : $filesize ),
2601
+ 'uploadid' => $uploadid,
2602
+ 'pageid' => $pageid,
2603
+ 'blogid' => $blogid,
2604
+ 'sid' => $sid,
2605
+ 'date_from' => $now_date,
2606
+ 'date_to' => 0,
2607
+ 'action' => $action
2608
+ ),
2609
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s' )) !== false ) {
2610
+ $retid = $wpdb->insert_id;
2611
+ // if new log record has been created, also create user data records
2612
+ if ( $userdata != null && $uploadid != '' ) {
2613
+ foreach ( $userdata as $userdata_key => $userdata_field ) {
2614
+ $existing = $wpdb->get_row('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$uploadid.'\' AND property = \''.esc_sql($userdata_field['label']).'\' AND date_to = 0');
2615
+ if ($existing == null)
2616
+ $wpdb->insert($table_name2,
2617
+ array(
2618
+ 'uploadid' => $uploadid,
2619
+ 'property' => $userdata_field['label'],
2620
+ 'propkey' => $userdata_key,
2621
+ 'propvalue' => $userdata_field['value'],
2622
+ 'date_from' => $now_date,
2623
+ 'date_to' => 0
2624
+ ),
2625
+ array( '%s', '%s', '%d', '%s', '%s', '%s' ));
2626
+ }
2627
+ }
2628
+ }
2629
+ }
2630
+ //for rename or move action the $action variable is of the form:
2631
+ // $action = 'rename:'.$newfilepath; (for rename action)
2632
+ // $action = 'move:'.$newfilepath; (for move action)
2633
+ //in order to pass the new file path
2634
+ elseif ( substr($action, 0, 6) == 'rename' || substr($action, 0, 4) == 'move' ) {
2635
+ $cleanaction = ( substr($action, 0, 6) == 'rename' ? 'rename' : 'move' );
2636
+ //get new filepath
2637
+ $newfilepath = substr($action, strlen($cleanaction) + 1);
2638
+ $relativepath = wfu_path_abs2rel($newfilepath);
2639
+ // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
2640
+ //get stored file data from database without user data
2641
+ $filerec = wfu_get_file_rec($filepath, false);
2642
+ //log action only if there are previous stored file data
2643
+ if ( $filerec != null ) {
2644
+ $now_date = date('Y-m-d H:i:s');
2645
+ //make previous record obsolete
2646
+ $wpdb->update($table_name1,
2647
+ array( 'date_to' => $now_date ),
2648
+ array( 'idlog' => $filerec->idlog ),
2649
+ array( '%s' ),
2650
+ array( '%d' )
2651
+ );
2652
+ //insert new rename record
2653
+ if ( $wpdb->insert($table_name1,
2654
+ array(
2655
+ 'userid' => $userid,
2656
+ 'uploaduserid' => $filerec->uploaduserid,
2657
+ 'uploadtime' => $filerec->uploadtime,
2658
+ 'sessionid' => $filerec->sessionid,
2659
+ 'filepath' => $relativepath,
2660
+ 'filehash' => $filerec->filehash,
2661
+ 'filesize' => $filerec->filesize,
2662
+ 'uploadid' => $filerec->uploadid,
2663
+ 'pageid' => $filerec->pageid,
2664
+ 'blogid' => $filerec->blogid,
2665
+ 'sid' => $filerec->sid,
2666
+ 'date_from' => $now_date,
2667
+ 'date_to' => 0,
2668
+ 'action' => $cleanaction,
2669
+ 'linkedto' => $filerec->idlog,
2670
+ 'filedata' => $filerec->filedata
2671
+ ),
2672
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' ) ) !== false )
2673
+ $retid = $wpdb->insert_id;
2674
+ }
2675
+ }
2676
+ elseif ( $action == 'delete' ) {
2677
+ //get stored file data from database without user data
2678
+ $filerec = wfu_get_file_rec($filepath, false);
2679
+ //log action only if there are previous stored file data
2680
+ if ( $filerec != null ) {
2681
+ $now_date = date('Y-m-d H:i:s');
2682
+ //make previous record obsolete
2683
+ $wpdb->update($table_name1,
2684
+ array( 'date_to' => $now_date ),
2685
+ array( 'idlog' => $filerec->idlog ),
2686
+ array( '%s' ),
2687
+ array( '%d' )
2688
+ );
2689
+ //insert new delete record
2690
+ if ( $wpdb->insert($table_name1,
2691
+ array(
2692
+ 'userid' => $userid,
2693
+ 'uploaduserid' => $filerec->uploaduserid,
2694
+ 'uploadtime' => $filerec->uploadtime,
2695
+ 'sessionid' => $filerec->sessionid,
2696
+ 'filepath' => $filerec->filepath,
2697
+ 'filehash' => $filerec->filehash,
2698
+ 'filesize' => $filerec->filesize,
2699
+ 'uploadid' => $filerec->uploadid,
2700
+ 'pageid' => $filerec->pageid,
2701
+ 'blogid' => $filerec->blogid,
2702
+ 'sid' => $filerec->sid,
2703
+ 'date_from' => $now_date,
2704
+ 'date_to' => $now_date,
2705
+ 'action' => 'delete',
2706
+ 'linkedto' => $filerec->idlog,
2707
+ 'filedata' => $filerec->filedata
2708
+ ),
2709
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
2710
+ $retid = $wpdb->insert_id;
2711
+ }
2712
+ }
2713
+ elseif ( $action == 'download' ) {
2714
+ //get stored file data from database without user data
2715
+ $filerec = wfu_get_file_rec($filepath, false);
2716
+ //log action only if there are previous stored file data
2717
+ if ( $filerec != null ) {
2718
+ $now_date = date('Y-m-d H:i:s');
2719
+ //make previous record obsolete
2720
+ $wpdb->update($table_name1,
2721
+ array( 'date_to' => $now_date ),
2722
+ array( 'idlog' => $filerec->idlog ),
2723
+ array( '%s' ),
2724
+ array( '%d' )
2725
+ );
2726
+ //insert new download record
2727
+ if ( $wpdb->insert($table_name1,
2728
+ array(
2729
+ 'userid' => $userid,
2730
+ 'uploaduserid' => $filerec->uploaduserid,
2731
+ 'uploadtime' => $filerec->uploadtime,
2732
+ 'sessionid' => $filerec->sessionid,
2733
+ 'filepath' => $filerec->filepath,
2734
+ 'filehash' => $filerec->filehash,
2735
+ 'filesize' => $filerec->filesize,
2736
+ 'uploadid' => $filerec->uploadid,
2737
+ 'pageid' => $filerec->pageid,
2738
+ 'blogid' => $filerec->blogid,
2739
+ 'sid' => $filerec->sid,
2740
+ 'date_from' => $now_date,
2741
+ 'date_to' => 0,
2742
+ 'action' => 'download',
2743
+ 'linkedto' => $filerec->idlog,
2744
+ 'filedata' => $filerec->filedata
2745
+ ),
2746
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
2747
+ $retid = $wpdb->insert_id;
2748
+ }
2749
+ }
2750
+ //for modify action the $action variable is of the form: $action = 'modify:'.$now_date; in order to pass the exact modify date
2751
+ elseif ( substr($action, 0, 6) == 'modify' ) {
2752
+ $now_date = substr($action, 7);
2753
+ //get stored file data from database without user data
2754
+ $filerec = wfu_get_file_rec($filepath, false);
2755
+ //log action only if there are previous stored file data
2756
+ if ( $filerec != null ) {
2757
+ //make previous record obsolete
2758
+ $wpdb->update($table_name1,
2759
+ array( 'date_to' => $now_date ),
2760
+ array( 'idlog' => $filerec->idlog ),
2761
+ array( '%s' ),
2762
+ array( '%d' )
2763
+ );
2764
+ //insert new modify record
2765
+ if ( $wpdb->insert($table_name1,
2766
+ array(
2767
+ 'userid' => $userid,
2768
+ 'uploaduserid' => $filerec->uploaduserid,
2769
+ 'uploadtime' => $filerec->uploadtime,
2770
+ 'sessionid' => $filerec->sessionid,
2771
+ 'filepath' => $filerec->filepath,
2772
+ 'filehash' => $filerec->filehash,
2773
+ 'filesize' => $filerec->filesize,
2774
+ 'uploadid' => $filerec->uploadid,
2775
+ 'pageid' => $filerec->pageid,
2776
+ 'blogid' => $filerec->blogid,
2777
+ 'sid' => $filerec->sid,
2778
+ 'date_from' => $now_date,
2779
+ 'date_to' => 0,
2780
+ 'action' => 'modify',
2781
+ 'linkedto' => $filerec->idlog,
2782
+ 'filedata' => $filerec->filedata
2783
+ ),
2784
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
2785
+ $retid = $wpdb->insert_id;
2786
+ }
2787
+ }
2788
+ elseif ( substr($action, 0, 10) == 'changeuser' ) {
2789
+ $new_user = substr($action, 11);
2790
+ //get stored file data from database without user data
2791
+ $filerec = wfu_get_file_rec($filepath, false);
2792
+ //log action only if there are previous stored file data
2793
+ if ( $filerec != null ) {
2794
+ $now_date = date('Y-m-d H:i:s');
2795
+ //make previous record obsolete
2796
+ $wpdb->update($table_name1,
2797
+ array( 'date_to' => $now_date ),
2798
+ array( 'idlog' => $filerec->idlog ),
2799
+ array( '%s' ),
2800
+ array( '%d' )
2801
+ );
2802
+ //insert new modify record
2803
+ if ( $wpdb->insert($table_name1,
2804
+ array(
2805
+ 'userid' => $userid,
2806
+ 'uploaduserid' => $new_user,
2807
+ 'uploadtime' => $filerec->uploadtime,
2808
+ 'sessionid' => $filerec->sessionid,
2809
+ 'filepath' => $filerec->filepath,
2810
+ 'filehash' => $filerec->filehash,
2811
+ 'filesize' => $filerec->filesize,
2812
+ 'uploadid' => $filerec->uploadid,
2813
+ 'pageid' => $filerec->pageid,
2814
+ 'blogid' => $filerec->blogid,
2815
+ 'sid' => $filerec->sid,
2816
+ 'date_from' => $now_date,
2817
+ 'date_to' => 0,
2818
+ 'action' => 'changeuser',
2819
+ 'linkedto' => $filerec->idlog,
2820
+ 'filedata' => $filerec->filedata
2821
+ ),
2822
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s' )) != false )
2823
+ $retid = $wpdb->insert_id;
2824
+ }
2825
+ }
2826
+ elseif ( substr($action, 0, 5) == 'other' ) {
2827
+ $info = substr($action, 6);
2828
+ $now_date = date('Y-m-d H:i:s');
2829
+ //insert new other type record
2830
+ if ( $wpdb->insert($table_name1,
2831
+ array(
2832
+ 'userid' => $userid,
2833
+ 'uploaduserid' => -1,
2834
+ 'uploadtime' => 0,
2835
+ 'sessionid' => '',
2836
+ 'filepath' => $info,
2837
+ 'filehash' => '',
2838
+ 'filesize' => 0,
2839
+ 'uploadid' => '',
2840
+ 'pageid' => 0,
2841
+ 'blogid' => 0,
2842
+ 'sid' => '',
2843
+ 'date_from' => $now_date,
2844
+ 'date_to' => $now_date,
2845
+ 'action' => 'other',
2846
+ 'linkedto' => -1
2847
+ ),
2848
+ array( '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d' )) != false )
2849
+ $retid = $wpdb->insert_id;
2850
+ }
2851
+ return $retid;
2852
+ }
2853
+
2854
+ /**
2855
+ * Revert Database Log Action.
2856
+ *
2857
+ * This function reverts an action that was recently added in the database. It
2858
+ * will also make effective the before-the-last one.
2859
+ *
2860
+ * @since 2.4.1
2861
+ *
2862
+ * @global object $wpdb The Wordpress database object.
2863
+ *
2864
+ * @param int $idlog The ID of the database record to revert.
2865
+ */
2866
+ function wfu_revert_log_action($idlog) {
2867
+ global $wpdb;
2868
+ $table_name1 = $wpdb->prefix . "wfu_log";
2869
+
2870
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
2871
+ if ( $filerec != null ) {
2872
+ $prevfilerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$filerec->linkedto);
2873
+ if ( $prevfilerec != null ) {
2874
+ $wpdb->delete($table_name1,
2875
+ array( 'idlog' => $filerec->idlog ),
2876
+ array( '%d' )
2877
+ );
2878
+ $wpdb->update($table_name1,
2879
+ array( 'date_to' => 0 ),
2880
+ array( 'idlog' => $prevfilerec->idlog ),
2881
+ array( '%s' ),
2882
+ array( '%d' )
2883
+ );
2884
+ }
2885
+ }
2886
+ }
2887
+
2888
+ /**
2889
+ * Get User Name by ID.
2890
+ *
2891
+ * This function retrieves a user's username by its ID. It will always return a
2892
+ * non-empty username, even if user is not found.
2893
+ *
2894
+ * @since 2.4.1
2895
+ *
2896
+ * @redeclarable
2897
+ *
2898
+ * @param int $id The ID of the user.
2899
+ *
2900
+ * @return string The username.
2901
+ */
2902
+ function wfu_get_username_by_id($id) {
2903
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2904
+ $user = get_user_by('id', $id);
2905
+ if ( $user == false && $id > 0 ) $username = 'unknown';
2906
+ elseif ( $user == false && $id == -999 ) $username = 'system';
2907
+ elseif ( $user == false ) $username = 'guest';
2908
+ else $username = $user->user_login;
2909
+ return $username;
2910
+ }
2911
+
2912
+ /**
2913
+ * Get Number of Unread Files.
2914
+ *
2915
+ * This function retrieves the number of uploaded files that have not been read
2916
+ * by the administrator (admin has not opened Uploaded Files page in Dashboard
2917
+ * to review them).
2918
+ *
2919
+ * @since 4.7.0
2920
+ *
2921
+ * @global object $wpdb The Wordpress database object.
2922
+ *
2923
+ * @redeclarable
2924
+ *
2925
+ * @return int The number of unread files.
2926
+ */
2927
+ function wfu_get_unread_files_count() {
2928
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2929
+ global $wpdb;
2930
+ $table_name1 = $wpdb->prefix . "wfu_log";
2931
+
2932
+ //get the last idlog read from options; create the option if it does not
2933
+ //exist pointing to the currently last idlog
2934
+ $last_idlog = get_option( "wordpress_file_upload_last_idlog" );
2935
+ if ( $last_idlog === false ) {
2936
+ $latest_idlog = $wpdb->get_var('SELECT MAX(idlog) FROM '.$table_name1);
2937
+ $last_idlog = array( 'pre' => $latest_idlog, 'post' => $latest_idlog, 'time' => time() );
2938
+ update_option( "wordpress_file_upload_last_idlog", $last_idlog );
2939
+ }
2940
+ $limit = (int)WFU_VAR("WFU_UPLOADEDFILES_RESET_TIME");
2941
+ $unread_files_count = 0;
2942
+ if ( $limit == -1 || time() > $last_idlog["time"] + $limit ) $unread_files_count = wfu_get_new_files_count($last_idlog["post"]);
2943
+ else $unread_files_count = wfu_get_new_files_count($last_idlog["pre"]);
2944
+
2945
+ return $unread_files_count;
2946
+ }
2947
+
2948
+ /**
2949
+ * Get Number of New Uploaded Files.
2950
+ *
2951
+ * This function retrieves the number of newly uploaded files by counting how
2952
+ * many where uploaded after a specific database record ID.
2953
+ *
2954
+ * @since 4.8.0
2955
+ *
2956
+ * @global object $wpdb The Wordpress database object.
2957
+ *
2958
+ * @redeclarable
2959
+ *
2960
+ * @param int $last_idlog The database record ID which is the base for counting.
2961
+ *
2962
+ * @return int The number of new uploaded files.
2963
+ */
2964
+ function wfu_get_new_files_count($last_idlog) {
2965
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2966
+ global $wpdb;
2967
+ $table_name1 = $wpdb->prefix . "wfu_log";
2968
+ return $wpdb->get_var('SELECT COUNT(idlog) FROM '.$table_name1.' WHERE action = \'upload\' AND idlog > '.(int)$last_idlog);
2969
+ }
2970
+
2971
+ /**
2972
+ * Decode Raw File Transfers Log Data.
2973
+ *
2974
+ * This function converts raw file transfers log data stored in filedata field
2975
+ * of a file's database record into a structured array.
2976
+ *
2977
+ * @since 4.9.0
2978
+ *
2979
+ * @redeclarable
2980
+ *
2981
+ * @param string $data The raw log data.
2982
+ *
2983
+ * @return array {
2984
+ * An array of file transfers log information.
2985
+ *
2986
+ * $type string $service The cloud service used for the file transfer.
2987
+ * $type bool $transferred True if the file transfer was successful.
2988
+ * $type string $error Error message if the file transfer failed.
2989
+ * $type string $destination The destination path of the transfer.
2990
+ * $type string $new_filename The new file name of the transferred file.
2991
+ * }
2992
+ */
2993
+ function wfu_read_log_data($data) {
2994
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
2995
+ $ret['service'] = "";
2996
+ $ret['transferred'] = "";
2997
+ $ret['error'] = "";
2998
+ $ret['destination'] = "";
2999
+ $ret['new_filename'] = "";
3000
+ if ( substr($data, 0, 5) == "json:" ) {
3001
+ $logdata = json_decode(substr($data, 5), true);
3002
+ $ret['service'] = $logdata["service"];
3003
+ $ret['transferred'] = $logdata["transferred"];
3004
+ $ret['error'] = $logdata["error"];
3005
+ $ret['destination'] = $logdata["destination"];
3006
+ $ret['new_filename'] = $logdata["new_filename"];
3007
+ }
3008
+ else list($ret['service'], $ret['destination']) = explode("|", $data);
3009
+
3010
+ return $ret;
3011
+ }
3012
+
3013
+ /**
3014
+ * Get Database File Record From File Path.
3015
+ *
3016
+ * This function gets the most current database record of an uploaded file from
3017
+ * its path and also includes any userdata.
3018
+ *
3019
+ * @since 2.4.1
3020
+ *
3021
+ * @global object $wpdb The Wordpress database object.
3022
+ *
3023
+ * @param string $filepath The path of the file.
3024
+ * @param bool $include_userdata Include any userdata information in the
3025
+ * returned record.
3026
+ *
3027
+ * @return object|null The database object of the file, or null if it is not
3028
+ * found.
3029
+ */
3030
+ function wfu_get_file_rec($filepath, $include_userdata) {
3031
+ global $wpdb;
3032
+ $table_name1 = $wpdb->prefix . "wfu_log";
3033
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3034
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3035
+
3036
+ if ( !file_exists($filepath) ) return null;
3037
+
3038
+ $relativepath = wfu_path_abs2rel($filepath);
3039
+ // if ( substr($relativepath, 0, 1) != '/' ) $relativepath = '/'.$relativepath;
3040
+ //if file hash is enabled, then search file based on its path and hash, otherwise find file based on its path and size
3041
+ if ( isset($plugin_options['hashfiles']) && $plugin_options['hashfiles'] == '1' ) {
3042
+ $filehash = md5_file($filepath);
3043
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND filehash = \''.$filehash.'\' AND date_to = 0 ORDER BY date_from DESC');
3044
+ }
3045
+ else {
3046
+ $stat = stat($filepath);
3047
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE filepath = \''.esc_sql($relativepath).'\' AND filesize = '.$stat['size'].' AND date_to = 0 ORDER BY date_from DESC');
3048
+ }
3049
+ //get user data
3050
+ if ( $filerec != null && $include_userdata ) {
3051
+ $filerec->userdata = null;
3052
+ if ( $filerec->uploadid != '' ) {
3053
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
3054
+ }
3055
+ }
3056
+ return $filerec;
3057
+ }
3058
+
3059
+ /**
3060
+ * Get Valid Files From a List of Database Records.
3061
+ *
3062
+ * This function checks which records in a given list of database records of
3063
+ * uploaded files contain valid files and returns their file paths.
3064
+ *
3065
+ * @since 4.9.1
3066
+ *
3067
+ * @param array $recs An array of database records of uploaded files.
3068
+ *
3069
+ * @return array An array of file paths of valid files.
3070
+ */
3071
+ function wfu_get_valid_affected_files($recs) {
3072
+ $valid_affected_files = array();
3073
+ $files_checked = array();
3074
+ foreach ($recs as $rec)
3075
+ if ( $latestrec = wfu_get_latest_rec_from_id($rec->idlog) ) {
3076
+ $file = wfu_path_rel2abs($latestrec->filepath);
3077
+ if ( !in_array($file, $files_checked) ) {
3078
+ if ( file_exists($file) ) array_push($valid_affected_files, $file);
3079
+ array_push($files_checked, $file);
3080
+ }
3081
+ }
3082
+
3083
+ return $valid_affected_files;
3084
+ }
3085
+
3086
+ /**
3087
+ * Get Database File Record From Record ID.
3088
+ *
3089
+ * This function gets the database record of an uploaded file from its record ID
3090
+ * and also includes any userdata.
3091
+ *
3092
+ * @since 3.9.4
3093
+ *
3094
+ * @global object $wpdb The Wordpress database object.
3095
+ *
3096
+ * @param int $idlog The database record ID.
3097
+ * @param bool $include_userdata Optional. Include any userdata information in
3098
+ * the returned record.
3099
+ *
3100
+ * @return object|null The database object of the file, or null if it is not
3101
+ * found.
3102
+ */
3103
+ function wfu_get_file_rec_from_id($idlog, $include_userdata = false) {
3104
+ global $wpdb;
3105
+ $table_name1 = $wpdb->prefix . "wfu_log";
3106
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3107
+
3108
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
3109
+ if ( $filerec != null && $include_userdata ) {
3110
+ $filerec->userdata = null;
3111
+ if ( $filerec->uploadid != '' ) {
3112
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
3113
+ }
3114
+ }
3115
+
3116
+ return $filerec;
3117
+ }
3118
+
3119
+ /**
3120
+ * Get Userdata of Uploaded File by Database Record ID.
3121
+ *
3122
+ * This function gets the userdata (if any) of an uploaded file from its
3123
+ * database record ID.
3124
+ *
3125
+ * @since 4.6.0
3126
+ *
3127
+ * @param int $idlog The database record ID.
3128
+ *
3129
+ * @return array {
3130
+ * An array of userdata.
3131
+ *
3132
+ * @type $arrayitem {
3133
+ * An individual userdata field.
3134
+ *
3135
+ * @type string $property The title of the userdata field.
3136
+ * @type string $value The value entered by the user in the field.
3137
+ * }
3138
+ * }
3139
+ */
3140
+ function wfu_get_userdata_from_id($idlog) {
3141
+ $userdata = array();
3142
+ $filerec = wfu_get_file_rec_from_id($idlog, true);
3143
+ if ( $filerec != null && $filerec->userdata != null )
3144
+ foreach ( $filerec->userdata as $item ) {
3145
+ $arrayitem = array(
3146
+ "property" => $item->property,
3147
+ "value" => $item->propvalue
3148
+ );
3149
+ array_push($userdata, $arrayitem);
3150
+ }
3151
+
3152
+ return $userdata;
3153
+ }
3154
+
3155
+ /**
3156
+ * Get Oldest Database Record From Unique ID.
3157
+ *
3158
+ * Every file upload has a unique ID. This unique ID remains the same for any
3159
+ * consecutive operations that happen on the file (renaming, transfer, deletion
3160
+ * etc.). This function gets the oldest (first) record related to this unique
3161
+ * ID, which is usually an 'upload' or 'include' action.
3162
+ *
3163
+ * @since 4.10.0
3164
+ *
3165
+ * @global object $wpdb The Wordpress database object.
3166
+ *
3167
+ * @param string $uniqueid The unique ID of the upload.
3168
+ *
3169
+ * @return object|null The oldest database record, or null if not found.
3170
+ */
3171
+ function wfu_get_oldestrec_from_uniqueid($uniqueid) {
3172
+ global $wpdb;
3173
+ $table_name1 = $wpdb->prefix . "wfu_log";
3174
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE idlog IN (SELECT MIN(idlog) FROM '.$table_name1.' WHERE uploadid = \''.$uniqueid.'\')');
3175
+ if ( $filerecs == null ) return null;
3176
+ if ( count($filerecs) > 0 ) return $filerecs[0];
3177
+ else return null;
3178
+ }
3179
+
3180
+ /**
3181
+ * Get Latest Database Record From Record ID.
3182
+ *
3183
+ * This function gets the most recend (latest) record of a linked series of
3184
+ * database upload records having the same unique ID. Every record is linked to
3185
+ * its newer one through 'linkedto' field.
3186
+ *
3187
+ * @since 4.2.0
3188
+ *
3189
+ * @global object $wpdb The Wordpress database object.
3190
+ *
3191
+ * @param int $idlog The database record ID.
3192
+ *
3193
+ * @return object|null The latest database record, or null if not found.
3194
+ */
3195
+ function wfu_get_latest_rec_from_id($idlog) {
3196
+ global $wpdb;
3197
+ $table_name1 = $wpdb->prefix . "wfu_log";
3198
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
3199
+ while ( $filerec != null && $filerec->date_to != "0000-00-00 00:00:00" )
3200
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE linkedto = '.$filerec->idlog);
3201
+
3202
+ return $filerec;
3203
+ }
3204
+
3205
+ /**
3206
+ * Get Newer Linked Database Records From Record ID.
3207
+ *
3208
+ * This function gets the newer records of a linked series of database upload
3209
+ * records having the same unique ID. Every record is linked to its newer one
3210
+ * through 'linkedto' field.
3211
+ *
3212
+ * @since 4.7.0
3213
+ *
3214
+ * @global object $wpdb The Wordpress database object.
3215
+ *
3216
+ * @param int $idlog The database record ID.
3217
+ *
3218
+ * @return array An array of newer linked database records.
3219
+ */
3220
+ function wfu_get_rec_new_history($idlog) {
3221
+ global $wpdb;
3222
+ $table_name1 = $wpdb->prefix . "wfu_log";
3223
+ $filerecs = array();
3224
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
3225
+ while ( $filerec != null ) {
3226
+ array_push($filerecs, $filerec);
3227
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE linkedto = '.$filerec->idlog);
3228
+ }
3229
+
3230
+ return $filerecs;
3231
+ }
3232
+
3233
+ /**
3234
+ * Get Older Linked Database Records From Record ID.
3235
+ *
3236
+ * This function gets the older records of a linked series of database upload
3237
+ * records having the same unique ID. Every record is linked to its newer one
3238
+ * through 'linkedto' field.
3239
+ *
3240
+ * @since 4.7.0
3241
+ *
3242
+ * @global object $wpdb The Wordpress database object.
3243
+ *
3244
+ * @param int $idlog The database record ID.
3245
+ *
3246
+ * @return array An array of older linked database records.
3247
+ */
3248
+ function wfu_get_rec_old_history($idlog) {
3249
+ global $wpdb;
3250
+ $table_name1 = $wpdb->prefix . "wfu_log";
3251
+ $filerecs = array();
3252
+ $filerec = $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$idlog);
3253
+ while ( $filerec != null ) {
3254
+ array_push($filerecs, $filerec);
3255
+ $filerec = ( $filerec->linkedto > 0 ? $wpdb->get_row('SELECT * FROM '.$table_name1.' WHERE idlog = '.$filerec->linkedto) : null );
3256
+ }
3257
+
3258
+ return $filerecs;
3259
+ }
3260
+
3261
+ /**
3262
+ * Get Latest Filedata Properties From Database Record ID
3263
+ *
3264
+ * This function uses an uploaded file's database record ID to return the
3265
+ * filedata property of the corresponding record of the file in the database
3266
+ * holding data about its transfer to a service account like Dropbox, provided
3267
+ * that this record is still valid. If the record does not exist or exists but
3268
+ * it is absolete, then the function returns null, otherwise it returns an
3269
+ * array.
3270
+ *
3271
+ * The [$service]["filepath"] item of the array is set to the final $filepath
3272
+ * of the file, in case that the original filename was renamed.
3273
+ *
3274
+ * @since 4.2.0
3275
+ *
3276
+ * @param int $idlog Database record ID of the uploaded file.
3277
+ * @param bool $is_new Optional. It must be true if the function is called
3278
+ * during addition of a new file.
3279
+ *
3280
+ * @return array|null Returns the filedata array or null if it is not found.
3281
+ */
3282
+ function wfu_get_latest_filedata_from_id($idlog, $is_new = false) {
3283
+ //get latest database record of file, if it is still valid
3284
+ $filerec = wfu_get_latest_rec_from_id($idlog);
3285
+ //return null if the record does not exist or it is obsolete
3286
+ if ( $filerec == null ) return null;
3287
+
3288
+ return wfu_get_filedata_from_rec($filerec, $is_new, true, false);
3289
+ }
3290
+
3291
+ /**
3292
+ * Get Filedata Properties From File Path
3293
+ *
3294
+ * This function uses an uploaded file's path to return the filedata property of
3295
+ * the corresponding record of the file in the database holding data about its
3296
+ * transfer to a service account like Dropbox, provided that this record is
3297
+ * still valid.
3298
+ *
3299
+ * @since 4.2.0
3300
+ *
3301
+ * @param string $filepath The path of the uploaded file.
3302
+ * @param bool $include_general_data Optional. Determines whether general upload
3303
+ * data will be included in the returned filedata structure.
3304
+ *
3305
+ * @return array|null Returns the filedata array or null if it is not found.
3306
+ */
3307
+ function wfu_get_filedata($filepath, $include_general_data = false) {
3308
+ $filerec = wfu_get_file_rec($filepath, false);
3309
+ if ( $filerec == null ) return null;
3310
+
3311
+ return wfu_get_filedata_from_rec($filerec, true, false, $include_general_data);
3312
+ }
3313
+
3314
+ /**
3315
+ * Get Filedata Properties From Database Record
3316
+ *
3317
+ * This function uses an uploaded file's database record to return the filedata
3318
+ * property of the corresponding record of the file in the database holding data
3319
+ * about its transfer to a service account like Dropbox, provided that this
3320
+ * record is still valid.
3321
+ *
3322
+ * @since 4.3.0
3323
+ *
3324
+ * @param object $filerec The database record of the uploaded file.
3325
+ * @param bool $is_new Optional. It must be true if the function is called
3326
+ * during addition of a new file.
3327
+ * @param bool $update_transfer Optional. Update filepath property in filedata
3328
+ * of "transfer" type, if service records exist.
3329
+ * @param bool $include_general_data Optional. Determines whether general upload
3330
+ * data will be included in the returned filedata structure.
3331
+ *
3332
+ * @return array|null Returns the filedata array or null if it is not found.
3333
+ */
3334
+ function wfu_get_filedata_from_rec($filerec, $is_new = false, $update_transfer = false, $include_general_data = false) {
3335
+ //return filedata, if it does not exist and we do not want to create a new
3336
+ //filedata structure return null, otherwise return an empty array
3337
+ if ( !isset($filerec->filedata) || is_null($filerec->filedata) ) $filedata = ( $is_new ? array() : null );
3338
+ else {
3339
+ $filedata = wfu_decode_array_from_string($filerec->filedata);
3340
+ if ( !is_array($filedata) ) $filedata = ( $is_new ? array() : null );
3341
+ }
3342
+ if ( !is_null($filedata) ) {
3343
+ //update filepath property in filedata of "transfer" type, if service
3344
+ //records exist
3345
+ if ( $update_transfer ) {
3346
+ foreach ( $filedata as $key => $data )
3347
+ if ( !isset($data["type"]) || $data["type"] == "transfer" )
3348
+ $filedata[$key]["filepath"] = $filerec->filepath;
3349
+ }
3350
+ //add idlog in filedata if $include_general_data is true
3351
+ if ( $include_general_data )
3352
+ $filedata["general"] = array(
3353
+ "type" => "data",
3354
+ "idlog" => $filerec->idlog
3355
+ );
3356
+ }
3357
+
3358
+ return $filedata;
3359
+ }
3360
+
3361
+ /**
3362
+ * Save Filedata To File Database Record
3363
+ *
3364
+ * This function updates the filedata field of the database record of an
3365
+ * uploaded file.
3366
+ *
3367
+ * @since 4.2.0
3368
+ *
3369
+ * @global object $wpdb The Wordpress database object.
3370
+ *
3371
+ * @param int $idlog The database record ID of the uploaded file to be updated.
3372
+ * @param array $filedata The new filedata structure to store.
3373
+ * @param bool $store_in_latest_rec Optional. Store in the latest linked
3374
+ * database record and not the current one.
3375
+ *
3376
+ * @return bool|int Returns false if errors, or the number of rows affected if
3377
+ * successful.
3378
+ */
3379
+ function wfu_save_filedata_from_id($idlog, $filedata, $store_in_latest_rec = true) {
3380
+ global $wpdb;
3381
+ $table_name1 = $wpdb->prefix . "wfu_log";
3382
+ if ( $store_in_latest_rec ) {
3383
+ $latestrec = wfu_get_latest_rec_from_id($idlog);
3384
+ $idlog = $latestrec->idlog;
3385
+ }
3386
+ return $wpdb->update($table_name1, array( 'filedata' => wfu_encode_array_to_string($filedata) ), array( 'idlog' => $idlog ), array( '%s' ), array( '%d' ));
3387
+ }
3388
+
3389
+ /**
3390
+ * Get Userdata of Uploaded File From Database Record.
3391
+ *
3392
+ * This function gets the database record of an uploaded file from its database
3393
+ * record.
3394
+ *
3395
+ * @since 4.7.0
3396
+ *
3397
+ * @see wfu_get_userdata_from_id() For more information on the response array
3398
+ * format.
3399
+ *
3400
+ * @global object $wpdb The Wordpress database object.
3401
+ *
3402
+ * @param object $filerec The database record of the uploaded file.
3403
+ *
3404
+ * @return array An array of userdata.
3405
+ */
3406
+ function wfu_get_userdata_from_rec($filerec) {
3407
+ global $wpdb;
3408
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3409
+
3410
+ $userdata = array();
3411
+ if ( $filerec->uploadid != '' ) {
3412
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
3413
+ if ( $filerec->userdata != null )
3414
+ foreach ( $filerec->userdata as $item ) {
3415
+ $arrayitem = array(
3416
+ "property" => $item->property,
3417
+ "value" => $item->propvalue
3418
+ );
3419
+ array_push($userdata, $arrayitem);
3420
+ }
3421
+ }
3422
+
3423
+ return $userdata;
3424
+ }
3425
+
3426
+ /**
3427
+ * Get Userdata of Uploaded File From Unique ID.
3428
+ *
3429
+ * This function gets the database record of an uploaded file from the unique ID
3430
+ * of the upload.
3431
+ *
3432
+ * @since 3.11.0
3433
+ *
3434
+ * @global object $wpdb The Wordpress database object.
3435
+ *
3436
+ * @param string $uploadid The unique ID of the upload.
3437
+ *
3438
+ * @return object|null A userdata database record or null if not found.
3439
+ */
3440
+ function wfu_get_userdata_from_uploadid($uploadid) {
3441
+ global $wpdb;
3442
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3443
+ $userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$uploadid.'\' AND date_to = 0 ORDER BY propkey');
3444
+
3445
+ return $userdata;
3446
+ }
3447
+
3448
+ /**
3449
+ * Reassign File Hashes.
3450
+ *
3451
+ * The plugin calculates md5 hashes for all uploaded files, upon selection, to
3452
+ * verify later if the files have changed or not. This function reassignes the
3453
+ * hashes for all valid uploaded files. This function may take a lot of time
3454
+ * depending on the number and size of the uploaded files.
3455
+ *
3456
+ * @since 2.4.1
3457
+ *
3458
+ * @global object $wpdb The Wordpress database object.
3459
+ */
3460
+ function wfu_reassign_hashes() {
3461
+ global $wpdb;
3462
+ $table_name1 = $wpdb->prefix . "wfu_log";
3463
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3464
+ if ( $plugin_options['hashfiles'] == '1' ) {
3465
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE filehash = \'\' AND date_to = 0');
3466
+ foreach( $filerecs as $filerec ) {
3467
+ //calculate full file path
3468
+ $filepath = wfu_path_rel2abs($filerec->filepath);
3469
+ if ( file_exists($filepath) ) {
3470
+ $filehash = md5_file($filepath);
3471
+ $wpdb->update($table_name1,
3472
+ array( 'filehash' => $filehash ),
3473
+ array( 'idlog' => $filerec->idlog ),
3474
+ array( '%s' ),
3475
+ array( '%d' )
3476
+ );
3477
+ }
3478
+ }
3479
+ }
3480
+ }
3481
+
3482
+ /**
3483
+ * Make Uploaded File Database Record Obsolete.
3484
+ *
3485
+ * This function makes a database record of an uploaded file obsolete. This
3486
+ * means that the file is considered not valid anymore. Any related thumbnails
3487
+ * are deleted.
3488
+ *
3489
+ * @since 3.11.0
3490
+ *
3491
+ * @global object $wpdb The Wordpress database object.
3492
+ *
3493
+ * @redeclarable
3494
+ *
3495
+ * @param object $filerec The database record to make obsolete.
3496
+ *
3497
+ * @return bool|int Returns false if errors, or the number of rows affected if
3498
+ * successful.
3499
+ */
3500
+ function wfu_make_rec_obsolete($filerec) {
3501
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
3502
+ global $wpdb;
3503
+ $table_name1 = $wpdb->prefix . "wfu_log";
3504
+ $filedata = wfu_get_filedata_from_rec($filerec, true);
3505
+ //update db record accordingly
3506
+ $wpdb->update($table_name1,
3507
+ array( 'date_to' => date('Y-m-d H:i:s'), 'filedata' => wfu_encode_array_to_string($filedata) ),
3508
+ array( 'idlog' => $filerec->idlog ),
3509
+ array( '%s', '%s' ),
3510
+ array( '%d' )
3511
+ );
3512
+ }
3513
+
3514
+ /**
3515
+ * Synchronize Plugin's Database.
3516
+ *
3517
+ * This function updates database to reflect the current status of files.
3518
+ *
3519
+ * @since 2.4.1
3520
+ *
3521
+ * @global object $wpdb The Wordpress database object.
3522
+ *
3523
+ * @redeclarable
3524
+ *
3525
+ * @return number The number of obsolete records found.
3526
+ */
3527
+ function wfu_sync_database() {
3528
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
3529
+ global $wpdb;
3530
+ $table_name1 = $wpdb->prefix . "wfu_log";
3531
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3532
+
3533
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND date_to = 0');
3534
+ $obsolete_count = 0;
3535
+ foreach( $filerecs as $filerec ) {
3536
+ $obsolete = true;
3537
+ //calculate full file path
3538
+ $filepath = wfu_path_rel2abs($filerec->filepath);
3539
+ if ( file_exists($filepath) ) {
3540
+ if ( $plugin_options['hashfiles'] == '1' ) {
3541
+ $filehash = md5_file($filepath);
3542
+ if ( $filehash == $filerec->filehash ) $obsolete = false;
3543
+ }
3544
+ else {
3545
+ $filesize = filesize($filepath);
3546
+ if ( $filesize == $filerec->filesize ) $obsolete = false;
3547
+ }
3548
+ }
3549
+ if ( $obsolete ) {
3550
+ wfu_make_rec_obsolete($filerec);
3551
+ $obsolete_count ++;
3552
+ }
3553
+ }
3554
+ return $obsolete_count;
3555
+ }
3556
+
3557
+ /**
3558
+ * Get Uploaded File Database Records of Specific User.
3559
+ *
3560
+ * This function is used the retrieve the files uploaded by a specific user by
3561
+ * returning all the valid uploaded files' database records. If the user ID
3562
+ * provided starts with 'guest' then this means that the user is a guest and
3563
+ * retrieval will be done based on the session ID of the session that was
3564
+ * generated between the user's browser and the website when the user uploaded
3565
+ * files. This function will check if there are obsolete records. It will also
3566
+ * return any additional user data.
3567
+ *
3568
+ * @since 3.0.0
3569
+ *
3570
+ * @global object $wpdb The Wordpress database object.
3571
+ *
3572
+ * @param int|string $userid The user ID. If the user is a guest, it must be a
3573
+ * string starting with 'guest' and then including the session ID.
3574
+ *
3575
+ * @return array An array of user's database records of uploaded files.
3576
+ */
3577
+ function wfu_get_recs_of_user($userid) {
3578
+ global $wpdb;
3579
+ $table_name1 = $wpdb->prefix . "wfu_log";
3580
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3581
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3582
+
3583
+ //if $userid starts with 'guest' then retrieval of records is done using sessionid and uploaduserid is zero (for guests)
3584
+ if ( substr($userid, 0, 5) == 'guest' )
3585
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND uploaduserid = 0 AND sessionid = \''.substr($userid, 5).'\' AND date_to = 0');
3586
+ else
3587
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND action <> \'datasubmit\' AND uploaduserid = '.$userid.' AND date_to = 0');
3588
+ $out = array();
3589
+ foreach( $filerecs as $filerec ) {
3590
+ $obsolete = true;
3591
+ //calculate full file path
3592
+ $filepath = wfu_path_rel2abs($filerec->filepath);
3593
+ if ( file_exists($filepath) ) {
3594
+ if ( $plugin_options['hashfiles'] == '1' ) {
3595
+ $filehash = md5_file($filepath);
3596
+ if ( $filehash == $filerec->filehash ) $obsolete = false;
3597
+ }
3598
+ else {
3599
+ $filesize = filesize($filepath);
3600
+ if ( $filesize == $filerec->filesize ) $obsolete = false;
3601
+ }
3602
+ }
3603
+ if ( $obsolete ) {
3604
+ wfu_make_rec_obsolete($filerec);
3605
+ }
3606
+ else {
3607
+ $filerec->userdata = null;
3608
+ if ( $filerec->uploadid != '' )
3609
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
3610
+ array_push($out, $filerec);
3611
+ }
3612
+ }
3613
+
3614
+ return $out;
3615
+ }
3616
+
3617
+ /**
3618
+ * Get Filtered Uploaded Files Database Records.
3619
+ *
3620
+ * This function gets a list of database records of uploaded files based on a
3621
+ * list of filters. This function will check if there are obsolete records. It
3622
+ * will also return any additional user data.
3623
+ *
3624
+ * @since 3.2.1
3625
+ *
3626
+ * @global object $wpdb The Wordpress database object.
3627
+ *
3628
+ * @redeclarable
3629
+ *
3630
+ * @param array $filter An array of filters to apply.
3631
+ *
3632
+ * @return array An array of matched database records of uploaded files.
3633
+ */
3634
+ function wfu_get_filtered_recs($filter) {
3635
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
3636
+ global $wpdb;
3637
+ $table_name1 = $wpdb->prefix . "wfu_log";
3638
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
3639
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
3640
+
3641
+ $queries = array();
3642
+ // add default filters
3643
+ array_push($queries, 'action <> \'other\' AND action <> \'datasubmit\'');
3644
+ array_push($queries, 'date_to = 0');
3645
+ // construct user filter
3646
+ if ( isset($filter['user']) ) {
3647
+ if ( $filter['user']['all'] ) {
3648
+ if ( $filter['user']['guests'] ) $query = 'uploaduserid >= 0';
3649
+ else $query = 'uploaduserid > 0';
3650
+ }
3651
+ elseif ( count($filter['user']['ids']) == 1 && substr($filter['user']['ids'][0], 0, 5) == 'guest' )
3652
+ $query = 'uploaduserid = 0 AND sessionid = \''.substr($filter['user']['ids'][0], 5).'\'';
3653
+ else {
3654
+ if ( $filter['user']['guests'] ) array_push($filter['user']['ids'], '0');
3655
+ if ( count($filter['user']['ids']) == 1 ) $query = 'uploaduserid = '.$filter['user']['ids'][0];
3656
+ else $query = 'uploaduserid in ('.implode(",",$filter['user']['ids']).')';
3657
+ }
3658
+ array_push($queries, $query);
3659
+ }
3660
+ // construct size filter
3661
+ if ( isset($filter['size']) ) {
3662
+ if ( isset($filter['size']['lower']) && isset($filter['size']['upper']) )
3663
+ $query = 'filesize > '.$filter['size']['lower'].' AND filesize < '.$filter['size']['upper'];
3664
+ elseif ( isset($filter['size']['lower']) ) $query = 'filesize > '.$filter['size']['lower'];
3665
+ else $query = 'filesize < '.$filter['size']['upper'];
3666
+ array_push($queries, $query);
3667
+ }
3668
+ // construct date filter
3669
+ if ( isset($filter['date']) ) {
3670
+ if ( isset($filter['date']['lower']) && isset($filter['date']['upper']) )
3671
+ $query = 'uploadtime > '.$filter['date']['lower'].' AND uploadtime < '.$filter['date']['upper'];
3672
+ elseif ( isset($filter['date']['lower']) ) $query = 'uploadtime > '.$filter['date']['lower'];
3673
+ else $query = 'uploadtime < '.$filter['date']['upper'];
3674
+ array_push($queries, $query);
3675
+ }
3676
+ // construct file pattern filter
3677
+ if ( isset($filter['pattern']) ) {
3678
+ $query = 'filepath REGEXP \''.wfu_upload_plugin_wildcard_to_mysqlregexp($filter['pattern']).'\'';
3679
+ array_push($queries, $query);
3680
+ }
3681
+ // construct page/post filter
3682
+ if ( isset($filter['post']) ) {
3683
+ if ( count($filter['post']['ids']) == 1 ) $query = 'pageid = '.$filter['post']['ids'][0];
3684
+ else $query = 'pageid in ('.implode(",",$filter['post']['ids']).')';
3685
+ array_push($queries, $query);
3686
+ }
3687
+ // construct blog filter
3688
+ if ( isset($filter['blog']) ) {
3689
+ if ( count($filter['blog']['ids']) == 1 ) $query = 'blogid = '.$filter['blog']['ids'][0];
3690
+ else $query = 'blogid in ('.implode(",",$filter['blog']['ids']).')';
3691
+ array_push($queries, $query);
3692
+ }
3693
+ // construct userdata filter
3694
+ if ( isset($filter['userdata']) ) {
3695
+ if ( $filter['userdata']['criterion'] == "equal to" ) $valuecriterion = 'propvalue = \''.esc_sql($filter['userdata']['value']).'\'';
3696
+ elseif ( $filter['userdata']['criterion'] == "starts with" ) $valuecriterion = 'propvalue LIKE \''.esc_sql($filter['userdata']['value']).'%\'';
3697
+ elseif ( $filter['userdata']['criterion'] == "ends with" ) $valuecriterion = 'propvalue LIKE \'%'.esc_sql($filter['userdata']['value']).'\'';
3698
+ elseif ( $filter['userdata']['criterion'] == "contains" ) $valuecriterion = 'propvalue LIKE \'%'.esc_sql($filter['userdata']['value']).'%\'';
3699
+ elseif ( $filter['userdata']['criterion'] == "not equal to" ) $valuecriterion = 'propvalue <> \''.esc_sql($filter['userdata']['value']).'\'';
3700
+ elseif ( $filter['userdata']['criterion'] == "does not start with" ) $valuecriterion = 'propvalue NOT LIKE \''.esc_sql($filter['userdata']['value']).'%\'';
3701
+ elseif ( $filter['userdata']['criterion'] == "does not end with" ) $valuecriterion = 'propvalue NOT LIKE \'%'.esc_sql($filter['userdata']['value']).'\'';
3702
+ elseif ( $filter['userdata']['criterion'] == "does not contain" ) $valuecriterion = 'propvalue NOT LIKE \'%'.esc_sql($filter['userdata']['value']).'%\'';
3703
+ else $valuecriterion = 'propvalue = \''.esc_sql($filter['userdata']['value']).'\'';
3704
+ $query = 'uploadid in (SELECT DISTINCT uploadid FROM '.$table_name2.' WHERE date_to = 0 AND property = \''.esc_sql($filter['userdata']['field']).'\' AND '.$valuecriterion.')';
3705
+ array_push($queries, $query);
3706
+ }
3707
+
3708
+ /**
3709
+ * Customize Filter Queries.
3710
+ *
3711
+ * This filter allows custom actions to midify the queries that will be used
3712
+ * to filter the selected records of a file viewer.
3713
+ *
3714
+ * @since 4.6.2
3715
+ *
3716
+ * @param array $queries An array of queries to filter the selected records.
3717
+ * @param array $filter The filter array that generated the queries.
3718
+ */
3719
+ $queries = apply_filters("_wfu_filtered_recs_queries", $queries, $filter);
3720
+
3721
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE '.implode(' AND ', $queries));
3722
+ $out = array();
3723
+ foreach( $filerecs as $filerec ) {
3724
+ $obsolete = true;
3725
+ //calculate full file path
3726
+ $filepath = wfu_path_rel2abs($filerec->filepath);
3727
+ if ( file_exists($filepath) ) {
3728
+ if ( $plugin_options['hashfiles'] == '1' ) {
3729
+ $filehash = md5_file($filepath);
3730
+ if ( $filehash == $filerec->filehash ) $obsolete = false;
3731
+ }
3732
+ else {
3733
+ $filesize = filesize($filepath);
3734
+ if ( $filesize == $filerec->filesize ) $obsolete = false;
3735
+ }
3736
+ }
3737
+ if ( $obsolete ) {
3738
+ wfu_make_rec_obsolete($filerec);
3739
+ }
3740
+ else {
3741
+ $filerec->userdata = null;
3742
+ if ( $filerec->uploadid != '' )
3743
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
3744
+ array_push($out, $filerec);
3745
+ }
3746
+ }
3747
+
3748
+ return $out;
3749
+ }
3750
+
3751
+ /**
3752
+ * Get Uncached Option.
3753
+ *
3754
+ * This function gets an option from the website's Options table. It will first
3755
+ * delete any cached values of the option, so that the stored value in database
3756
+ * is returned.
3757
+ *
3758
+ * @since 3.5.0
3759
+ *
3760
+ * @param string $option The option name to retrieve.
3761
+ * @param mixed $default Optional. A default value to return in case option does
3762
+ * not exist.
3763
+ *
3764
+ * @return mixed The uncached value of the option.
3765
+ */
3766
+ function wfu_get_uncached_option($option, $default = false) {
3767
+ $GLOBALS['wp_object_cache']->delete( $option, 'options' );
3768
+ return get_option($option, $default);
3769
+ }
3770
+
3771
+ /**
3772
+ * Get Plugin Option.
3773
+ *
3774
+ * This function gets a plugin option from the website's Options table. It uses
3775
+ * direct access to options table of the website in order to avoid caching
3776
+ * problems that may happen when retrieving plugin options from parallel server-
3777
+ * side scripts.
3778
+ *
3779
+ * @since 3.5.0
3780
+ *
3781
+ * @global object $wpdb The Wordpress database object.
3782
+ *
3783
+ * @param string $option The option name to retrieve.
3784
+ * @param mixed $default A default value to return in case option does not
3785
+ * exist.
3786
+ * @param string $type Optional. The value type.
3787
+ *
3788
+ * @return mixed The value of the option.
3789
+ */
3790
+ function wfu_get_option($option, $default, $type = "array") {
3791
+ global $wpdb;
3792
+ $table_name1 = $wpdb->prefix . "options";
3793
+ $val = $wpdb->get_var($wpdb->prepare("SELECT option_value FROM $table_name1 WHERE option_name = %s", $option));
3794
+ if ( $val === null && $default !== false ) $val = $default;
3795
+ elseif ( $val !== null ) $val = ( $type == "array" ? wfu_decode_array_from_string($val) : $val );
3796
+ return $val;
3797
+ }
3798
+
3799
+ /**
3800
+ * Get Plugin Option Item.
3801
+ *
3802
+ * This function gets an option item from the website's Options table. Option
3803
+ * items are stored in the option value in an encoded format like this:
3804
+ *
3805
+ * [item_name1]item_value1{item_name1}[item_name2]item_value2{item_name2}...
3806
+ *
3807
+ * This format can be parsed and get the value of a specific item using a single
3808
+ * SQL command. This is exptremely important when working with parallel server-
3809
+ * side scripts, otherwise data may be lost.
3810
+ *
3811
+ * @since 4.12.0
3812
+ *
3813
+ * @global object $wpdb The Wordpress database object.
3814
+ *
3815
+ * @param string $option The option name that contains the item.
3816
+ * @param string $item The item name whose value to retrieve.
3817
+ *
3818
+ * @return null|string Null will be returned if option are item is not found,
3819
+ * otherwise the item value will be returned as string.
3820
+ */
3821
+ function wfu_get_option_item($option, $item) {
3822
+ global $wpdb;
3823
+ $table_name1 = $wpdb->prefix . "options";
3824
+ $val = $wpdb->get_var($wpdb->prepare("SELECT SQL_NO_CACHE IF (COUNT(option_value) = 0, NULL, IF (INSTR(option_value, %s) > 0, SUBSTRING_INDEX(SUBSTRING_INDEX(option_value, %s, -1), %s, 1), NULL)) FROM $table_name1 WHERE option_name = %s", '['.$item.']', '['.$item.']', '{'.$item.'}', $option));
3825
+ //wfu_debug_log("read:".$item." value:".$val."\n");
3826
+ return $val;
3827
+ }
3828
+
3829
+ /**
3830
+ * Check If Plugin Option Item Exists.
3831
+ *
3832
+ * This function checks if an option item in the website's Options table exists.
3833
+ * Option items and their format are described in wfu_get_option_item() function
3834
+ * above.
3835
+ *
3836
+ * @since 4.12.0
3837
+ *
3838
+ * @global object $wpdb The Wordpress database object.
3839
+ *
3840
+ * @param string $option The option name that contains the item.
3841
+ * @param string $item The item name whose existence to check.
3842
+ *
3843
+ * @return null|bool Null will be returned if option is not found, true if the
3844
+ * item exists, false otherwise.
3845
+ */
3846
+ function wfu_option_item_exists($option, $item) {
3847
+ global $wpdb;
3848
+ $table_name1 = $wpdb->prefix . "options";
3849
+ $exists = $wpdb->get_var($wpdb->prepare("SELECT SQL_NO_CACHE IF (COUNT(option_value) = 0, NULL, IF (INSTR(option_value, %s) > 0, TRUE, FALSE)) FROM $table_name1 WHERE option_name = %s", '['.$item.']', $option));
3850
+ return $exists;
3851
+ }
3852
+
3853
+ /**
3854
+ * Update Plugin Option.
3855
+ *
3856
+ * This function updates a plugin array option in the website's Options table or
3857
+ * creates it if it does not exist. It makes direct access to the website's
3858
+ * Options database table. It uses a single SQL command to insert or update the
3859
+ * option. This is necessary when working with parallel server-side scripts,
3860
+ * like the ones created when transferring multiple files to cloud services
3861
+ * asynchronously. The common Wordpress functions get_option() and
3862
+ * update_option() are not sufficient for such operations.
3863
+ *
3864
+ * @since 3.5.0
3865
+ *
3866
+ * @global object $wpdb The Wordpress database object.
3867
+ *
3868
+ * @param string $option The option name to update.
3869
+ * @param mixed $value The new value of the option.
3870
+ * @param string $type Optional. The value type.
3871
+ */
3872
+ function wfu_update_option($option, $value, $type = "array") {
3873
+ global $wpdb;
3874
+ $table_name1 = $wpdb->prefix . "options";
3875
+ $value = ( $type == "array" ? wfu_encode_array_to_string($value) : $value );
3876
+ $wpdb->query($wpdb->prepare("INSERT INTO $table_name1 (option_name, option_value) VALUES (%s, %s) ON DUPLICATE KEY UPDATE option_value = VALUES(option_value)", $option, $value));
3877
+ }
3878
+
3879
+ /**
3880
+ * Run Process in Queue.
3881
+ *
3882
+ * It has been observed that parallel PHP scripts can read/write to the database
3883
+ * and also the file system concurrently. This will cause problems with uploads.
3884
+ * File parts are uploaded concurrently, however it is necessary that each one
3885
+ * is processed at the server-side separately, before the next one starts. The
3886
+ * reason is that when the server reads a new chunk, it stores and retrieves
3887
+ * data from session. If more than one chunks write to session at the same time,
3888
+ * then mixups will happen and the upload will eventually fail.
3889
+ *
3890
+ * This function put processes that need to run concurrently (called 'threads')
3891
+ * in a FIFO queue based on a unique queue ID. The first thread that comes is
3892
+ * the first to be executed. The next one will be executed after the first one
3893
+ * finishes. A timeout loop checks the thread status. If a thread takes too long
3894
+ * to complete, it is considered as failed and it is removed from the queue, so
3895
+ * that the queue continues to the next threads.
3896
+ *
3897
+ * @since 4.12.0
3898
+ *
3899
+ * @param string $queue_id The unique queue ID.
3900
+ * @param string $proc The function that is put in queue.
3901
+ * @param array $params The function parameters.
3902
+ *
3903
+ * @return array {
3904
+ * The result of queue execution.
3905
+ *
3906
+ * @type bool $result True if the process was executed successfully,
3907
+ * false otherwise.
3908
+ * @type string $thread_code The unique code of the current thread.
3909
+ * @type integer $thread_index The index of the current thread.
3910
+ * @type null|mixed $output The return value of the executed function in
3911
+ * case of success, null otherwise.
3912
+ * @type string $error Error code in case of thread execution failure.
3913
+ * }
3914
+ */
3915
+ function wfu_run_process_in_queue($queue_id, $proc, $params) {
3916
+ $ret = array(
3917
+ "result" => false,
3918
+ "thread_code" => "",
3919
+ "thread_index" => 0,
3920
+ "output" => null,
3921
+ "error" => ""
3922
+ );
3923
+ if ( WFU_VAR("WFU_QUEUE_ACTIVE") == "true" ) {
3924
+ $queue = "wfu_queue_".$queue_id;
3925
+ if ( $queue_id == "" ) {
3926
+ $ret["error"] = "noid";
3927
+ return $ret;
3928
+ }
3929
+ $thread_code = wfu_create_random_string(16);
3930
+ wfu_join_queue($queue_id, $thread_code);
3931
+ $limit = intval(WFU_VAR("WFU_QUEUE_THREAD_TIMEOUT"));
3932
+ $waitloop = intval(WFU_VAR("WFU_QUEUE_LOOP_DELAY")) * 1000;
3933
+ $tcheck = time() + $limit;
3934
+ $last_thread = "";
3935
+ $abort = false;
3936
+ while (true) {
3937
+ $cur_thread = wfu_get_queue_thread($queue_id);
3938
+ if ( $cur_thread == $thread_code ) break;
3939
+ //calculate queue activity; if thread has changed then reset timer
3940
+ if ( $cur_thread != $last_thread ) {
3941
+ $last_thread = $cur_thread;
3942
+ $tcheck = time() + $limit;
3943
+ }
3944
+ //if time limit has passed this means that the current queue thread is
3945
+ //not progressing, so we need to exit the queue otherwise there will be
3946
+ //an infinite loop
3947
+ elseif ( time() > $tcheck ) {
3948
+ wfu_remove_queue_thread($queue_id, $thread_code);
3949
+ wfu_remove_queue_thread($queue_id, $cur_thread);
3950
+ $abort = true;
3951
+ break;
3952
+ }
3953
+ usleep($waitloop);
3954
+ }
3955
+ if ( $abort ) {
3956
+ $ret["error"] = "abort_thread";
3957
+ return $ret;
3958
+ }
3959
+ $thread_index = intval(wfu_get_option($queue."_count", 0, "string")) + 1;
3960
+ wfu_update_option($queue."_count", $thread_index, "string");
3961
+ }
3962
+ //create an array of references to the function arguments and pass this to
3963
+ //call_user_func_array instead of $args; this is a workaround to avoid PHP
3964
+ //warnings when the original function passes arguments by reference
3965
+ $args_byref = array();
3966
+ foreach ( $params as $key => &$arg ) $args_byref[$key] = &$arg;
3967
+ $output = call_user_func_array($proc, $args_byref);
3968
+ $ret["result"] = true;
3969
+ $ret["output"] = $output;
3970
+ if ( WFU_VAR("WFU_QUEUE_ACTIVE") == "true" ) {
3971
+ $ret["thread_code"] = $thread_code;
3972
+ $ret["thread_index"] = $thread_index;
3973
+ wfu_advance_queue($queue_id);
3974
+ }
3975
+ return $ret;
3976
+ }
3977
+
3978
+ /**
3979
+ * Join Thread in Queue.
3980
+ *
3981
+ * This function adds a new thread in a queue. If the queue does not exist it
3982
+ * will be created.
3983
+ *
3984
+ * @since 4.12.0
3985
+ *
3986
+ * @param string $queue_id The unique queue ID.
3987
+ * @param string $thread The new thread code.
3988
+ */
3989
+ function wfu_join_queue($queue_id, $thread) {
3990
+ global $wpdb;
3991
+ if ( $queue_id == "" ) return;
3992
+ $queue = "wfu_queue_".$queue_id;
3993
+ $table_name1 = $wpdb->prefix . "options";
3994
+ $wpdb->query($wpdb->prepare("INSERT INTO $table_name1 (option_name, option_value) VALUES (%s, %s) ON DUPLICATE KEY UPDATE option_value = CONCAT(option_value, IF (option_value = '', '', '|'), %s)", $queue, $thread, $thread));
3995
+ }
3996
+
3997
+ /**
3998
+ * Advance Queue.
3999
+ *
4000
+ * This function advances a queue to the next thread.
4001
+ *
4002
+ * @since 4.12.0
4003
+ *
4004
+ * @param string $queue_id The unique queue ID.
4005
+ */
4006
+ function wfu_advance_queue($queue_id) {
4007
+ global $wpdb;
4008
+ if ( $queue_id == "" ) return;
4009
+ $queue = "wfu_queue_".$queue_id;
4010
+ $table_name1 = $wpdb->prefix . "options";
4011
+ $wpdb->query($wpdb->prepare("UPDATE $table_name1 SET option_value = if (instr(option_value, '|') = 0, '', substr(option_value, instr(option_value, '|') + 1)) WHERE option_name = %s", $queue));
4012
+ }
4013
+
4014
+ /**
4015
+ * Get Running Queue Thread.
4016
+ *
4017
+ * This function gets the currently running thread of a queue.
4018
+ *
4019
+ * @since 4.12.0
4020
+ *
4021
+ * @param string $queue_id The unique queue ID.
4022
+ */
4023
+ function wfu_get_queue_thread($queue_id) {
4024
+ global $wpdb;
4025
+ if ( $queue_id == "" ) return;
4026
+ $queue = "wfu_queue_".$queue_id;
4027
+ $table_name1 = $wpdb->prefix . "options";
4028
+ return $wpdb->get_var($wpdb->prepare("SELECT substring_index(option_value, '|', 1) FROM $table_name1 WHERE option_name = %s", $queue));
4029
+ }
4030
+
4031
+ /**
4032
+ * Remove Thread from Queue.
4033
+ *
4034
+ * This function removes a thread from a queue.
4035
+ *
4036
+ * @since 4.12.0
4037
+ *
4038
+ * @param string $queue_id The unique queue ID.
4039
+ * @param string $thread The thread code to remove.
4040
+ */
4041
+ function wfu_remove_queue_thread($queue_id, $thread) {
4042
+ global $wpdb;
4043
+ if ( $queue_id == "" ) return;
4044
+ $queue = "wfu_queue_".$queue_id;
4045
+ $table_name1 = $wpdb->prefix . "options";
4046
+ $wpdb->query($wpdb->prepare("UPDATE $table_name1 SET option_value = replace(replace(replace(replace(option_value, concat('|', %s, '|'), '|'), concat(%s, '|'), ''), concat('|', %s), ''), %s, '') WHERE option_name = %s", $thread, $thread, $thread, $thread, $queue));
4047
+ }
4048
+
4049
+ /**
4050
+ * Remove Queue.
4051
+ *
4052
+ * This function removes a queue from options database table.
4053
+ *
4054
+ * @since 4.12.0
4055
+ *
4056
+ * @param string $queue_id The unique queue ID.
4057
+ */
4058
+ function wfu_remove_queue($queue_id) {
4059
+ if ( $queue_id == "" ) return;
4060
+ $queue = "wfu_queue_".$queue_id;
4061
+ delete_option($queue);
4062
+ }
4063
+
4064
+ /**
4065
+ * Update Plugin Option Item.
4066
+ *
4067
+ * This function updates an option item in the website's Options table. Option
4068
+ * items and their format are described in wfu_get_option_item() function above.
4069
+ * It has to be noted that the update of an option item requires a complex SQL
4070
+ * query, consisting of an INSERT statement calling a SELECT statement. In case
4071
+ * that many such queries are executed at the same time (like it happens when
4072
+ * uploading a file in chunks), database deadlocks may occur. To overcome the
4073
+ * situation, the transaction will be repeated until it succeeds or when a pre-
4074
+ * defined timeout is reached.
4075
+ *
4076
+ * @since 4.12.0
4077
+ *
4078
+ * @global object $wpdb The Wordpress database object.
4079
+ *
4080
+ * @param string $option The option name that contains the item.
4081
+ * @param string $item The item name whose value to retrieve.
4082
+ * @param string $value The new value of the item.
4083
+ *
4084
+ * @return false|int False if there was a DB error, or the number of rows
4085
+ * affected.
4086
+ */
4087
+ function wfu_update_option_item($option, $item, $value) {
4088
+ global $wpdb;
4089
+ $table_name1 = $wpdb->prefix . "options";
4090
+ $timeout = time();
4091
+ $val = false;
4092
+ $suppress_wpdb_errors = $wpdb->suppress_errors;
4093
+ if ( !$suppress_wpdb_errors ) $wpdb->suppress_errors(true);
4094
+ while ( $val === false && time() < $timeout + intval(WFU_VAR("WFU_US_DEADLOCK_TIMEOUT")) ) {
4095
+ $val = $wpdb->query($wpdb->prepare("INSERT INTO $table_name1 (option_name, option_value) SELECT SQL_NO_CACHE %s, IF (COUNT(option_value) = 0, %s, IF (INSTR(option_value, %s) = 0, CONCAT(option_value, %s), CONCAT(SUBSTRING_INDEX(option_value, %s, 1), %s, SUBSTRING_INDEX(option_value, %s, -1)))) FROM $table_name1 WHERE option_name = %s ON DUPLICATE KEY UPDATE option_value = VALUES(option_value)", $option, '['.$item.']'.$value.'{'.$item.'}', '['.$item.']', '['.$item.']'.$value.'{'.$item.'}', '['.$item.']', '['.$item.']'.$value.'{'.$item.'}', '{'.$item.'}', $option));
4096
+ if ( $val === false && WFU_VAR("WFU_US_LOG_DBERRORS") == "true" ) error_log("Database error: ".$wpdb->last_error);
4097
+ }
4098
+ if ( !$suppress_wpdb_errors ) $wpdb->suppress_errors(false);
4099
+ return $val;
4100
+ }
4101
+
4102
+ /**
4103
+ * Delete Plugin Option.
4104
+ *
4105
+ * This function deletes a plugin array option from the website's Options table.
4106
+ * It makes direct access to the website's Options database table so that
4107
+ * caching problems are avoided, when used together with the previous
4108
+ * wfu_get_option() and wfu_update_option() functions.
4109
+ *
4110
+ * @since 4.5.0
4111
+ *
4112
+ * @global object $wpdb The Wordpress database object.
4113
+ *
4114
+ * @param string $option The option name to update.
4115
+ */
4116
+ function wfu_delete_option($option) {
4117
+ global $wpdb;
4118
+ $table_name1 = $wpdb->prefix . "options";
4119
+ $val = $wpdb->get_var($wpdb->prepare("SELECT option_value FROM $table_name1 WHERE option_name = %s", $option));
4120
+ $wpdb->query($wpdb->prepare("DELETE FROM $table_name1 WHERE option_name = %s", $option));
4121
+ }
4122
+
4123
+ /**
4124
+ * Delete Plugin Option Item.
4125
+ *
4126
+ * This function deletes an option item in the website's Options table. Option
4127
+ * items and their format are described in wfu_get_option_item() function above.
4128
+ *
4129
+ * @since 4.12.0
4130
+ *
4131
+ * @global object $wpdb The Wordpress database object.
4132
+ *
4133
+ * @param string $option The option name that contains the item.
4134
+ * @param string $item The item name whose value to retrieve.
4135
+ *
4136
+ * @return false|int False if there was a DB error, or the number of rows
4137
+ * affected.
4138
+ */
4139
+ function wfu_delete_option_item($option, $item) {
4140
+ global $wpdb;
4141
+ $table_name1 = $wpdb->prefix . "options";
4142
+ $timeout = time();
4143
+ $val = false;
4144
+ $suppress_wpdb_errors = $wpdb->suppress_errors;
4145
+ if ( !$suppress_wpdb_errors ) $wpdb->suppress_errors(true);
4146
+ while ( $val === false && time() < $timeout + intval(WFU_VAR("WFU_US_DEADLOCK_TIMEOUT")) ) {
4147
+ $val = $wpdb->query($wpdb->prepare("INSERT INTO $table_name1 (option_name, option_value) SELECT SQL_NO_CACHE %s, IF (COUNT(option_value) = 0, '', IF (INSTR(option_value, %s) = 0, option_value, CONCAT(SUBSTRING_INDEX(option_value, %s, 1), SUBSTRING_INDEX(option_value, %s, -1)))) FROM $table_name1 WHERE option_name = %s ON DUPLICATE KEY UPDATE option_value = VALUES(option_value)", $option, '['.$item.']', '['.$item.']', '{'.$item.'}', $option));
4148
+ if ( $val === false && WFU_VAR("WFU_US_LOG_DBERRORS") == "true" ) error_log("Database error: ".$wpdb->last_error);
4149
+ }
4150
+ if ( !$suppress_wpdb_errors ) $wpdb->suppress_errors(false);
4151
+ return $val;
4152
+ }
4153
+
4154
+ /**
4155
+ * Prepare Data of Uploaded Files for Export.
4156
+ *
4157
+ * This function generates a file that contains data of uploaded files in csv
4158
+ * format for export. It will either export data of all valid uploaded files or
4159
+ * data of all uploaded files (valid or not) of a specififc user.
4160
+ *
4161
+ * @since 3.5.0
4162
+ *
4163
+ * @global object $wpdb The Wordpress database object.
4164
+ *
4165
+ * @redeclarable
4166
+ *
4167
+ * @param array $params An array of parameters to pass to the function.
4168
+ *
4169
+ * @return string The path of the file that contains the prepared data.
4170
+ */
4171
+ function wfu_export_uploaded_files($params) {
4172
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4173
+ global $wpdb;
4174
+ $table_name1 = $wpdb->prefix . "wfu_log";
4175
+ $table_name2 = $wpdb->prefix . "wfu_userdata";
4176
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
4177
+ $sep = WFU_VAR("WFU_EXPORT_DATA_SEPARATOR");
4178
+ $sep2 = WFU_VAR("WFU_EXPORT_USERDATA_SEPARATOR");
4179
+ $includeall = isset($params["username"]);
4180
+
4181
+ $contents = "";
4182
+ $header = 'Name'.$sep.'Path'.$sep.'Upload User'.$sep.'Upload Time'.$sep.'Size'.$sep.'Page ID'.$sep.'Blog ID'.$sep.'Shortcode ID'.$sep.'Upload ID'.$sep.'User Data';
4183
+ $contents = $header;
4184
+ if ( $includeall ) {
4185
+ $user = get_user_by('login', $params["username"]);
4186
+ $userid = $user->ID;
4187
+ $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE uploaduserid = '.$userid);
4188
+ }
4189
+ else $filerecs = $wpdb->get_results('SELECT * FROM '.$table_name1.' WHERE action <> \'other\' AND date_to = 0');
4190
+ foreach( $filerecs as $filerec ) {
4191
+ if ( $filerec->action == 'datasubmit' ) $obsolete = false;
4192
+ else {
4193
+ $obsolete = true;
4194
+ //calculate full file path
4195
+ $filepath = wfu_path_rel2abs($filerec->filepath);
4196
+ if ( file_exists($filepath) ) {
4197
+ if ( $plugin_options['hashfiles'] == '1' ) {
4198
+ $filehash = md5_file($filepath);
4199
+ if ( $filehash == $filerec->filehash ) $obsolete = false;
4200
+ }
4201
+ else {
4202
+ $filesize = filesize($filepath);
4203
+ if ( $filesize == $filerec->filesize ) $obsolete = false;
4204
+ }
4205
+ }
4206
+ }
4207
+ //export file data if file is not obsolete
4208
+ if ( !$obsolete || $includeall ) {
4209
+ $username = wfu_get_username_by_id($filerec->uploaduserid);
4210
+ $filerec->userdata = $wpdb->get_results('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$filerec->uploadid.'\' AND date_to = 0 ORDER BY propkey');
4211
+ $line = ( $filerec->action == 'datasubmit' ? 'datasubmit' : wfu_basename($filerec->filepath) );
4212
+ $line .= $sep.( $filerec->action == 'datasubmit' ? '' : wfu_basedir($filerec->filepath) );
4213
+ $line .= $sep.$username;
4214
+ $line .= $sep.( $filerec->uploadtime == null ? "" : date("Y-m-d H:i:s", $filerec->uploadtime) );
4215
+ $line .= $sep.( $filerec->action == 'datasubmit' ? '0' : $filerec->filesize );
4216
+ $line .= $sep.( $filerec->pageid == null ? "" : $filerec->pageid );
4217
+ $line .= $sep.( $filerec->blogid == null ? "" : $filerec->blogid );
4218
+ $line .= $sep.( $filerec->sid == null ? "" : $filerec->sid );
4219
+ $line .= $sep.$filerec->uploadid;
4220
+ $line2 = "";
4221
+ foreach ( $filerec->userdata as $userdata ) {
4222
+ if ( $line2 != "" ) $line2 .= $sep2;
4223
+ $line2 .= $userdata->property.":".str_replace(array("\n", "\r", "\r\n"), " ", $userdata->propvalue);
4224
+ }
4225
+ $line .= $sep.$line2;
4226
+ $contents .= "\n".$line;
4227
+ }
4228
+ }
4229
+ //create file
4230
+ $path = tempnam(sys_get_temp_dir(), 'wfu');
4231
+ file_put_contents($path, $contents);
4232
+
4233
+ return $path;
4234
+ }
4235
+
4236
+ /**
4237
+ * Get All Plugin Options.
4238
+ *
4239
+ * This function gets a list of all plugin's options and variables stored in
4240
+ * user space (usually session).
4241
+ *
4242
+ * @since 4.9.1
4243
+ *
4244
+ * @return array {
4245
+ * An array of all plugin options.
4246
+ *
4247
+ * $type string $name Name of option, an asterisk (*) denotes many
4248
+ * occurencies.
4249
+ * $type string $location Location of option, "db" or "session".
4250
+ * $type bool $deleteOnPurge Delete this option when purging all plugin
4251
+ * data.
4252
+ * $type bool $extract Store this option when extracting plugin data.
4253
+ * }
4254
+ */
4255
+ function wfu_get_all_plugin_options() {
4256
+ //structure of $options array; every item has the following properties:
4257
+ // 0: name of option, an asterisk (*) denotes many occurencies
4258
+ // 1: location of option, "db" or "session"
4259
+ // 2: delete this option when purging all plugin data
4260
+ // 3: store this option when extracting plugin data
4261
+ $options = array(
4262
+ //stored plugin's Settings
4263
+ array( "wordpress_file_upload_options", "db", true, true ),
4264
+ //wfu_log table version
4265
+ array( "wordpress_file_upload_table_log_version", "db", true, true ),
4266
+ //wfu_userdata version
4267
+ array( "wordpress_file_upload_table_userdata_version", "db", true, true ),
4268
+ //wfu_dbxqueue version
4269
+ array( "wordpress_file_upload_table_dbxqueue_version", "db", true, true ),
4270
+ //stored hooks
4271
+ array( "wordpress_file_upload_hooks", "db", true, true ),
4272
+ //transfer manager properties
4273
+ array( "wfu_transfermanager_props", "db", true, true ),
4274
+ //last file record that was read
4275
+ array( "wordpress_file_upload_last_idlog", "db", true, false ),
4276
+ //indices of stored shortcode parameters
4277
+ array( "wfu_params_index", "db", true, false ),
4278
+ //stored shortcode parameters
4279
+ array( "wfu_params_*", "db", true, false ),
4280
+ //stored advanced environment variables
4281
+ array( "wfu_environment_variables", "db", true, true ),
4282
+ //stored global tokens
4283
+ array( "wfu_gst_*", "db", true, false ),
4284
+ //data of unfinished uploaded files
4285
+ array( "wordpress_file_upload_unfinished_data", "db", true, false ),
4286
+ //list of stored variables in dboption user state
4287
+ array( "wfu_userstate_list", "db", true, false ),
4288
+ //stored variable value in dboption user state
4289
+ array( "wfu_userstate_*", "db", true, false ),
4290
+ //last time dboption user state was checked
4291
+ array( "wfu_userstate_list_last_check", "db", true, false ),
4292
+ //stored personal data policies
4293
+ array( "wordpress_file_upload_pd_policies", "db", true, true ),
4294
+ //last time admin was notified about DOS attack
4295
+ array( "wfu_admin_notification_about_DOS", "db", true, false ),
4296
+ //stored token for adding uploader shortcode
4297
+ array( "wfu_add_shortcode_ticket_for_wordpress_file_upload", "session", true, false ),
4298
+ //stored token for adding file viewer shortcode
4299
+ array( "wfu_add_shortcode_ticket_for_wordpress_file_upload_browser", "session", true, false ),
4300
+ //session array holding dir and file paths
4301
+ array( "wfu_filepath_safe_storage", "session", true, false ),
4302
+ //stored rename file flag when renaming file
4303
+ array( "wfu_rename_file", "session", true, false ),
4304
+ //stored rename file error when renaming file
4305
+ array( "wfu_rename_file_error", "session", true, false ),
4306
+ //stored create dir flag when creating dir
4307
+ array( "wfu_create_dir", "session", true, false ),
4308
+ //stored create dir error when creating dir
4309
+ array( "wfu_create_dir_error", "session", true, false ),
4310
+ //stored file details error when updating file details
4311
+ array( "wfu_filedetails_error", "session", true, false ),
4312
+ //stored hook data key when updating a hook
4313
+ array( "wfu_hook_data_key", "session", true, false ),
4314
+ //stored hook data title when updating a hook
4315
+ array( "wfu_hook_data_title", "session", true, false ),
4316
+ //stored hook data description when updating a hook
4317
+ array( "wfu_hook_data_description", "session", true, false ),
4318
+ //stored hook data code when updating a hook
4319
+ array( "wfu_hook_data_code", "session", true, false ),
4320
+ //stored hook data status when updating a hook
4321
+ array( "wfu_hook_data_status", "session", true, false ),
4322
+ //stored hook data scope when updating a hook
4323
+ array( "wfu_hook_data_scope", "session", true, false ),
4324
+ //stored hook data error message when updating a hook
4325
+ array( "wfu_hook_data_message", "session", true, false ),
4326
+ //stored data of file transfers tab
4327
+ array( "wfu_transfers_data", "session", true, false ),
4328
+ //stored token of upload form
4329
+ array( "wfu_token_*", "session", true, false ),
4330
+ //stored data of uploaded files
4331
+ array( "filedata_*", "session", true, false ),
4332
+ //stored status of upload
4333
+ array( "wfu_uploadstatus_*", "session", true, false ),
4334
+ //flag determining if this is the first pass of an upload
4335
+ array( "wfu_upload_first_pass_*", "session", true, false ),
4336
+ //stored approved captcha verification code
4337
+ array( "wfu_approvedcaptcha_*", "session", true, false ),
4338
+ //stored short tokens
4339
+ array( "wfu_ust_*", "session", true, false ),
4340
+ //stored shortcode data
4341
+ array( "wfu_shortcode_data_safe_storage", "session", true, false ),
4342
+ //stored number of deleted thumbnails
4343
+ array( "wfu_deleted_thumbnails_counter", "session", true, false ),
4344
+ //stored number of added thumbnails
4345
+ array( "wfu_added_thumbnails_counter", "session", true, false ),
4346
+ //stored consent data
4347
+ array( "WFU_Consent_Data", "session", true, false ),
4348
+ //stored browser actions
4349
+ array( "wfu_browser_actions_safe_storage", "session", true, false ),
4350
+ //stored data of chunked uploads
4351
+ array( "chunkdata_*", "session", true, false ),
4352
+ //stored flag of uploader form refresh status
4353
+ array( "wfu_check_refresh_*", "session", true, false ),
4354
+ //stored upload start time
4355
+ array( "wfu_start_time_*", "session", true, false ),
4356
+ //stored upload start time
4357
+ array( "wfu_start_time_*", "session", true, false )
4358
+ );
4359
+
4360
+
4361
+ return $options;
4362
+ }
4363
+
4364
+ //********************* Widget Functions ****************************************************************************************
4365
+
4366
+ /**
4367
+ * Get Plugin Widget Object From ID.
4368
+ *
4369
+ * This function gets the object instance of a plugin widget from its ID.
4370
+ *
4371
+ * @since 3.4.0
4372
+ *
4373
+ * @global array $wp_registered_widgets List of all registered widgets.
4374
+ *
4375
+ * @param string $widgetid The ID of the widget object instance.
4376
+ *
4377
+ * @return WP_Widget|false The widget object instance or false if not found.
4378
+ */
4379
+ function wfu_get_widget_obj_from_id($widgetid) {
4380
+ global $wp_registered_widgets;
4381
+
4382
+ if ( !isset($wp_registered_widgets[$widgetid]) ) return false;
4383
+ if ( !isset($wp_registered_widgets[$widgetid]['callback']) ) return false;
4384
+ if ( !isset($wp_registered_widgets[$widgetid]['callback'][0]) ) return false;
4385
+ $obj = $wp_registered_widgets[$widgetid]['callback'][0];
4386
+ if ( !($obj instanceof WP_Widget) ) return false;
4387
+
4388
+ return $obj;
4389
+ }
4390
+
4391
+ //********************* Shortcode Options Functions ****************************************************************************************
4392
+
4393
+ /**
4394
+ * Adjust Shortcode Definitions For Multi-Occurrencies
4395
+ *
4396
+ * This function adjusts shortcode definitions so that more than one attribute
4397
+ * definition exists for components who appear more than one time in placements
4398
+ * attribute (like userdata).
4399
+ *
4400
+ * @since 3.3.0
4401
+ *
4402
+ * @param array $shortcode_atts The shortcode attributes.
4403
+ *
4404
+ * @return array The adjusted shortcode attributes.
4405
+ */
4406
+ function wfu_shortcode_attribute_definitions_adjusted($shortcode_atts) {
4407
+ //get attribute definitions
4408
+ $defs = wfu_attribute_definitions();
4409
+ $defs_indexed = array();
4410
+ $defs_indexed_flat = array();
4411
+ foreach ( $defs as $def ) {
4412
+ $defs_indexed[$def["attribute"]] = $def;
4413
+ $defs_indexed_flat[$def["attribute"]] = $def["value"];
4414
+ }
4415
+ //get placement attribute from shortcode
4416
+ $placements = "";
4417
+ if ( isset($shortcode_atts["placements"]) ) $placements = $shortcode_atts["placements"];
4418
+ else $placements = $defs_indexed_flat["placements"];
4419
+ //get component definitions
4420
+ $components = wfu_component_definitions();
4421
+ //analyse components that can appear more than once in placements
4422
+ foreach ( $components as $component ) {
4423
+ if ( $component["multiplacements"] ) {
4424
+ $componentid = $component["id"];
4425
+ //count component occurrences in placements
4426
+ $component_occurrences = substr_count($placements, $componentid);
4427
+ if ( $component_occurrences > 1 && isset($defs_indexed[$componentid]) ) {
4428
+ //add incremented attribute definitions in $defs_indexed_flat
4429
+ //array if occurrences are more than one
4430
+ for ( $i = 2; $i <= $component_occurrences; $i++ ) {
4431
+ foreach ( $defs_indexed[$componentid]["dependencies"] as $attribute )
4432
+ $defs_indexed_flat[$attribute.$i] = $defs_indexed_flat[$attribute];
4433
+ }
4434
+ }
4435
+ }
4436
+ }
4437
+
4438
+ return $defs_indexed_flat;
4439
+ }
4440
+
4441
+ /**
4442
+ * Generate Shortcode Parameters Index.
4443
+ *
4444
+ * This function generates a unique index number for each shortcode parameters.
4445
+ * The function takes into account the current post ID, the shortcode ID and the
4446
+ * current user's username to construct the index. All identifiers are stored in
4447
+ * 'wfu_params_index' option. The index is used to store the shortcode
4448
+ * attributes in options table for later use.
4449
+ *
4450
+ * @since 2.1.2
4451
+ *
4452
+ * @global object $post The current Post object.
4453
+ *
4454
+ * @param int $shortcode_id The ID of the shortcode.
4455
+ * @param string $user_login The current user's username.
4456
+ *
4457
+ * @return string The index number of the shortcode parameters.
4458
+ */
4459
+ function wfu_generate_current_params_index($shortcode_id, $user_login) {
4460
+ global $post;
4461
+ $cur_index_str = '||'.$post->ID.'||'.$shortcode_id.'||'.$user_login;
4462
+ $cur_index_str_search = '\|\|'.$post->ID.'\|\|'.$shortcode_id.'\|\|'.$user_login;
4463
+ $index_str = get_option('wfu_params_index');
4464
+ $index = explode("&&", $index_str);
4465
+ foreach ($index as $key => $value) if ($value == "") unset($index[$key]);
4466
+ $index_match = preg_grep("/".$cur_index_str_search."$/", $index);
4467
+ if ( count($index_match) == 1 )
4468
+ foreach ( $index_match as $key => $value )
4469
+ if ( $value == "" ) unset($index_match[$key]);
4470
+ if ( count($index_match) <= 0 ) {
4471
+ $cur_index_rand = wfu_create_random_string(16);
4472
+ array_push($index, $cur_index_rand.$cur_index_str);
4473
+ }
4474
+ else {
4475
+ reset($index_match);
4476
+ $cur_index_rand = substr(current($index_match), 0, 16);
4477
+ if ( count($index_match) > 1 ) {
4478
+ $index_match_keys = array_keys($index_match);
4479
+ for ($i = 1; $i < count($index_match); $i++) {
4480
+ $ii = $index_match_keys[$i];
4481
+ unset($index[array_search($index_match[$ii], $index, true)]);
4482
+ }
4483
+ }
4484
+ }
4485
+ if ( count($index_match) != 1 ) {
4486
+ $index_str = implode("&&", $index);
4487
+ update_option('wfu_params_index', $index_str);
4488
+ }
4489
+ return $cur_index_rand;
4490
+ }
4491
+
4492
+ /**
4493
+ * Get Stored Shortcode Parameters.
4494
+ *
4495
+ * This function gets the shortcode parameters, stored in options table, from
4496
+ * its parameters index. Some times the index corresponds to 2 or more sets of
4497
+ * params, so an additional check, based on session token needs to be done in
4498
+ * order to find the correct one.
4499
+ *
4500
+ * @since 2.1.2
4501
+ *
4502
+ * @param string $params_index The parameters index.
4503
+ * @param string $session_token Optional. A session token used to find the
4504
+ * correct params.
4505
+ *
4506
+ * @return array {
4507
+ * The shortcode parameters.
4508
+ *
4509
+ * $type string $unique_id The unique ID of the upload.
4510
+ * $type int $page_id The ID of the page with the upload form.
4511
+ * $type int $shortcode_id The ID of the shortcode.
4512
+ * $type string $user_login The username of the user who made the
4513
+ * upload.
4514
+ * }
4515
+ */
4516
+ function wfu_get_params_fields_from_index($params_index, $session_token = "") {
4517
+ $fields = array();
4518
+ $index_str = get_option('wfu_params_index');
4519
+ $index = explode("&&", $index_str);
4520
+ $index_match = preg_grep("/^".$params_index."/", $index);
4521
+ if ( count($index_match) >= 1 )
4522
+ foreach ( $index_match as $key => $value )
4523
+ if ( $value == "" ) unset($index_match[$key]);
4524
+ if ( count($index_match) > 0 ) {
4525
+ if ( $session_token == "" ) {
4526
+ reset($index_match);
4527
+ list($fields['unique_id'], $fields['page_id'], $fields['shortcode_id'], $fields['user_login']) = explode("||", current($index_match));
4528
+ }
4529
+ //some times $params_index corresponds to 2 or more sets of params, so
4530
+ //we need to check session token in order to find the correct one
4531
+ else {
4532
+ $found = false;
4533
+ foreach ( $index_match as $value ) {
4534
+ list($fields['unique_id'], $fields['page_id'], $fields['shortcode_id'], $fields['user_login']) = explode("||", $value);
4535
+ $sid = $fields['shortcode_id'];
4536
+ if ( WFU_USVAR_exists("wfu_token_".$sid) && WFU_USVAR("wfu_token_".$sid) == $session_token ) {
4537
+ $found = true;
4538
+ break;
4539
+ }
4540
+ }
4541
+ if ( !$found ) $fields = array();
4542
+ }
4543
+ }
4544
+ return $fields;
4545
+ }
4546
+
4547
+ /**
4548
+ * Store Shortcode Data in User's Space.
4549
+ *
4550
+ * This function stores shortcode data in current user's user space (usually
4551
+ * session).
4552
+ *
4553
+ * @since 3.2.0
4554
+ *
4555
+ * @param array $data The shortcode data to store.
4556
+ *
4557
+ * @return string A unique code representing the stored data.
4558
+ */
4559
+ function wfu_safe_store_shortcode_data($data) {
4560
+ $code = wfu_create_random_string(16);
4561
+ $safe_storage = ( WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ? WFU_USVAR('wfu_shortcode_data_safe_storage') : array() );
4562
+ $safe_storage[$code] = $data;
4563
+ WFU_USVAR_store('wfu_shortcode_data_safe_storage', $safe_storage);
4564
+ return $code;
4565
+ }
4566
+
4567
+ /**
4568
+ * Get Stored Shortcode Data from User's Space.
4569
+ *
4570
+ * This function gets stored shortcode data from current user's user space
4571
+ * (usually session).
4572
+ *
4573
+ * @since 3.2.0
4574
+ *
4575
+ * @param string $code A unique code representing the stored data.
4576
+ *
4577
+ * @return array $data The stored shortcode data.
4578
+ */
4579
+ function wfu_get_shortcode_data_from_safe($code) {
4580
+ //sanitize $code
4581
+ $code = wfu_sanitize_code($code);
4582
+ if ( $code == "" ) return '';
4583
+ //return shortcode data from session variable, if exists
4584
+ if ( !WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ) return '';
4585
+ $safe_storage = WFU_USVAR('wfu_shortcode_data_safe_storage');
4586
+ if ( !isset($safe_storage[$code]) ) return '';
4587
+ return $safe_storage[$code];
4588
+ }
4589
+
4590
+ /**
4591
+ * Clear Stored Shortcode Data from User's Space.
4592
+ *
4593
+ * This function clears stored shortcode data from current user's user space
4594
+ * (usually session).
4595
+ *
4596
+ * @since 3.2.0
4597
+ *
4598
+ * @param string $code A unique code representing the stored data.
4599
+ */
4600
+ function wfu_clear_shortcode_data_from_safe($code) {
4601
+ //sanitize $code
4602
+ $code = wfu_sanitize_code($code);
4603
+ if ( $code == "" ) return;
4604
+ //clear shortcode data from session variable, if exists
4605
+ if ( !WFU_USVAR_exists('wfu_shortcode_data_safe_storage') ) return;
4606
+ $safe_storage = WFU_USVAR('wfu_shortcode_data_safe_storage');
4607
+ if ( !isset($safe_storage[$code]) ) return;
4608
+ unset($safe_storage[$code]);
4609
+ WFU_USVAR_store('wfu_shortcode_data_safe_storage', $safe_storage);
4610
+ }
4611
+
4612
+ /**
4613
+ * Decode Dimensions Shortcode Attribute.
4614
+ *
4615
+ * This function converts shortcode attributes keeping dimensions data from
4616
+ * string to array.
4617
+ *
4618
+ * @since 2.1.2
4619
+ *
4620
+ * @param string $dimensions_str The dimensions shortcode attribute.
4621
+ *
4622
+ * @return array An array of element dimension values.
4623
+ */
4624
+ function wfu_decode_dimensions($dimensions_str) {
4625
+ $components = wfu_component_definitions();
4626
+ $dimensions = array();
4627
+
4628
+ foreach ( $components as $comp ) {
4629
+ if ( $comp['dimensions'] == null ) $dimensions[$comp['id']] = "";
4630
+ else foreach ( $comp['dimensions'] as $dimraw ) {
4631
+ list($dim_id, $dim_name) = explode("/", $dimraw);
4632
+ $dimensions[$dim_id] = "";
4633
+ }
4634
+ }
4635
+ $dimensions_raw = explode(",", $dimensions_str);
4636
+ foreach ( $dimensions_raw as $dimension_str ) {
4637
+ $dimension_raw = explode(":", $dimension_str);
4638
+ $item = strtolower(trim($dimension_raw[0]));
4639
+ foreach ( array_keys($dimensions) as $key ) {
4640
+ if ( $item == $key ) $dimensions[$key] = trim($dimension_raw[1]);
4641
+ }
4642
+ }
4643
+ return $dimensions;
4644
+ }
4645
+
4646
+ /**
4647
+ * Remove Item From Placements Attribute.
4648
+ *
4649
+ * This function correctly removes an item from placements attribute of the
4650
+ * uploader shortcode.
4651
+ *
4652
+ * @since 3.8.0
4653
+ *
4654
+ * @param string $placements The placements shortcode attribute.
4655
+ * @param string $item The item to remove.
4656
+ *
4657
+ * @return string The new placements attribute.
4658
+ */
4659
+ function wfu_placements_remove_item($placements, $item) {
4660
+ $itemplaces = explode("/", $placements);
4661
+ $newplacements = array();
4662
+ foreach ( $itemplaces as $section ) {
4663
+ $items_in_section = explode("+", trim($section));
4664
+ $newsection = array();
4665
+ foreach ( $items_in_section as $item_in_section ) {
4666
+ $item_in_section = strtolower(trim($item_in_section));
4667
+ if ( $item_in_section != "" && $item_in_section != $item ) array_push($newsection, $item_in_section);
4668
+ }
4669
+ if ( count($newsection) > 0 ) array_push($newplacements, implode("+", $newsection));
4670
+ }
4671
+ if ( count($newplacements) > 0 ) return implode("/", $newplacements);
4672
+ else return "";
4673
+ }
4674
+
4675
+ //********************* Plugin Design Functions ********************************************************************************************
4676
+
4677
+ /**
4678
+ * Get Uploader Form Template.
4679
+ *
4680
+ * This function gets the template that will be used to render the uploader form
4681
+ * of the plugin. If not template name is defined, the default template will be
4682
+ * used.
4683
+ *
4684
+ * @since 4.0.0
4685
+ *
4686
+ * @redeclarable
4687
+ *
4688
+ * @param string $templatename The template to use.
4689
+ *
4690
+ * @return object The template object to use.
4691
+ */
4692
+ function wfu_get_uploader_template($templatename = "") {
4693
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4694
+ if ($templatename != "") {
4695
+ $classname = "WFU_UploaderTemplate_$templatename";
4696
+ if ( class_exists($classname) )
4697
+ return call_user_func(array($classname, 'get_instance'));
4698
+ $filepath = ABSWPFILEUPLOAD_DIR."templates/uploader-$templatename.php";
4699
+ if ( file_exists($filepath) ) {
4700
+ include_once $filepath;
4701
+ $classname = "WFU_UploaderTemplate_$templatename";
4702
+ if ( class_exists($classname) )
4703
+ return call_user_func(array($classname, 'get_instance'));
4704
+ }
4705
+ }
4706
+ return WFU_Original_Template::get_instance();
4707
+ }
4708
+
4709
+ /**
4710
+ * Get Front-End File Viewer Template.
4711
+ *
4712
+ * This function gets the template that will be used to render the front-end
4713
+ * file viewer of the plugin. If not template name is defined, the default
4714
+ * template will be used.
4715
+ *
4716
+ * @since 4.0.0
4717
+ *
4718
+ * @redeclarable
4719
+ *
4720
+ * @param string $templatename The template to use.
4721
+ *
4722
+ * @return object The template object to use.
4723
+ */
4724
+ function wfu_get_browser_template($templatename = "") {
4725
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4726
+ if ($templatename != "") {
4727
+ $classname = "WFU_BrowserTemplate_$templatename";
4728
+ if ( class_exists($classname) )
4729
+ return call_user_func(array($classname, 'get_instance'));
4730
+ $filepath = ABSWPFILEUPLOAD_DIR."templates/browser-$templatename.php";
4731
+ if ( file_exists($filepath) ) {
4732
+ include_once $filepath;
4733
+ $classname = "WFU_BrowserTemplate_$templatename";
4734
+ if ( class_exists($classname) )
4735
+ return call_user_func(array($classname, 'get_instance'));
4736
+ }
4737
+ }
4738
+ return WFU_Original_Template::get_instance();
4739
+ }
4740
+
4741
+ /**
4742
+ * Add Section in Uploader Form.
4743
+ *
4744
+ * This function adds a section in uploader form with the elements passed in
4745
+ * parameters. The first parameter passed is an array of the shortcode
4746
+ * attributes. The next parameters are the items to add in the new section.
4747
+ *
4748
+ * @since 2.1.2
4749
+ *
4750
+ * @redeclarable
4751
+ *
4752
+ * @return string The HTML code of the new section.
4753
+ */
4754
+ function wfu_add_div() {
4755
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4756
+ $items_count = func_num_args();
4757
+ if ( $items_count == 0 ) return "";
4758
+ $items_raw = func_get_args();
4759
+ $params = $items_raw[0];
4760
+ unset($items_raw[0]);
4761
+ $items = array( );
4762
+ foreach ( $items_raw as $item_raw ) {
4763
+ if ( is_array($item_raw) ) array_push($items, $item_raw);
4764
+ }
4765
+ $items_count = count($items);
4766
+ if ( $items_count == 0 ) return "";
4767
+
4768
+ $template = wfu_get_uploader_template($params["uploadertemplate"]);
4769
+ $data["ID"] = $params["uploadid"];
4770
+ $data["responsive"] = ( $params["fitmode"] == "responsive" );
4771
+ $data["items"] = $items;
4772
+ $data["params"] = $params;
4773
+
4774
+ ob_start();
4775
+ $template->wfu_row_container_template($data);
4776
+ $str_output = ob_get_clean();
4777
+ return $str_output;
4778
+ }
4779
+
4780
+ /**
4781
+ * Generate Plugin Element Template Output.
4782
+ *
4783
+ * This function generates the output of a plugin's element based on the defined
4784
+ * template and the data that the element will have.
4785
+ *
4786
+ * @since 4.0.0
4787
+ *
4788
+ * @param string $blockname The name of the element.
4789
+ * @param array $data An array of data to pass to the element.
4790
+ *
4791
+ * @return array An array holding the output of element. The item 'css' of the
4792
+ * array holds CSS code of the element. The item 'js' holds Javascript
4793
+ * code of the element. Items 'line1', 'line2' and so on hold the lines
4794
+ * of the HTML code of the element.
4795
+ */
4796
+ function wfu_read_template_output($blockname, $data) {
4797
+ $output = array();
4798
+ if ( isset($data["params"]["uploadertemplate"]) ) $template = wfu_get_uploader_template($data["params"]["uploadertemplate"]);
4799
+ else $template = wfu_get_browser_template($data["params"]["browsertemplate"]);
4800
+ $func = "wfu_".$blockname."_template";
4801
+ $sid = $data["ID"];
4802
+ ob_start();
4803
+ call_user_func(array($template, $func), $data);
4804
+ $str_output = ob_get_clean();
4805
+
4806
+ $str_output = str_replace('$ID', $sid, $str_output);
4807
+ //extract css, javascript and HTML from output
4808
+ $match = array();
4809
+ preg_match("/<style>(.*)<\/style><script.*?>(.*)<\/script>(.*)/s", $str_output, $match);
4810
+ if ( count($match) == 4 ) {
4811
+ $output["css"] = trim($match[1]);
4812
+ $output["js"] = trim($match[2]);
4813
+ $html = trim($match[3]);
4814
+ $i = 1;
4815
+ foreach( preg_split("/((\r?\n)|(\r\n?))/", $html) as $line )
4816
+ $output["line".$i++] = $line;
4817
+ }
4818
+
4819
+ return $output;
4820
+ }
4821
+
4822
+ /**
4823
+ * Generate Plugin Element Output.
4824
+ *
4825
+ * This function generates the final HTML code of a plugin's element that is
4826
+ * ready for output.
4827
+ *
4828
+ * @since 4.0.0
4829
+ *
4830
+ * @param string $blockname The name of the element.
4831
+ * @param array $params The shortcode attributes.
4832
+ * @param array $additional_params Additional parameters passed to the function
4833
+ * specific to the element.
4834
+ * @param int $occurrence_index The occurrence index of the element, in case
4835
+ * that placements attribute contains more than one occurrencies of this
4836
+ * element.
4837
+ *
4838
+ * @return string The HTML code of the element.
4839
+ */
4840
+ function wfu_template_to_HTML($blockname, $params, $additional_params, $occurrence_index) {
4841
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
4842
+ $block = call_user_func("wfu_prepare_".$blockname."_block", $params, $additional_params, $occurrence_index);
4843
+ if ( isset($params["uploadid"]) ) {
4844
+ $ID = $params["uploadid"];
4845
+ $WF = "WFU";
4846
+ }
4847
+ else {
4848
+ $ID = $params["browserid"];
4849
+ $WF = "WFUB";
4850
+ }
4851
+ $css = $block["css"];
4852
+ if ( $block["js"] != "" ) {
4853
+ $js = 'var '.$WF.'_JS_'.$ID.'_'.$blockname.' = function() {';
4854
+ $js .= "\n".$block["js"];
4855
+ $js .= "\n".'}';
4856
+ $js .= "\n".'wfu_run_js("window", "'.$WF.'_JS_'.$ID.'_'.$blockname.'");';
4857
+ }
4858
+ //relax css rules if this option is enabled
4859
+ if ( $plugin_options['relaxcss'] == '1' ) $css = preg_replace('#.*?/\*relax\*/\s*#', '', $css);
4860
+ $echo_str = wfu_css_to_HTML($css);
4861
+ $echo_str .= "\n".wfu_js_to_HTML($js);
4862
+ $k = 1;
4863
+ while ( isset($block["line".$k]) ) {
4864
+ if ( $block["line".$k] != "" ) $echo_str .= "\n".$block["line".$k];
4865
+ $k++;
4866
+ }
4867
+
4868
+ return $echo_str;
4869
+ }
4870
+
4871
+ /**
4872
+ * Extract CSS and Javascript Code From Components.
4873
+ *
4874
+ * This function extracts CSS and Javascript code from a components array
4875
+ * holding its output.
4876
+ *
4877
+ * @since 4.0.0
4878
+ *
4879
+ * @param array $section_array The component output to analyse.
4880
+ * @param string $css The parameter to store extracted CSS code.
4881
+ * @param string $js The parameter to store extracted Javascript code.
4882
+ */
4883
+ function wfu_extract_css_js_from_components($section_array, &$css, &$js) {
4884
+ for ( $i = 1; $i < count($section_array); $i++ ) {
4885
+ if ( isset($section_array[$i]["css"]) ) $css .= ( $css == "" ? "" : "\n" ).$section_array[$i]["css"];
4886
+ if ( isset($section_array[$i]["js"]) ) $js .= ( $js == "" ? "" : "\n" ).$section_array[$i]["js"];
4887
+ }
4888
+ return;
4889
+ }
4890
+
4891
+ /**
4892
+ * Add Loading Overlay in Plugin's Form.
4893
+ *
4894
+ * This function adds an overlay onto a plugin's form (uploader form or file
4895
+ * viewer) that shows a 'loading' icon when necessary.
4896
+ *
4897
+ * @since 3.5.0
4898
+ *
4899
+ * @redeclarable
4900
+ *
4901
+ * @param string $dlp Tab prefix of each HTML line.
4902
+ * @param string $code A code string to uniquely identify the overlay.
4903
+ *
4904
+ * @return string The HTML code of the loading overlay.
4905
+ */
4906
+ function wfu_add_loading_overlay($dlp, $code) {
4907
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4908
+ $echo_str = $dlp.'<div id="wfu_'.$code.'_overlay" style="margin:0; padding: 0; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background:none; display:none;">';
4909
+ $echo_str .= $dlp."\t".'<div style="margin:0; padding: 0; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background-color:rgba(255,255,255,0.8); z-index:1;""></div>';
4910
+ $echo_str .= $dlp."\t".'<table style="margin:0; padding: 0; table-layout:fixed; width:100%; height:100%; position:absolute; left:0; top:0; border:none; background:none; z-index:2;"><tbody><tr><td align="center" style="border:none;">';
4911
+ $echo_str .= $dlp."\t\t".'<img src="'.WFU_IMAGE_OVERLAY_LOADING.'" /><br /><span>loading...</span>';
4912
+ $echo_str .= $dlp."\t".'</td></tr></tbody></table>';
4913
+ $echo_str .= $dlp.'</div>';
4914
+
4915
+ return $echo_str;
4916
+ }
4917
+
4918
+ /**
4919
+ * Add Pagination Header in Plugin's Form.
4920
+ *
4921
+ * This function adds a pagination header onto a plugin's form (uploader form or
4922
+ * file viewer).
4923
+ *
4924
+ * @since 3.5.0
4925
+ *
4926
+ * @redeclarable
4927
+ *
4928
+ * @param string $dlp Tab prefix of each HTML line.
4929
+ * @param string $code A code string to uniquely identify the pagination header.
4930
+ * @param int $curpage The current page to show in the pagination header.
4931
+ * @param int $pages Number of pages of the pagination header.
4932
+ * @param bool $nonce Optional. If false then a nonce will also be created.
4933
+ *
4934
+ * @return string The HTML code of the pagination header.
4935
+ */
4936
+ function wfu_add_pagination_header($dlp, $code, $curpage, $pages, $nonce = false) {
4937
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4938
+ if ($nonce === false) $nonce = wp_create_nonce( 'wfu-'.$code.'-page' );
4939
+ $echo_str = $dlp.'<div style="float:right;">';
4940
+ $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_first_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == 1 ? 'inline' : 'none' ).';">&#60;&#60;</label>';
4941
+ $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_prev_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == 1 ? 'inline' : 'none' ).';">&#60;</label>';
4942
+ $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_first" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'first\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == 1 ? 'none' : 'inline' ).';">&#60;&#60;</a>';
4943
+ $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_prev" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'prev\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == 1 ? 'none' : 'inline' ).';">&#60;</a>';
4944
+ $echo_str .= $dlp."\t".'<label style="margin:0 0 0 4px; cursor:default;">'.WFU_PAGINATION_PAGE.'</label>';
4945
+ $echo_str .= $dlp."\t".'<select id="wfu_'.$code.'_pages" style="margin:0 4px;" onchange="wfu_goto_'.$code.'_page(\''.$nonce.'\', \'sel\');">';
4946
+ for ( $i = 1; $i <= $pages; $i++ )
4947
+ $echo_str .= $dlp."\t\t".'<option value="'.$i.'"'.( $i == $curpage ? ' selected="selected"' : '' ).'>'.$i.'</option>';
4948
+ $echo_str .= $dlp."\t".'</select>';
4949
+ $echo_str .= $dlp."\t".'<label style="margin:0 4px 0 0; cursor:default;">'.WFU_PAGINATION_OF.$pages.'</label>';
4950
+ $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_next_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == $pages ? 'inline' : 'none' ).';">&#62;</label>';
4951
+ $echo_str .= $dlp."\t".'<label id="wfu_'.$code.'_last_disabled" style="margin:0 4px; font-weight:bold; opacity:0.5; cursor:default; display:'.( $curpage == $pages ? 'inline' : 'none' ).';">&#62;&#62;</label>';
4952
+ $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_next" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'next\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == $pages ? 'none' : 'inline' ).';">&#62;</a>';
4953
+ $echo_str .= $dlp."\t".'<a id="wfu_'.$code.'_last" href="javascript:wfu_goto_'.$code.'_page(\''.$nonce.'\', \'last\');" style="margin:0 4px; font-weight:bold; display:'.( $curpage == $pages ? 'none' : 'inline' ).';">&#62;&#62;</a>';
4954
+ $echo_str .= $dlp.'</div>';
4955
+
4956
+ return $echo_str;
4957
+ }
4958
+
4959
+ /**
4960
+ * Add Bulk Actions Header in Plugin's Form.
4961
+ *
4962
+ * This function adds a bulk actions header onto a plugin's form (file viewer).
4963
+ *
4964
+ * @since 3.8.5
4965
+ *
4966
+ * @redeclarable
4967
+ *
4968
+ * @param string $dlp Tab prefix of each HTML line.
4969
+ * @param string $code A code string to uniquely identify the bulk actions
4970
+ * header.
4971
+ * @param array $actions {
4972
+ * The list of actions of the bulk actions header.
4973
+ *
4974
+ * $type string $name The name slug of the action.
4975
+ * $type string $title The title of the action.
4976
+ * }
4977
+ *
4978
+ * @return string The HTML code of the bulk actions header.
4979
+ */
4980
+ function wfu_add_bulkactions_header($dlp, $code, $actions) {
4981
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
4982
+ $echo_str = $dlp.'<div style="float:left;">';
4983
+ $echo_str .= $dlp."\t".'<select id="wfu_'.$code.'_bulkactions">';
4984
+ $echo_str .= $dlp."\t\t".'<option value="" selected="selected">'.( substr($code, 0, 8) == "browser_" ? WFU_BROWSER_BULKACTION_TITLE : "Bulk Actions").'</option>';
4985
+ foreach ( $actions as $action )
4986
+ $echo_str .= $dlp."\t\t".'<option value="'.$action["name"].'">'.$action["title"].'</option>';
4987
+ $echo_str .= $dlp."\t".'</select>';
4988
+ $echo_str .= $dlp."\t".'<input type="button" class="button action" value="'.( substr($code, 0, 8) == "browser_" ? WFU_BROWSER_BULKACTION_LABEL : "Apply").'" onclick="wfu_apply_'.$code.'_bulkaction();" />';
4989
+ $echo_str .= $dlp."\t".'<img src="'.WFU_IMAGE_OVERLAY_LOADING.'" style="display:none;" />';
4990
+ $echo_str .= $dlp.'</div>';
4991
+
4992
+ return $echo_str;
4993
+ }
4994
+
4995
+ /**
4996
+ * Parse Colors From Color Template.
4997
+ *
4998
+ * This function converts a color template (color triplet) into an array of
4999
+ * color values.
5000
+ *
5001
+ * @since 2.1.2
5002
+ *
5003
+ * @param string $template A color template to parse.
5004
+ *
5005
+ * @return array {
5006
+ * A triplet of color values.
5007
+ *
5008
+ * $type string $color Text color value.
5009
+ * $type string $bgcolor Background color value.
5010
+ * $type string $borcolor Border color value.
5011
+ * }
5012
+ */
5013
+ function wfu_prepare_message_colors($template) {
5014
+ $color_array = explode(",", $template);
5015
+ $colors['color'] = $color_array[0];
5016
+ $colors['bgcolor'] = $color_array[1];
5017
+ $colors['borcolor'] = $color_array[2];
5018
+ return $colors;
5019
+ }
5020
+
5021
+ //********************* Email Functions ****************************************************************************************************
5022
+
5023
+ /**
5024
+ * Send Notification Email.
5025
+ *
5026
+ * This function sends a notification email after files have been uploaded.
5027
+ *
5028
+ * @since 2.1.2
5029
+ *
5030
+ * @global object $blog_id The ID of the current blog.
5031
+ *
5032
+ * @redeclarable
5033
+ *
5034
+ * @param object $user The user that uploaded the files.
5035
+ * @param array $uploaded_file_paths An array of full paths of the uploaded
5036
+ * files.
5037
+ * @param array $userdata_fields An array of userdata fields, if any.
5038
+ * @param array $params The shortcode attributes.
5039
+ *
5040
+ * @return string Empty if operation was successful, an error message otherwise.
5041
+ */
5042
+ function wfu_send_notification_email($user, $uploaded_file_paths, $userdata_fields, $params) {
5043
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5044
+ global $blog_id;
5045
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
5046
+
5047
+ //get consent status
5048
+ $consent_revoked = ( $plugin_options["personaldata"] == "1" && $params["consent_result"] == "0" );
5049
+ $not_store_files = ( $params["personaldatatypes"] == "userdata and files" );
5050
+ //create necessary variables
5051
+ $only_filename_list = "";
5052
+ $target_path_list = "";
5053
+ foreach ( $uploaded_file_paths as $filepath ) {
5054
+ $only_filename_list .= ( $only_filename_list == "" ? "" : ", " ).wfu_basename($filepath);
5055
+ $target_path_list .= ( $target_path_list == "" ? "" : ", " ).$filepath;
5056
+ }
5057
+
5058
+ //apply wfu_before_email_notification filter
5059
+ $changable_data['recipients'] = $params["notifyrecipients"];
5060
+ $changable_data['subject'] = $params["notifysubject"];
5061
+ $changable_data['message'] = $params["notifymessage"];
5062
+ $changable_data['headers'] = $params["notifyheaders"];
5063
+ $changable_data['user_data'] = $userdata_fields;
5064
+ $changable_data['filename'] = $only_filename_list;
5065
+ $changable_data['filepath'] = $target_path_list;
5066
+ $changable_data['error_message'] = '';
5067
+ $additional_data['shortcode_id'] = $params["uploadid"];
5068
+ /**
5069
+ * Customize Notification Email.
5070
+ *
5071
+ * This filter allows custom actions to modify the notification email
5072
+ * that is sent after a file upload.
5073
+ *
5074
+ * @since 2.7.3
5075
+ *
5076
+ * @param array $changable_data {
5077
+ * Email parameters that can be changed.
5078
+ *
5079
+ * @type string $recipients A comma-separated list of email recipients.
5080
+ * @type string $subject The email subject.
5081
+ * @type string $message The email body.
5082
+ * @type array $user_data Additional user data associated with the
5083
+ * uploaded files.
5084
+ * @type string $filename A comma-separated list of file names.
5085
+ * @type string $filepath A comma-separated list of file full paths.
5086
+ * @type string $error_message An error message that needs to be
5087
+ * populated in case the email must not be sent.
5088
+ * }
5089
+ * @param array $additional_data {
5090
+ * Additional parameters of the upload.
5091
+ *
5092
+ * @type int $shortcode_id The plugin ID of the upload form.
5093
+ * }
5094
+ */
5095
+ $ret_data = apply_filters('wfu_before_email_notification', $changable_data, $additional_data);
5096
+
5097
+ if ( $ret_data['error_message'] == '' ) {
5098
+ $notifyrecipients = $ret_data['recipients'];
5099
+ $notifysubject = $ret_data['subject'];
5100
+ $notifymessage = $ret_data['message'];
5101
+ $notifyheaders = $ret_data['headers'];
5102
+ $userdata_fields = $ret_data['user_data'];
5103
+ $only_filename_list = $ret_data['filename'];
5104
+ $target_path_list = $ret_data['filepath'];
5105
+
5106
+ if ( 0 == $user->ID ) {
5107
+ $user_login = "guest";
5108
+ $user_email = "";
5109
+ }
5110
+ else {
5111
+ $user_login = $user->user_login;
5112
+ $user_email = $user->user_email;
5113
+ }
5114
+ $search = array ('/%useremail%/', '/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
5115
+ $replace = array ($user_email, "\n", "\"", "[", "]");
5116
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
5117
+ $ind = 1 + $userdata_key;
5118
+ array_push($search, '/%userdata'.$ind.'%/');
5119
+ array_push($replace, $userdata_field["value"]);
5120
+ }
5121
+ // $notifyrecipients = trim(preg_replace('/%useremail%/', $user_email, $params["notifyrecipients"]));
5122
+ $notifyrecipients = preg_replace($search, $replace, $notifyrecipients);
5123
+ $search = array ('/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
5124
+ $replace = array ("\n", "\"", "[", "]");
5125
+ $notifyheaders = preg_replace($search, $replace, $notifyheaders);
5126
+ $search = array ('/%username%/', '/%useremail%/', '/%filename%/', '/%filepath%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/', '/%n%/', '/%dq%/', '/%brl%/', '/%brr%/');
5127
+ $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename_list, $target_path_list, $blog_id, $params["pageid"], get_the_title($params["pageid"]), "\n", "\"", "[", "]");
5128
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
5129
+ $ind = 1 + $userdata_key;
5130
+ array_push($search, '/%userdata'.$ind.'%/');
5131
+ array_push($replace, $userdata_field["value"]);
5132
+ }
5133
+ $notifysubject = preg_replace($search, $replace, $notifysubject);
5134
+ $notifymessage = preg_replace($search, $replace, $notifymessage);
5135
+
5136
+ if ( $params["attachfile"] == "true" ) {
5137
+ $notify_sent = wp_mail($notifyrecipients, $notifysubject, $notifymessage, $notifyheaders, $uploaded_file_paths);
5138
+ }
5139
+ else {
5140
+ $notify_sent = wp_mail($notifyrecipients, $notifysubject, $notifymessage, $notifyheaders);
5141
+ }
5142
+ //delete files if it is required by consent policy
5143
+ if ( $consent_revoked && $not_store_files ) {
5144
+ foreach ( $uploaded_file_paths as $file ) unlink($file);
5145
+ }
5146
+ return ( $notify_sent ? "" : WFU_WARNING_NOTIFY_NOTSENT_UNKNOWNERROR );
5147
+ }
5148
+ else return $ret_data['error_message'];
5149
+ }
5150
+
5151
+ /**
5152
+ * Send Notification Email to Admin.
5153
+ *
5154
+ * This function sends a notification email to admin.
5155
+ *
5156
+ * @since 3.9.0
5157
+ *
5158
+ * @redeclarable
5159
+ *
5160
+ * @param string $subject The email subject.
5161
+ * @param string $message The emal message.
5162
+ */
5163
+ function wfu_notify_admin($subject, $message) {
5164
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5165
+ $admin_email = get_option("admin_email");
5166
+ if ( $admin_email === false ) return;
5167
+ wp_mail($admin_email, $subject, $message);
5168
+ }
5169
+
5170
+ //********************* Media Functions ****************************************************************************************************
5171
+
5172
+ /**
5173
+ * Create Media Attachment of Uploaded File.
5174
+ *
5175
+ * This function creates a media attachment and associates it with an uploaded
5176
+ * file.
5177
+ *
5178
+ * This function incorporates contributions from Aaron Olin who made some
5179
+ * corrections regarding the upload path.
5180
+ *
5181
+ * @since 2.2.1
5182
+ *
5183
+ * @redeclarable
5184
+ *
5185
+ * @param string $file_path The file path of the uploaded file.
5186
+ * @param array $userdata_fields Any userdata fields defined with the file.
5187
+ * @param int $page_id The ID of a page to link the attachment.
5188
+ *
5189
+ * @return int The ID of the created Media attachment.
5190
+ */
5191
+ function wfu_process_media_insert($file_path, $userdata_fields, $page_id){
5192
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5193
+ $wp_upload_dir = wp_upload_dir();
5194
+ $filetype = wp_check_filetype( wfu_basename( $file_path ), null );
5195
+
5196
+ $attachment = array(
5197
+ 'guid' => $wp_upload_dir['url'] . '/' . wfu_basename( $file_path ),
5198
+ 'post_mime_type' => $filetype['type'],
5199
+ 'post_title' => preg_replace( '/\.[^.]+$/', '', wfu_basename( $file_path ) ),
5200
+ 'post_content' => '',
5201
+ 'post_status' => 'inherit'
5202
+ );
5203
+
5204
+ $attach_id = wp_insert_attachment( $attachment, $file_path, $page_id );
5205
+
5206
+ // If file is an image, process the default thumbnails for previews
5207
+ require_once(ABSPATH . 'wp-admin/includes/image.php');
5208
+ $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
5209
+ // Add userdata as attachment metadata
5210
+ foreach ( $userdata_fields as $userdata_field )
5211
+ $attach_data["WFU User Data"][$userdata_field["label"]] = $userdata_field["value"];
5212
+ $update_attach = wp_update_attachment_metadata( $attach_id, $attach_data );
5213
+ // link attachment with file in plugin's database
5214
+ $filedata = wfu_get_filedata($file_path, true);
5215
+ if ( $filedata != null ) {
5216
+ $filedata["media"] = array(
5217
+ "type" => "data",
5218
+ "attach_id" => $attach_id
5219
+ );
5220
+ wfu_save_filedata_from_id($filedata["general"]["idlog"], $filedata);
5221
+ }
5222
+
5223
+ return $attach_id;
5224
+ }
5225
+
5226
+ //********************* Form Fields Functions ****************************************************************************************************
5227
+
5228
+ /**
5229
+ * Parse Userdata Callback.
5230
+ *
5231
+ * This is a callback function used in userdata parsing.
5232
+ *
5233
+ * @since 3.3.1
5234
+ *
5235
+ * @param string $matches A preg_replace_callback() function match.
5236
+ *
5237
+ * @return string The processed $matches string.
5238
+ */
5239
+ function wfu_preg_replace_callback_func($matches) {
5240
+ return str_replace("[/]", "/", $matches[0]);
5241
+ }
5242
+
5243
+ /**
5244
+ * Parse Upload Form Userdata.
5245
+ *
5246
+ * This function parses userdatalabel attribute, which holds userdata fields
5247
+ * properties, into an array.
5248
+ *
5249
+ * @since 3.3.0
5250
+ *
5251
+ * @param string $value Upload form userdatalabel attribute.
5252
+ *
5253
+ * @return array {
5254
+ * Parsed userdata fields properties.
5255
+ *
5256
+ * $type array {
5257
+ * Parsed userdata field properties.
5258
+ *
5259
+ * $type string $type The type of the field.
5260
+ * $type string $label The label of the field.
5261
+ * $type string $labelposition The position of the label in
5262
+ * relation to the field.
5263
+ * $type bool $required Field is required.
5264
+ * $type bool $donotautocomplete Field must not be autocompleted.
5265
+ * $type bool $validate Validate the field before upload.
5266
+ * $type bool $typehook Apply a hook on the field while typing.
5267
+ * $type string $hintposition The position of the hint text in
5268
+ * relation to the field.
5269
+ * $type string $default The default value of the field.
5270
+ * $type string $data A data property specific per field type.
5271
+ * $type string $group The field is grouped with other fields.
5272
+ * $type string $format Field format, specific per type.
5273
+ * }
5274
+ * }
5275
+ */
5276
+ function wfu_parse_userdata_attribute($value){
5277
+ $fields = array();
5278
+ //read defaults
5279
+ $definitions_unindexed = wfu_formfield_definitions();
5280
+ $defaults = array();
5281
+ foreach ( $definitions_unindexed as $def ) {
5282
+ $default = array();
5283
+ $default["type"] = $def["type"];
5284
+ $default["label"] = $def["label"];
5285
+ $default["labelposition"] = "".substr($def["labelposition"], 5);
5286
+ $default["required"] = ( substr($def["required"], 5) == "true" );
5287
+ $default["donotautocomplete"] = ( substr($def["donotautocomplete"], 5) == "true" );
5288
+ $default["validate"] = ( substr($def["validate"], 5) == "true" );
5289
+ $default["typehook"] = ( substr($def["typehook"], 5) == "true" );
5290
+ $default["hintposition"] = "".substr($def["hintposition"], 5);
5291
+ $default["default"] = "".substr($def["default"], 5);
5292
+ $default["data"] = "".substr($def["data"], 5);
5293
+ $default["group"] = "".substr($def["group"], 5);
5294
+ $default["format"] = "".substr($def["format"], 5);
5295
+ $defaults[$def["type"]] = $default;
5296
+ }
5297
+ // $fields_arr = explode("/", $value);
5298
+ $value = str_replace("/", "[/]", $value);
5299
+ $value = preg_replace_callback("/\(.*\)/", "wfu_preg_replace_callback_func", $value);
5300
+ $fields_arr = explode("[/]", $value);
5301
+ //parse shortcode attribute to $fields
5302
+ foreach ( $fields_arr as $field_raw ) {
5303
+ $field_raw = trim($field_raw);
5304
+ $fieldprops = $defaults["text"];
5305
+ //read old default attribute
5306
+ if ( substr($field_raw, 0, 1) == "*" ) {
5307
+ $fieldprops["required"] = true;
5308
+ $field_raw = substr($field_raw, 1);
5309
+ }
5310
+ $field_parts = explode("|", $field_raw);
5311
+ //proceed if the first part, which is the label, is non-empty
5312
+ if ( trim($field_parts[0]) != "" ) {
5313
+ //get type, if exists, in order to adjust defaults
5314
+ $type_key = -1;
5315
+ $new_type = "";
5316
+ foreach ( $field_parts as $key => $part ) {
5317
+ $part = ltrim($part);
5318
+ $flag = substr($part, 0, 2);
5319
+ $val = substr($part, 2);
5320
+ if ( $flag == "t:" && $key > 0 && array_key_exists($val, $defaults) ) {
5321
+ $new_type = $val;
5322
+ $type_key = $key;
5323
+ break;
5324
+ }
5325
+ }
5326
+ if ( $new_type != "" ) {
5327
+ $fieldprops = $defaults[$new_type];
5328
+ unset($field_parts[$type_key]);
5329
+ }
5330
+ //store label
5331
+ $fieldprops["label"] = trim($field_parts[0]);
5332
+ unset($field_parts[0]);
5333
+ //get other properties
5334
+ foreach ( $field_parts as $part ) {
5335
+ $part = ltrim($part);
5336
+ $flag = substr($part, 0, 2);
5337
+ $val = "".substr($part, 2);
5338
+ if ( $flag == "s:" ) $fieldprops["labelposition"] = $val;
5339
+ elseif ( $flag == "r:" ) $fieldprops["required"] = ( $val == "1" );
5340
+ elseif ( $flag == "a:" ) $fieldprops["donotautocomplete"] = ( $val == "1" );
5341
+ elseif ( $flag == "v:" ) $fieldprops["validate"] = ( $val == "1" );
5342
+ elseif ( $flag == "d:" ) $fieldprops["default"] = $val;
5343
+ elseif ( $flag == "l:" ) $fieldprops["data"] = $val;
5344
+ elseif ( $flag == "g:" ) $fieldprops["group"] = $val;
5345
+ elseif ( $flag == "f:" ) $fieldprops["format"] = $val;
5346
+ elseif ( $flag == "p:" ) $fieldprops["hintposition"] = $val;
5347
+ elseif ( $flag == "h:" ) $fieldprops["typehook"] = ( $val == "1" );
5348
+ }
5349
+ array_push($fields, $fieldprops);
5350
+ }
5351
+ }
5352
+
5353
+ return $fields;
5354
+ }
5355
+
5356
+ /**
5357
+ * Checke and Remove Honeypot Fields.
5358
+ *
5359
+ * The plugin uses honeypot userdata fields as an additional security measure
5360
+ * against bots. A honeypot is a field which is not visible to the user, but it
5361
+ * can be filled with a value. A human will not see the field, so it will not
5362
+ * fill it with data. On the other hand, a bot does not care about visibility.
5363
+ * If the field has a common name, like 'url' or 'website' it will think that it
5364
+ * is a normal field and will fill it with data. In this case the upload will
5365
+ * fail silently (the bot will think that it succeeded). If the honeypot field
5366
+ * is empty, then the upload will continue normally, however it will be removed
5367
+ * from userdata fields list because it is not necessary anymore.
5368
+ *
5369
+ * @since 4.10.1
5370
+ *
5371
+ * @param array $userdata_fields An array of userdata fields.
5372
+ * @param string $post_key A string to locate the value of the honeypot field
5373
+ * in received POST parameters.
5374
+ *
5375
+ * @return bool True if the honeypot field is filled, false otherwise.
5376
+ */
5377
+ function wfu_check_remove_honeypot_fields(&$userdata_fields, $post_key) {
5378
+ //check if honeypot userdata fields have been added to the form and if they
5379
+ //contain any data
5380
+ $honeypot_filled = false;
5381
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
5382
+ if ( $userdata_field["type"] == "honeypot" ) {
5383
+ $val = ( isset($_POST[$post_key.$userdata_key]) ? $_POST[$post_key.$userdata_key] : "" );
5384
+ //if a non-zero value has been passed to the server, this means
5385
+ //that it has been filled by a bot
5386
+ if ( $val != "" ) {
5387
+ $honeypot_filled = true;
5388
+ break;
5389
+ }
5390
+ //if the honeypot field is empty then remove it from
5391
+ //userdata_fields array because we do not want to be stored
5392
+ else unset($userdata_fields[$userdata_key]);
5393
+ }
5394
+ }
5395
+
5396
+ //if any honeypot field has been filled then return true to denote that
5397
+ //the upload must be aborted
5398
+ return $honeypot_filled;
5399
+ }
5400
+
5401
+ //************************* Cookie Functions ***********************************
5402
+
5403
+ /**
5404
+ * Read Session Cookie.
5405
+ *
5406
+ * This function reads the session cookie of the plugin that is used to store
5407
+ * user state information when User State handler is set to 'dboption'.
5408
+ *
5409
+ * @since 4.12.0
5410
+ *
5411
+ * @return string The session ID.
5412
+ */
5413
+ function wfu_get_session_cookie() {
5414
+ return isset($_COOKIE[WPFILEUPLOAD_COOKIE]) ? wfu_sanitize_code(substr($_COOKIE[WPFILEUPLOAD_COOKIE], 0, 32)) : "";
5415
+ }
5416
+
5417
+ /**
5418
+ * Set Session Cookie.
5419
+ *
5420
+ * This function sets the session cookie of the plugin that is used to store
5421
+ * user state information when User State handler is set to 'dboption'. This
5422
+ * function generates a session ID that composes of a random 32-digit string.
5423
+ *
5424
+ * @since 4.12.0
5425
+ *
5426
+ * @redeclarable
5427
+ */
5428
+ function wfu_set_session_cookie() {
5429
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5430
+ if ( !headers_sent() ) {
5431
+ $cookie = wfu_create_random_string(32);
5432
+ setcookie(
5433
+ WPFILEUPLOAD_COOKIE,
5434
+ $cookie,
5435
+ time() + intval(WFU_VAR("WFU_US_COOKIE_LIFE")) * 3600,
5436
+ COOKIEPATH ? COOKIEPATH : '/',
5437
+ COOKIE_DOMAIN,
5438
+ false,
5439
+ false
5440
+ );
5441
+ $_COOKIE[WPFILEUPLOAD_COOKIE] = $cookie;
5442
+ }
5443
+ }
5444
+
5445
+ //********************* User State Functions ***********************************
5446
+
5447
+ /**
5448
+ * Initialize User State.
5449
+ *
5450
+ * This function initializes the user state. If user state handler is 'dboption'
5451
+ * then it sets the session cookie. If it is 'session' it starts the session
5452
+ * now or on demand, depending on 'WFU_US_SESSION_LEGACY' variable.
5453
+ *
5454
+ * @since 4.12.0
5455
+ *
5456
+ * @global string $wfu_user_state_handler The defined User State handler.
5457
+ *
5458
+ * @redeclarable
5459
+ */
5460
+ function wfu_initialize_user_state() {
5461
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5462
+ global $wfu_user_state_handler;
5463
+ if ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "cookies" ) {
5464
+ if ( wfu_get_session_cookie() == "" ) wfu_set_session_cookie();
5465
+ }
5466
+ elseif ( WFU_VAR("WFU_US_SESSION_LEGACY") == "true" && !headers_sent() && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) ) { session_start(); }
5467
+ }
5468
+
5469
+ /**
5470
+ * Check if User State Variable Exists.
5471
+ *
5472
+ * This function checks if a variable exists in User State.
5473
+ *
5474
+ * @since 4.3.2
5475
+ *
5476
+ * @global string $wfu_user_state_handler The defined User State handler.
5477
+ *
5478
+ * @redeclarable
5479
+ *
5480
+ * @param string $var The variable to check.
5481
+ *
5482
+ * @return bool True if the variable exists, false otherwise.
5483
+ */
5484
+ function WFU_USVAR_exists($var) {
5485
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5486
+ global $wfu_user_state_handler;
5487
+ if ( $wfu_user_state_handler == "dboption" )
5488
+ return ( WFU_VAR("WFU_US_DBOPTION_USEOLD") == "false" ? WFU_USVAR_exists_dboption($var) : WFU_USVAR_exists_dboption_old($var) );
5489
+ else return WFU_USVAR_exists_session($var);
5490
+ }
5491
+
5492
+ /**
5493
+ * Get Variable From User State.
5494
+ *
5495
+ * This function gets the value of a variable from User State.
5496
+ *
5497
+ * @since 4.3.2
5498
+ *
5499
+ * @global string $wfu_user_state_handler The defined User State handler.
5500
+ *
5501
+ * @redeclarable
5502
+ *
5503
+ * @param string $var The variable to get.
5504
+ *
5505
+ * @return mixed The value of the variable.
5506
+ */
5507
+ function WFU_USVAR($var) {
5508
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5509
+ global $wfu_user_state_handler;
5510
+ if ( $wfu_user_state_handler == "dboption" )
5511
+ return ( WFU_VAR("WFU_US_DBOPTION_USEOLD") == "false" ? WFU_USVAR_dboption($var) : WFU_USVAR_dboption_old($var) );
5512
+ else return WFU_USVAR_session($var);
5513
+ }
5514
+
5515
+ /**
5516
+ * Get All User State Variables.
5517
+ *
5518
+ * This function gets the values of all User State variables.
5519
+ *
5520
+ * @since 4.3.2
5521
+ *
5522
+ * @global string $wfu_user_state_handler The defined User State handler.
5523
+ *
5524
+ * @redeclarable
5525
+ *
5526
+ * @return array An array of all User State variables.
5527
+ */
5528
+ function WFU_USALL() {
5529
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5530
+ global $wfu_user_state_handler;
5531
+ if ( $wfu_user_state_handler == "dboption" )
5532
+ return ( WFU_VAR("WFU_US_DBOPTION_USEOLD") == "false" ? WFU_USALL_dboption() : WFU_USALL_dboption_old() );
5533
+ else return WFU_USALL_session();
5534
+ }
5535
+
5536
+ /**
5537
+ * Store Variable In User State.
5538
+ *
5539
+ * This function stores the value of a variable in User State.
5540
+ *
5541
+ * @since 4.3.2
5542
+ *
5543
+ * @global string $wfu_user_state_handler The defined User State handler.
5544
+ *
5545
+ * @redeclarable
5546
+ *
5547
+ * @param string $var The variable to store.
5548
+ * @param mixed $value The value of the variable.
5549
+ */
5550
+ function WFU_USVAR_store($var, $value) {
5551
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5552
+ global $wfu_user_state_handler;
5553
+ if ( $wfu_user_state_handler == "dboption" )
5554
+ ( WFU_VAR("WFU_US_DBOPTION_USEOLD") == "false" ? WFU_USVAR_store_dboption($var, $value) : WFU_USVAR_store_dboption_old($var, $value) );
5555
+ else WFU_USVAR_store_session($var, $value);
5556
+ }
5557
+
5558
+ /**
5559
+ * Remove Variable From User State.
5560
+ *
5561
+ * This function removes a variable from User State.
5562
+ *
5563
+ * @since 4.3.2
5564
+ *
5565
+ * @global string $wfu_user_state_handler The defined User State handler.
5566
+ *
5567
+ * @redeclarable
5568
+ *
5569
+ * @param string $var The variable to remove.
5570
+ */
5571
+ function WFU_USVAR_unset($var) {
5572
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5573
+ global $wfu_user_state_handler;
5574
+ if ( $wfu_user_state_handler == "dboption" )
5575
+ ( WFU_VAR("WFU_US_DBOPTION_USEOLD") == "false" ? WFU_USVAR_unset_dboption($var) : WFU_USVAR_unset_dboption_old($var) );
5576
+ else WFU_USVAR_unset_session($var);
5577
+ }
5578
+
5579
+ /**
5580
+ * Check if Session Variable Exists.
5581
+ *
5582
+ * This function checks if a variable exists in Session.
5583
+ *
5584
+ * @since 4.4.0
5585
+ *
5586
+ * @param string $var The variable to check.
5587
+ *
5588
+ * @return bool True if the variable exists, false otherwise.
5589
+ */
5590
+ function WFU_USVAR_exists_session($var) {
5591
+ $session_id = session_id();
5592
+ $open_session = ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
5593
+ if ( $open_session ) session_start();
5594
+ $exists = isset($_SESSION[$var]);
5595
+ if ( $open_session ) session_write_close();
5596
+ return $exists;
5597
+ }
5598
+
5599
+ /**
5600
+ * Get Variable From Session.
5601
+ *
5602
+ * This function gets the value of a variable from Session.
5603
+ *
5604
+ * @since 4.4.0
5605
+ *
5606
+ * @param string $var The variable to get.
5607
+ *
5608
+ * @return mixed The value of the variable.
5609
+ */
5610
+ function WFU_USVAR_session($var) {
5611
+ $session_id = session_id();
5612
+ $open_session = ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
5613
+ if ( $open_session ) session_start();
5614
+ $value = $_SESSION[$var];
5615
+ if ( $open_session ) session_write_close();
5616
+ return $value;
5617
+ }
5618
+
5619
+ /**
5620
+ * Get All Session Variables.
5621
+ *
5622
+ * This function gets the values of all Session variables.
5623
+ *
5624
+ * @since 4.4.0
5625
+ *
5626
+ * @return array An array of all Session variables.
5627
+ */
5628
+ function WFU_USALL_session() {
5629
+ $session_id = session_id();
5630
+ $open_session = ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
5631
+ if ( $open_session ) session_start();
5632
+ $all = $_SESSION;
5633
+ if ( $open_session ) session_write_close();
5634
+ return $all;
5635
+ }
5636
+
5637
+ /**
5638
+ * Store Variable In Session.
5639
+ *
5640
+ * This function stores the value of a variable in Session.
5641
+ *
5642
+ * @since 4.4.0
5643
+ *
5644
+ * @param string $var The variable to store.
5645
+ * @param mixed $value The value of the variable.
5646
+ */
5647
+ function WFU_USVAR_store_session($var, $value) {
5648
+ $session_id = session_id();
5649
+ $open_session = ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
5650
+ if ( $open_session ) session_start();
5651
+ $_SESSION[$var] = $value;
5652
+ if ( $open_session ) session_write_close();
5653
+ }
5654
+
5655
+ /**
5656
+ * Remove Variable From Session.
5657
+ *
5658
+ * This function removes a variable from Session.
5659
+ *
5660
+ * @since 4.4.0
5661
+ *
5662
+ * @param string $var The variable to remove.
5663
+ */
5664
+ function WFU_USVAR_unset_session($var) {
5665
+ $session_id = session_id();
5666
+ $open_session = ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
5667
+ if ( $open_session ) session_start();
5668
+ unset($_SESSION[$var]);
5669
+ if ( $open_session ) session_write_close();
5670
+ }
5671
+
5672
+ /**
5673
+ * Get Session ID.
5674
+ *
5675
+ * This function gets session ID depending on the user state handler and
5676
+ * relevant advanced variables.
5677
+ *
5678
+ * @since 4.12.0
5679
+ *
5680
+ * @global string $wfu_user_state_handler The defined User State handler.
5681
+ *
5682
+ * @return string The Session ID.
5683
+ */
5684
+ function wfu_get_session_id() {
5685
+ global $wfu_user_state_handler;
5686
+ $key = "";
5687
+ if ( ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "session" ) || $wfu_user_state_handler != "dboption" ) {
5688
+ $key = session_id();
5689
+ if ( WFU_VAR("WFU_US_SESSION_LEGACY") != "true" && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) ) {
5690
+ session_start();
5691
+ $key = session_id();
5692
+ session_write_close();
5693
+ }
5694
+ }
5695
+ elseif ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "cookies" )
5696
+ $key = wfu_get_session_cookie();
5697
+ return $key;
5698
+ }
5699
+
5700
+ /**
5701
+ * Flatten Session ID.
5702
+ *
5703
+ * This function removes dots and other symbols from session ID.
5704
+ *
5705
+ * @since 4.4.0
5706
+ *
5707
+ * @return string Flattened Session ID.
5708
+ */
5709
+ function wfu_get_safe_session_id() {
5710
+ return preg_replace("/[^a-z0-9_]/", "", strtolower(wfu_get_session_id()));
5711
+ }
5712
+
5713
+ /**
5714
+ * Get DB Option Data.
5715
+ *
5716
+ * This function gets User State data for a specific session, stored in the
5717
+ * website's database.
5718
+ *
5719
+ * @since 4.4.0
5720
+ *
5721
+ * @param string $id The Session ID.
5722
+ * @param string $default Optional. Default value for the data.
5723
+ * @param string $type Optional. The type of data value.
5724
+ *
5725
+ * @return array The DB Option data.
5726
+ */
5727
+ function wfu_get_US_dboption_data($id, $default = false, $type = "array") {
5728
+ if ( $id == "" ) return false;
5729
+ return wfu_get_option("wfu_userstate_".$id, $default, $type);
5730
+ }
5731
+
5732
+ /**
5733
+ * Update DB Option Time.
5734
+ *
5735
+ * This function updates the time that DB Option data of a specific Session
5736
+ * where last used.
5737
+ *
5738
+ * @since 4.4.0
5739
+ *
5740
+ * @param string $id The Session ID.
5741
+ */
5742
+ function wfu_update_US_dboption_time($id) {
5743
+ $list = wfu_get_option("wfu_userstate_list", array());
5744
+ $list[$id] = time();
5745
+ wfu_update_option("wfu_userstate_list", $list);
5746
+ }
5747
+
5748
+ /**
5749
+ * Check if Variable Exists in DB Option (old handler).
5750
+ *
5751
+ * This function checks if a variable exists in DB Option.
5752
+ *
5753
+ * @since 4.4.0
5754
+ *
5755
+ * @param string $var The variable to check.
5756
+ *
5757
+ * @return bool True if the variable exists, false otherwise.
5758
+ */
5759
+ function WFU_USVAR_exists_dboption_old($var) {
5760
+ $id = wfu_get_safe_session_id();
5761
+ $data = wfu_get_US_dboption_data($id);
5762
+ if ( $data === false ) return false;
5763
+ wfu_update_US_dboption_time($id);
5764
+ return isset($data[$var]);
5765
+ }
5766
+
5767
+ /**
5768
+ * Check if Variable Exists in DB Option.
5769
+ *
5770
+ * This function checks if a variable exists in DB Option.
5771
+ *
5772
+ * @since 4.4.0
5773
+ *
5774
+ * @param string $var The variable to check.
5775
+ *
5776
+ * @return bool True if the variable exists, false otherwise.
5777
+ */
5778
+ function WFU_USVAR_exists_dboption($var) {
5779
+ $id = wfu_get_safe_session_id();
5780
+ if ( $id == "" ) return false;
5781
+ $exists = wfu_option_item_exists("wfu_userstate_".$id, $var);
5782
+ wfu_update_US_dboption_time($id);
5783
+ if ( $exists === null ) return false;
5784
+ else return $exists;
5785
+ }
5786
+
5787
+ /**
5788
+ * Get Variable From DB Option (old handler).
5789
+ *
5790
+ * This function gets the value of a variable from DB Option.
5791
+ *
5792
+ * @since 4.4.0
5793
+ *
5794
+ * @param string $var The variable to get.
5795
+ *
5796
+ * @return mixed The value of the variable.
5797
+ */
5798
+ function WFU_USVAR_dboption_old($var) {
5799
+ $id = wfu_get_safe_session_id();
5800
+ $data = wfu_get_US_dboption_data($id);
5801
+ if ( $data === false ) return "";
5802
+ wfu_update_US_dboption_time($id);
5803
+ return $data[$var];
5804
+ }
5805
+
5806
+ /**
5807
+ * Get Variable From DB Option.
5808
+ *
5809
+ * This function gets the value of a variable from DB Option.
5810
+ *
5811
+ * @since 4.4.0
5812
+ *
5813
+ * @param string $var The variable to get.
5814
+ *
5815
+ * @return mixed The value of the variable.
5816
+ */
5817
+ function WFU_USVAR_dboption($var) {
5818
+ $id = wfu_get_safe_session_id();
5819
+ if ( $id == "" ) return "";
5820
+ $value = wfu_get_option_item("wfu_userstate_".$id, $var);
5821
+ wfu_update_US_dboption_time($id);
5822
+ if ( $value === null ) return "";
5823
+ else return wfu_decode_array_from_string($value);
5824
+ }
5825
+
5826
+ /**
5827
+ * Get All DB Option Variables (old handler).
5828
+ *
5829
+ * This function gets the values of all DB Option variables.
5830
+ *
5831
+ * @since 4.4.0
5832
+ *
5833
+ * @return array An array of all DB Option variables.
5834
+ */
5835
+ function WFU_USALL_dboption_old() {
5836
+ $id = wfu_get_safe_session_id();
5837
+ $data = wfu_get_US_dboption_data($id);
5838
+ if ( $data === false ) return array();
5839
+ wfu_update_US_dboption_time($id);
5840
+ return $data;
5841
+ }
5842
+
5843
+ /**
5844
+ * Get All DB Option Variables.
5845
+ *
5846
+ * This function gets the values of all DB Option variables.
5847
+ *
5848
+ * @since 4.4.0
5849
+ *
5850
+ * @return array An array of all DB Option variables.
5851
+ */
5852
+ function WFU_USALL_dboption() {
5853
+ $id = wfu_get_safe_session_id();
5854
+ $data = wfu_get_US_dboption_data($id, false, "string");
5855
+ if ( $data === null ) return array();
5856
+ wfu_update_US_dboption_time($id);
5857
+ $arr = preg_split("/\[([^\]]*\][^{]*){[^}]*}/", $data, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
5858
+ $data_arr = array();
5859
+ foreach ( $arr as $item ) {
5860
+ list($key, $value) = explode("]", $item);
5861
+ $data_arr[$key] = wfu_decode_array_from_string($value);
5862
+ }
5863
+ return $data_arr;
5864
+ }
5865
+
5866
+ /**
5867
+ * Store Variable In DB Option (old handler).
5868
+ *
5869
+ * This function stores the value of a variable in DB Option.
5870
+ *
5871
+ * @since 4.4.0
5872
+ *
5873
+ * @param string $var The variable to store.
5874
+ * @param mixed $value The value of the variable.
5875
+ */
5876
+ function WFU_USVAR_store_dboption_old($var, $value) {
5877
+ $id = wfu_get_safe_session_id();
5878
+ $data = wfu_get_US_dboption_data($id, array());
5879
+ if ( $data === false ) return;
5880
+ $data[$var] = $value;
5881
+ wfu_update_option("wfu_userstate_".$id, $data);
5882
+ wfu_update_US_dboption_time($id);
5883
+ wfu_update_US_dboption_list();
5884
+ }
5885
+
5886
+ /**
5887
+ * Store Variable In DB Option.
5888
+ *
5889
+ * This function stores the value of a variable in DB Option.
5890
+ *
5891
+ * @since 4.4.0
5892
+ *
5893
+ * @param string $var The variable to store.
5894
+ * @param mixed $value The value of the variable.
5895
+ */
5896
+ function WFU_USVAR_store_dboption($var, $value) {
5897
+ $id = wfu_get_safe_session_id();
5898
+ if ( $id == "" ) return;
5899
+ wfu_update_option_item("wfu_userstate_".$id, $var, wfu_encode_array_to_string($value));
5900
+ wfu_update_US_dboption_time($id);
5901
+ wfu_update_US_dboption_list();
5902
+ }
5903
+
5904
+ /**
5905
+ * Remove Variable From DB Option (old handler).
5906
+ *
5907
+ * This function removes a variable from DB Option.
5908
+ *
5909
+ * @since 4.4.0
5910
+ *
5911
+ * @param string $var The variable to remove.
5912
+ */
5913
+ function WFU_USVAR_unset_dboption_old($var) {
5914
+ $id = wfu_get_safe_session_id();
5915
+ $data = wfu_get_US_dboption_data($id);
5916
+ if ( $data === false ) return;
5917
+ unset($data[$var]);
5918
+ wfu_update_option("wfu_userstate_".$id, $data);
5919
+ wfu_update_US_dboption_time($id);
5920
+ }
5921
+
5922
+ /**
5923
+ * Remove Variable From DB Option.
5924
+ *
5925
+ * This function removes a variable from DB Option.
5926
+ *
5927
+ * @since 4.4.0
5928
+ *
5929
+ * @param string $var The variable to remove.
5930
+ */
5931
+ function WFU_USVAR_unset_dboption($var) {
5932
+ $id = wfu_get_safe_session_id();
5933
+ if ( $id == "" ) return;
5934
+ wfu_delete_option_item("wfu_userstate_".$id, $var);
5935
+ wfu_update_US_dboption_time($id);
5936
+ }
5937
+
5938
+ /**
5939
+ * Update DB Option List.
5940
+ *
5941
+ * This function checks when all DB Option Data were last used. DB Option data
5942
+ * that were last used before a long time, means that their Session has expired,
5943
+ * so they are not useful anymore and will be removed.
5944
+ *
5945
+ * @since 4.4.0
5946
+ */
5947
+ function wfu_update_US_dboption_list() {
5948
+ $last_check_interval = time() - wfu_get_option("wfu_userstate_list_last_check", 0);
5949
+ $limit = WFU_VAR("WFU_US_DBOPTION_CHECK");
5950
+ if ( $last_check_interval < $limit ) return;
5951
+
5952
+ $list = wfu_get_option("wfu_userstate_list", array());
5953
+ $changed = false;
5954
+ $limit = WFU_VAR("WFU_US_DBOPTION_LIFE");
5955
+ foreach ( $list as $id => $time ) {
5956
+ $interval = time() - $time;
5957
+ if ( $interval > $limit ) {
5958
+ $changed = true;
5959
+ unset($list[$id]);
5960
+ wfu_delete_option("wfu_userstate_".$id);
5961
+ }
5962
+ }
5963
+ if ( $changed ) wfu_update_option("wfu_userstate_list", $list);
5964
+ wfu_update_option("wfu_userstate_list_last_check", time());
5965
+ }
5966
+
5967
+ //********************* Javascript Related Functions ****************************************************************************************************
5968
+
5969
+ /**
5970
+ * Inject Javascript Code.
5971
+ *
5972
+ * This function generates HTML output for injecting Javascript code. After
5973
+ * execution of the code, the HTML output is erased leaving no traces.
5974
+ *
5975
+ * @since 3.3.0
5976
+ *
5977
+ * @param string $code The Javascript code to inject.
5978
+ *
5979
+ * @return string The HTML output.
5980
+ */
5981
+ function wfu_inject_js_code($code){
5982
+ $id = 'code_'.wfu_create_random_string(8);
5983
+ $html = '<div id="'.$id.'" style="display:none;"><script type="text/javascript">'.$code.'</script><script type="text/javascript">var div = document.getElementById("'.$id.'"); div.parentNode.removeChild(div);</script></div>';
5984
+
5985
+ return $html;
5986
+ }
5987
+
5988
+ //********************* Consent Functions ****************************************************************************************************
5989
+
5990
+ /**
5991
+ * Get Consent Status of User.
5992
+ *
5993
+ * This function gets the consent status of a user.
5994
+ *
5995
+ * @since 4.5.0
5996
+ *
5997
+ * @param WPUser $user The user to get its consent status.
5998
+ *
5999
+ * @return string The consent status of the user:
6000
+ * "1": the user has given its consent.
6001
+ * "0": the user has not given its consent.
6002
+ * "": the user has not answered to consent question.
6003
+ */
6004
+ function wfu_check_user_consent($user) {
6005
+ //returns empty string if user has not completed consent question yet, "1"
6006
+ //if user has given consent, "0" otherwise
6007
+ $result = "";
6008
+ if ( $user->ID > 0 ) {
6009
+ //check in user meta for consent
6010
+ $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
6011
+ if ( $data && isset($data["consent_status"]) )
6012
+ $result = $data["consent_status"];
6013
+ }
6014
+ else {
6015
+ //check in user state for consent
6016
+ if ( WFU_USVAR_exists('WFU_Consent_Data') ) {
6017
+ $data = WFU_USVAR('WFU_Consent_Data');
6018
+ if ( isset($data["consent_status"]) )
6019
+ $result = $data["consent_status"];
6020
+ }
6021
+ }
6022
+
6023
+ return $result;
6024
+ }
6025
+
6026
+ /**
6027
+ * Update Consent Status of User From Front-End.
6028
+ *
6029
+ * This function updates the consent status of a user when asked through an
6030
+ * upload form. If user is logged in, then consent status is stored in its
6031
+ * profile. If the user is not logged in, then consent status is store in User
6032
+ * State.
6033
+ *
6034
+ * @since 4.5.0
6035
+ *
6036
+ * @param WPUser $user The user to store its consent status.
6037
+ * @param string $consent_result The new consent status. It can be "yes", "no"
6038
+ * or "".
6039
+ */
6040
+ function wfu_update_user_consent($user, $consent_result) {
6041
+ if ( $user->ID > 0 ) {
6042
+ //check in user meta for consent
6043
+ $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
6044
+ if ( !$data ) $data = array();
6045
+ $data["consent_status"] = ( $consent_result == "yes" ? "1" : ( $consent_result == "no" ? "0" : "" ) );
6046
+ update_user_meta( $user->ID, 'WFU_Consent_Data', $data );
6047
+ }
6048
+ else {
6049
+ //check in user state for consent
6050
+ if ( WFU_USVAR_exists('WFU_Consent_Data') ) $data = WFU_USVAR('WFU_Consent_Data');
6051
+ else $data = array();
6052
+ $data["consent_status"] = ( $consent_result == "yes" ? "1" : ( $consent_result == "no" ? "0" : "" ) );
6053
+ WFU_USVAR_store( 'WFU_Consent_Data', $data );
6054
+ }
6055
+ }
6056
+
6057
+ /**
6058
+ * Show Consent Status Fields in User's Profile Page.
6059
+ *
6060
+ * This function outputs the HTML code of the consent status fields shown in
6061
+ * user's profile page.
6062
+ *
6063
+ * @since 4.5.0
6064
+ *
6065
+ * @param WPUser $user The involved user.
6066
+ */
6067
+ function wfu_show_consent_profile_fields($user) {
6068
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
6069
+ if ( $plugin_options["personaldata"] != "1" ) return;
6070
+
6071
+ $data = get_the_author_meta( 'WFU_Consent_Data', $user->ID );
6072
+ if ( !$data ) $data = array();
6073
+ if ( !isset($data["consent_status"]) ) $data["consent_status"] = "";
6074
+ $status = $data["consent_status"];
6075
+
6076
+ $echo_str = "\n\t".'<h3>'.esc_html__( 'Wordpress File Upload Consent Status', 'wp-file-upload' ).'</h3>';
6077
+ $echo_str .= "\n\t".'<table class="form-table">';
6078
+ $echo_str .= "\n\t\t".'<tr>';
6079
+ $echo_str .= "\n\t\t\t".'<th><label>'.esc_html__( 'Consent Status', 'wp-file-upload' ).'</label></th>';
6080
+ $echo_str .= "\n\t\t\t".'<td>';
6081
+ $echo_str .= "\n\t\t\t\t".'<label style="font-weight: bold;">'.( $status == "1" ? esc_html__( 'You have given your consent to store personal data.', 'wp-file-upload' ) : ( $status == "0" ? esc_html__( 'You have denied to store personal data.', 'wp-file-upload' ) : esc_html__( 'You have not answered to consent yet.', 'wp-file-upload' ) ) ).'</label>';
6082
+ $echo_str .= "\n\t\t\t".'</td>';
6083
+ $echo_str .= "\n\t\t".'</tr>';
6084
+ $echo_str .= "\n\t\t".'<tr>';
6085
+ $echo_str .= "\n\t\t\t".'<th></th>';
6086
+ $echo_str .= "\n\t\t\t".'<td>';
6087
+ $echo_str .= "\n\t\t\t\t".'<label>'.esc_html__( 'Change status to', 'wp-file-upload' ).'</label>';
6088
+ $echo_str .= "\n\t\t\t\t".'<select name="consent_status">';
6089
+ $echo_str .= "\n\t\t\t\t\t".'<option value="-1" selected="selected">'.esc_html__( 'No change', 'wp-file-upload' ).'</option>';
6090
+ if ( $status == "1" ) {
6091
+ $echo_str .= "\n\t\t\t\t\t".'<option value="0">'.esc_html__( 'Revoke Consent', 'wp-file-upload' ).'</option>';
6092
+ $echo_str .= "\n\t\t\t\t\t".'<option value="">'.esc_html__( 'Clear Consent', 'wp-file-upload' ).'</option>';
6093
+ }
6094
+ elseif ( $status == "0" ) {
6095
+ $echo_str .= "\n\t\t\t\t\t".'<option value="1">'.esc_html__( 'Give Consent', 'wp-file-upload' ).'</option>';
6096
+ $echo_str .= "\n\t\t\t\t\t".'<option value="">'.esc_html__( 'Clear Consent', 'wp-file-upload' ).'</option>';
6097
+ }
6098
+ if ( $status == "" ) {
6099
+ $echo_str .= "\n\t\t\t\t\t".'<option value="0">'.esc_html__( 'Revoke Consent', 'wp-file-upload' ).'</option>';
6100
+ $echo_str .= "\n\t\t\t\t\t".'<option value="1">'.esc_html__( 'Give Consent', 'wp-file-upload' ).'</option>';
6101
+ }
6102
+ $echo_str .= "\n\t\t\t\t".'</select>';
6103
+ $echo_str .= "\n\t\t\t".'</td>';
6104
+ $echo_str .= "\n\t\t".'</tr>';
6105
+ /*
6106
+ if ( current_user_can( 'manage_options' ) ) {
6107
+ $echo_str .= "\n\t\t".'<tr>';
6108
+ $echo_str .= "\n\t\t\t".'<th><label>'.esc_html__( 'Personal Data Operations', 'wp-file-upload' ).'</label></th>';
6109
+ $echo_str .= "\n\t\t\t".'<td>';
6110
+ $echo_str .= "\n\t\t\t\t".'<input id="wfu_download_file_nonce" type="hidden" value="'.wp_create_nonce('wfu_download_file_invoker').'" />';
6111
+ $echo_str .= "\n\t\t\t\t".'<button type="button" class="button" onclick="wfu_download_file(\'exportdata\', 1);">'.esc_html__( 'Export User Data', 'wp-file-upload' ).'</button>';
6112
+ $echo_str .= "\n\t\t\t".'</td>';
6113
+ $echo_str .= "\n\t\t".'</tr>';
6114
+ }*/
6115
+ $echo_str .= "\n\t".'</table>';
6116
+
6117
+ echo $echo_str;
6118
+ }
6119
+
6120
+ /**
6121
+ * Update Consent Status of User From Back-End.
6122
+ *
6123
+ * This function updates the consent status of a user from its User Profile
6124
+ * page.
6125
+ *
6126
+ * @since 4.5.0
6127
+ *
6128
+ * @param int $user_id The ID of the involved user.
6129
+ */
6130
+ function wfu_update_consent_profile_fields( $user_id ) {
6131
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
6132
+ if ( $plugin_options["personaldata"] != "1" ) return false;
6133
+
6134
+ if ( ! current_user_can( 'edit_user', $user_id ) ) {
6135
+ return false;
6136
+ }
6137
+
6138
+ $status = $_POST['consent_status'];
6139
+ if ( $status == '1' || $status == '0' || $status == '' ) {
6140
+ $data = get_the_author_meta( 'WFU_Consent_Data', $user_id );
6141
+ if ( !$data ) $data = array();
6142
+ $data["consent_status"] = $status;
6143
+ update_user_meta( $user_id, 'WFU_Consent_Data', $data );
6144
+ }
6145
+ }
6146
+
6147
+ //********************* Browser Functions ****************************************************************************************************
6148
+
6149
+ /**
6150
+ * Store Front-End File Viewer Shortcode Attributes.
6151
+ *
6152
+ * This function stores the shortcode attributes of a front-end file viewer in
6153
+ * User Space for future retrieval.
6154
+ *
6155
+ * @since 3.6.1
6156
+ *
6157
+ * @param string $params The front-end file viewer shortcode attributes.
6158
+ *
6159
+ * @return string A unique code representing the stored shortcode.
6160
+ */
6161
+ function wfu_safe_store_browser_params($params) {
6162
+ $code = wfu_create_random_string(16);
6163
+ $safe_storage = ( WFU_USVAR_exists('wfu_browser_actions_safe_storage') ? WFU_USVAR('wfu_browser_actions_safe_storage') : array() );
6164
+ $safe_storage[$code] = $params;
6165
+ WFU_USVAR_store('wfu_browser_actions_safe_storage', $safe_storage);
6166
+ return $code;
6167
+ }
6168
+
6169
+ /**
6170
+ * Retrieve Stored Front-End File Viewer Shortcode Attributes.
6171
+ *
6172
+ * This function retrieved stored shortcode attributes of a front-end file
6173
+ * viewer from User Space.
6174
+ *
6175
+ * @since 3.6.1
6176
+ *
6177
+ * @param string $code A unique code representing the stored shortcode.
6178
+ *
6179
+ * @return string The stored shortcode attributes.
6180
+ */
6181
+ function wfu_get_browser_params_from_safe($code) {
6182
+ //sanitize $code
6183
+ $code = wfu_sanitize_code($code);
6184
+ if ( $code == "" ) return false;
6185
+ //return params from session variable, if exists
6186
+ if ( !WFU_USVAR_exists('wfu_browser_actions_safe_storage') ) return false;
6187
+ $safe_storage = WFU_USVAR('wfu_browser_actions_safe_storage');
6188
+ if ( !isset($safe_storage[$code]) ) return false;
6189
+ return $safe_storage[$code];
6190
+ }
6191
+
6192
+ //********************* POST/GET Requests Functions ****************************************************************************************************
6193
+
6194
+ /**
6195
+ * Add Proxy in HTTP Request.
6196
+ *
6197
+ * This function adds proxy information inside an HTTP request configuration, if
6198
+ * proxy information is defined inside the website's configuration and if it is
6199
+ * active.
6200
+ *
6201
+ * @since 4.10.0
6202
+ *
6203
+ * @param array $config An HTTP request configuration structure.
6204
+ *
6205
+ * @return bool True if proxy is enabled and added, false otherwise.
6206
+ */
6207
+ function wfu_add_proxy_param(&$config) {
6208
+ //include proxy support
6209
+ $proxy = new \WP_HTTP_Proxy();
6210
+ $proxy_enabled = $proxy->is_enabled();
6211
+ if ( $proxy_enabled ) {
6212
+ $config['proxy']['http'] = 'http://'.( $proxy->use_authentication() ? $proxy->authentication().'@' : '' ).$proxy->host().":".$proxy->port();
6213
+ $config['proxy']['https'] = 'http://'.( $proxy->use_authentication() ? $proxy->authentication().'@' : '' ).$proxy->host().":".$proxy->port();
6214
+ //make sure that wildcard asterisks (*) are removed from bypass hosts
6215
+ //to make it compatible with Guzzle format
6216
+ if ( defined('WP_PROXY_BYPASS_HOSTS') ) $config['proxy']['no'] = preg_split('|,\s*|', str_replace('*', '', WP_PROXY_BYPASS_HOSTS));
6217
+ }
6218
+
6219
+ return $proxy_enabled;
6220
+ }
6221
+
6222
+ /**
6223
+ * Parse Socket HTTP Response.
6224
+ *
6225
+ * This function tries to decode an HTTP response received through sockets and
6226
+ * return the clean response data.
6227
+ *
6228
+ * @since 3.10.0
6229
+ *
6230
+ * @param string $response The raw sockets HTTP response.
6231
+ *
6232
+ * @return string The clean HTTP response data.
6233
+ */
6234
+ function wfu_decode_socket_response($response) {
6235
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
6236
+ $ret = "";
6237
+ if (0 === strpos($response, 'HTTP/1.1 200 OK')) {
6238
+ $parts = preg_split("#\n\s*\n#Uis", $response);
6239
+ if ( count($parts) > 1 ) {
6240
+ $rawheader = strtolower(preg_replace("/\s/", "", $parts[0]));
6241
+ if ( strpos($rawheader, 'transfer-encoding:chunked') !== false ) {
6242
+ $ret = "";
6243
+ $pos = 0;
6244
+ while ( $pos < strlen($parts[1]) ) {
6245
+ $next = strpos($parts[1], "\r\n", $pos);
6246
+ $len = ( $next === false || $next == $pos ? 0 : hexdec(substr($parts[1], $pos, $next - $pos)) );
6247
+ if ( $len <= 0 ) break;
6248
+ $ret .= substr($parts[1], $next + 2, $len);
6249
+ $pos = $next + $len + 4;
6250
+ }
6251
+ }
6252
+ else $ret = $parts[1];
6253
+ }
6254
+ }
6255
+ return $ret;
6256
+ }
6257
+
6258
+ /**
6259
+ * Send POST Request.
6260
+ *
6261
+ * This function sends a POST request using the method defined in Post Method
6262
+ * option of the plugin's Settings. It is noted that the post request is
6263
+ * executed synchronously. The function will wait for the response and then it
6264
+ * will finish.
6265
+ *
6266
+ * @since 2.6.0
6267
+ *
6268
+ * @param string $url The destination URL of the request.
6269
+ * @param array $params Parameters to pass to the POST request.
6270
+ * @param bool $verifypeer Optional. Verify the peer for secure (SSL) requests.
6271
+ * @param bool $internal_request Optional. True if this is an internal request
6272
+ * to targetting /wp-admin area. In this case a username/password will
6273
+ * also be passed to the request if Dashboard is password protected.
6274
+ * @param int $timeout Optional. Timeout of the request in seconds.
6275
+ *
6276
+ * @return string The response of the POST request.
6277
+ */
6278
+ function wfu_post_request($url, $params, $verifypeer = true, $internal_request = false, $timeout = 0) {
6279
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
6280
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
6281
+ $default_args = array(
6282
+ 'url' => $url,
6283
+ 'params' => $params,
6284
+ 'verifypeer' => $verifypeer,
6285
+ 'internal_request' => $internal_request,
6286
+ 'timeout' => $timeout
6287
+ );
6288
+ //check proxy
6289
+ $proxy = new WP_HTTP_Proxy();
6290
+ if ( isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'curl' ) {
6291
+ // POST request using CURL
6292
+ $ch = curl_init($url);
6293
+ $options = array(
6294
+ CURLOPT_POST => true,
6295
+ CURLOPT_POSTFIELDS => http_build_query($params),
6296
+ CURLOPT_HTTPHEADER => array(
6297
+ 'Content-Type: application/x-www-form-urlencoded'
6298
+ ),
6299
+ CURLINFO_HEADER_OUT => false,
6300
+ CURLOPT_HEADER => false,
6301
+ CURLOPT_RETURNTRANSFER => true,
6302
+ CURLOPT_SSL_VERIFYPEER => $verifypeer,
6303
+ CURLOPT_SSL_VERIFYHOST => ( $verifypeer ? CURLOPT_SSL_VERIFYHOST : false )
6304
+ );
6305
+ if ( $timeout > 0 ) $options[CURLOPT_TIMEOUT] = $timeout;
6306
+ //for internal requests to /wp-admin area that is password protected
6307
+ //authorization is required
6308
+ if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
6309
+ $options[CURLOPT_HTTPAUTH] = CURLAUTH_ANY;
6310
+ $options[CURLOPT_USERPWD] = WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD");
6311
+ }
6312
+ if ( WFU_VAR("WFU_RELAX_CURL_VERIFY_HOST") == "true" ) $options[CURLOPT_SSL_VERIFYHOST] = false;
6313
+ //configure cURL request for proxy
6314
+ if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
6315
+ $options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
6316
+ $options[CURLOPT_PROXY] = $proxy->host().":".$proxy->port();
6317
+ if ( $proxy->use_authentication() ) {
6318
+ $options[CURLOPT_PROXYAUTH] = CURLAUTH_ANY;
6319
+ $options[CURLOPT_PROXYUSERPWD] = $proxy->authentication();
6320
+ }
6321
+ }
6322
+ /**
6323
+ * Customize POST Request Options.
6324
+ *
6325
+ * This filter allows custom actions to modify the POST request options
6326
+ * before the request is sent.
6327
+ *
6328
+ * @since 4.10.0
6329
+ *
6330
+ * @param array $options An array of POST options.
6331
+ * @param string $method The POST method. It can be 'fopen', 'curl' or
6332
+ * 'sockets'.
6333
+ * @param array $default_args {
6334
+ * Parameters of the POST request.
6335
+ *
6336
+ * @type string $url Destination URL.
6337
+ * @type array $params The POST parameters.
6338
+ * @type bool $verifypeer True if peer needs to be verified.
6339
+ * @type bool $internal_request True if this is an internal
6340
+ * request (sent back to the website).
6341
+ * @type int $timeout The request timeout in seconds.
6342
+ * }
6343
+ */
6344
+ $options = apply_filters("_wfu_post_request_options", $options, "curl", $default_args);
6345
+ curl_setopt_array($ch, $options);
6346
+ $result = curl_exec($ch);
6347
+ curl_close ($ch);
6348
+ return $result;
6349
+ }
6350
+ elseif ( isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'socket' ) {
6351
+ // POST request using sockets
6352
+ $scheme = "";
6353
+ $port = 80;
6354
+ $errno = 0;
6355
+ $errstr = '';
6356
+ $ret = '';
6357
+ $url_parts = parse_url($url);
6358
+ $host = $url_parts['host'];
6359
+ $socket_host = $host;
6360
+ $path = $url_parts['path'];
6361
+ if ( $url_parts['scheme'] == 'https' ) {
6362
+ $scheme = "ssl://";
6363
+ $port = 443;
6364
+ if ( $timeout == 0 ) $timeout = 30;
6365
+ }
6366
+ elseif ( $url['scheme'] != 'http' ) return '';
6367
+ //configure sockets request for proxy
6368
+ if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
6369
+ $scheme = "";
6370
+ $socket_host = $proxy->host();
6371
+ $port = $proxy->port();
6372
+ $path = $url;
6373
+ }
6374
+ if ( $verifypeer ) $handle = fsockopen($scheme.$socket_host, $port, $errno, $errstr, ($timeout == 0 ? ini_get("default_socket_timeout") : $timeout));
6375
+ else {
6376
+ $context = stream_context_create(array(
6377
+ 'ssl' => array(
6378
+ 'verify_peer' => false,
6379
+ 'verify_peer_name' => false
6380
+ )));
6381
+ $handle = stream_socket_client($scheme.$socket_host.":".$port, $errno, $errstr, ($timeout == 0 ? ini_get("default_socket_timeout") : $timeout), STREAM_CLIENT_CONNECT, $context);
6382
+ }
6383
+ if ( $errno !== 0 || $errstr !== '' ) $handle = false;
6384
+ if ( $handle !== false ) {
6385
+ $content = http_build_query($params);
6386
+ $request = "POST " . $path . " HTTP/1.1\r\n";
6387
+ $request .= "Host: " . $host . "\r\n";
6388
+ $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
6389
+ //for internal requests to /wp-admin area that is password protected
6390
+ //authorization is required
6391
+ if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" )
6392
+ $request .= "Authorization: Basic ".base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD"))."\r\n";
6393
+ //add proxy authentication if exists and is required
6394
+ if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) && $proxy->use_authentication() )
6395
+ $request .= $proxy->authentication_header()."\r\n";
6396
+ $request .= "Content-length: " . strlen($content) . "\r\n";
6397
+ $request .= "Connection: close\r\n\r\n";
6398
+ $request .= $content . "\r\n\r\n";
6399
+ /** This filter is explained above. */
6400
+ $request = apply_filters("_wfu_post_request_options", $request, "socket", $default_args);
6401
+ fwrite($handle, $request, strlen($request));
6402
+ $response = '';
6403
+ while ( !feof($handle) ) {
6404
+ $response .= fgets($handle, 4096);
6405
+ }
6406
+ fclose($handle);
6407
+ $ret = wfu_decode_socket_response($response);
6408
+ }
6409
+ return $ret;
6410
+ }
6411
+ else {
6412
+ // POST request using file_get_contents
6413
+ if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
6414
+ $url = preg_replace("/^(http|https):\/\//", "$1://".WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD")."@", $url);
6415
+ }
6416
+ $peer_key = version_compare(PHP_VERSION, '5.6.0', '<') ? 'CN_name' : 'peer_name';
6417
+ $http_array = array(
6418
+ 'method' => 'POST',
6419
+ 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
6420
+ 'content' => http_build_query($params)
6421
+ );
6422
+ //configure fopen request for proxy
6423
+ if ( $proxy->is_enabled() && $proxy->send_through_proxy($url) ) {
6424
+ $http_array['proxy'] = 'tcp://'.$proxy->host().":".$proxy->port();
6425
+ if ( $proxy->use_authentication() )
6426
+ $http_array['header'] .= $proxy->authentication_header()."\r\n";
6427
+ }
6428
+ if ( $timeout > 0 ) $http_array['timeout'] = $timeout;
6429
+ //for internal requests to /wp-admin area that is password protected
6430
+ //authorization is required
6431
+ if ( $internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true" ) {
6432
+ $http_array['header'] .= "Authorization: Basic ".base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME").":".WFU_VAR("WFU_DASHBOARD_PASSWORD"))."\r\n";
6433
+ }
6434
+ $context_params = array( 'http' => $http_array );
6435
+ if ( !$verifypeer ) $context_params['ssl'] = array( 'verify_peer' => false, 'allow_self_signed' => true, 'verify_peer_name' => false );
6436
+ /** This filter is explained above. */
6437
+ $context_params = apply_filters("_wfu_post_request_options", $context_params, "fopen", $default_args);
6438
+ $context = stream_context_create($context_params);
6439
+ return file_get_contents($url, false, $context);
6440
+ }
6441
+ }
6442
+
6443
+ ?>
lib/wfu_io.php CHANGED
@@ -1,5 +1,19 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  function wfu_mk_dir_deep($conn_id, $basepath, $path) {
4
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
5
  @ftp_chdir($conn_id, $basepath);
@@ -13,29 +27,38 @@ function wfu_mk_dir_deep($conn_id, $basepath, $path) {
13
  }
14
  }
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  function wfu_is_dir($path, $ftpdata) {
17
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
18
  $result = false;
 
19
  if ( substr($path, 0, 7) == "sftp://" ) {
20
- $ftpdata_flat = str_replace(array('\:', '\@'), array('\_', '\_'), $ftpdata);
21
- $pos1 = strpos($ftpdata_flat, ":");
22
- $pos2 = strpos($ftpdata_flat, "@");
23
- if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
24
- $ftp_username = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
25
- $ftp_password = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, $pos1 + 1, $pos2 - $pos1 - 1));
26
- $ftp_host = substr($ftpdata, $pos2 + 1);
27
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
28
- $ftp_host_clean = preg_replace("/:.*/", "", $ftp_host);
29
- if ( substr($ftp_port, 0, 1) == "s" ) {
30
- $ftp_port = substr($ftp_port, 1);
31
- if ( $ftp_port == "" ) $ftp_port = "22";
32
- $ftp_host = $ftp_host_clean.":".$ftp_port;
33
- $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $ftp_host);
34
- $pos1 = strpos($path, $flat_host);
35
- if ( $pos1 ) {
36
- $path = substr($path, $pos1 + strlen($flat_host));
37
- $conn = ssh2_connect($ftp_host_clean, $ftp_port);
38
- if ( $conn && @ssh2_auth_password($conn, $ftp_username, $ftp_password) ) {
39
  $sftp = @ssh2_sftp($conn);
40
  if ( $sftp ) {
41
  $result = is_dir('ssh2.sftp://'.intval($sftp).$path);
@@ -44,13 +67,28 @@ function wfu_is_dir($path, $ftpdata) {
44
  }
45
  }
46
  }
47
-
48
  }
49
  else $result = is_dir($path);
50
 
51
  return $result;
52
  }
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  function wfu_create_directory($path, $method, $ftpdata) {
55
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
56
  $ret_message = "";
@@ -58,33 +96,23 @@ function wfu_create_directory($path, $method, $ftpdata) {
58
  mkdir($path, 0777, true);
59
  }
60
  else if ( $method == "ftp" && $ftpdata != "" ) {
61
- $ftpdata_flat = str_replace(array('\:', '\@'), array('\_', '\_'), $ftpdata);
62
- $pos1 = strpos($ftpdata_flat, ":");
63
- $pos2 = strpos($ftpdata_flat, "@");
64
- if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
65
- $ftp_username = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
66
- $ftp_password = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, $pos1 + 1, $pos2 - $pos1 - 1));
67
- $ftp_host = substr($ftpdata, $pos2 + 1);
68
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
69
- $ftp_host_clean = preg_replace("/:.*/", "", $ftp_host);
70
- $is_sftp = false;
71
- if ( substr($ftp_port, 0, 1) == "s" ) {
72
- $is_sftp = true;
73
- $ftp_port = substr($ftp_port, 1);
74
- if ( $ftp_port == "" ) $ftp_port = "22";
75
- }
76
- if ( $ftp_port != "" ) $ftp_host = $ftp_host_clean.":".$ftp_port;
77
- $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $ftp_host);
78
  $pos1 = strpos($path, $flat_host);
79
  if ( $pos1 ) {
80
  $path = substr($path, $pos1 + strlen($flat_host));
81
- if ( $is_sftp && $ftp_port != "" ) {
82
- wfu_create_dir_deep_sftp($ftp_host_clean, $ftp_port, $ftp_username, $ftp_password, $path);
83
  }
84
  else {
85
- if ( $ftp_port != "" ) $conn_id = ftp_connect($ftp_host_clean, $ftp_port);
86
- else $conn_id = ftp_connect($ftp_host_clean);
87
- $login_result = ftp_login($conn_id, $ftp_username, $ftp_password);
88
  if ( $conn_id && $login_result ) {
89
  wfu_mk_dir_deep($conn_id, '/', $path);
90
  }
@@ -98,7 +126,6 @@ function wfu_create_directory($path, $method, $ftpdata) {
98
  $ret_message = WFU_ERROR_ADMIN_FTPFILE_RESOLVE;
99
  }
100
  }
101
-
102
  else {
103
  $ret_message = WFU_ERROR_ADMIN_FTPINFO_EXTRACT;
104
  }
@@ -109,7 +136,33 @@ function wfu_create_directory($path, $method, $ftpdata) {
109
  return $ret_message;
110
  }
111
 
112
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  function wfu_upload_file($source, $target, $method, $ftpdata, $passive, $fileperms) {
114
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
115
  $ret_array = array();
@@ -127,35 +180,25 @@ function wfu_upload_file($source, $target, $method, $ftpdata, $passive, $fileper
127
  }
128
  elseif ( $method == "ftp" && $ftpdata != "" ) {
129
  $result = false;
130
- $ftpdata_flat = str_replace(array('\:', '\@'), array('\_', '\_'), $ftpdata);
131
- $pos1 = strpos($ftpdata_flat, ":");
132
- $pos2 = strpos($ftpdata_flat, "@");
133
- if ( $pos1 && $pos2 && $pos2 > $pos1 ) {
134
- $ftp_username = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, 0, $pos1));
135
- $ftp_password = str_replace(array('\:', '\@'), array(':', '@'), substr($ftpdata, $pos1 + 1, $pos2 - $pos1 - 1));
136
- $ftp_host = substr($ftpdata, $pos2 + 1);
137
- $ftp_port = preg_replace("/^[^:]*:?/", "", $ftp_host);
138
- $ftp_host_clean = preg_replace("/:.*/", "", $ftp_host);
139
- $is_sftp = false;
140
- if ( substr($ftp_port, 0, 1) == "s" ) {
141
- $is_sftp = true;
142
- $ftp_port = substr($ftp_port, 1);
143
- if ( $ftp_port == "" ) $ftp_port = "22";
144
- }
145
- if ( $ftp_port != "" ) $ftp_host = $ftp_host_clean.":".$ftp_port;
146
- $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $ftp_host);
147
  $pos1 = strpos($target, $flat_host);
148
  if ( $pos1 ) {
149
  $target = substr($target, $pos1 + strlen($flat_host));
150
- if ( $is_sftp && $ftp_port != "" ) {
151
- $ret_message = wfu_upload_file_sftp($ftp_host_clean, $ftp_port, $ftp_username, $ftp_password, $source, $target, $fileperms);
152
  $ret_array["uploaded"] = ( $ret_message == "" );
153
  unlink($source);
154
  }
155
  else {
156
- if ( $ftp_port != "" ) $conn_id = ftp_connect($ftp_host_clean, $ftp_port);
157
- else $conn_id = ftp_connect($ftp_host_clean);
158
- $login_result = ftp_login($conn_id, $ftp_username, $ftp_password);
159
  if ( $conn_id && $login_result ) {
160
  if ( $passive == "true" ) ftp_pasv($conn_id, true);
161
  // $temp_fname = tempnam(dirname($target), "tmp");
@@ -187,7 +230,7 @@ function wfu_upload_file($source, $target, $method, $ftpdata, $passive, $fileper
187
  }
188
  }
189
  else {
190
- $ret_message = WFU_ERROR_ADMIN_FTPINFO_EXTRACT.$ftpdata_flat;
191
  }
192
  }
193
  else {
@@ -198,33 +241,56 @@ function wfu_upload_file($source, $target, $method, $ftpdata, $passive, $fileper
198
  return $ret_array;
199
  }
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  function wfu_upload_file_sftp($ftp_host, $ftp_port, $ftp_username, $ftp_password, $source, $target, $fileperms) {
202
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
203
  $ret_message = "";
204
- $conn = @ssh2_connect($ftp_host, $ftp_port);
205
- if ( !$conn ) $ret_message = WFU_ERROR_ADMIN_FTPHOST_FAIL;
206
- else {
207
- if ( !@ssh2_auth_password($conn, $ftp_username, $ftp_password) ) $ret_message = WFU_ERROR_ADMIN_FTPLOGIN_FAIL;
208
  else {
209
- $sftp = @ssh2_sftp($conn);
210
- if ( !$sftp ) $ret_message = WFU_ERROR_ADMIN_SFTPINIT_FAIL;
211
  else {
212
- $f = @fopen("ssh2.sftp://".intval($sftp)."$target", 'w');
213
- if ( !$f ) $ret_message = WFU_ERROR_ADMIN_FTPFILE_RESOLVE;
214
  else {
215
- $contents = @file_get_contents($source);
216
- if ( $contents === false ) $ret_message = WFU_ERROR_ADMIN_FTPSOURCE_FAIL;
217
  else {
218
- if ( @fwrite($f, $contents) === false ) $ret_message = WFU_ERROR_ADMIN_FTPTRANSFER_FAIL;
219
- //apply user-defined permissions to file
220
- $fileperms = trim($fileperms);
221
- if ( strlen($fileperms) == 4 && sprintf("%04o", octdec($fileperms)) == $fileperms ) {
222
- $fileperms = octdec($fileperms);
223
- $fileperms = (int)$fileperms;
224
- ssh2_sftp_chmod($sftp, $target, $fileperms);
 
 
 
 
225
  }
 
226
  }
227
- @fclose($f);
228
  }
229
  }
230
  }
@@ -233,18 +299,39 @@ function wfu_upload_file_sftp($ftp_host, $ftp_port, $ftp_username, $ftp_password
233
  return $ret_message;
234
  }
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  function wfu_create_dir_deep_sftp($ftp_host, $ftp_port, $ftp_username, $ftp_password, $path) {
237
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
238
  $ret_message = "";
239
- $conn = @ssh2_connect($ftp_host, $ftp_port);
240
- if ( !$conn ) $ret_message = WFU_ERROR_ADMIN_FTPHOST_FAIL;
241
- else {
242
- if ( !@ssh2_auth_password($conn, $ftp_username, $ftp_password) ) $ret_message = WFU_ERROR_ADMIN_FTPLOGIN_FAIL;
243
  else {
244
- $sftp = @ssh2_sftp($conn);
245
- if ( !$sftp ) $ret_message = WFU_ERROR_ADMIN_SFTPINIT_FAIL;
246
  else {
247
- ssh2_sftp_mkdir($sftp, $path, 493, true );
 
 
 
 
248
  }
249
  }
250
  }
1
  <?php
2
 
3
+ /**
4
+ * Create FTP Directory Recursively.
5
+ *
6
+ * This function creates an FTP directory recursively (including
7
+ * subdirectories).
8
+ *
9
+ * @since 3.10.0
10
+ *
11
+ * @redeclarable
12
+ *
13
+ * @param stream $conn_id The FTP connection ID.
14
+ * @param string $basepath The parent path of the directory to be created.
15
+ * @param string $path The directory to be created.
16
+ */
17
  function wfu_mk_dir_deep($conn_id, $basepath, $path) {
18
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
19
  @ftp_chdir($conn_id, $basepath);
27
  }
28
  }
29
 
30
+ /**
31
+ * Check If Path Is Directory.
32
+ *
33
+ * This function checks whether a path is a valid directory.
34
+ *
35
+ * @since 3.9.1
36
+ *
37
+ * @redeclarable
38
+ *
39
+ * @param string $path The path to check.
40
+ * @param string $ftpdata FTP credentials in case of FTP method.
41
+ *
42
+ * @return bool True if the path is directory, false otherwise.
43
+ */
44
  function wfu_is_dir($path, $ftpdata) {
45
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
46
  $result = false;
47
+ //check whether this is an sftp dir
48
  if ( substr($path, 0, 7) == "sftp://" ) {
49
+ $ftpinfo = wfu_decode_ftpinfo($ftpdata);
50
+ if ( !$ftpinfo["error"] ) {
51
+ $data = $ftpinfo["data"];
52
+ //extract relative FTP path
53
+ $ftp_port = $data["port"];
54
+ if ( $ftp_port == "" ) $ftp_port = "22";
55
+ $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $data["ftpdomain"].":".$ftp_port);
56
+ $pos1 = strpos($path, $flat_host);
57
+ if ( $pos1 ) {
58
+ $path = substr($path, $pos1 + strlen($flat_host));
59
+ {
60
+ $conn = ssh2_connect($data["ftpdomain"], $ftp_port);
61
+ if ( $conn && @ssh2_auth_password($conn, $data["username"], $data["password"]) ) {
 
 
 
 
 
 
62
  $sftp = @ssh2_sftp($conn);
63
  if ( $sftp ) {
64
  $result = is_dir('ssh2.sftp://'.intval($sftp).$path);
67
  }
68
  }
69
  }
 
70
  }
71
  else $result = is_dir($path);
72
 
73
  return $result;
74
  }
75
 
76
+ /**
77
+ * Create Directory.
78
+ *
79
+ * This function creates a directory.
80
+ *
81
+ * @since 2.1.2
82
+ *
83
+ * @redeclarable
84
+ *
85
+ * @param string $path The path of the directory to create.
86
+ * @param string $method File upload method, 'normal' or 'ftp'.
87
+ * @param string $ftpdata FTP credentials in case of FTP method.
88
+ *
89
+ * @return string Empty string if the directory was created successfully, or an
90
+ * error message if it failed.
91
+ */
92
  function wfu_create_directory($path, $method, $ftpdata) {
93
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
94
  $ret_message = "";
96
  mkdir($path, 0777, true);
97
  }
98
  else if ( $method == "ftp" && $ftpdata != "" ) {
99
+ $ftpinfo = wfu_decode_ftpinfo($ftpdata);
100
+ if ( !$ftpinfo["error"] ) {
101
+ $data = $ftpinfo["data"];
102
+ //extract relative FTP path
103
+ $ftp_port = $data["port"];
104
+ if ( $data["sftp"] && $ftp_port == "" ) $ftp_port = "22";
105
+ $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $data["ftpdomain"].( $ftp_port != "" ? ":".$ftp_port : "" ));
 
 
 
 
 
 
 
 
 
 
106
  $pos1 = strpos($path, $flat_host);
107
  if ( $pos1 ) {
108
  $path = substr($path, $pos1 + strlen($flat_host));
109
+ if ( $data["sftp"] ) {
110
+ wfu_create_dir_deep_sftp($data["ftpdomain"], $ftp_port, $data["username"], $data["password"], $path);
111
  }
112
  else {
113
+ if ( $ftp_port != "" ) $conn_id = ftp_connect($data["ftpdomain"], $ftp_port);
114
+ else $conn_id = ftp_connect($data["ftpdomain"]);
115
+ $login_result = ftp_login($conn_id, $data["username"], $data["password"]);
116
  if ( $conn_id && $login_result ) {
117
  wfu_mk_dir_deep($conn_id, '/', $path);
118
  }
126
  $ret_message = WFU_ERROR_ADMIN_FTPFILE_RESOLVE;
127
  }
128
  }
 
129
  else {
130
  $ret_message = WFU_ERROR_ADMIN_FTPINFO_EXTRACT;
131
  }
136
  return $ret_message;
137
  }
138
 
139
+ /**
140
+ * Store the Uploaded File.
141
+ *
142
+ * This function stores the uploaded file that was saved in a temporary location
143
+ * to its final destination. In case of a chunked upload, then the source does
144
+ * not contain the whole file, but only a part of it. The chunk is stored in the
145
+ * partial file in the correct position.
146
+ *
147
+ * @since 2.1.2
148
+ *
149
+ * @redeclarable
150
+ *
151
+ * @param string $source The temporary source path of the uploaded file.
152
+ * @param string $target The final path of the uploaded file.
153
+ * @param string $method File upload method, 'normal', 'ftp' or 'chunked'. In
154
+ * case of 'chunked' method it contains information about the chunks.
155
+ * @param string $ftpdata FTP credentials in case of FTP method.
156
+ * @param string $passive 'true' if FTP passive mode will be used.
157
+ * @param string $fileperms File permissions of the stored file (FTP method).
158
+ *
159
+ * @return array {
160
+ * Store result info.
161
+ *
162
+ * @type bool $uploaded True if the file was stored successfully.
163
+ * @type string $admin_message An admin error message on failure.
164
+ * }
165
+ */
166
  function wfu_upload_file($source, $target, $method, $ftpdata, $passive, $fileperms) {
167
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
168
  $ret_array = array();
180
  }
181
  elseif ( $method == "ftp" && $ftpdata != "" ) {
182
  $result = false;
183
+ $ftpinfo = wfu_decode_ftpinfo($ftpdata);
184
+ if ( !$ftpinfo["error"] ) {
185
+ $data = $ftpinfo["data"];
186
+ //extract relative FTP path
187
+ $ftp_port = $data["port"];
188
+ if ( $data["sftp"] && $ftp_port == "" ) $ftp_port = "22";
189
+ $flat_host = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $data["ftpdomain"].( $ftp_port != "" ? ":".$ftp_port : "" ));
 
 
 
 
 
 
 
 
 
 
190
  $pos1 = strpos($target, $flat_host);
191
  if ( $pos1 ) {
192
  $target = substr($target, $pos1 + strlen($flat_host));
193
+ if ( $data["sftp"] ) {
194
+ $ret_message = wfu_upload_file_sftp($data["ftpdomain"], $ftp_port, $data["username"], $data["password"], $source, $target, $fileperms);
195
  $ret_array["uploaded"] = ( $ret_message == "" );
196
  unlink($source);
197
  }
198
  else {
199
+ if ( $ftp_port != "" ) $conn_id = ftp_connect($data["ftpdomain"], $ftp_port);
200
+ else $conn_id = ftp_connect($data["ftpdomain"]);
201
+ $login_result = ftp_login($conn_id, $data["username"], $data["password"]);
202
  if ( $conn_id && $login_result ) {
203
  if ( $passive == "true" ) ftp_pasv($conn_id, true);
204
  // $temp_fname = tempnam(dirname($target), "tmp");
230
  }
231
  }
232
  else {
233
+ $ret_message = WFU_ERROR_ADMIN_FTPINFO_EXTRACT.$ftpdata;
234
  }
235
  }
236
  else {
241
  return $ret_array;
242
  }
243
 
244
+ /**
245
+ * Store the Uploaded File in sFTP.
246
+ *
247
+ * This function stores the uploaded file that was saved in a temporary location
248
+ * to its final sFTP destination.
249
+ *
250
+ * @since 4.0.0
251
+ *
252
+ * @redeclarable
253
+ *
254
+ * @param string $ftp_host The sFTP host.
255
+ * @param string $ftp_port The sFTP port.
256
+ * @param string $ftp_username Username for sFTP authentication.
257
+ * @param string $ftp_password Password for sFTP authentication.
258
+ * @param string $source The temporary source path of the uploaded file.
259
+ * @param string $target The final path of the uploaded file.
260
+ * @param string $fileperms File permissions of the stored file (FTP method).
261
+ *
262
+ * @return string Empty string if the file was stored successfully, or an error
263
+ * message if it failed.
264
+ */
265
  function wfu_upload_file_sftp($ftp_host, $ftp_port, $ftp_username, $ftp_password, $source, $target, $fileperms) {
266
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
267
  $ret_message = "";
268
+ {
269
+ $conn = @ssh2_connect($ftp_host, $ftp_port);
270
+ if ( !$conn ) $ret_message = WFU_ERROR_ADMIN_FTPHOST_FAIL;
 
271
  else {
272
+ if ( !@ssh2_auth_password($conn, $ftp_username, $ftp_password) ) $ret_message = WFU_ERROR_ADMIN_FTPLOGIN_FAIL;
 
273
  else {
274
+ $sftp = @ssh2_sftp($conn);
275
+ if ( !$sftp ) $ret_message = WFU_ERROR_ADMIN_SFTPINIT_FAIL;
276
  else {
277
+ $f = @fopen("ssh2.sftp://".intval($sftp)."$target", 'w');
278
+ if ( !$f ) $ret_message = WFU_ERROR_ADMIN_FTPFILE_RESOLVE;
279
  else {
280
+ $contents = @file_get_contents($source);
281
+ if ( $contents === false ) $ret_message = WFU_ERROR_ADMIN_FTPSOURCE_FAIL;
282
+ else {
283
+ if ( @fwrite($f, $contents) === false ) $ret_message = WFU_ERROR_ADMIN_FTPTRANSFER_FAIL;
284
+ //apply user-defined permissions to file
285
+ $fileperms = trim($fileperms);
286
+ if ( strlen($fileperms) == 4 && sprintf("%04o", octdec($fileperms)) == $fileperms ) {
287
+ $fileperms = octdec($fileperms);
288
+ $fileperms = (int)$fileperms;
289
+ ssh2_sftp_chmod($sftp, $target, $fileperms);
290
+ }
291
  }
292
+ @fclose($f);
293
  }
 
294
  }
295
  }
296
  }
299
  return $ret_message;
300
  }
301
 
302
+ /**
303
+ * Create sFTP Directory Recursively.
304
+ *
305
+ * This function creates an sFTP directory recursively (including
306
+ * subdirectories).
307
+ *
308
+ * @since 4.0.0
309
+ *
310
+ * @redeclarable
311
+ *
312
+ * @param string $ftp_host The sFTP host.
313
+ * @param string $ftp_port The sFTP port.
314
+ * @param string $ftp_username Username for sFTP authentication.
315
+ * @param string $ftp_password Password for sFTP authentication.
316
+ * @param string $path The path of the directory to create.
317
+ *
318
+ * @return string Empty string if the directory was created successfully, or an
319
+ * error message if it failed.
320
+ */
321
  function wfu_create_dir_deep_sftp($ftp_host, $ftp_port, $ftp_username, $ftp_password, $path) {
322
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
323
  $ret_message = "";
324
+ {
325
+ $conn = @ssh2_connect($ftp_host, $ftp_port);
326
+ if ( !$conn ) $ret_message = WFU_ERROR_ADMIN_FTPHOST_FAIL;
 
327
  else {
328
+ if ( !@ssh2_auth_password($conn, $ftp_username, $ftp_password) ) $ret_message = WFU_ERROR_ADMIN_FTPLOGIN_FAIL;
 
329
  else {
330
+ $sftp = @ssh2_sftp($conn);
331
+ if ( !$sftp ) $ret_message = WFU_ERROR_ADMIN_SFTPINIT_FAIL;
332
+ else {
333
+ ssh2_sftp_mkdir($sftp, $path, 493, true );
334
+ }
335
  }
336
  }
337
  }
lib/wfu_processfiles.php CHANGED
@@ -1,857 +1,886 @@
1
- <?php
2
-
3
- function wfu_process_files($params, $method) {
4
- $sid = $params["uploadid"];
5
- $sesid = session_id();
6
- $user = wp_get_current_user();
7
- if ( 0 == $user->ID ) {
8
- $user_id = 0;
9
- $user_login = "guest";
10
- $user_email = "";
11
- $is_admin = false;
12
- }
13
- else {
14
- $user_id = $user->ID;
15
- $user_login = $user->user_login;
16
- $user_email = $user->user_email;
17
- $is_admin = current_user_can('manage_options');
18
- }
19
- $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
20
- $unique_id = sanitize_text_field($_POST['uniqueuploadid_'.$sid]);
21
- // determine if this routine is only for checking the file
22
- $only_check = ( isset($_POST['only_check']) ? ( $_POST['only_check'] == "1" ) : false );
23
- // determine if this is an upload without a file
24
- $nofileupload = ( $params["allownofile"] == "true" && isset($_POST['nofileupload_'.$sid]) ? ( $_POST['nofileupload_'.$sid] == "1" ) : false );
25
- $force_notifications = ( WFU_VAR("WFU_FORCE_NOTIFICATIONS") == "true" );
26
- $consent_revoked = ( $plugin_options["personaldata"] == "1" && $params["consent_result"] == "0" );
27
- $not_store_files = ( $params["personaldatatypes"] == "userdata and files" );
28
- $empty_userdata_fields = $params["userdata_fields"];
29
- $store_nothing = ( $consent_revoked && $not_store_files );
30
-
31
- $suppress_admin_messages = ( $params["adminmessages"] != "true" || !$is_admin );
32
- $success_count = 0;
33
- $warning_count = 0;
34
- $error_count = 0;
35
- $default_colors = wfu_prepare_message_colors(WFU_VAR("WFU_DEFAULTMESSAGECOLORS"));
36
- $notify_by_email = 0;
37
- $notify_target_path_list = array();
38
- $uploadedfile = 'uploadedfile_'.$sid;
39
- $hiddeninput = 'hiddeninput_'.$sid;
40
- $allowed_patterns = explode(",",$params["uploadpatterns"]);
41
- foreach ($allowed_patterns as $key => $allowed_pattern) {
42
- $allowed_patterns[$key] = trim($allowed_pattern);
43
- }
44
- $userdata_fields = $params["userdata_fields"];
45
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
46
- $userdata_fields[$userdata_key]["value"] = ( isset($_POST[$hiddeninput.'_userdata_'.$userdata_key]) ? strip_tags($_POST[$hiddeninput.'_userdata_'.$userdata_key]) : "" );
47
- }
48
- $params_output_array["version"] = "full";
49
- $params_output_array["general"]['shortcode_id'] = $sid;
50
- $params_output_array["general"]['unique_id'] = $unique_id;
51
- $params_output_array["general"]['state'] = 0;
52
- $params_output_array["general"]['files_count'] = 0;
53
- $params_output_array["general"]['update_wpfilebase'] = "";
54
- $params_output_array["general"]['redirect_link'] = ( $params["redirect"] == "true" ? $params["redirectlink"] : "" );
55
- $params_output_array["general"]['upload_finish_time'] = 0;
56
- $params_output_array["general"]['message'] = "";
57
- $params_output_array["general"]['message_type'] = "";
58
- $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
59
- $params_output_array["general"]['admin_messages']['notify'] = "";
60
- $params_output_array["general"]['admin_messages']['redirect'] = "";
61
- $params_output_array["general"]['admin_messages']['other'] = "";
62
- $params_output_array["general"]['errors']['wpfilebase'] = "";
63
- $params_output_array["general"]['errors']['notify'] = "";
64
- $params_output_array["general"]['errors']['redirect'] = "";
65
- $params_output_array["general"]['color'] = $default_colors['color'];
66
- $params_output_array["general"]['bgcolor'] = $default_colors['bgcolor'];
67
- $params_output_array["general"]['borcolor'] = $default_colors['borcolor'];
68
- $params_output_array["general"]['notify_by_email'] = 0;
69
- $params_output_array["general"]['fail_message'] = "";
70
- $params_output_array["general"]['fail_admin_message'] = "";
71
- /* safe_output is a minimized version of params_output_array, that is passed as text, in case JSON parse fails
72
- its data are separated by semicolon (;) and are the following:
73
- upload state: the upload state number
74
- default colors: the default color, bgcolor and borcolor values, separated by comma(,)
75
- file_count: the number of files processed
76
- filedata: message type, header, message and admin message of each file, encoded and separated by comma (,) */
77
- $params_output_array["general"]['safe_output'] = "";
78
- /* js_script is javascript code that is executed after each file upload and is defined in wfu_after_file_upload action */
79
- $params_output_array["general"]['js_script'] = "";
80
-
81
- /* adjust $uploadedfile variable (holding file data) if this is a redirection caused because the browser of the user could not handle AJAX upload */
82
- if ( isset($_FILES[$uploadedfile.'_redirected']) ) $uploadedfile .= '_redirected';
83
- /* notify admin if this is a redirection caused because the browser of the user could not handle AJAX upload */
84
- $params_output_array["general"]['admin_messages']['other'] = $params['adminerrors'];
85
-
86
- if ( isset($_FILES[$uploadedfile]['error']) || $only_check || $nofileupload ) {
87
- $files_count = 1;
88
- // in case of checking of file or no file upload, then the $_FILES
89
- // variable has not been set because no file has been uploaded,
90
- // so we set it manually in order to allow the routine to continue
91
- if ( $only_check || $nofileupload ) {
92
- $_FILES[$uploadedfile]['name'] = wfu_plugin_decode_string($_POST[$uploadedfile.'_name']);
93
- $_FILES[$uploadedfile]['type'] = 'any';
94
- $_FILES[$uploadedfile]['tmp_name'] = 'any';
95
- $_FILES[$uploadedfile]['error'] = '';
96
- $_FILES[$uploadedfile]['size'] = wfu_sanitize_int($_POST[$uploadedfile.'_size']);
97
- }
98
- }
99
- else $files_count = 0;
100
- $params_output_array["general"]['files_count'] = $files_count;
101
- // index of uploaded file in case of ajax uploads (in ajax uploads only one file is uploaded in every ajax call)
102
- // the index is used to store any file data in session variables, in case the file is uploaded in two or more passes
103
- // (like the case were in the first pass it is only checked)
104
- $single_file_index = ( isset($_POST[$uploadedfile.'_index']) ? $_POST[$uploadedfile.'_index'] : -1 );
105
- $single_file_index = wfu_sanitize_int($single_file_index);
106
-
107
- /* append userdata fields to upload path */
108
- $search = array ( );
109
- $replace = array ( );
110
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
111
- $ind = 1 + $userdata_key;
112
- array_push($search, '/%userdata'.$ind.'%/');
113
- array_push($replace, $userdata_field["value"]);
114
- }
115
- $params["uploadpath"] = preg_replace($search, $replace, $params["uploadpath"]);
116
-
117
- /* append subfolder name to upload path */
118
- if ( $params["askforsubfolders"] == "true" ) {
119
- if ( $params["subfoldertree"] == "auto+" && $params['subdir_selection_index'] != '' ) {
120
- if ( substr($params["uploadpath"], -1, 1) == "/" ) $params["uploadpath"] .= $params['subdir_selection_index'];
121
- else $params["uploadpath"] .= '/'.$params['subdir_selection_index'];
122
- }
123
- elseif ( $params["subfoldertree"] != "auto+" && $params['subdir_selection_index'] >= 1 ) {
124
- if ( substr($params["uploadpath"], -1, 1) == "/" ) $params["uploadpath"] .= $params['subfoldersarray'][$params['subdir_selection_index']];
125
- else $params["uploadpath"] .= '/'.$params['subfoldersarray'][$params['subdir_selection_index']];
126
- }
127
- }
128
-
129
- /* if webcam uploads are enabled, then correct the filename */
130
- if ( strpos($params["placements"], "webcam") !== false && $params["webcam"] == "true" ) {
131
- $initial_file_name = $_FILES[$uploadedfile]['name'];
132
- $dotfileext = wfu_fileext($initial_file_name, true);
133
- $file_name = wfu_filename($initial_file_name);
134
- if ( $file_name == "video" ) $file_name = $params["videoname"];
135
- else $file_name = $params["imagename"];
136
- $search = array ('/%userid%/', '/%username%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/');
137
- $replace = array ($user_id, $user_login, $params['blogid'], $params['pageid'], get_the_title($params['pageid']));
138
- foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
139
- $ind = 1 + $userdata_key;
140
- array_push($search, '/%userdata'.$ind.'%/');
141
- array_push($replace, $userdata_field["value"]);
142
- }
143
- $file_name = preg_replace($search, $replace, $file_name);
144
- $_FILES[$uploadedfile]['name'] = $file_name.$dotfileext;
145
- }
146
-
147
- if ( $files_count == 1 ) {
148
-
149
- foreach ( $_FILES[$uploadedfile] as $key => $prop )
150
- $fileprops[$key] = $prop;
151
-
152
- $sftp_not_supported = false;
153
- $upload_path_ok = false;
154
- $allowed_file_ok = false;
155
- $size_file_ok = false;
156
- $size_file_phpenv_ok = true;
157
- $ignore_server_actions = false;
158
- $file_output['color'] = $default_colors['color'];
159
- $file_output['bgcolor'] = $default_colors['bgcolor'];
160
- $file_output['borcolor'] = $default_colors['borcolor'];
161
- $file_output['header'] = "";
162
- $file_output['message'] = "";
163
- $file_output['message_type'] = "";
164
- $file_output['admin_messages'] = "";
165
- $file_output['uploaded_file_props'] = "";
166
- $fileid = -1;
167
-
168
- //calculate index of file
169
- $real_file_index = $single_file_index;
170
- if ( $single_file_index == -1 ) $real_file_index = ( isset($i) ? $i : 0 );
171
- // determine if file data have been saved to session variables, due to a previous pass of this file
172
- $file_map = "filedata_".$unique_id."_".$real_file_index;
173
- // retrieve unique id of the file, used in filter actions for identifying each separate file
174
- if ( WFU_USVAR_exists($file_map) ) {
175
- $file_map_arr = WFU_USVAR($file_map);
176
- $file_unique_id = $file_map_arr['file_unique_id'];
177
- }
178
- else $file_unique_id = '';
179
- $filedata_previously_defined = ( $file_unique_id != '' );
180
- /* generate unique id for each file for use in filter actions if it has not been previously defined */
181
- if ( !$filedata_previously_defined )
182
- $file_unique_id = wfu_create_random_string(20);
183
-
184
- /* Get uploaded file size in Mbytes */
185
- // correct file size in case of checking of file or no file upload
186
- // otherwise $upload_file_size will be zero and the routine will fail
187
- if ( $only_check || $nofileupload ) {
188
- $upload_file_size = $fileprops['size'];
189
- if ( $upload_file_size == 0 ) $upload_file_size ++;
190
- }
191
- else {
192
- $upload_file_size = filesize($fileprops['tmp_name']);
193
- if ( $upload_file_size == 0 && file_exists($fileprops['tmp_name']) && $fileprops['error'] == 0 ) $upload_file_size ++;
194
- }
195
- $upload_file_size_MB = $upload_file_size / 1024 / 1024;
196
-
197
- $only_filename = $fileprops['name'];
198
- $target_path = wfu_upload_plugin_full_path($params).$only_filename;
199
-
200
- if ( $upload_file_size > 0 ) {
201
- /* Section to perform filter action wfu_before_file_check before file is checked in order to perform
202
- any filename or userdata modifications or reject the upload of the file by setting error_message item
203
- of $ret_data array to a non-empty value */
204
- $filter_error_message = '';
205
- $filter_admin_message = '';
206
- if ( $file_unique_id != '' && !$filedata_previously_defined ) {
207
- // get correct file size
208
- if ( $only_check || $nofileupload ) $filesize = $fileprops['size'];
209
- else $filesize = filesize($fileprops['tmp_name']);
210
- /* store file data and upload result to filedata session array
211
- for use by after_upload filters */
212
- if ( !$nofileupload ) {
213
- if ( !WFU_USVAR_exists("filedata_".$unique_id) ) WFU_USVAR_store("filedata_".$unique_id, array());
214
- $filedata_id = WFU_USVAR("filedata_".$unique_id);
215
- $filedata_id[$real_file_index] = array(
216
- "file_unique_id" => $file_unique_id,
217
- "original_filename" => $only_filename,
218
- "filesize" => $filesize,
219
- );
220
- WFU_USVAR_store("filedata_".$unique_id, $filedata_id);
221
- }
222
- // prepare parameters for wfu_before_file_check filter
223
- // if this is a no file upload the prepare parameters for
224
- // wfu_before_data_submit filter
225
- if ( !$nofileupload ) $changable_data['file_path'] = $target_path;
226
- $changable_data['user_data'] = $userdata_fields;
227
- $changable_data['error_message'] = $filter_error_message;
228
- $changable_data['admin_message'] = $filter_admin_message;
229
- $additional_data['shortcode_id'] = $sid;
230
- $additional_data['unique_id'] = $unique_id;
231
- if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
232
- if ( !$nofileupload ) $additional_data['file_size'] = $filesize;
233
- $additional_data['user_id'] = $user->ID;
234
- $additional_data['page_id'] = $params["pageid"];
235
- if ( !$nofileupload ) $ret_data = apply_filters('wfu_before_file_check', $changable_data, $additional_data);
236
- else $ret_data = apply_filters('wfu_before_data_submit', $changable_data, $additional_data);
237
- if ( !$nofileupload ) $target_path = $ret_data['file_path'];
238
- if ( !$nofileupload ) $only_filename = wfu_basename($target_path);
239
- $userdata_fields = $ret_data['user_data'];
240
- $filter_error_message = $ret_data['error_message'];
241
- $filter_admin_message = $ret_data['admin_message'];
242
- // if this is a file check, which means that a second pass of
243
- // the file will follow, then we do not want to apply the
244
- // filters again, so we store the changable data to session
245
- // variables for this specific file
246
- if ( $only_check && !$nofileupload ) {
247
- if ( !WFU_USVAR_exists($file_map) ) WFU_USVAR_store($file_map, array());
248
- $file_map_arr = WFU_USVAR($file_map);
249
- $file_map_arr['file_unique_id'] = $file_unique_id;
250
- $file_map_arr['filepath'] = $target_path;
251
- $file_map_arr['userdata'] = $userdata_fields;
252
- WFU_USVAR_store($file_map, $file_map_arr);
253
- }
254
- }
255
- // if this is a second pass of the file, because a first pass with file checking was done before, then retrieve
256
- // file data that may have previously changed because of application of filters
257
- if ( $filedata_previously_defined ) {
258
- $file_map_arr = WFU_USVAR($file_map);
259
- $target_path = $file_map_arr['filepath'];
260
- $only_filename = wfu_basename($target_path);
261
- $userdata_fields = $file_map_arr['userdata'];
262
- }
263
- if ( $filter_error_message != '' ) {
264
- //errorabort flag designates that file will be aborted and no resuming will be attempted
265
- $file_output['message_type'] = "errorabort";
266
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
267
- if ( $filter_admin_message != '' )
268
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
269
- }
270
- /* Perform security test for denial-of-service (DOS) attacks by
271
- counting the number of files that have been uploaded within a
272
- specific time interval, if DOS Attack Check is enabled. If the
273
- number of files exceeds the limit then the file is rejected and a
274
- message is sent to the administrator. */
275
- elseif ( WFU_VAR("WFU_DOS_ATTACKS_CHECK") == "true" && wfu_check_DOS_attack() ) {
276
- //notify admin about DOS attacks
277
- $last_notification = wfu_get_option("wfu_admin_notification_about_DOS", null);
278
- if ( $last_notification == null || time() - (int)$last_notification > (int)WFU_VAR("WFU_DOS_ATTACKS_ADMIN_EMAIL_FREQUENCY") ) {
279
- $home = get_option("home");
280
- $subject = str_replace("{SITE}", $home, WFU_WARNING_POTENTIAL_DOS_EMAIL_SUBJECT);
281
- $message = str_replace(array( "{SITE}", "{FILENUM}", "{INTERVAL}" ), array( $home, WFU_VAR("WFU_DOS_ATTACKS_FILE_LIMIT"), WFU_VAR("WFU_DOS_ATTACKS_TIME_INTERVAL") ), WFU_WARNING_POTENTIAL_DOS_EMAIL_MESSAGE);
282
- wfu_notify_admin($subject, $message);
283
- wfu_update_option("wfu_admin_notification_about_DOS", time());
284
- }
285
- //errorabort flag designates that file will be aborted and no resuming will be attempted
286
- $file_output['message_type'] = "errorabort";
287
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DOS_ATTACK);
288
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DOS_ATTACK);
289
- }
290
- else {
291
- if ( !$nofileupload ) {
292
- /* generate safe filename by removing invalid characters if
293
- forcefilename is deactivated */
294
- if ( $params['forcefilename'] != "true" ) $only_filename = wfu_upload_plugin_clean( $only_filename );
295
- /* in case that forcefilename is activated then strip tags
296
- as a minimum measure against hacking */
297
- else $only_filename = strip_tags( $only_filename );
298
- //reconstruct target_path
299
- $target_path = wfu_basedir($target_path).$only_filename;
300
-
301
- /* if medialink or postlink is activated then the target path becomes the current wordpress upload folder */
302
- if ( $params["medialink"] == "true" || $params["postlink"] == "true" ) {
303
- $mediapath = wp_upload_dir();
304
- $target_path = $mediapath['path'].'/'.$only_filename;
305
- }
306
- /* Check if this is an sftp upload and sftp is supported */
307
- if ( substr($target_path, 0, 7) == "sftp://" && !function_exists("ssh2_connect") ) {
308
- $upload_path_ok = false;
309
- $sftp_not_supported = true;
310
- }
311
- /* Check if upload path exists */
312
- elseif ( wfu_is_dir( wfu_basedir($target_path), $params["ftpinfo"] ) ) {
313
- $upload_path_ok = true;
314
- }
315
- /* Attempt to create path if user has selected to do so */
316
- else if ( $params["createpath"] == "true" ) {
317
- $wfu_create_directory_ret = wfu_create_directory(wfu_basedir($target_path), $params["accessmethod"], $params["ftpinfo"]);
318
- if ( $wfu_create_directory_ret != "" ) {
319
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_create_directory_ret);
320
- }
321
- if ( wfu_is_dir( wfu_basedir($target_path), $params["ftpinfo"] ) ) {
322
- $upload_path_ok = true;
323
- }
324
- }
325
-
326
- /* File name control, reject files with .php, .js (and other) extensions for security reasons.
327
- This is the first pass of extension control, which only checks the filename.
328
- A second pass is performed after the file has completely uploaded, using WP inherent file
329
- extension control, which provides better security. */
330
- if ( !wfu_file_extension_blacklisted(strtolower($only_filename)) )
331
- foreach ($allowed_patterns as $allowed_pattern) {
332
- if ( wfu_file_extension_matches_pattern($allowed_pattern, strtolower($only_filename)) ) {
333
- $allowed_file_ok = true;
334
- break ;
335
- }
336
- }
337
-
338
- /* File size control */
339
- if ( $upload_file_size_MB <= $params["maxsize"] ) {
340
- if ( $params['php_env'] == '32bit' && $upload_file_size > 2147483647 ) $size_file_phpenv_ok = false;
341
- else $size_file_ok = true;
342
- }
343
- }
344
- /* In case of no file upload then bypass above checks */
345
- else {
346
- $upload_path_ok = true;
347
- $allowed_file_ok = true;
348
- $size_file_ok = true;
349
- }
350
-
351
- if ( !$upload_path_ok or !$allowed_file_ok or !$size_file_ok ) {
352
- //abort the file, no resuming will be attempted
353
- $file_output['message_type'] = "errorabort";
354
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UPLOAD_FAILED);
355
-
356
- if ( !$upload_path_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], ( $sftp_not_supported ? WFU_ERROR_ADMIN_SFTP_UNSUPPORTED : WFU_ERROR_DIR_EXIST ));
357
- if ( !$allowed_file_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_ALLOW);
358
- if ( !$size_file_ok ) {
359
- if ( $size_file_phpenv_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_SIZE);
360
- else $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_2GBSIZE);
361
- }
362
- }
363
- }
364
- }
365
- else {
366
- // This block is executed when there is an error
367
- $upload_error = $fileprops['error'];
368
- if ( $upload_error == 1 ) {
369
- $message_text = WFU_ERROR_FILE_PHP_SIZE;
370
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_SIZE);
371
- }
372
- elseif ( $upload_error == 2 ) $message_text = WFU_ERROR_FILE_HTML_SIZE;
373
- elseif ( $upload_error == 3 ) $message_text = WFU_ERROR_FILE_PARTIAL;
374
- elseif ( $upload_error == 4 ) $message_text = WFU_ERROR_FILE_NOTHING;
375
- elseif ( $upload_error == 6 ) $message_text = WFU_ERROR_DIR_NOTEMP;
376
- elseif ( $upload_error == 7 ) $message_text = WFU_ERROR_FILE_WRITE;
377
- elseif ( $upload_error == 8 ) $message_text = WFU_ERROR_UPLOAD_STOPPED;
378
- else {
379
- $upload_time_limit = ini_get("max_input_time");
380
- $params_output_array["general"]['upload_finish_time'] = $params["upload_start_time"] + $upload_time_limit * 1000;
381
- $message_text = WFU_ERROR_FILE_PHP_TIME;
382
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_TIME);
383
- }
384
- //error (and not errorabort) flag designates that a resuming of the file may be attempted
385
- $file_output['message_type'] = "error";
386
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $message_text);
387
- }
388
-
389
- $message_processed = false;
390
- // if ( $upload_path_ok and $allowed_file_ok and $size_file_ok ) {
391
- if ( substr($file_output['message_type'], 0, 5) != "error" ) {
392
-
393
- if ( is_uploaded_file($fileprops['tmp_name']) || $only_check || $nofileupload ) {
394
- $source_path = $fileprops['tmp_name'];
395
-
396
- if ( $only_check || $ignore_server_actions || $nofileupload ) $file_copied = true;
397
- else {
398
- $file_copied = false;
399
-
400
- if ($source_path) {
401
- $file_exists = wfu_file_exists($target_path);
402
- if ( !$file_exists || $params["duplicatespolicy"] == "" || $params["duplicatespolicy"] == "overwrite" ) {
403
- //redirect echo in internal buffer to receive and process any unwanted warning messages from wfu_upload_file
404
- ob_start();
405
- ob_clean();
406
- /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
407
- If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
408
- previous filter wfu_before_file_check, corresponding them to the unique file id */
409
- if ( $file_unique_id != '' ) {
410
- $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
411
- $file_map_arr = WFU_USVAR($file_map);
412
- $file_map_arr['filepath'] = $target_path;
413
- WFU_USVAR_store($file_map, $file_map_arr);
414
- }
415
- //recalculate $only_filename in case it changed with wfu_before_file_upload filter
416
- $only_filename = wfu_basename($target_path);
417
- //move the uploaded file to its final destination
418
- $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
419
- $file_copied = $wfu_upload_file_ret["uploaded"];
420
- //process warning messages from wfu_upload_file
421
- $echo_message = ob_get_contents();
422
- //finish redirecting of echo to internal buffer
423
- ob_end_clean();
424
- if ( $echo_message != "" && !$file_copied ) {
425
- //error (and not errorabort) flag designates that file may be resumed
426
- $file_output['message_type'] = "error";
427
- if ( stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move") ) {
428
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
429
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
430
- }
431
- else {
432
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
433
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], strip_tags($echo_message));
434
- }
435
- $message_processed = true;
436
- }
437
- if ( $wfu_upload_file_ret["admin_message"] != "" ) {
438
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
439
- }
440
- }
441
- else if ( $file_exists && $params["duplicatespolicy"] == "maintain both" ) {
442
- $full_path = wfu_basedir($target_path);
443
- $name_part = $only_filename;
444
- $ext_part = "";
445
- $dot_pos = strrpos($name_part, ".");
446
- if ( $dot_pos ) {
447
- $ext_part = substr($name_part, $dot_pos);
448
- $name_part = substr($name_part, 0, $dot_pos);
449
- }
450
- if ( $params["uniquepattern"] != "datetimestamp" ) {
451
- $unique_ind = 1;
452
- do {
453
- $unique_ind += 1;
454
- $only_filename = $name_part . "(" . $unique_ind . ")" . $ext_part;
455
- $target_path = $full_path . $only_filename;
456
- }
457
- while ( wfu_file_exists($target_path) );
458
- }
459
- else {
460
- $current_datetime = gmdate("U") - 1;
461
- do {
462
- $current_datetime += 1;
463
- $only_filename = $name_part . "-" . gmdate("YmdHis", $current_datetime) . $ext_part;
464
- $target_path = $full_path . $only_filename;
465
- }
466
- while ( wfu_file_exists($target_path) );
467
- }
468
- //redirect echo in internal buffer to receive and process any unwanted warning messages from move_uploaded_file
469
- ob_start();
470
- ob_clean();
471
- /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
472
- If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
473
- previous filter wfu_before_file_check, corresponding them to the unique file id */
474
- if ( $file_unique_id != '' ) {
475
- $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
476
- $file_map_arr = WFU_USVAR($file_map);
477
- $file_map_arr['filepath'] = $target_path;
478
- WFU_USVAR_store($file_map, $file_map_arr);
479
- }
480
- //recalculate $only_filename in case it changed with wfu_before_file_upload filter
481
- $only_filename = wfu_basename($target_path);
482
- //move the uploaded file to its final destination
483
- $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
484
- $file_copied = $wfu_upload_file_ret["uploaded"];
485
- //process warning messages from move_uploaded_file
486
- $echo_message = ob_get_contents();
487
- //finish redirecting of echo to internal buffer
488
- ob_end_clean();
489
- if ( $echo_message != "" && !$file_copied ) {
490
- //error (and not errorabort) flag designates that file may be resumed
491
- $file_output['message_type'] = "error";
492
- if ( stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move") ) {
493
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
494
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
495
- }
496
- else {
497
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
498
- $file_output['admin_messages'] = wfu_join_strings("<br />n", $file_output['admin_messages'], strip_tags($echo_message));
499
- }
500
- $message_processed = true;
501
- }
502
- if ( $wfu_upload_file_ret["admin_message"] != "" ) {
503
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
504
- }
505
- }
506
- else {
507
- //abort the file and do not allow resuming
508
- $file_output['message_type'] = "errorabort";
509
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_EXISTS);
510
- $message_processed = true;
511
- $file_copied = false;
512
- }
513
- }
514
- }
515
-
516
- if ( $file_copied ) {
517
- /* prepare email notification parameters if email notification is enabled */
518
- if ( $params["notify"] == "true" && (!$only_check || $nofileupload) ) {
519
- if ( !$nofileupload ) array_push($notify_target_path_list, $target_path);
520
- }
521
-
522
- /* prepare redirect link if redirection is enabled */
523
- if ( $params["redirect"] == "true" ) {
524
- /* Define dynamic redirect link from variables */
525
- $search = array ('/%filename%/', '/%username%/');
526
- $replace = array ($only_filename, $user_login);
527
- $params_output_array["general"]['redirect_link'] = trim(preg_replace($search, $replace, $params["redirectlink"]));
528
- }
529
-
530
- if ( !$message_processed ) {
531
- $file_output['message_type'] = "success";
532
- }
533
- }
534
- else if ( !$message_processed ) {
535
- //abort the file and do not allow resuming
536
- $file_output['message_type'] = "errorabort";
537
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
538
- }
539
-
540
- /* Delete temporary file (in tmp directory) */
541
- // unlink($source_path);
542
- }
543
- else {
544
- //abort the file and do not allow resuming
545
- $file_output['message_type'] = "errorabort";
546
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
547
- }
548
- }
549
-
550
- /* last check of output file status */
551
- if ( $file_output['message_type'] == "" ) {
552
- if ( $file_copied ) $file_output['message_type'] = "success";
553
- else {
554
- //abort the file and do not allow resuming
555
- $file_output['message_type'] = "errorabort";
556
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
557
- }
558
- }
559
-
560
- /* suppress any admin messages if user is not administrator or adminmessages is not activated */
561
- if ( $suppress_admin_messages ) $file_output['admin_messages'] = "";
562
-
563
- /* set file status to "warning" if the file has been uploaded but there are messages */
564
- if ( $file_output['message_type'] == "success" ) {
565
- if ( $file_output['message'] != "" || $file_output['admin_messages'] != "" )
566
- $file_output['message_type'] = "warning";
567
- }
568
-
569
- /* set success status of the file, to be used for medialink and post actions */
570
- $file_finished_successfully = ( (!$only_check || $nofileupload) && ( $file_output['message_type'] == "success" || $file_output['message_type'] == "warning" ) );
571
- /* set non-success status of the file, to be used for medialink and post actions */
572
- $file_finished_unsuccessfully = ( substr($file_output['message_type'], 0, 5) == "error" );
573
-
574
-
575
- /* perform custom actions after file is completely uploaded in order to determine if file is valid ir not */
576
- if ( $file_finished_successfully && !$ignore_server_actions && !$nofileupload ) {
577
- /* Here the second pass of file extension control is performed after the file has completely
578
- uploaded, using WP inherent functions that determine the real extension from analyzing the
579
- data and not from the filename extension. If this check reveals an extension which is not
580
- permitted then the file will be rejected and erased. If the real extension is different
581
- than the original one but it is permitted, then the file will remain as it is but a warning
582
- message will notify the user that the extension of the file does not match its contents. */
583
- $check = wp_check_filetype_and_ext( $target_path, $only_filename, false );
584
- if ( $check['proper_filename'] !== false ) {
585
- $proper_filename = $check['proper_filename'];
586
- if ( wfu_file_extension_blacklisted(strtolower($only_filename)) ) {
587
- $file_finished_successfully = false;
588
- $file_finished_unsuccessfully = true;
589
- unlink($target_path);
590
- $file_output['message_type'] = "errorabort";
591
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_REJECT);
592
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_WRONGEXT.$check['proper_filename']);
593
- }
594
- else {
595
- $file_output['message_type'] = "warning";
596
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_SUSPICIOUS);
597
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_WARNING_ADMIN_FILE_SUSPICIOUS.$check['proper_filename']);
598
- }
599
- }
600
- // run any wfu_after_file_loaded filters to make any last file checks and accept or reject it
601
- if ( $file_finished_successfully ) {
602
- $filter_error_message = '';
603
- $filter_admin_message = '';
604
- $changable_data['error_message'] = $filter_error_message;
605
- $changable_data['admin_message'] = $filter_admin_message;
606
- $additional_data['file_unique_id'] = $file_unique_id;
607
- $additional_data['file_path'] = $target_path;
608
- $additional_data['shortcode_id'] = $sid;
609
- $ret_data = apply_filters('wfu_after_file_loaded', $changable_data, $additional_data);
610
- //this is a call to wfu_after_file_complete filters, which is
611
- //the old name of wfu_after_file_loaded filters, for maintaining
612
- //backward compatibility
613
- $changable_data = $ret_data;
614
- $ret_data = apply_filters('wfu_after_file_complete', $changable_data, $additional_data);
615
- $filter_error_message = $ret_data['error_message'];
616
- $filter_admin_message = $ret_data['admin_message'];
617
- if ( $filter_error_message != '' ) {
618
- $file_finished_successfully = false;
619
- $file_finished_unsuccessfully = true;
620
- unlink($target_path);
621
- $file_output['message_type'] = "errorabort";
622
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
623
- if ( $filter_admin_message != '' )
624
- $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
625
- }
626
- }
627
- }
628
-
629
- /* in case that the file will not be saved due to personal data policy
630
- then convert any success message_type to warning */
631
- if ( $store_nothing && $file_output['message_type'] == "success" ) {
632
- $file_output['message_type'] = "warning";
633
- $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_UPLOAD_STATE19_SINGLEFILE);
634
- }
635
-
636
- /* adjust message details and colors according to file result */
637
- /* FileResult: A */
638
- $search = array ('/%username%/', '/%useremail%/', '/%filename%/', '/%filepath%/');
639
- $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename, $target_path);
640
- if ( $file_output['message_type'] == "success" ) {
641
- $success_count ++;
642
- $color_array = explode(",", $params['successmessagecolors']);
643
- $file_output['color'] = $color_array[0];
644
- $file_output['bgcolor'] = $color_array[1];
645
- $file_output['borcolor'] = $color_array[2];
646
- $file_output['header'] = preg_replace($search, $replace, $params['successmessage']);
647
- /* prepare details of successful file upload, visible only to administrator */
648
- $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
649
- }
650
- /* FileResult: B */
651
- elseif ( $file_output['message_type'] == "warning" ) {
652
- $warning_count ++;
653
- $color_array = explode(",", $params['warningmessagecolors']);
654
- $file_output['color'] = $color_array[0];
655
- $file_output['bgcolor'] = $color_array[1];
656
- $file_output['borcolor'] = $color_array[2];
657
- $file_output['header'] = preg_replace($search, $replace, ( $store_nothing ? WFU_WARNINGMESSAGE_NOSAVE : $params['warningmessage'] ));
658
- /* prepare and prepend details of successful file upload, visible only to administrator */
659
- $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
660
- }
661
- /* FileResult: C */
662
- elseif ( substr($file_output['message_type'], 0, 5) == "error" ) {
663
- $error_count ++;
664
- $color_array = explode(",", $params['failmessagecolors']);
665
- $file_output['color'] = $color_array[0];
666
- $file_output['bgcolor'] = $color_array[1];
667
- $file_output['borcolor'] = $color_array[2];
668
- $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename, $target_path);
669
- $file_output['header'] = preg_replace($search, $replace, $params['errormessage']);
670
- /* prepare and prepend details of failed file upload, visible only to administrator */
671
- if ( !$nofileupload ) $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_FAILMESSAGE_DETAILS), $file_output['admin_messages']);
672
- }
673
-
674
- /* suppress again any admin messages if user is not administrator or adminmessages is not activated */
675
- if ( $suppress_admin_messages ) $file_output['admin_messages'] = "";
676
-
677
- $params_output_array[0] = $file_output;
678
-
679
- if ( $file_unique_id != '' && $file_finished_unsuccessfully && !$ignore_server_actions ) {
680
- /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
681
- If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
682
- the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
683
- This actions allows to define custom javascript code to run after each file finishes (either succeeded or failed).
684
- For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
685
- still remains. */
686
- $changable_data['ret_value'] = null;
687
- $changable_data['js_script'] = '';
688
- $additional_data['shortcode_id'] = $sid;
689
- $additional_data['unique_id'] = $unique_id;
690
- if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
691
- if ( !$nofileupload ) $additional_data['upload_result'] = $file_output['message_type'];
692
- else $additional_data['submit_result'] = $file_output['message_type'];
693
- $additional_data['error_message'] = $file_output['message'];
694
- $additional_data['admin_messages'] = $file_output['admin_messages'];
695
- if ( !$nofileupload ) $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
696
- else $ret_data = apply_filters('wfu_after_data_submit', $changable_data, $additional_data);
697
- $params_output_array["general"]['js_script'] = $ret_data['js_script'];
698
- // do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
699
- }
700
-
701
- if ( $file_finished_successfully && !$ignore_server_actions ) {
702
- /* Log file upload action if file has finished uploading
703
- uccessfully. If this is a no file upload then log action will be
704
- datasubmit. */
705
- if ( !$nofileupload ) {
706
- if ( !$consent_revoked ) $fileid = wfu_log_action('upload', $target_path, $user->ID, $unique_id, $params['pageid'], $params['blogid'], $sid, $userdata_fields);
707
- elseif ( !$not_store_files ) $fileid = wfu_log_action('upload', $target_path, 0, $unique_id, $params['pageid'], $params['blogid'], $sid, $empty_userdata_fields);
708
- }
709
- else {
710
- if ( !$consent_revoked ) $fileid = wfu_log_action('datasubmit', '', $user->ID, $unique_id, $params['pageid'], $params['blogid'], $sid, $userdata_fields);
711
- }
712
- /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
713
- If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
714
- the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
715
- This actions allows to define custom javascript code to run after each file finishes (either suceeded or failed).
716
- For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
717
- still remains. */
718
- $changable_data['ret_value'] = null;
719
- $changable_data['js_script'] = '';
720
- $additional_data['shortcode_id'] = $sid;
721
- $additional_data['unique_id'] = $unique_id;
722
- if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
723
- if ( !$nofileupload ) $additional_data['upload_result'] = $file_output['message_type'];
724
- else $additional_data['submit_result'] = $file_output['message_type'];
725
- $additional_data['error_message'] = $file_output['message'];
726
- $additional_data['admin_messages'] = $file_output['admin_messages'];
727
- if ( !$nofileupload ) $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
728
- else $ret_data = apply_filters('wfu_after_data_submit', $changable_data, $additional_data);
729
- $params_output_array["general"]['js_script'] = $ret_data['js_script'];
730
- // do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
731
- }
732
-
733
- /* add file to Media or attach file to current post if any of these options is activated and the file has finished uploading successfully */
734
- if ( ( $params["medialink"] == "true" || $params["postlink"] == "true" ) && $file_finished_successfully && !$ignore_server_actions && !$nofileupload ) {
735
- $pageid = ( $params["postlink"] == "true" ? $params['pageid'] : 0 );
736
- if ( !$consent_revoked ) wfu_process_media_insert($target_path, $userdata_fields, $pageid);
737
- elseif ( !$not_store_files ) wfu_process_media_insert($target_path, empty_userdata_fields, $pageid);
738
- }
739
-
740
- /* store final file data and upload result to filemap session array for
741
- use by after_upload filters */
742
- if ( ( $file_finished_successfully || $file_finished_unsuccessfully ) && !$ignore_server_actions && !$nofileupload ) {
743
- if ( WFU_USVAR_exists("filedata_".$unique_id) ) {
744
- $filedata_id = WFU_USVAR("filedata_".$unique_id);
745
- if ( isset($filedata_id[$real_file_index]) ) {
746
- $filedata_id[$real_file_index]["filepath"] = $target_path;
747
- $filedata_id[$real_file_index]["user_data"] = $userdata_fields;
748
- $filedata_id[$real_file_index]["upload_result"] = $file_output['message_type'];
749
- $filedata_id[$real_file_index]["message"] = $file_output['message'];
750
- $filedata_id[$real_file_index]["admin_messages"] = $file_output['admin_messages'];
751
- WFU_USVAR_store("filedata_".$unique_id, $filedata_id);
752
- }
753
- }
754
- }
755
- }
756
-
757
- // in case of file check set files_count to 0 in order to denote that the file was not really uploaded
758
- if ( $only_check && !$nofileupload ) $params_output_array["general"]['files_count'] = 0;
759
-
760
- $somefiles_Ok = ( ( $warning_count + $success_count ) > 0 );
761
- $allfiles_Ok = ( $somefiles_Ok && ( $error_count == 0 ) );
762
-
763
- /* Prepare WPFileBase Plugin update url, if this option has been selected and only if at least one file has been successfully uploaded.
764
- Execution will happen only if accumulated $params_output_array["general"]['update_wpfilebase'] is not empty */
765
- if ( $params["filebaselink"] == "true" && !$nofileupload ) {
766
- if ( $somefiles_Ok ) {
767
- $filebaseurl = site_url();
768
- if ( substr($filebaseurl, -1, 1) == "/" ) $filebaseurl = substr($filebaseurl, 0, strlen($filebaseurl) - 1);
769
- /* if the following variable is not empty, then WPFileBase Plugin update must be executed
770
- and any admin messages must be suppressed */
771
- $params_output_array["general"]['update_wpfilebase'] = $filebaseurl;
772
- }
773
- else {
774
- $params_output_array["general"]['admin_messages']['wpfilebase'] = WFU_WARNING_WPFILEBASE_NOTUPDATED_NOFILES;
775
- $params_output_array["general"]['errors']['wpfilebase'] = "error";
776
- }
777
- }
778
-
779
- /* Prepare email notification parameters if email notification is enabled and only if at least one file has been successfully uploaded
780
- if $method = "no-ajax" then send the email to the recipients
781
- if $method = "ajax" then return the notification parameters to the handler for further processing
782
- In case of ajax, execution will happen only if notify_by_email is greater than 0 */
783
- if ( $params["notify"] == "true" ) {
784
- /* verify that there are recipients */
785
- $notifyrecipients = trim(preg_replace('/%useremail%/', $user_email, $params["notifyrecipients"]));
786
- if ( $notifyrecipients != "" ) {
787
- if ( $somefiles_Ok || $force_notifications ) {
788
- if ( $method == 'no_ajax' && !$ignore_server_actions ) {
789
- $send_error = wfu_send_notification_email($user, $notify_target_path_list, $userdata_fields, $params);
790
- if ( $send_error != "" ) {
791
- $params_output_array["general"]['admin_messages']['notify'] = $send_error;
792
- $params_output_array["general"]['errors']['notify'] = "error";
793
- }
794
- }
795
- else {
796
- /* if the following variable is not empty, then email notification must be sent
797
- and any admin messages must be suppressed */
798
- $params_output_array["general"]['notify_by_email'] = ( !$nofileupload && !$force_notifications ? count($notify_target_path_list) : 1 );
799
- }
800
- }
801
- else {
802
- $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NOFILES;
803
- $params_output_array["general"]['errors']['notify'] = "error";
804
- }
805
- }
806
- else {
807
- $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NORECIPIENTS;
808
- $params_output_array["general"]['errors']['notify'] = "error";
809
- }
810
- }
811
-
812
- /* Prepare redirect link if redirection is enabled and only if all files have been successfully uploaded
813
- Execution will happen only if accumulated redirect_link is not empty and accumulated redirect errors are empty */
814
- if ( $params["redirect"] == "true" ) {
815
- if ( $params_output_array["general"]['redirect_link'] == "" ) {
816
- $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_EMPTY;
817
- $params_output_array["general"]['errors']['redirect'] = "error";
818
- }
819
- elseif ( !$allfiles_Ok ) {
820
- $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_FILESFAILED;
821
- $params_output_array["general"]['errors']['redirect'] = "error";
822
- }
823
- }
824
-
825
- /* suppress any admin messages if user is not administrator or adminmessages is not activated */
826
- if ( $suppress_admin_messages ) {
827
- $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
828
- $params_output_array["general"]['admin_messages']['notify'] = "";
829
- $params_output_array["general"]['admin_messages']['redirect'] = "";
830
- $params_output_array["general"]['admin_messages']['other'] = "";
831
- }
832
-
833
- /* Calculate upload state from file results */
834
- if ( $allfiles_Ok && ( $warning_count == 0 ) ) $params_output_array["general"]['state'] = ( !$nofileupload ? 4 : 14 );
835
- else if ( $allfiles_Ok ) $params_output_array["general"]['state'] = 5;
836
- else if ( $somefiles_Ok ) $params_output_array["general"]['state'] = 6; //only valid in no-ajax method
837
- else if ( !$somefiles_Ok && $error_count > 0 ) $params_output_array["general"]['state'] = ( !$nofileupload ? 7 : 15 );
838
- else $params_output_array["general"]['state'] = 8;
839
- /* in case that the files will not be saved due to personal data policy
840
- then adjust general state accordingly (effective for no-ajax uploads) */
841
- if ( !$nofileupload && $somefiles_Ok && $store_nothing ) $params_output_array["general"]['state'] = 19;
842
-
843
- /* construct safe output */
844
- $sout = $params_output_array["general"]['state'].";".WFU_VAR("WFU_DEFAULTMESSAGECOLORS").";".$files_count;
845
- for ($i = 0; $i < $files_count; $i++) {
846
- $sout .= ";".wfu_plugin_encode_string($file_output['message_type']);
847
- $sout .= ",".wfu_plugin_encode_string($file_output['header']);
848
- $sout .= ",".wfu_plugin_encode_string($file_output['message']);
849
- $sout .= ",".wfu_plugin_encode_string($file_output['admin_messages']);
850
- $sout .= ",".$file_output['uploaded_file_props'];
851
- }
852
- $params_output_array["general"]['safe_output'] = $sout;
853
-
854
- return $params_output_array;
855
- }
856
-
857
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ function wfu_process_files_queue($params, $method) {
4
+ $sid = $params["uploadid"];
5
+ $unique_id = sanitize_text_field($_POST['uniqueuploadid_'.$sid]);
6
+ $queue = "wfu_queue_".$unique_id;
7
+ if ( $unique_id != "" ) {
8
+ $queue_id = wfu_create_random_string(16);
9
+ wfu_join_queue($queue, $queue_id);
10
+ while (true) {
11
+ $cur_id = wfu_get_queue_thread($queue);
12
+ if ( $cur_id == $queue_id ) break;
13
+ usleep(100000);
14
+ }
15
+ }
16
+ $queue_count = intval(wfu_get_option("wfu_queue_".$unique_id."_count", 0, "string")) + 1;
17
+ wfu_debug_log("queue_count:".$queue_count."\n");
18
+ $chunk_data = explode(",", ( isset($_POST['chunk_data']) ? $_POST['chunk_data'] : "0,0,0,0," ));
19
+ if ( count($chunk_data) != 5 ) $chunk_data = array( "0", "0", "0", "0", "" );
20
+ list($file_id, $file_size, $chunk_count, $chunk_id, $filename_enc) = $chunk_data;
21
+ $file_id = wfu_sanitize_int($file_id);
22
+ $file_size = wfu_sanitize_int($file_size);
23
+ $chunk_id = wfu_sanitize_int($chunk_id);
24
+ wfu_debug_log("chunk_data:".( isset($_POST['chunk_data']) ? $_POST['chunk_data'] : "0,0,0,0," )."\n");
25
+ wfu_update_option("wfu_queue_".$unique_id."_count", $queue_count, "string");
26
+ /*if ( $queue_count >= 3 && $queue_count <= 5 ) $ret = "abort";
27
+ else */$ret = wfu_process_files_net($params, $method);
28
+ wfu_advance_queue($queue);
29
+ return $ret;
30
+ }
31
+
32
+ function wfu_process_files($params, $method) {
33
+ $sid = $params["uploadid"];
34
+ $sesid = wfu_get_session_id();
35
+ $user = wp_get_current_user();
36
+ if ( 0 == $user->ID ) {
37
+ $user_id = 0;
38
+ $user_login = "guest";
39
+ $user_email = "";
40
+ $is_admin = false;
41
+ }
42
+ else {
43
+ $user_id = $user->ID;
44
+ $user_login = $user->user_login;
45
+ $user_email = $user->user_email;
46
+ $is_admin = current_user_can('manage_options');
47
+ }
48
+ $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
49
+ $unique_id = sanitize_text_field($_POST['uniqueuploadid_'.$sid]);
50
+ // determine if this routine is only for checking the file
51
+ $only_check = ( isset($_POST['only_check']) ? ( $_POST['only_check'] == "1" ) : false );
52
+ // determine if this is an upload without a file
53
+ $nofileupload = ( $params["allownofile"] == "true" && isset($_POST['nofileupload_'.$sid]) ? ( $_POST['nofileupload_'.$sid] == "1" ) : false );
54
+ $force_notifications = ( WFU_VAR("WFU_FORCE_NOTIFICATIONS") == "true" );
55
+ $consent_revoked = ( $plugin_options["personaldata"] == "1" && $params["consent_result"] == "0" );
56
+ $not_store_files = ( $params["personaldatatypes"] == "userdata and files" );
57
+ $empty_userdata_fields = $params["userdata_fields"];
58
+ $store_nothing = ( $consent_revoked && $not_store_files );
59
+
60
+ $suppress_admin_messages = ( $params["adminmessages"] != "true" || !$is_admin );
61
+ $success_count = 0;
62
+ $warning_count = 0;
63
+ $error_count = 0;
64
+ $default_colors = wfu_prepare_message_colors(WFU_VAR("WFU_DEFAULTMESSAGECOLORS"));
65
+ $notify_by_email = 0;
66
+ $notify_target_path_list = array();
67
+ $uploadedfile = 'uploadedfile_'.$sid;
68
+ $hiddeninput = 'hiddeninput_'.$sid;
69
+ $allowed_patterns = explode(",",$params["uploadpatterns"]);
70
+ foreach ($allowed_patterns as $key => $allowed_pattern) {
71
+ $allowed_patterns[$key] = trim($allowed_pattern);
72
+ }
73
+ $userdata_fields = $params["userdata_fields"];
74
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
75
+ $userdata_fields[$userdata_key]["value"] = ( isset($_POST[$hiddeninput.'_userdata_'.$userdata_key]) ? strip_tags($_POST[$hiddeninput.'_userdata_'.$userdata_key]) : "" );
76
+ }
77
+ $params_output_array["version"] = "full";
78
+ $params_output_array["general"]['shortcode_id'] = $sid;
79
+ $params_output_array["general"]['unique_id'] = $unique_id;
80
+ $params_output_array["general"]['state'] = 0;
81
+ $params_output_array["general"]['files_count'] = 0;
82
+ $params_output_array["general"]['update_wpfilebase'] = "";
83
+ $params_output_array["general"]['redirect_link'] = ( $params["redirect"] == "true" ? $params["redirectlink"] : "" );
84
+ $params_output_array["general"]['upload_finish_time'] = 0;
85
+ $params_output_array["general"]['message'] = "";
86
+ $params_output_array["general"]['message_type'] = "";
87
+ $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
88
+ $params_output_array["general"]['admin_messages']['notify'] = "";
89
+ $params_output_array["general"]['admin_messages']['redirect'] = "";
90
+ $params_output_array["general"]['admin_messages']['other'] = "";
91
+ $params_output_array["general"]['errors']['wpfilebase'] = "";
92
+ $params_output_array["general"]['errors']['notify'] = "";
93
+ $params_output_array["general"]['errors']['redirect'] = "";
94
+ $params_output_array["general"]['color'] = $default_colors['color'];
95
+ $params_output_array["general"]['bgcolor'] = $default_colors['bgcolor'];
96
+ $params_output_array["general"]['borcolor'] = $default_colors['borcolor'];
97
+ $params_output_array["general"]['notify_by_email'] = 0;
98
+ $params_output_array["general"]['fail_message'] = "";
99
+ $params_output_array["general"]['fail_admin_message'] = "";
100
+ /* safe_output is a minimized version of params_output_array, that is passed as text, in case JSON parse fails
101
+ its data are separated by semicolon (;) and are the following:
102
+ upload state: the upload state number
103
+ default colors: the default color, bgcolor and borcolor values, separated by comma(,)
104
+ file_count: the number of files processed
105
+ filedata: message type, header, message and admin message of each file, encoded and separated by comma (,) */
106
+ $params_output_array["general"]['safe_output'] = "";
107
+ /* js_script is javascript code that is executed after each file upload and is defined in wfu_after_file_upload action */
108
+ $params_output_array["general"]['js_script'] = "";
109
+
110
+ /* adjust $uploadedfile variable (holding file data) if this is a redirection caused because the browser of the user could not handle AJAX upload */
111
+ if ( isset($_FILES[$uploadedfile.'_redirected']) ) $uploadedfile .= '_redirected';
112
+ /* notify admin if this is a redirection caused because the browser of the user could not handle AJAX upload */
113
+ $params_output_array["general"]['admin_messages']['other'] = $params['adminerrors'];
114
+
115
+ if ( isset($_FILES[$uploadedfile]['error']) || $only_check || $nofileupload ) {
116
+ $files_count = 1;
117
+ // in case of checking of file or no file upload, then the $_FILES
118
+ // variable has not been set because no file has been uploaded,
119
+ // so we set it manually in order to allow the routine to continue
120
+ if ( $only_check || $nofileupload ) {
121
+ $_FILES[$uploadedfile]['name'] = wfu_plugin_decode_string($_POST[$uploadedfile.'_name']);
122
+ $_FILES[$uploadedfile]['type'] = 'any';
123
+ $_FILES[$uploadedfile]['tmp_name'] = 'any';
124
+ $_FILES[$uploadedfile]['error'] = '';
125
+ $_FILES[$uploadedfile]['size'] = wfu_sanitize_int($_POST[$uploadedfile.'_size']);
126
+ }
127
+ }
128
+ else $files_count = 0;
129
+ $params_output_array["general"]['files_count'] = $files_count;
130
+ // index of uploaded file in case of ajax uploads (in ajax uploads only one file is uploaded in every ajax call)
131
+ // the index is used to store any file data in session variables, in case the file is uploaded in two or more passes
132
+ // (like the case were in the first pass it is only checked)
133
+ $single_file_index = ( isset($_POST[$uploadedfile.'_index']) ? $_POST[$uploadedfile.'_index'] : -1 );
134
+ $single_file_index = wfu_sanitize_int($single_file_index);
135
+
136
+ /* append userdata fields to upload path */
137
+ $search = array ( );
138
+ $replace = array ( );
139
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
140
+ $ind = 1 + $userdata_key;
141
+ array_push($search, '/%userdata'.$ind.'%/');
142
+ array_push($replace, $userdata_field["value"]);
143
+ }
144
+ $params["uploadpath"] = preg_replace($search, $replace, $params["uploadpath"]);
145
+
146
+ /* append subfolder name to upload path */
147
+ if ( $params["askforsubfolders"] == "true" ) {
148
+ if ( $params["subfoldertree"] == "auto+" && $params['subdir_selection_index'] != '' ) {
149
+ if ( substr($params["uploadpath"], -1, 1) == "/" ) $params["uploadpath"] .= $params['subdir_selection_index'];
150
+ else $params["uploadpath"] .= '/'.$params['subdir_selection_index'];
151
+ }
152
+ elseif ( $params["subfoldertree"] != "auto+" && $params['subdir_selection_index'] >= 1 ) {
153
+ if ( substr($params["uploadpath"], -1, 1) == "/" ) $params["uploadpath"] .= $params['subfoldersarray'][$params['subdir_selection_index']];
154
+ else $params["uploadpath"] .= '/'.$params['subfoldersarray'][$params['subdir_selection_index']];
155
+ }
156
+ }
157
+
158
+ /* if webcam uploads are enabled, then correct the filename */
159
+ if ( strpos($params["placements"], "webcam") !== false && $params["webcam"] == "true" ) {
160
+ $initial_file_name = $_FILES[$uploadedfile]['name'];
161
+ $dotfileext = wfu_fileext($initial_file_name, true);
162
+ $file_name = wfu_filename($initial_file_name);
163
+ if ( $file_name == "video" ) $file_name = $params["videoname"];
164
+ else $file_name = $params["imagename"];
165
+ $search = array ('/%userid%/', '/%username%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/');
166
+ $replace = array ($user_id, $user_login, $params['blogid'], $params['pageid'], get_the_title($params['pageid']));
167
+ foreach ( $userdata_fields as $userdata_key => $userdata_field ) {
168
+ $ind = 1 + $userdata_key;
169
+ array_push($search, '/%userdata'.$ind.'%/');
170
+ array_push($replace, $userdata_field["value"]);
171
+ }
172
+ $file_name = preg_replace($search, $replace, $file_name);
173
+ $_FILES[$uploadedfile]['name'] = $file_name.$dotfileext;
174
+ }
175
+
176
+ if ( $files_count == 1 ) {
177
+
178
+ foreach ( $_FILES[$uploadedfile] as $key => $prop )
179
+ $fileprops[$key] = $prop;
180
+
181
+ $sftp_not_supported = false;
182
+ $upload_path_ok = false;
183
+ $allowed_file_ok = false;
184
+ $size_file_ok = false;
185
+ $size_file_phpenv_ok = true;
186
+ $ignore_server_actions = false;
187
+ $file_output['color'] = $default_colors['color'];
188
+ $file_output['bgcolor'] = $default_colors['bgcolor'];
189
+ $file_output['borcolor'] = $default_colors['borcolor'];
190
+ $file_output['header'] = "";
191
+ $file_output['message'] = "";
192
+ $file_output['message_type'] = "";
193
+ $file_output['admin_messages'] = "";
194
+ $file_output['uploaded_file_props'] = "";
195
+ $fileid = -1;
196
+
197
+ //calculate index of file
198
+ $real_file_index = $single_file_index;
199
+ if ( $single_file_index == -1 ) $real_file_index = ( isset($i) ? $i : 0 );
200
+ // determine if file data have been saved to session variables, due to a previous pass of this file
201
+ $file_map = "filedata_".$unique_id."_".$real_file_index;
202
+ // retrieve unique id of the file, used in filter actions for identifying each separate file
203
+ if ( WFU_USVAR_exists($file_map) ) {
204
+ $file_map_arr = WFU_USVAR($file_map);
205
+ $file_unique_id = $file_map_arr['file_unique_id'];
206
+ }
207
+ else $file_unique_id = '';
208
+ $filedata_previously_defined = ( $file_unique_id != '' );
209
+ /* generate unique id for each file for use in filter actions if it has not been previously defined */
210
+ if ( !$filedata_previously_defined )
211
+ $file_unique_id = wfu_create_random_string(20);
212
+
213
+ /* Get uploaded file size in Mbytes */
214
+ // correct file size in case of checking of file or no file upload
215
+ // otherwise $upload_file_size will be zero and the routine will fail
216
+ if ( $only_check || $nofileupload ) {
217
+ $upload_file_size = $fileprops['size'];
218
+ if ( $upload_file_size == 0 ) $upload_file_size ++;
219
+ }
220
+ else {
221
+ $upload_file_size = filesize($fileprops['tmp_name']);
222
+ if ( $upload_file_size == 0 && file_exists($fileprops['tmp_name']) && $fileprops['error'] == 0 ) $upload_file_size ++;
223
+ }
224
+ $upload_file_size_MB = $upload_file_size / 1024 / 1024;
225
+
226
+ $only_filename = $fileprops['name'];
227
+ $target_path = wfu_upload_plugin_full_path($params).$only_filename;
228
+
229
+ if ( $upload_file_size > 0 ) {
230
+ /* Section to perform filter action wfu_before_file_check before file is checked in order to perform
231
+ any filename or userdata modifications or reject the upload of the file by setting error_message item
232
+ of $ret_data array to a non-empty value */
233
+ $filter_error_message = '';
234
+ $filter_admin_message = '';
235
+ if ( $file_unique_id != '' && !$filedata_previously_defined ) {
236
+ // get correct file size
237
+ if ( $only_check || $nofileupload ) $filesize = $fileprops['size'];
238
+ else $filesize = filesize($fileprops['tmp_name']);
239
+ /* store file data and upload result to filedata session array
240
+ for use by after_upload filters */
241
+ if ( !$nofileupload ) {
242
+ if ( !WFU_USVAR_exists("filedata_".$unique_id) ) WFU_USVAR_store("filedata_".$unique_id, array());
243
+ $filedata_id = WFU_USVAR("filedata_".$unique_id);
244
+ $filedata_id[$real_file_index] = array(
245
+ "file_unique_id" => $file_unique_id,
246
+ "original_filename" => $only_filename,
247
+ "filesize" => $filesize,
248
+ );
249
+ WFU_USVAR_store("filedata_".$unique_id, $filedata_id);
250
+ }
251
+ // prepare parameters for wfu_before_file_check filter
252
+ // if this is a no file upload the prepare parameters for
253
+ // wfu_before_data_submit filter
254
+ if ( !$nofileupload ) $changable_data['file_path'] = $target_path;
255
+ $changable_data['user_data'] = $userdata_fields;
256
+ $changable_data['error_message'] = $filter_error_message;
257
+ $changable_data['admin_message'] = $filter_admin_message;
258
+ $additional_data['shortcode_id'] = $sid;
259
+ $additional_data['unique_id'] = $unique_id;
260
+ if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
261
+ if ( !$nofileupload ) $additional_data['file_size'] = $filesize;
262
+ $additional_data['user_id'] = $user->ID;
263
+ $additional_data['page_id'] = $params["pageid"];
264
+ if ( !$nofileupload ) $ret_data = apply_filters('wfu_before_file_check', $changable_data, $additional_data);
265
+ else $ret_data = apply_filters('wfu_before_data_submit', $changable_data, $additional_data);
266
+ if ( !$nofileupload ) $target_path = $ret_data['file_path'];
267
+ if ( !$nofileupload ) $only_filename = wfu_basename($target_path);
268
+ $userdata_fields = $ret_data['user_data'];
269
+ $filter_error_message = $ret_data['error_message'];
270
+ $filter_admin_message = $ret_data['admin_message'];
271
+ // if this is a file check, which means that a second pass of
272
+ // the file will follow, then we do not want to apply the
273
+ // filters again, so we store the changable data to session
274
+ // variables for this specific file
275
+ if ( $only_check && !$nofileupload ) {
276
+ if ( !WFU_USVAR_exists($file_map) ) WFU_USVAR_store($file_map, array());
277
+ $file_map_arr = WFU_USVAR($file_map);
278
+ $file_map_arr['file_unique_id'] = $file_unique_id;
279
+ $file_map_arr['filepath'] = $target_path;
280
+ $file_map_arr['userdata'] = $userdata_fields;
281
+ WFU_USVAR_store($file_map, $file_map_arr);
282
+ }
283
+ }
284
+ // if this is a second pass of the file, because a first pass with file checking was done before, then retrieve
285
+ // file data that may have previously changed because of application of filters
286
+ if ( $filedata_previously_defined ) {
287
+ $file_map_arr = WFU_USVAR($file_map);
288
+ $target_path = $file_map_arr['filepath'];
289
+ $only_filename = wfu_basename($target_path);
290
+ $userdata_fields = $file_map_arr['userdata'];
291
+ }
292
+ if ( $filter_error_message != '' ) {
293
+ //errorabort flag designates that file will be aborted and no resuming will be attempted
294
+ $file_output['message_type'] = "errorabort";
295
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
296
+ if ( $filter_admin_message != '' )
297
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
298
+ }
299
+ /* Perform security test for denial-of-service (DOS) attacks by
300
+ counting the number of files that have been uploaded within a
301
+ specific time interval, if DOS Attack Check is enabled. If the
302
+ number of files exceeds the limit then the file is rejected and a
303
+ message is sent to the administrator. */
304
+ elseif ( WFU_VAR("WFU_DOS_ATTACKS_CHECK") == "true" && wfu_check_DOS_attack() ) {
305
+ //notify admin about DOS attacks
306
+ $last_notification = wfu_get_option("wfu_admin_notification_about_DOS", null);
307
+ if ( $last_notification == null || time() - (int)$last_notification > (int)WFU_VAR("WFU_DOS_ATTACKS_ADMIN_EMAIL_FREQUENCY") ) {
308
+ $home = get_option("home");
309
+ $subject = str_replace("{SITE}", $home, WFU_WARNING_POTENTIAL_DOS_EMAIL_SUBJECT);
310
+ $message = str_replace(array( "{SITE}", "{FILENUM}", "{INTERVAL}" ), array( $home, WFU_VAR("WFU_DOS_ATTACKS_FILE_LIMIT"), WFU_VAR("WFU_DOS_ATTACKS_TIME_INTERVAL") ), WFU_WARNING_POTENTIAL_DOS_EMAIL_MESSAGE);
311
+ wfu_notify_admin($subject, $message);
312
+ wfu_update_option("wfu_admin_notification_about_DOS", time());
313
+ }
314
+ //errorabort flag designates that file will be aborted and no resuming will be attempted
315
+ $file_output['message_type'] = "errorabort";
316
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DOS_ATTACK);
317
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DOS_ATTACK);
318
+ }
319
+ else {
320
+ if ( !$nofileupload ) {
321
+ /* generate safe filename by removing invalid characters if
322
+ forcefilename is deactivated */
323
+ if ( $params['forcefilename'] != "true" ) $only_filename = wfu_upload_plugin_clean( $only_filename );
324
+ /* in case that forcefilename is activated then strip tags
325
+ as a minimum measure against hacking */
326
+ else $only_filename = strip_tags( $only_filename );
327
+ //reconstruct target_path
328
+ $target_path = wfu_basedir($target_path).$only_filename;
329
+
330
+ /* if medialink or postlink is activated then the target path becomes the current wordpress upload folder */
331
+ if ( $params["medialink"] == "true" || $params["postlink"] == "true" ) {
332
+ $mediapath = wp_upload_dir();
333
+ $target_path = $mediapath['path'].'/'.$only_filename;
334
+ }
335
+ /* Check if this is an sftp upload and sftp is supported */
336
+ if ( substr($target_path, 0, 7) == "sftp://" && !function_exists("ssh2_connect") ) {
337
+ $upload_path_ok = false;
338
+ $sftp_not_supported = true;
339
+ }
340
+ /* Check if upload path exists */
341
+ elseif ( wfu_is_dir( wfu_basedir($target_path), $params["ftpinfo"] ) ) {
342
+ $upload_path_ok = true;
343
+ }
344
+ /* Attempt to create path if user has selected to do so */
345
+ else if ( $params["createpath"] == "true" ) {
346
+ $wfu_create_directory_ret = wfu_create_directory(wfu_basedir($target_path), $params["accessmethod"], $params["ftpinfo"]);
347
+ if ( $wfu_create_directory_ret != "" ) {
348
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_create_directory_ret);
349
+ }
350
+ if ( wfu_is_dir( wfu_basedir($target_path), $params["ftpinfo"] ) ) {
351
+ $upload_path_ok = true;
352
+ }
353
+ }
354
+
355
+ /* File name control, reject files with .php, .js (and other) extensions for security reasons.
356
+ This is the first pass of extension control, which only checks the filename.
357
+ A second pass is performed after the file has completely uploaded, using WP inherent file
358
+ extension control, which provides better security. */
359
+ if ( !wfu_file_extension_blacklisted(strtolower($only_filename)) )
360
+ foreach ($allowed_patterns as $allowed_pattern) {
361
+ if ( wfu_file_extension_matches_pattern($allowed_pattern, strtolower($only_filename)) ) {
362
+ $allowed_file_ok = true;
363
+ break ;
364
+ }
365
+ }
366
+
367
+ /* File size control */
368
+ if ( $upload_file_size_MB <= $params["maxsize"] ) {
369
+ if ( $params['php_env'] == '32bit' && $upload_file_size > 2147483647 ) $size_file_phpenv_ok = false;
370
+ else $size_file_ok = true;
371
+ }
372
+ }
373
+ /* In case of no file upload then bypass above checks */
374
+ else {
375
+ $upload_path_ok = true;
376
+ $allowed_file_ok = true;
377
+ $size_file_ok = true;
378
+ }
379
+
380
+ if ( !$upload_path_ok or !$allowed_file_ok or !$size_file_ok ) {
381
+ //abort the file, no resuming will be attempted
382
+ $file_output['message_type'] = "errorabort";
383
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UPLOAD_FAILED);
384
+
385
+ if ( !$upload_path_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], ( $sftp_not_supported ? WFU_ERROR_ADMIN_SFTP_UNSUPPORTED : WFU_ERROR_DIR_EXIST ));
386
+ if ( !$allowed_file_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_ALLOW);
387
+ if ( !$size_file_ok ) {
388
+ if ( $size_file_phpenv_ok ) $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_SIZE);
389
+ else $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_2GBSIZE);
390
+ }
391
+ }
392
+ }
393
+ }
394
+ else {
395
+ // This block is executed when there is an error
396
+ $upload_error = $fileprops['error'];
397
+ if ( $upload_error == 1 ) {
398
+ $message_text = WFU_ERROR_FILE_PHP_SIZE;
399
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_SIZE);
400
+ }
401
+ elseif ( $upload_error == 2 ) $message_text = WFU_ERROR_FILE_HTML_SIZE;
402
+ elseif ( $upload_error == 3 ) $message_text = WFU_ERROR_FILE_PARTIAL;
403
+ elseif ( $upload_error == 4 ) $message_text = WFU_ERROR_FILE_NOTHING;
404
+ elseif ( $upload_error == 6 ) $message_text = WFU_ERROR_DIR_NOTEMP;
405
+ elseif ( $upload_error == 7 ) $message_text = WFU_ERROR_FILE_WRITE;
406
+ elseif ( $upload_error == 8 ) $message_text = WFU_ERROR_UPLOAD_STOPPED;
407
+ else {
408
+ $upload_time_limit = ini_get("max_input_time");
409
+ $params_output_array["general"]['upload_finish_time'] = $params["upload_start_time"] + $upload_time_limit * 1000;
410
+ $message_text = WFU_ERROR_FILE_PHP_TIME;
411
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_TIME);
412
+ }
413
+ //error (and not errorabort) flag designates that a resuming of the file may be attempted
414
+ $file_output['message_type'] = "error";
415
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $message_text);
416
+ }
417
+
418
+ $message_processed = false;
419
+ // if ( $upload_path_ok and $allowed_file_ok and $size_file_ok ) {
420
+ if ( substr($file_output['message_type'], 0, 5) != "error" ) {
421
+
422
+ if ( is_uploaded_file($fileprops['tmp_name']) || $only_check || $nofileupload ) {
423
+ $source_path = $fileprops['tmp_name'];
424
+
425
+ if ( $only_check || $ignore_server_actions || $nofileupload ) $file_copied = true;
426
+ else {
427
+ $file_copied = false;
428
+
429
+ if ($source_path) {
430
+ $file_exists = wfu_file_exists_extended($target_path);
431
+ if ( !$file_exists || $params["duplicatespolicy"] == "" || $params["duplicatespolicy"] == "overwrite" ) {
432
+ //redirect echo in internal buffer to receive and process any unwanted warning messages from wfu_upload_file
433
+ ob_start();
434
+ ob_clean();
435
+ /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
436
+ If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
437
+ previous filter wfu_before_file_check, corresponding them to the unique file id */
438
+ if ( $file_unique_id != '' ) {
439
+ $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
440
+ $file_map_arr = WFU_USVAR($file_map);
441
+ $file_map_arr['filepath'] = $target_path;
442
+ WFU_USVAR_store($file_map, $file_map_arr);
443
+ }
444
+ //recalculate $only_filename in case it changed with wfu_before_file_upload filter
445
+ $only_filename = wfu_basename($target_path);
446
+ //move the uploaded file to its final destination
447
+ $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
448
+ $file_copied = $wfu_upload_file_ret["uploaded"];
449
+ //process warning messages from wfu_upload_file
450
+ $echo_message = ob_get_contents();
451
+ //finish redirecting of echo to internal buffer
452
+ ob_end_clean();
453
+ if ( $echo_message != "" && !$file_copied ) {
454
+ //error (and not errorabort) flag designates that file may be resumed
455
+ $file_output['message_type'] = "error";
456
+ if ( stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move") ) {
457
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
458
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
459
+ }
460
+ else {
461
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
462
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], strip_tags($echo_message));
463
+ }
464
+ $message_processed = true;
465
+ }
466
+ if ( $wfu_upload_file_ret["admin_message"] != "" ) {
467
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
468
+ }
469
+ }
470
+ else if ( $file_exists && $params["duplicatespolicy"] == "maintain both" ) {
471
+ $full_path = wfu_basedir($target_path);
472
+ $name_part = $only_filename;
473
+ $ext_part = "";
474
+ $dot_pos = strrpos($name_part, ".");
475
+ if ( $dot_pos ) {
476
+ $ext_part = substr($name_part, $dot_pos);
477
+ $name_part = substr($name_part, 0, $dot_pos);
478
+ }
479
+ if ( $params["uniquepattern"] != "datetimestamp" ) {
480
+ $unique_ind = 1;
481
+ do {
482
+ $unique_ind += 1;
483
+ $only_filename = $name_part . "(" . $unique_ind . ")" . $ext_part;
484
+ $target_path = $full_path . $only_filename;
485
+ }
486
+ while ( wfu_file_exists_extended($target_path) );
487
+ }
488
+ else {
489
+ $current_datetime = gmdate("U") - 1;
490
+ do {
491
+ $current_datetime += 1;
492
+ $only_filename = $name_part . "-" . gmdate("YmdHis", $current_datetime) . $ext_part;
493
+ $target_path = $full_path . $only_filename;
494
+ }
495
+ while ( wfu_file_exists_extended($target_path) );
496
+ }
497
+ //redirect echo in internal buffer to receive and process any unwanted warning messages from move_uploaded_file
498
+ ob_start();
499
+ ob_clean();
500
+ /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
501
+ If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
502
+ previous filter wfu_before_file_check, corresponding them to the unique file id */
503
+ if ( $file_unique_id != '' ) {
504
+ $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
505
+ $file_map_arr = WFU_USVAR($file_map);
506
+ $file_map_arr['filepath'] = $target_path;
507
+ WFU_USVAR_store($file_map, $file_map_arr);
508
+ }
509
+ //recalculate $only_filename in case it changed with wfu_before_file_upload filter
510
+ $only_filename = wfu_basename($target_path);
511
+ //move the uploaded file to its final destination
512
+ $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
513
+ $file_copied = $wfu_upload_file_ret["uploaded"];
514
+ //process warning messages from move_uploaded_file
515
+ $echo_message = ob_get_contents();
516
+ //finish redirecting of echo to internal buffer
517
+ ob_end_clean();
518
+ if ( $echo_message != "" && !$file_copied ) {
519
+ //error (and not errorabort) flag designates that file may be resumed
520
+ $file_output['message_type'] = "error";
521
+ if ( stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move") ) {
522
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
523
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
524
+ }
525
+ else {
526
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
527
+ $file_output['admin_messages'] = wfu_join_strings("<br />n", $file_output['admin_messages'], strip_tags($echo_message));
528
+ }
529
+ $message_processed = true;
530
+ }
531
+ if ( $wfu_upload_file_ret["admin_message"] != "" ) {
532
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
533
+ }
534
+ }
535
+ else {
536
+ //abort the file and do not allow resuming
537
+ $file_output['message_type'] = "errorabort";
538
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_EXISTS);
539
+ $message_processed = true;
540
+ $file_copied = false;
541
+ }
542
+ }
543
+ }
544
+
545
+ if ( $file_copied ) {
546
+ /* prepare email notification parameters if email notification is enabled */
547
+ if ( $params["notify"] == "true" && (!$only_check || $nofileupload) ) {
548
+ if ( !$nofileupload ) array_push($notify_target_path_list, $target_path);
549
+ }
550
+
551
+ /* prepare redirect link if redirection is enabled */
552
+ if ( $params["redirect"] == "true" ) {
553
+ /* Define dynamic redirect link from variables */
554
+ $search = array ('/%filename%/', '/%username%/');
555
+ $replace = array ($only_filename, $user_login);
556
+ $params_output_array["general"]['redirect_link'] = trim(preg_replace($search, $replace, $params["redirectlink"]));
557
+ }
558
+
559
+ if ( !$message_processed ) {
560
+ $file_output['message_type'] = "success";
561
+ }
562
+ }
563
+ else if ( !$message_processed ) {
564
+ //abort the file and do not allow resuming
565
+ $file_output['message_type'] = "errorabort";
566
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
567
+ }
568
+
569
+ /* Delete temporary file (in tmp directory) */
570
+ // unlink($source_path);
571
+ }
572
+ else {
573
+ //abort the file and do not allow resuming
574
+ $file_output['message_type'] = "errorabort";
575
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
576
+ }
577
+ }
578
+
579
+ /* last check of output file status */
580
+ if ( $file_output['message_type'] == "" ) {
581
+ if ( $file_copied ) $file_output['message_type'] = "success";
582
+ else {
583
+ //abort the file and do not allow resuming
584
+ $file_output['message_type'] = "errorabort";
585
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
586
+ }
587
+ }
588
+
589
+ /* suppress any admin messages if user is not administrator or adminmessages is not activated */
590
+ if ( $suppress_admin_messages ) $file_output['admin_messages'] = "";
591
+
592
+ /* set file status to "warning" if the file has been uploaded but there are messages */
593
+ if ( $file_output['message_type'] == "success" ) {
594
+ if ( $file_output['message'] != "" || $file_output['admin_messages'] != "" )
595
+ $file_output['message_type'] = "warning";
596
+ }
597
+
598
+ /* set success status of the file, to be used for medialink and post actions */
599
+ $file_finished_successfully = ( (!$only_check || $nofileupload) && ( $file_output['message_type'] == "success" || $file_output['message_type'] == "warning" ) );
600
+ /* set non-success status of the file, to be used for medialink and post actions */
601
+ $file_finished_unsuccessfully = ( substr($file_output['message_type'], 0, 5) == "error" );
602
+
603
+
604
+ /* perform custom actions after file is completely uploaded in order to determine if file is valid ir not */
605
+ if ( $file_finished_successfully && !$ignore_server_actions && !$nofileupload ) {
606
+ /* Here the second pass of file extension control is performed after the file has completely
607
+ uploaded, using WP inherent functions that determine the real extension from analyzing the
608
+ data and not from the filename extension. If this check reveals an extension which is not
609
+ permitted then the file will be rejected and erased. If the real extension is different
610
+ than the original one but it is permitted, then the file will remain as it is but a warning
611
+ message will notify the user that the extension of the file does not match its contents. */
612
+ $check = wp_check_filetype_and_ext( $target_path, $only_filename, false );
613
+ if ( $check['proper_filename'] !== false ) {
614
+ $proper_filename = $check['proper_filename'];
615
+ if ( wfu_file_extension_blacklisted(strtolower($only_filename)) ) {
616
+ $file_finished_successfully = false;
617
+ $file_finished_unsuccessfully = true;
618
+ unlink($target_path);
619
+ $file_output['message_type'] = "errorabort";
620
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_REJECT);
621
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_WRONGEXT.$check['proper_filename']);
622
+ }
623
+ else {
624
+ $file_output['message_type'] = "warning";
625
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_SUSPICIOUS);
626
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_WARNING_ADMIN_FILE_SUSPICIOUS.$check['proper_filename']);
627
+ }
628
+ }
629
+ // run any wfu_after_file_loaded filters to make any last file checks and accept or reject it
630
+ if ( $file_finished_successfully ) {
631
+ $filter_error_message = '';
632
+ $filter_admin_message = '';
633
+ $changable_data['error_message'] = $filter_error_message;
634
+ $changable_data['admin_message'] = $filter_admin_message;
635
+ $additional_data['file_unique_id'] = $file_unique_id;
636
+ $additional_data['file_path'] = $target_path;
637
+ $additional_data['shortcode_id'] = $sid;
638
+ $ret_data = apply_filters('wfu_after_file_loaded', $changable_data, $additional_data);
639
+ //this is a call to wfu_after_file_complete filters, which is
640
+ //the old name of wfu_after_file_loaded filters, for maintaining
641
+ //backward compatibility
642
+ $changable_data = $ret_data;
643
+ $ret_data = apply_filters('wfu_after_file_complete', $changable_data, $additional_data);
644
+ $filter_error_message = $ret_data['error_message'];
645
+ $filter_admin_message = $ret_data['admin_message'];
646
+ if ( $filter_error_message != '' ) {
647
+ $file_finished_successfully = false;
648
+ $file_finished_unsuccessfully = true;
649
+ unlink($target_path);
650
+ $file_output['message_type'] = "errorabort";
651
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
652
+ if ( $filter_admin_message != '' )
653
+ $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
654
+ }
655
+ }
656
+ }
657
+
658
+ /* in case that the file will not be saved due to personal data policy
659
+ then convert any success message_type to warning */
660
+ if ( $store_nothing && $file_output['message_type'] == "success" ) {
661
+ $file_output['message_type'] = "warning";
662
+ $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_UPLOAD_STATE19_SINGLEFILE);
663
+ }
664
+
665
+ /* adjust message details and colors according to file result */
666
+ /* FileResult: A */
667
+ $search = array ('/%username%/', '/%useremail%/', '/%filename%/', '/%filepath%/');
668
+ $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename, $target_path);
669
+ if ( $file_output['message_type'] == "success" ) {
670
+ $success_count ++;
671
+ $color_array = explode(",", $params['successmessagecolors']);
672
+ $file_output['color'] = $color_array[0];
673
+ $file_output['bgcolor'] = $color_array[1];
674
+ $file_output['borcolor'] = $color_array[2];
675
+ $file_output['header'] = preg_replace($search, $replace, $params['successmessage']);
676
+ /* prepare details of successful file upload, visible only to administrator */
677
+ $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
678
+ }
679
+ /* FileResult: B */
680
+ elseif ( $file_output['message_type'] == "warning" ) {
681
+ $warning_count ++;
682
+ $color_array = explode(",", $params['warningmessagecolors']);
683
+ $file_output['color'] = $color_array[0];
684
+ $file_output['bgcolor'] = $color_array[1];
685
+ $file_output['borcolor'] = $color_array[2];
686
+ $file_output['header'] = preg_replace($search, $replace, ( $store_nothing ? WFU_WARNINGMESSAGE_NOSAVE : $params['warningmessage'] ));
687
+ /* prepare and prepend details of successful file upload, visible only to administrator */
688
+ $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
689
+ }
690
+ /* FileResult: C */
691
+ elseif ( substr($file_output['message_type'], 0, 5) == "error" ) {
692
+ $error_count ++;
693
+ $color_array = explode(",", $params['failmessagecolors']);
694
+ $file_output['color'] = $color_array[0];
695
+ $file_output['bgcolor'] = $color_array[1];
696
+ $file_output['borcolor'] = $color_array[2];
697
+ $replace = array ($user_login, ( $user_email == "" ? "no email" : $user_email ), $only_filename, $target_path);
698
+ $file_output['header'] = preg_replace($search, $replace, $params['errormessage']);
699
+ /* prepare and prepend details of failed file upload, visible only to administrator */
700
+ if ( !$nofileupload ) $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_FAILMESSAGE_DETAILS), $file_output['admin_messages']);
701
+ }
702
+
703
+ /* suppress again any admin messages if user is not administrator or adminmessages is not activated */
704
+ if ( $suppress_admin_messages ) $file_output['admin_messages'] = "";
705
+
706
+ $params_output_array[0] = $file_output;
707
+
708
+ if ( $file_unique_id != '' && $file_finished_unsuccessfully && !$ignore_server_actions ) {
709
+ /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
710
+ If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
711
+ the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
712
+ This actions allows to define custom javascript code to run after each file finishes (either succeeded or failed).
713
+ For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
714
+ still remains. */
715
+ $changable_data['ret_value'] = null;
716
+ $changable_data['js_script'] = '';
717
+ $additional_data['shortcode_id'] = $sid;
718
+ $additional_data['unique_id'] = $unique_id;
719
+ if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
720
+ if ( !$nofileupload ) $additional_data['upload_result'] = $file_output['message_type'];
721
+ else $additional_data['submit_result'] = $file_output['message_type'];
722
+ $additional_data['error_message'] = $file_output['message'];
723
+ $additional_data['admin_messages'] = $file_output['admin_messages'];
724
+ if ( !$nofileupload ) $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
725
+ else $ret_data = apply_filters('wfu_after_data_submit', $changable_data, $additional_data);
726
+ $params_output_array["general"]['js_script'] = $ret_data['js_script'];
727
+ // do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
728
+ }
729
+
730
+ if ( $file_finished_successfully && !$ignore_server_actions ) {
731
+ /* Log file upload action if file has finished uploading
732
+ uccessfully. If this is a no file upload then log action will be
733
+ datasubmit. */
734
+ if ( !$nofileupload ) {
735
+ if ( !$consent_revoked ) $fileid = wfu_log_action('upload', $target_path, $user->ID, $unique_id, $params['pageid'], $params['blogid'], $sid, $userdata_fields);
736
+ elseif ( !$not_store_files ) $fileid = wfu_log_action('upload', $target_path, 0, $unique_id, $params['pageid'], $params['blogid'], $sid, $empty_userdata_fields);
737
+ }
738
+ else {
739
+ if ( !$consent_revoked ) $fileid = wfu_log_action('datasubmit', '', $user->ID, $unique_id, $params['pageid'], $params['blogid'], $sid, $userdata_fields);
740
+ }
741
+ /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
742
+ If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
743
+ the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
744
+ This actions allows to define custom javascript code to run after each file finishes (either suceeded or failed).
745
+ For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
746
+ still remains. */
747
+ $changable_data['ret_value'] = null;
748
+ $changable_data['js_script'] = '';
749
+ $additional_data['shortcode_id'] = $sid;
750
+ $additional_data['unique_id'] = $unique_id;
751
+ if ( !$nofileupload ) $additional_data['file_unique_id'] = $file_unique_id;
752
+ if ( !$nofileupload ) $additional_data['upload_result'] = $file_output['message_type'];
753
+ else $additional_data['submit_result'] = $file_output['message_type'];
754
+ $additional_data['error_message'] = $file_output['message'];
755
+ $additional_data['admin_messages'] = $file_output['admin_messages'];
756
+ if ( !$nofileupload ) $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
757
+ else $ret_data = apply_filters('wfu_after_data_submit', $changable_data, $additional_data);
758
+ $params_output_array["general"]['js_script'] = $ret_data['js_script'];
759
+ // do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
760
+ }
761
+
762
+ /* add file to Media or attach file to current post if any of these options is activated and the file has finished uploading successfully */
763
+ if ( ( $params["medialink"] == "true" || $params["postlink"] == "true" ) && $file_finished_successfully && !$ignore_server_actions && !$nofileupload ) {
764
+ $pageid = ( $params["postlink"] == "true" ? $params['pageid'] : 0 );
765
+ if ( !$consent_revoked ) wfu_process_media_insert($target_path, $userdata_fields, $pageid);
766
+ elseif ( !$not_store_files ) wfu_process_media_insert($target_path, empty_userdata_fields, $pageid);
767
+ }
768
+
769
+ /* store final file data and upload result to filemap session array for
770
+ use by after_upload filters */
771
+ if ( ( $file_finished_successfully || $file_finished_unsuccessfully ) && !$ignore_server_actions && !$nofileupload ) {
772
+ if ( WFU_USVAR_exists("filedata_".$unique_id) ) {
773
+ $filedata_id = WFU_USVAR("filedata_".$unique_id);
774
+ if ( isset($filedata_id[$real_file_index]) ) {
775
+ $filedata_id[$real_file_index]["filepath"] = $target_path;
776
+ $filedata_id[$real_file_index]["user_data"] = $userdata_fields;
777
+ $filedata_id[$real_file_index]["upload_result"] = $file_output['message_type'];
778
+ $filedata_id[$real_file_index]["message"] = $file_output['message'];
779
+ $filedata_id[$real_file_index]["admin_messages"] = $file_output['admin_messages'];
780
+ WFU_USVAR_store("filedata_".$unique_id, $filedata_id);
781
+ }
782
+ }
783
+ }
784
+ }
785
+
786
+ // in case of file check set files_count to 0 in order to denote that the file was not really uploaded
787
+ if ( $only_check && !$nofileupload ) $params_output_array["general"]['files_count'] = 0;
788
+
789
+ $somefiles_Ok = ( ( $warning_count + $success_count ) > 0 );
790
+ $allfiles_Ok = ( $somefiles_Ok && ( $error_count == 0 ) );
791
+
792
+ /* Prepare WPFileBase Plugin update url, if this option has been selected and only if at least one file has been successfully uploaded.
793
+ Execution will happen only if accumulated $params_output_array["general"]['update_wpfilebase'] is not empty */
794
+ if ( $params["filebaselink"] == "true" && !$nofileupload ) {
795
+ if ( $somefiles_Ok ) {
796
+ $filebaseurl = site_url();
797
+ if ( substr($filebaseurl, -1, 1) == "/" ) $filebaseurl = substr($filebaseurl, 0, strlen($filebaseurl) - 1);
798
+ /* if the following variable is not empty, then WPFileBase Plugin update must be executed
799
+ and any admin messages must be suppressed */
800
+ $params_output_array["general"]['update_wpfilebase'] = $filebaseurl;
801
+ }
802
+ else {
803
+ $params_output_array["general"]['admin_messages']['wpfilebase'] = WFU_WARNING_WPFILEBASE_NOTUPDATED_NOFILES;
804
+ $params_output_array["general"]['errors']['wpfilebase'] = "error";
805
+ }
806
+ }
807
+
808
+ /* Prepare email notification parameters if email notification is enabled and only if at least one file has been successfully uploaded
809
+ if $method = "no-ajax" then send the email to the recipients
810
+ if $method = "ajax" then return the notification parameters to the handler for further processing
811
+ In case of ajax, execution will happen only if notify_by_email is greater than 0 */
812
+ if ( $params["notify"] == "true" ) {
813
+ /* verify that there are recipients */
814
+ $notifyrecipients = trim(preg_replace('/%useremail%/', $user_email, $params["notifyrecipients"]));
815
+ if ( $notifyrecipients != "" ) {
816
+ if ( $somefiles_Ok || $force_notifications ) {
817
+ if ( $method == 'no_ajax' && !$ignore_server_actions ) {
818
+ $send_error = wfu_send_notification_email($user, $notify_target_path_list, $userdata_fields, $params);
819
+ if ( $send_error != "" ) {
820
+ $params_output_array["general"]['admin_messages']['notify'] = $send_error;
821
+ $params_output_array["general"]['errors']['notify'] = "error";
822
+ }
823
+ }
824
+ else {
825
+ /* if the following variable is not empty, then email notification must be sent
826
+ and any admin messages must be suppressed */
827
+ $params_output_array["general"]['notify_by_email'] = ( !$nofileupload && !$force_notifications ? count($notify_target_path_list) : 1 );
828
+ }
829
+ }
830
+ else {
831
+ $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NOFILES;
832
+ $params_output_array["general"]['errors']['notify'] = "error";
833
+ }
834
+ }
835
+ else {
836
+ $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NORECIPIENTS;
837
+ $params_output_array["general"]['errors']['notify'] = "error";
838
+ }
839
+ }
840
+
841
+ /* Prepare redirect link if redirection is enabled and only if all files have been successfully uploaded
842
+ Execution will happen only if accumulated redirect_link is not empty and accumulated redirect errors are empty */
843
+ if ( $params["redirect"] == "true" ) {
844
+ if ( $params_output_array["general"]['redirect_link'] == "" ) {
845
+ $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_EMPTY;
846
+ $params_output_array["general"]['errors']['redirect'] = "error";
847
+ }
848
+ elseif ( !$allfiles_Ok ) {
849
+ $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_FILESFAILED;
850
+ $params_output_array["general"]['errors']['redirect'] = "error";
851
+ }
852
+ }
853
+
854
+ /* suppress any admin messages if user is not administrator or adminmessages is not activated */
855
+ if ( $suppress_admin_messages ) {
856
+ $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
857
+ $params_output_array["general"]['admin_messages']['notify'] = "";
858
+ $params_output_array["general"]['admin_messages']['redirect'] = "";
859
+ $params_output_array["general"]['admin_messages']['other'] = "";
860
+ }
861
+
862
+ /* Calculate upload state from file results */
863
+ if ( $allfiles_Ok && ( $warning_count == 0 ) ) $params_output_array["general"]['state'] = ( !$nofileupload ? 4 : 14 );
864
+ else if ( $allfiles_Ok ) $params_output_array["general"]['state'] = 5;
865
+ else if ( $somefiles_Ok ) $params_output_array["general"]['state'] = 6; //only valid in no-ajax method
866
+ else if ( !$somefiles_Ok && $error_count > 0 ) $params_output_array["general"]['state'] = ( !$nofileupload ? 7 : 15 );
867
+ else $params_output_array["general"]['state'] = 8;
868
+ /* in case that the files will not be saved due to personal data policy
869
+ then adjust general state accordingly (effective for no-ajax uploads) */
870
+ if ( !$nofileupload && $somefiles_Ok && $store_nothing ) $params_output_array["general"]['state'] = 19;
871
+
872
+ /* construct safe output */
873
+ $sout = $params_output_array["general"]['state'].";".WFU_VAR("WFU_DEFAULTMESSAGECOLORS").";".$files_count;
874
+ for ($i = 0; $i < $files_count; $i++) {
875
+ $sout .= ";".wfu_plugin_encode_string($file_output['message_type']);
876
+ $sout .= ",".wfu_plugin_encode_string($file_output['header']);
877
+ $sout .= ",".wfu_plugin_encode_string($file_output['message']);
878
+ $sout .= ",".wfu_plugin_encode_string($file_output['admin_messages']);
879
+ $sout .= ",".$file_output['uploaded_file_props'];
880
+ }
881
+ $params_output_array["general"]['safe_output'] = $sout;
882
+
883
+ return $params_output_array;
884
+ }
885
+
886
+ ?>
readme.txt CHANGED
@@ -3,7 +3,7 @@ Contributors: nickboss
3
  Donate link: http://www.iptanus.com/support/wordpress-file-upload
4
  Tags: file, upload, ajax, form, page, post, sidebar, responsive, widget, webcam, ftp
5
  Requires at least: 2.9.2
6
- Tested up to: 5.2
7
  Stable tag: "trunk"
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
@@ -149,6 +149,17 @@ There is an option in plugin's settings in Dashboard to relax the CSS rules, so
149
 
150
  == Changelog ==
151
 
 
 
 
 
 
 
 
 
 
 
 
152
  = 4.11.2 =
153
  * added easier configuration of FTP Credentials (ftpinfo) attribute of the uploader shortcode
154
 
@@ -839,6 +850,9 @@ Initial version.
839
 
840
  == Upgrade Notice ==
841
 
 
 
 
842
  = 4.11.2 =
843
  Minor update to introduce some improvements.
844
 
3
  Donate link: http://www.iptanus.com/support/wordpress-file-upload
4
  Tags: file, upload, ajax, form, page, post, sidebar, responsive, widget, webcam, ftp
5
  Requires at least: 2.9.2
6
+ Tested up to: 5.3
7
  Stable tag: "trunk"
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
149
 
150
  == Changelog ==
151
 
152
+ = 4.12.0 =
153
+ * corrected bug where export data file was not deleted after download
154
+ * corrected bug in FTP credentials configurator about double backslash (\\) issue
155
+ * added cookies user state handler that has been integrated with dboption as 'Cookies (DBOption)' to comply with Wordpress directives not to use session
156
+ * 'Cookies (DBOption)' user state handler has been set as the default one
157
+ * added advanced option WFU_US_DBOPTION_BASE so that dboption can also work with session
158
+ * added advanced option WFU_US_SESSION_LEGACY to use the old session functionality of the plugin, having session_start() in header
159
+ * added auto-adjustment of user state handler to 'dboption' during activation (or update) of the plugin
160
+ * bug "Error: [] cURL error 28" in Wordpress Site Health disappears when setting user state handler to 'Cookies (DBOption)' or when WFU_US_SESSION_LEGACY advanced option is false
161
+ * added the ability to run PHP processes in queue, which is necessary for correctly handling uploads when user state handler is dboption
162
+
163
  = 4.11.2 =
164
  * added easier configuration of FTP Credentials (ftpinfo) attribute of the uploader shortcode
165
 
850
 
851
  == Upgrade Notice ==
852
 
853
+ = 4.12.0 =
854
+ Significant update to introduce some improvements, new features and fix some bugs.
855
+
856
  = 4.11.2 =
857
  Minor update to introduce some improvements.
858
 
release_notes.txt CHANGED
@@ -1,3 +1,10 @@
1
- <!-- --><span><strong>Version 4.11.2</strong> is a regular release introducing a minor improvement. The configuration of <strong>FTP Credentials</strong> (ftpinfo) attribute of the <strong>uploader shortcode</strong> has now become easier.<br /><br />
 
 
 
 
 
 
 
2
  For more details about this version's changes please visit the Release Notes of the plugin's </span><a href="http://www.iptanus.com/wordpress-plugins/wordpress-file-upload/">support page</a><span>.</span><!-- -->
3
  <!-- -->
1
+ <!-- --><span><strong>Version 4.12.0</strong> is a significant release introducing <strong>session-less</strong> operation. Until now the plugin was using session to store <strong>User State</strong>, however this was causing problems with the latest versions of Wordpress (loopback errors in Site Health, could not edit files with Theme and Plugin Editor, performance issues). Even <strong>DBOption</strong> user state handler of the plugin was using session.<br /><br />
2
+ When this version is activated the plugin will </span><span style="text-decoration: underline;">automatically switch</span><span> user state handler to <strong>Cookies/DB</strong>. The new handler uses <strong>cookies</strong> and the <strong>database</strong> to store user state. It fully complies with Wordpress directives and resolves the aforementioned problems. It also complies with EU regulation for data protection, <strong>GDPR</strong>, since no user information is kept in cookies.<br /><br />
3
+ </span><span style="font-weight: bold; color: red;">NOTE:</span><span> Please note that in case you have added hooks (PHP scripts) in your website to customize the plugin and these hooks use session (they contain the variable <strong>$_SESSION</strong>), they may not work with Cookies/DB handler. For this reason and also for facing unpredictable issues of the new handler, <strong>Session</strong> user state handler still remains as an option in plugin's <strong>Settings</strong>.<br /><br />
4
+ Other improvements introduced in this version are:
5
+ <ul style="list-style: disc; padding-left: 20px;">
6
+ <li><strong>SFTP</strong> support improved using <strong>PHPSecLib</strong> library.</li>
7
+ <li>Corrected a bug in <strong>FTP Credentials Configurator</strong> that was not correctly handling usernames and passwords containing at (@) and colon (:) characters.</li>
8
+ </ul>
9
  For more details about this version's changes please visit the Release Notes of the plugin's </span><a href="http://www.iptanus.com/wordpress-plugins/wordpress-file-upload/">support page</a><span>.</span><!-- -->
10
  <!-- -->
wfu_file_downloader.php CHANGED
@@ -1,51 +1,74 @@
1
  <?php
2
- if( !session_id() ) { session_start(); }
3
  include_once( dirname(__FILE__).'/lib/wfu_functions.php' );
4
  include_once( dirname(__FILE__).'/lib/wfu_security.php' );
5
- wfu_download_file();
 
 
 
 
 
 
 
 
 
6
 
7
  function wfu_download_file() {
8
  $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
9
  $ticket = (isset($_POST['ticket']) ? $_POST['ticket'] : (isset($_GET['ticket']) ? $_GET['ticket'] : ''));
10
  if ( $file_code == '' || $ticket == '' ) die();
11
 
12
- $ticket = wfu_sanitize_code($ticket);
 
 
 
13
  //if download ticket does not exist or is expired die
14
- if ( !WFU_USVAR_exists_session('wfu_download_ticket_'.$ticket) || time() > WFU_USVAR_session('wfu_download_ticket_'.$ticket) ) die();
 
 
 
 
 
15
  //destroy ticket so it cannot be used again
16
- WFU_USVAR_unset_session('wfu_download_ticket_'.$ticket);
17
 
18
- $file_code = wfu_sanitize_code($file_code);
19
  //if file_code starts with exportdata, then this is a request for export of
20
  //uploaded file data, so disposition_name will not be the filename of the file
21
  //but wfu_export.csv; also set flag to delete file after download operation
22
  if ( substr($file_code, 0, 10) == "exportdata" ) {
23
  $file_code = substr($file_code, 10);
24
  //$filepath = wfu_get_filepath_from_safe($file_code);
25
- $filepath = WFU_USVAR_session('wfu_storage_'.$file_code);
26
  $disposition_name = "wfu_export.csv";
27
  $delete_file = true;
28
  }
29
  else {
30
  //$filepath = wfu_get_filepath_from_safe($file_code);
31
- $filepath = WFU_USVAR_session('wfu_storage_'.$file_code);
32
- if ( $filepath === false ) die();
 
 
 
 
33
  $filepath = wfu_flatten_path($filepath);
34
  if ( substr($filepath, 0, 1) == "/" ) $filepath = substr($filepath, 1);
35
- $filepath = ( substr($filepath, 0, 6) == 'ftp://' || substr($filepath, 0, 7) == 'ftps://' || substr($filepath, 0, 7) == 'sftp://' ? $filepath : WFU_USVAR_session('wfu_ABSPATH').$filepath );
36
  $disposition_name = wfu_basename($filepath);
37
  $delete_file = false;
38
  }
 
 
39
  //check that file exists
40
  if ( !file_exists($filepath) ) {
41
- WFU_USVAR_store_session('wfu_download_status_'.$ticket, 'failed');
42
- die('<script language="javascript">alert("'.( WFU_USVAR_exists_session('wfu_browser_downloadfile_notexist') ? WFU_USVAR_session('wfu_browser_downloadfile_notexist') : 'File does not exist!' ).'");</script>');
43
  }
44
- //get mime type
45
 
 
46
  @set_time_limit(0); // disable the time limit for this script
47
  $fsize = filesize($filepath);
48
  if ( $fd = @fopen ($filepath, "rb") ) {
 
 
49
  header('Content-Type: application/octet-stream');
50
  header("Content-Disposition: attachment; filename=\"".$disposition_name."\"");
51
  header('Content-Transfer-Encoding: binary');
@@ -69,16 +92,40 @@ function wfu_download_file() {
69
  }
70
  else $failed = true;
71
 
72
- if ( $delete_file ) unset($filepath);
73
 
74
  if ( !$failed ) {
75
- WFU_USVAR_store_session('wfu_download_status_'.$ticket, 'downloaded');
 
76
  die();
77
  }
78
  else {
79
- WFU_USVAR_store_session('wfu_download_status_'.$ticket, 'failed');
80
- die('<script language="javascript">alert("'.( WFU_USVAR_exists_session('wfu_browser_downloadfile_failed') ? WFU_USVAR_session('wfu_browser_downloadfile_failed') : 'Could not download file!' ).'");</script>');
 
81
  }
82
  }
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  ?>
1
  <?php
 
2
  include_once( dirname(__FILE__).'/lib/wfu_functions.php' );
3
  include_once( dirname(__FILE__).'/lib/wfu_security.php' );
4
+ $handler = (isset($_POST['handler']) ? $_POST['handler'] : (isset($_GET['handler']) ? $_GET['handler'] : '-1'));
5
+ $session_legacy = (isset($_POST['session_legacy']) ? $_POST['session_legacy'] : (isset($_GET['session_legacy']) ? $_GET['session_legacy'] : ''));
6
+ $dboption_base = (isset($_POST['dboption_base']) ? $_POST['dboption_base'] : (isset($_GET['dboption_base']) ? $_GET['dboption_base'] : '-1'));
7
+ if ( $handler == '-1' || $session_legacy == '' || $dboption_base == '-1' ) die();
8
+ else {
9
+ $GLOBALS["wfu_user_state_handler"] = wfu_sanitize_code($handler);
10
+ $GLOBALS["WFU_GLOBALS"]["WFU_US_SESSION_LEGACY"] = array( "", "", "", ( $session_legacy == '1' ? 'true' : 'false' ), "", true );
11
+ $GLOBALS["WFU_GLOBALS"]["WFU_US_DBOPTION_BASE"] = array( "", "", "", wfu_sanitize_code($dboption_base), "", true );
12
+ wfu_download_file();
13
+ }
14
 
15
  function wfu_download_file() {
16
  $file_code = (isset($_POST['file']) ? $_POST['file'] : (isset($_GET['file']) ? $_GET['file'] : ''));
17
  $ticket = (isset($_POST['ticket']) ? $_POST['ticket'] : (isset($_GET['ticket']) ? $_GET['ticket'] : ''));
18
  if ( $file_code == '' || $ticket == '' ) die();
19
 
20
+ wfu_initialize_user_state();
21
+
22
+ $ticket = wfu_sanitize_code($ticket);
23
+ $file_code = wfu_sanitize_code($file_code);
24
  //if download ticket does not exist or is expired die
25
+ if ( !WFU_USVAR_exists_downloader('wfu_download_ticket_'.$ticket) || time() > WFU_USVAR_downloader('wfu_download_ticket_'.$ticket) ) {
26
+ WFU_USVAR_unset_downloader('wfu_download_ticket_'.$ticket);
27
+ WFU_USVAR_unset_downloader('wfu_storage_'.$file_code);
28
+ wfu_update_download_status($ticket, 'failed');
29
+ die();
30
+ }
31
  //destroy ticket so it cannot be used again
32
+ WFU_USVAR_unset_downloader('wfu_download_ticket_'.$ticket);
33
 
 
34
  //if file_code starts with exportdata, then this is a request for export of
35
  //uploaded file data, so disposition_name will not be the filename of the file
36
  //but wfu_export.csv; also set flag to delete file after download operation
37
  if ( substr($file_code, 0, 10) == "exportdata" ) {
38
  $file_code = substr($file_code, 10);
39
  //$filepath = wfu_get_filepath_from_safe($file_code);
40
+ $filepath = WFU_USVAR_downloader('wfu_storage_'.$file_code);
41
  $disposition_name = "wfu_export.csv";
42
  $delete_file = true;
43
  }
44
  else {
45
  //$filepath = wfu_get_filepath_from_safe($file_code);
46
+ $filepath = WFU_USVAR_downloader('wfu_storage_'.$file_code);
47
+ if ( $filepath === false ) {
48
+ WFU_USVAR_unset_downloader('wfu_storage_'.$file_code);
49
+ wfu_update_download_status($ticket, 'failed');
50
+ die();
51
+ }
52
  $filepath = wfu_flatten_path($filepath);
53
  if ( substr($filepath, 0, 1) == "/" ) $filepath = substr($filepath, 1);
54
+ $filepath = ( substr($filepath, 0, 6) == 'ftp://' || substr($filepath, 0, 7) == 'ftps://' || substr($filepath, 0, 7) == 'sftp://' ? $filepath : WFU_USVAR_downloader('wfu_ABSPATH').$filepath );
55
  $disposition_name = wfu_basename($filepath);
56
  $delete_file = false;
57
  }
58
+ //destroy file code as it is no longer needed
59
+ WFU_USVAR_unset_downloader('wfu_storage_'.$file_code);
60
  //check that file exists
61
  if ( !file_exists($filepath) ) {
62
+ wfu_update_download_status($ticket, 'failed');
63
+ die('<script language="javascript">alert("'.( WFU_USVAR_exists_downloader('wfu_browser_downloadfile_notexist') ? WFU_USVAR_downloader('wfu_browser_downloadfile_notexist') : 'File does not exist!' ).'");</script>');
64
  }
 
65
 
66
+ $open_session = false;
67
  @set_time_limit(0); // disable the time limit for this script
68
  $fsize = filesize($filepath);
69
  if ( $fd = @fopen ($filepath, "rb") ) {
70
+ $open_session = ( ( $wfu_user_state_handler == "session" || $wfu_user_state_handler == "" ) && ( function_exists("session_status") ? ( PHP_SESSION_ACTIVE !== session_status() ) : ( empty(session_id()) ) ) );
71
+ if ( $open_session ) session_start();
72
  header('Content-Type: application/octet-stream');
73
  header("Content-Disposition: attachment; filename=\"".$disposition_name."\"");
74
  header('Content-Transfer-Encoding: binary');
92
  }
93
  else $failed = true;
94
 
95
+ if ( $delete_file ) unlink($filepath);
96
 
97
  if ( !$failed ) {
98
+ wfu_update_download_status($ticket, 'downloaded');
99
+ if ( $open_session ) session_write_close();
100
  die();
101
  }
102
  else {
103
+ wfu_update_download_status($ticket, 'failed');
104
+ if ( $open_session ) session_write_close();
105
+ die('<script type="text/javascript">alert("'.( WFU_USVAR_exists_downloader('wfu_browser_downloadfile_failed') ? WFU_USVAR_downloader('wfu_browser_downloadfile_failed') : 'Could not download file!' ).'");</script>');
106
  }
107
  }
108
 
109
+ function wfu_update_download_status($ticket, $new_status) {
110
+ require_once WFU_USVAR_downloader('wfu_ABSPATH').'wp-load.php';
111
+ WFU_USVAR_store('wfu_download_status_'.$ticket, $new_status);
112
+ }
113
+
114
+ function WFU_USVAR_exists_downloader($var) {
115
+ global $wfu_user_state_handler;
116
+ if ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "cookies" ) return isset($_COOKIE[$var]);
117
+ else return WFU_USVAR_exists_session($var);
118
+ }
119
+
120
+ function WFU_USVAR_downloader($var) {
121
+ global $wfu_user_state_handler;
122
+ if ( $wfu_user_state_handler == "dboption" && WFU_VAR("WFU_US_DBOPTION_BASE") == "cookies" ) return $_COOKIE[$var];
123
+ else return WFU_USVAR_session($var);
124
+ }
125
+
126
+ function WFU_USVAR_unset_downloader($var) {
127
+ global $wfu_user_state_handler;
128
+ if ( $wfu_user_state_handler == "session" || $wfu_user_state_handler == "" ) WFU_USVAR_unset_session($var);
129
+ }
130
+
131
  ?>
wfu_loader.php CHANGED
@@ -1,9 +1,21 @@
1
  <?php
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  if ( !defined("WPFILEUPLOAD_PLUGINFILE") ) return;
4
 
5
- if( !session_id() ) { session_start(); }
6
-
7
  //set global db variables
8
  //wfu_tb_log_version v2.0 changes:
9
  // sessionid field added
@@ -18,6 +30,7 @@ $wfu_tb_dbxqueue_version = "1.0";
18
 
19
  DEFINE("WPFILEUPLOAD_DIR", plugin_dir_url( WPFILEUPLOAD_PLUGINFILE ));
20
  DEFINE("ABSWPFILEUPLOAD_DIR", plugin_dir_path( WPFILEUPLOAD_PLUGINFILE ));
 
21
  add_shortcode("wordpress_file_upload", "wordpress_file_upload_handler");
22
  //activation-deactivation hooks
23
  register_activation_hook(WPFILEUPLOAD_PLUGINFILE,'wordpress_file_upload_install');
@@ -75,6 +88,17 @@ add_filter("wfu_before_upload", "wfu_consent_ask_server_handler", 10, 2);
75
  add_filter("_wfu_before_upload", "wfu_classic_before_upload_handler", 10, 2);
76
  wfu_include_lib();
77
 
 
 
 
 
 
 
 
 
 
 
 
78
  function wordpress_file_upload_initialize() {
79
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
80
  load_plugin_textdomain('wp-file-upload', false, dirname(plugin_basename (WPFILEUPLOAD_PLUGINFILE)).'/languages');
@@ -83,15 +107,31 @@ function wordpress_file_upload_initialize() {
83
  //plugin's routines
84
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
85
  $GLOBALS["wfu_user_state_handler"] = $plugin_options['userstatehandler'];
86
- //add abspath in session for use by downloader; exclude internal ajax requests
87
- if ( !isset($_POST["action"]) || ( $_POST["action"] != "wfu_ajax_action_wfu_call_async" && $_POST["action"] != "wfu_ajax_action_load_hook_code" ) )
88
- WFU_USVAR_store_session('wfu_ABSPATH', wfu_abspath());
89
  }
90
 
 
 
 
 
 
 
 
 
91
  function register_wfu_widget() {
92
  register_widget( 'WFU_Widget' );
93
  }
94
 
 
 
 
 
 
 
 
 
 
95
  function wfu_enqueue_frontpage_scripts() {
96
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
97
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
@@ -99,6 +139,29 @@ function wfu_enqueue_frontpage_scripts() {
99
  if ( isset($plugin_options['relaxcss']) ) $relaxcss = ( $plugin_options['relaxcss'] == '1' );
100
  //apply wfu_before_frontpage_scripts to get additional settings
101
  $changable_data = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  $ret_data = apply_filters('wfu_before_frontpage_scripts', $changable_data);
103
  //if $ret_data contains 'return_value' key then no scripts will be enqueued
104
  if ( isset($ret_data['return_value']) ) return $ret_data['return_value'];
@@ -128,6 +191,13 @@ function wfu_enqueue_frontpage_scripts() {
128
  }
129
  }
130
 
 
 
 
 
 
 
 
131
  function wfu_include_lib() {
132
  $dir = plugin_dir_path( WPFILEUPLOAD_PLUGINFILE )."lib/";
133
  if ( $handle = opendir($dir) ) {
@@ -146,9 +216,23 @@ function wfu_include_lib() {
146
  /* exit if we are in admin pages (in case of ajax call) */
147
  if ( is_admin() ) return;
148
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  function wordpress_file_upload_handler($incomingfrompost) {
150
  //replace old attribute definitions with new ones
151
  $incomingfrompost = wfu_old_to_new_attributes($incomingfrompost);
 
 
152
  //process incoming attributes assigning defaults if required
153
  $defs_indexed = wfu_shortcode_attribute_definitions_adjusted($incomingfrompost);
154
  $incomingfrompost = shortcode_atts($defs_indexed, $incomingfrompost);
@@ -158,6 +242,18 @@ function wordpress_file_upload_handler($incomingfrompost) {
158
  return $wordpress_file_upload_output;
159
  }
160
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  function wordpress_file_upload_browser_handler($incomingfrompost) {
162
  //process incoming attributes assigning defaults if required
163
  $defs = wfu_browser_attribute_definitions();
@@ -170,6 +266,24 @@ function wordpress_file_upload_browser_handler($incomingfrompost) {
170
  return $wordpress_file_upload_browser_output;
171
  }
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  function wordpress_file_upload_function($incomingfromhandler) {
174
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
175
  global $post;
@@ -242,6 +356,16 @@ function wordpress_file_upload_function($incomingfromhandler) {
242
  $uploadrole = trim($uploadrole);
243
  }
244
  $plugin_upload_user_role = wfu_get_user_role($user, $uploadroles);
 
 
 
 
 
 
 
 
 
 
245
  if ( $plugin_upload_user_role == 'nomatch' ) return apply_filters("_wfu_file_upload_hide_output", "");
246
 
247
  //activate debug mode only for admins
@@ -327,6 +451,17 @@ function wordpress_file_upload_function($incomingfromhandler) {
327
  /* set the template that will be used, default is empty (the original) */
328
  $params["uploadertemplate"] = "";
329
  // $params["uploadertemplate"] = "Custom1";
 
 
 
 
 
 
 
 
 
 
 
330
  $params["uploadertemplate"] = apply_filters("_wfu_uploader_template", $params["uploadertemplate"], $params);
331
  $uploadertemplate = wfu_get_uploader_template($params["uploadertemplate"]);
332
  /* Compose the html code for the plugin */
@@ -442,6 +577,17 @@ function wordpress_file_upload_function($incomingfromhandler) {
442
  if ( !WFU_USVAR_exists($check_refresh_sid) || WFU_USVAR($check_refresh_sid) != "form button pressed" ) {
443
  WFU_USVAR_store($check_refresh_sid, 'do not process');
444
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
 
 
 
 
 
 
 
 
 
 
 
445
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
446
  return $wordpress_file_upload_output."\n";
447
  }
@@ -458,6 +604,7 @@ function wordpress_file_upload_function($incomingfromhandler) {
458
 
459
  if ( $params['forceclassic'] != "true" ) {
460
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
 
461
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
462
  return $wordpress_file_upload_output."\n";
463
  }
@@ -539,20 +686,60 @@ function wordpress_file_upload_function($incomingfromhandler) {
539
  }
540
 
541
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
 
542
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
543
  return $wordpress_file_upload_output."\n";
544
  }
545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546
  function wfu_add_visual_editor_button($shortcode_tag, $params) {
547
  return wfu_template_to_HTML("visualeditorbutton", $params, array( "shortcode_tag" => $shortcode_tag ), 0);
548
  }
549
 
 
 
 
 
 
 
 
 
 
 
 
550
  function wfu_post_plugin_actions($params) {
 
551
  $echo_str = '';
552
 
553
  return $echo_str;
554
  }
555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  function wfu_get_subfolders_paths($params) {
557
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
558
  $subfolder_paths = array ( );
@@ -572,6 +759,18 @@ function wfu_get_subfolders_paths($params) {
572
  return $subfolder_paths;
573
  }
574
 
 
 
 
 
 
 
 
 
 
 
 
 
575
  function wfu_old_to_new_attributes($shortcode_attrs) {
576
  //old to new attribute definitions
577
  $old_to_new = array(
@@ -587,6 +786,44 @@ function wfu_old_to_new_attributes($shortcode_attrs) {
587
  return $shortcode_attrs;
588
  }
589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  function wfu_classic_before_upload_handler($ret, $attr) {
591
  //run only if start_time exists in $_REQUEST parameters
592
  if ( !isset($_REQUEST['start_time']) ) return $ret;
@@ -605,6 +842,22 @@ function wfu_classic_before_upload_handler($ret, $attr) {
605
  return $ret;
606
  }
607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
  function wfu_consent_ask_server_handler($changable_data, $attr) {
609
  //run only if consent_check and consent rejection message exist in
610
  //$_REQUEST parameters
@@ -617,6 +870,18 @@ function wfu_consent_ask_server_handler($changable_data, $attr) {
617
  return $changable_data;
618
  }
619
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  function wfu_execute_after_upload_filters($sid, $unique_id, $params) {
621
  //apply internal filters from extensions
622
  $ret = array( "echo" => "" );
@@ -624,10 +889,84 @@ function wfu_execute_after_upload_filters($sid, $unique_id, $params) {
624
  $filedata_id = "filedata_".$unique_id;
625
  if ( WFU_USVAR_exists($filedata_id) ) $files = WFU_USVAR($filedata_id);
626
  $attr = array( "sid" => $sid, "unique_id" => $unique_id, "files" => $files );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  $ret = apply_filters("_wfu_after_upload", $ret, $attr, $params);
628
  //then apply any custom filters created by admin
629
  $echo_str = "";
630
  $ret = array( "js_script" => "" );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
  $ret = apply_filters("wfu_after_upload", $ret, $attr);
632
  return $ret;
633
  }
1
  <?php
2
 
3
+ /**
4
+ * Initialize plugin
5
+ *
6
+ * This file initializes the plugin; defines constants, loads plugin's files,
7
+ * defines shortcodes and text domain, registers filters and actions and
8
+ * processes website requests.
9
+ *
10
+ * @link /wfu_loader.php
11
+ *
12
+ * @package WordPress File Upload Plugin
13
+ * @subpackage Core Components
14
+ * @since 4.9.1
15
+ */
16
+
17
  if ( !defined("WPFILEUPLOAD_PLUGINFILE") ) return;
18
 
 
 
19
  //set global db variables
20
  //wfu_tb_log_version v2.0 changes:
21
  // sessionid field added
30
 
31
  DEFINE("WPFILEUPLOAD_DIR", plugin_dir_url( WPFILEUPLOAD_PLUGINFILE ));
32
  DEFINE("ABSWPFILEUPLOAD_DIR", plugin_dir_path( WPFILEUPLOAD_PLUGINFILE ));
33
+ DEFINE("WPFILEUPLOAD_COOKIE", "wp_wpfileupload_".COOKIEHASH);
34
  add_shortcode("wordpress_file_upload", "wordpress_file_upload_handler");
35
  //activation-deactivation hooks
36
  register_activation_hook(WPFILEUPLOAD_PLUGINFILE,'wordpress_file_upload_install');
88
  add_filter("_wfu_before_upload", "wfu_classic_before_upload_handler", 10, 2);
89
  wfu_include_lib();
90
 
91
+ /**
92
+ * Initialize plugin.
93
+ *
94
+ * Runs after plugins are loaded in order to correctly load the plugin's text
95
+ * domain and then load all translatable strings. Then it loads the User State
96
+ * Handler (session or db). Then it executes all active plugin hooks.
97
+ *
98
+ * @since 4.7.0
99
+ *
100
+ * @redeclarable
101
+ */
102
  function wordpress_file_upload_initialize() {
103
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
104
  load_plugin_textdomain('wp-file-upload', false, dirname(plugin_basename (WPFILEUPLOAD_PLUGINFILE)).'/languages');
107
  //plugin's routines
108
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
109
  $GLOBALS["wfu_user_state_handler"] = $plugin_options['userstatehandler'];
110
+ wfu_initialize_user_state();
111
+
 
112
  }
113
 
114
+ /**
115
+ * Register Upload Form Widget.
116
+ *
117
+ * Runs on widget initialization to register the upload form widget of the
118
+ * plugin.
119
+ *
120
+ * @since 3.4.0
121
+ */
122
  function register_wfu_widget() {
123
  register_widget( 'WFU_Widget' );
124
  }
125
 
126
+ /**
127
+ * Enqueue frontpage styles and scripts.
128
+ *
129
+ * It enqueues all necessary frontpage styles and scripts of the plugin.
130
+ *
131
+ * @since 2.4.6
132
+ *
133
+ * @redeclarable
134
+ */
135
  function wfu_enqueue_frontpage_scripts() {
136
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
137
  $plugin_options = wfu_decode_plugin_options(get_option( "wordpress_file_upload_options" ));
139
  if ( isset($plugin_options['relaxcss']) ) $relaxcss = ( $plugin_options['relaxcss'] == '1' );
140
  //apply wfu_before_frontpage_scripts to get additional settings
141
  $changable_data = array();
142
+ /**
143
+ * Execute Custom Actions Before Loading Frontpage Scripts.
144
+ *
145
+ * This filter allows to execute custom actions before frontpage scripts are
146
+ * loaded. Loading of plugin's scripts can be completely customised.
147
+ *
148
+ * @since 3.5.0
149
+ *
150
+ * @param array $changable_data {
151
+ * Controls loading of frontpage scripts.
152
+ *
153
+ * @type mixed $return_value Optional. If it is set then no frontpage
154
+ * scripts will be loaded.
155
+ * @type string $correct_NextGenGallery_incompatibility Optional. If it
156
+ * is set to "true" then JQuery UI styles will not be loaded in
157
+ * order to avoid incompatibility with NextGEN Gallery plugin.
158
+ * @type string $correct_JQueryUI_incompatibility Optional. If it is set
159
+ * to "true" then JQuery UI styles will not be loaded (same as
160
+ * previous parameter).
161
+ * @type string $exclude_timepicker Optional. If it is set to "true"
162
+ * then jQuery timepicker styles and scripts will not be loaded.
163
+ * }
164
+ */
165
  $ret_data = apply_filters('wfu_before_frontpage_scripts', $changable_data);
166
  //if $ret_data contains 'return_value' key then no scripts will be enqueued
167
  if ( isset($ret_data['return_value']) ) return $ret_data['return_value'];
191
  }
192
  }
193
 
194
+ /**
195
+ * Load plugin libraries.
196
+ *
197
+ * It loads all plugin libraries located in /lib folder of the plugin.
198
+ *
199
+ * @since 2.1.2
200
+ */
201
  function wfu_include_lib() {
202
  $dir = plugin_dir_path( WPFILEUPLOAD_PLUGINFILE )."lib/";
203
  if ( $handle = opendir($dir) ) {
216
  /* exit if we are in admin pages (in case of ajax call) */
217
  if ( is_admin() ) return;
218
 
219
+ /**
220
+ * Render uploader form shortcode.
221
+ *
222
+ * It receives the attributes of an uploader form shortcode and returns the HTML
223
+ * code of the generated upload form.
224
+ *
225
+ * @since 2.1.2
226
+ *
227
+ * @param array $incomingfrompost An associative array of shortcode attributes
228
+ * (array keys) and their values (array values).
229
+ * @return string The HTML code of the generated upload form
230
+ */
231
  function wordpress_file_upload_handler($incomingfrompost) {
232
  //replace old attribute definitions with new ones
233
  $incomingfrompost = wfu_old_to_new_attributes($incomingfrompost);
234
+ //preprocess attributes
235
+ $incomingfrompost = wfu_preprocess_attributes($incomingfrompost);
236
  //process incoming attributes assigning defaults if required
237
  $defs_indexed = wfu_shortcode_attribute_definitions_adjusted($incomingfrompost);
238
  $incomingfrompost = shortcode_atts($defs_indexed, $incomingfrompost);
242
  return $wordpress_file_upload_output;
243
  }
244
 
245
+ /**
246
+ * Render front-end file viewer shortcode.
247
+ *
248
+ * It receives the attributes of a front-end file viewer shortcode and returns
249
+ * the HTML code of the generated file viewer.
250
+ *
251
+ * @since 3.1.0
252
+ *
253
+ * @param array $incomingfrompost An associative array of shortcode attributes
254
+ * (array keys) and their values (array values).
255
+ * @return string The HTML code of the generated file viewer
256
+ */
257
  function wordpress_file_upload_browser_handler($incomingfrompost) {
258
  //process incoming attributes assigning defaults if required
259
  $defs = wfu_browser_attribute_definitions();
266
  return $wordpress_file_upload_browser_output;
267
  }
268
 
269
+ /**
270
+ * Generate the HTML code of uploader form.
271
+ *
272
+ * It receives the processed attributes of an uploader form shortcode and
273
+ * returns the HTML code of the generated upload form.
274
+ *
275
+ * @since 2.1.2
276
+ *
277
+ * @redeclarable
278
+ *
279
+ * @global object $post The current post
280
+ * @global int $blog_id The ID of the current blog
281
+ *
282
+ * @param array $incomingfromhandler An associative array of shortcode
283
+ * attributes (array keys) and their values (array values).
284
+ *
285
+ * @return string The HTML code of the generated upload form
286
+ */
287
  function wordpress_file_upload_function($incomingfromhandler) {
288
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
289
  global $post;
356
  $uploadrole = trim($uploadrole);
357
  }
358
  $plugin_upload_user_role = wfu_get_user_role($user, $uploadroles);
359
+ /**
360
+ * Filter When the Upload Form Must Not be Shown.
361
+ *
362
+ * This filter is executed when the upload form must be shown on the page.
363
+ * It allows to return custom HTML output instead of empty content.
364
+ *
365
+ * @since 4.1.0
366
+ *
367
+ * @param string $ret The HTML output to return to the page. Default "".
368
+ */
369
  if ( $plugin_upload_user_role == 'nomatch' ) return apply_filters("_wfu_file_upload_hide_output", "");
370
 
371
  //activate debug mode only for admins
451
  /* set the template that will be used, default is empty (the original) */
452
  $params["uploadertemplate"] = "";
453
  // $params["uploadertemplate"] = "Custom1";
454
+ /**
455
+ * Filter To Define Custom Uploader Template.
456
+ *
457
+ * This filter is used to define a custom uploader template that will be
458
+ * used to generate the upload form.
459
+ *
460
+ * @since 4.0.0
461
+ *
462
+ * @param string $ret The uploader template to use. Default "".
463
+ * @param array $params An associative array with the shortcode attributes.
464
+ */
465
  $params["uploadertemplate"] = apply_filters("_wfu_uploader_template", $params["uploadertemplate"], $params);
466
  $uploadertemplate = wfu_get_uploader_template($params["uploadertemplate"]);
467
  /* Compose the html code for the plugin */
577
  if ( !WFU_USVAR_exists($check_refresh_sid) || WFU_USVAR($check_refresh_sid) != "form button pressed" ) {
578
  WFU_USVAR_store($check_refresh_sid, 'do not process');
579
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
580
+ /**
581
+ * Filter To Customise Uploader Output.
582
+ *
583
+ * This filter is used to customise the HTML code generated by the
584
+ * plugin for showing the upload form.
585
+ *
586
+ * @since 3.9.6
587
+ *
588
+ * @param string $wordpress_file_upload_output The HTML output.
589
+ * @param array $params An associative array with shortcode attributes.
590
+ */
591
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
592
  return $wordpress_file_upload_output."\n";
593
  }
604
 
605
  if ( $params['forceclassic'] != "true" ) {
606
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
607
+ /** This filter is documented above */
608
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
609
  return $wordpress_file_upload_output."\n";
610
  }
686
  }
687
 
688
  $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
689
+ /** This filter is documented above */
690
  $wordpress_file_upload_output = apply_filters("_wfu_file_upload_output", $wordpress_file_upload_output, $params);
691
  return $wordpress_file_upload_output."\n";
692
  }
693
 
694
+ /**
695
+ * Generate HTML code of Shortcode Visual Editor button.
696
+ *
697
+ * It generates the HTML code of the button that invokes the visual editor of
698
+ * the shortcode (shortcode composer).
699
+ *
700
+ * @since 3.1.0
701
+ *
702
+ * @param string $shortcode_tag The tag of the shortcode for which the button
703
+ * will be generated.
704
+ * @param array $params The shortcode attributes
705
+ * @return string The HTML code of the visual editor button
706
+ */
707
  function wfu_add_visual_editor_button($shortcode_tag, $params) {
708
  return wfu_template_to_HTML("visualeditorbutton", $params, array( "shortcode_tag" => $shortcode_tag ), 0);
709
  }
710
 
711
+ /**
712
+ * Additional content after upload form.
713
+ *
714
+ * It generates additional HTML code to be added after the upload form.
715
+ *
716
+ * @since 2.4.1
717
+ *
718
+ * @redeclarable
719
+ *
720
+ * @return string The additional HTML code
721
+ */
722
  function wfu_post_plugin_actions($params) {
723
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
724
  $echo_str = '';
725
 
726
  return $echo_str;
727
  }
728
 
729
+ /**
730
+ * Get the list of subfolders of the upload directory.
731
+ *
732
+ * It calculates the subfolders of the upload directory of an upload form in
733
+ * case that subfolders feature is activated in the shortcode and it is
734
+ * configured to calculate the subfolders automatically.
735
+ *
736
+ * @since 3.3.0
737
+ *
738
+ * @redeclarable
739
+ *
740
+ * @param array $params The shortcode attributes
741
+ * @return array The calculated subfolders
742
+ */
743
  function wfu_get_subfolders_paths($params) {
744
  $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
745
  $subfolder_paths = array ( );
759
  return $subfolder_paths;
760
  }
761
 
762
+ /**
763
+ * Convert old attribute names to new.
764
+ *
765
+ * Some shortcode attributes have changed name. This function makes sure that
766
+ * shortcode attributes with old names are converted to new names so that they
767
+ * can be processed correctly.
768
+ *
769
+ * @since 3.8.4
770
+ *
771
+ * @param array $shortcode_attrs The shortcode attributes
772
+ * @return array The processed shortcode attributes
773
+ */
774
  function wfu_old_to_new_attributes($shortcode_attrs) {
775
  //old to new attribute definitions
776
  $old_to_new = array(
786
  return $shortcode_attrs;
787
  }
788
 
789
+ /**
790
+ * Preprocess Attributes Before Handler.
791
+ *
792
+ * Preprocess attributes before they enter the handler. For instance, ftpinfo
793
+ * attribute is not parsed correctly and needs to be adjusted.
794
+ *
795
+ * @since 4.12.0
796
+ *
797
+ * @redeclarable
798
+ *
799
+ * @param array $shortcode_attrs The shortcode attributes
800
+ * @return array The processed shortcode attributes
801
+ */
802
+ function wfu_preprocess_attributes($shortcode_attrs) {
803
+ $a = func_get_args(); $a = WFU_FUNCTION_HOOK(__FUNCTION__, $a, $out); if (isset($out['vars'])) foreach($out['vars'] as $p => $v) $$p = $v; switch($a) { case 'R': return $out['output']; break; case 'D': die($out['output']); }
804
+ //correct ftpinfo backslashes
805
+ if ( isset($shortcode_attrs['ftpinfo']) )
806
+ $shortcode_attrs['ftpinfo'] = str_replace(array( '\\:', '\\@' ), array( '\\\\:', '\\\\@' ), $shortcode_attrs['ftpinfo']);
807
+ return $shortcode_attrs;
808
+ }
809
+
810
+ /**
811
+ * Execute custom actions before upload for non-AJAX uploads.
812
+ *
813
+ * This function is executed right after an upload has started for a classic
814
+ * (non-AJAX) upload. It ensures that when the page reloads the plugin will
815
+ * show the result of the upload (and will not render the upload form from the
816
+ * beginning).
817
+ *
818
+ * @since 3.7.0
819
+ *
820
+ * @see _wfu_before_upload filter For more information on parameters and
821
+ * response array format.
822
+ *
823
+ * @param array $ret An array with information how this function must respond.
824
+ * @param array $attr Information about the upload.
825
+ * @return array The processed $ret array
826
+ */
827
  function wfu_classic_before_upload_handler($ret, $attr) {
828
  //run only if start_time exists in $_REQUEST parameters
829
  if ( !isset($_REQUEST['start_time']) ) return $ret;
842
  return $ret;
843
  }
844
 
845
+ /**
846
+ * Check Consent Status of User.
847
+ *
848
+ * This function is executed before an upload starts in order to check the
849
+ * current user's consent status, when consent is activated in the shortcode.
850
+ *
851
+ * @since 4.10.1
852
+ *
853
+ * @see wfu_before_upload filter For more information on parameters and
854
+ * response array format.
855
+ *
856
+ * @param array $changable_data An array with information that can be changed
857
+ * by the function
858
+ * @param array $attr Information about the upload.
859
+ * @return array The processed $changable_data array
860
+ */
861
  function wfu_consent_ask_server_handler($changable_data, $attr) {
862
  //run only if consent_check and consent rejection message exist in
863
  //$_REQUEST parameters
870
  return $changable_data;
871
  }
872
 
873
+ /**
874
+ * Execute After Upload Filters.
875
+ *
876
+ * This function executes internal and custom after upload filters.
877
+ *
878
+ * @since 3.7.0
879
+ *
880
+ * @param int $sid The shortcode ID
881
+ * @param string $unique_id The unique identifier the upload.
882
+ * @param array $params The shortcode attributes.
883
+ * @return array An array holding data after the upload filters
884
+ */
885
  function wfu_execute_after_upload_filters($sid, $unique_id, $params) {
886
  //apply internal filters from extensions
887
  $ret = array( "echo" => "" );
889
  $filedata_id = "filedata_".$unique_id;
890
  if ( WFU_USVAR_exists($filedata_id) ) $files = WFU_USVAR($filedata_id);
891
  $attr = array( "sid" => $sid, "unique_id" => $unique_id, "files" => $files );
892
+ /**
893
+ * Execute Internal Post Upload Actions.
894
+ *
895
+ * This is an internal filter which allows to execute custom actions after
896
+ * an upload has completely finished.
897
+ *
898
+ * @since 3.7.0
899
+ *
900
+ * @param array $ret {
901
+ * Parameters to return to the plugin.
902
+ *
903
+ * @type string $echo Custom output to return (not used).
904
+ * }
905
+ * @param array $attr {
906
+ * Various attributes of the upload.
907
+ *
908
+ * @type string $sid The ID of the shortcode.
909
+ * @type string $unique_id The unique ID of the upload.
910
+ * @type array $files {
911
+ * Contains an array of the uploaded files.
912
+ *
913
+ * @type array $file {
914
+ * Contains information for each uploaded file.
915
+ *
916
+ * @type string $file_unique_id A unique ID identifying every
917
+ * individual file.
918
+ * @type string $original_filename The original filename of the
919
+ * file before any filters might have changed it.
920
+ * @type string $filepath The final path of the file, including
921
+ * the filename.
922
+ * @type int $filesize The size of the file.
923
+ * @type array|null $user_data {
924
+ * An array of user data values if userdata are activated.
925
+ *
926
+ * @type array $item {
927
+ * Contains information about each user data field.
928
+ *
929
+ * @type string $label The label of the user data field.
930
+ * @type string $value The value of the user data field.
931
+ * }
932
+ * }
933
+ * @type string $upload_result The result of the upload process.
934
+ * It can take the following values:
935
+ * success: the upload was successful.
936
+ * warning: the upload was successful but it contains
937
+ * warning messages.
938
+ * error: the upload failed
939
+ * @type string $error_message Warning or error messages
940
+ * generated during the upload process.
941
+ * @type string $admin_messages Detailed error messages for
942
+ * administrators generated during the upload process.
943
+ * }
944
+ * }
945
+ * }
946
+ * @param array $params The shortcode attributes of the upload form.
947
+ */
948
  $ret = apply_filters("_wfu_after_upload", $ret, $attr, $params);
949
  //then apply any custom filters created by admin
950
  $echo_str = "";
951
  $ret = array( "js_script" => "" );
952
+ /**
953
+ * Execute Post Upload Actions.
954
+ *
955
+ * This filter allows to execute custom actions after an upload has
956
+ * completely finished. Custom Javascript code can be defined that will be
957
+ * executed on user's browser after the filter finishes.
958
+ *
959
+ * @since 3.7.0
960
+ *
961
+ * @param array $ret {
962
+ * Parameters to return to the plugin.
963
+ *
964
+ * @type string $js_script Custom Javascript code to execute on user's
965
+ * browser.
966
+ * }
967
+ * @param array $attr Various attributes of the upload. See previous hook
968
+ * for details.
969
+ */
970
  $ret = apply_filters("wfu_after_upload", $ret, $attr);
971
  return $ret;
972
  }
wordpress_file_upload.php CHANGED
@@ -3,7 +3,7 @@
3
  /*
4
  Plugin URI: http://www.iptanus.com/support/wordpress-file-upload
5
  Description: Simple interface to upload files from a page.
6
- Version: 4.11.2
7
  Author: Nickolas Bossinas
8
  Author URI: http://www.iptanus.com
9
  Text Domain: wp-file-upload
@@ -27,6 +27,14 @@ You should have received a copy of the GNU General Public License
27
  along with this program. If not, see <http://www.gnu.org/licenses/>.
28
  */
29
 
 
 
 
 
 
 
 
 
30
  function wfu_get_request_uri() {
31
  $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
32
  list( $pathinfo ) = explode( '?', $pathinfo );
@@ -44,6 +52,15 @@ function wfu_get_request_uri() {
44
  return $req_uri;
45
  }
46
 
 
 
 
 
 
 
 
 
 
47
  function wordpress_file_upload_preload_check() {
48
  //do not load plugin if this is the login page
49
  $uri = wfu_get_request_uri();
3
  /*
4
  Plugin URI: http://www.iptanus.com/support/wordpress-file-upload
5
  Description: Simple interface to upload files from a page.
6
+ Version: 4.12.0
7
  Author: Nickolas Bossinas
8
  Author URI: http://www.iptanus.com
9
  Text Domain: wp-file-upload
27
  along with this program. If not, see <http://www.gnu.org/licenses/>.
28
  */
29
 
30
+ /**
31
+ * Extract the Request URI.
32
+ *
33
+ * In some web servers the request URL is not mentioned correctly and it must be
34
+ * calculated in combination with other $_SERVER variables.
35
+ *
36
+ * @return string the correct request URI
37
+ */
38
  function wfu_get_request_uri() {
39
  $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
40
  list( $pathinfo ) = explode( '?', $pathinfo );
52
  return $req_uri;
53
  }
54
 
55
+ /**
56
+ * Checks before plugin loading.
57
+ *
58
+ * This function performs checks in order to decide if the plugin will be loaded
59
+ * or not. It enables to load the plugin only for specific pages defined by the
60
+ * admin.
61
+ *
62
+ * @return bool true if the plugin must be loaded, false if not.
63
+ */
64
  function wordpress_file_upload_preload_check() {
65
  //do not load plugin if this is the login page
66
  $uri = wfu_get_request_uri();