Dynamic Web Twain - PHP - Adding Additional HTML Fields - php

I've got a Laravel project but I think I have an idea of how to incorporate the Dynamic Web Twain (https://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx) into it.
The only problem is I'm not quite sure how I would go about adding additional fields to the scanner UI (like what you see here: https://demo.dynamsoft.com/dwt/online_demo_scan.aspx).
At the moment my Laravel site has a working upload portion to a model where I can submit attachments, however, with the attachment form are fields that include "visibility", "type", "upload location" etc. etc. But I can't seem to figure out how I would add fields like what I already use.
From what I've tested, this is an incredibly useful tool and would work well if I could integrate it into all aspects of my site.
The closest thing I can find is here: https://developer.dynamsoft.com/dwt/api-reference/uploading-downloading/sethttpformfield
Which references what is done in this demo: https://demo.dynamsoft.com/Samples/dwt/Scan-Documents-and-Upload-Them/DWT_Scan_Upload_Demo.html
As you can see, you can add a field name and field value, using the "+" button, but I want to add some fields in the form that are available immediately. The other issue that I might need to work around is if I use this demo and add a value and name, this is how everything is posted and I'm not sure how to translate to something my project can understand.
-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"
Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream
ÿØÿà
This aspect is a necessary part of my project, so unfortunately there's no real way around this besides moving forward.
This is the current script in the online demo:
Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used
var DWObject, blankField = "", extrFieldsCount = 0, upload_returnSth = true;
var CurrentPathName = unescape(location.pathname);
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
var strHTTPServer = location.hostname;
var strActionPage;
var scriptLanguages = [
{ desc: "PHP", val: "php" },
{ desc: "PHP-MySQL", val: "phpMySQL" },
{ desc: "CSharp", val: "csharp" },
{ desc: "CSharp-MSSQL", val: "csMSSQL" },
{ desc: "VB.NET", val: "vbnet" },
{ desc: "VBNET-MSSQL", val: "vbnetMSSQL" },
{ desc: "JSP", val: "jsp" },
{ desc: "JSP-Oracle", val: "jspOracle" },
{ desc: "ASP", val: "asp" },
{ desc: "ASP-MSSQL", val: "aspMSSQL" },
{ desc: "ColdFusion", val: "cfm" },
{ desc: "CS-Azure", val: "csAzure" }
];
function languageSelected() {
if (document.getElementById("ddlLanguages").selectedIndex > 7)
upload_returnSth = false;
else
upload_returnSth = true;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) == -1) {
document.getElementById("extra-fields-div-id").style.display = 'none';
document.getElementById('div-extra-fields').style.display = 'none';
}
else {
document.getElementById("extra-fields-div-id").style.display = '';
if (document.getElementById('div-extra-fields').children.length > 1 ||
document.getElementById('div-extra-fields').children[0].children[0].value != '') {
document.getElementById('div-extra-fields').style.display = '';
}
}
}
function addAField() {
extrFieldsCount++;
if (extrFieldsCount == 3) {
document.getElementById('div-extra-fields').style.overflowY = 'scroll';
}
if (document.getElementById('div-extra-fields').style.display == "none")
document.getElementById('div-extra-fields').style.display = '';
else {
document.getElementById('div-extra-fields').appendChild(blankField);
blankField = document.getElementsByClassName('div-fields-item')[extrFieldsCount - 1].cloneNode(true);
}
}
function downloadPDFR() {
DCP_DWT_OnClickCloseInstall();
DWObject.Addon.PDF.Download(
CurrentPath + '/Resources/addon/Pdf.zip',
function () {/*console.log('PDF dll is installed');*/
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
function Dynamsoft_OnReady() {
blankField = document.getElementsByClassName('div-fields-item')[0].cloneNode(true);
DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
DWObject.Width = 505;
DWObject.Height = 600;
for (var i = 0; i < scriptLanguages.length; i++)
document.getElementById("ddlLanguages").options.add(new Option(scriptLanguages[i].desc, i));
document.getElementById("ddlLanguages").options.selectedIndex = 2;
/*
* Make sure the PDF Rasterizer and OCR add-on are already installedsample
*/
if (!Dynamsoft.Lib.env.bMac) {
var localPDFRVersion = '';
if(Dynamsoft.Lib.product.bChromeEdition){
localPDFRVersion = DWObject._innerFun('GetAddOnVersion', '["pdf"]');
}
else {
localPDFRVersion = DWObject.getSWebTwain().GetAddonVersion("pdf");
}
if (localPDFRVersion != Dynamsoft.PdfVersion) {
var ObjString = [];
ObjString.push('<div class="p15" id="pdfr-install-dlg">');
ObjString.push('The <strong>PDF Rasterizer</strong> is not installed on this PC<br />Please click the button below to get it installed');
ObjString.push('<p class="tc mt15 mb15"><input type="button" value="Install PDF Rasterizer" onclick="downloadPDFR();" class="btn lgBtn bgBlue" /><hr></p>');
ObjString.push('<i><strong>The installation is a one-time process</strong> <br />It might take some time depending on your network.</i>');
ObjString.push('</div>');
Dynamsoft.WebTwainEnv.ShowDialog(400, 310, ObjString.join(''));
}
else {
/**/
}
}
}
}
function AcquireImage() {
if (DWObject) {
var bSelected = DWObject.SelectSource();
if (bSelected) {
var OnAcquireImageSuccess, OnAcquireImageFailure;
OnAcquireImageSuccess = OnAcquireImageFailure = function () {
DWObject.CloseSource();
};
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; //Scanner source will be disabled/closed automatically after the scan.
DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
}
}
}
function LoadImages() {
if (DWObject) {
DWObject.Addon.PDF.SetResolution(300);
DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL);
DWObject.LoadImageEx('', 5,
function () {
},
function (errorCode, errorString) {
alert('Load Image:' + errorString);
}
);
}
}
function OnHttpUploadSuccess() {
console.log('successful');
}
function OnHttpServerReturnedSomething(errorCode, errorString, sHttpResponse) {
//console.log(errorString);
var textFromServer = sHttpResponse;
_printUploadedFiles(textFromServer);
}
function _printUploadedFiles(info) {
//console.log(info);
if (info.indexOf('DWTUploadFileName') != -1) {
var url, _strPort;
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
_strPort = location.port == "" ? 80 : location.port
url = 'http://' + location.hostname + ':' + location.port
if (Dynamsoft.Lib.detect.ssl == true) {
_strPort = location.port == "" ? 443 : location.port;
url = 'https://' + location.hostname + ':' + location.port
}
var savedIntoToDB = false, imgIndexInDB = "-1";
if (info.indexOf("DWTUploadFileIndex:") != -1) {
savedIntoToDB = true;
imgIndexInDB = info.substring(info.indexOf('DWTUploadFileIndex') + 19, info.indexOf('DWTUploadFileName'));
//console.log(imgIndexInDB);
}
var fileName = info.substring(info.indexOf('DWTUploadFileName') + 18, info.indexOf('UploadedFileSize'));
var fileSize = info.substr(info.indexOf('UploadedFileSize') + 17);
if (savedIntoToDB) {
if (info.indexOf('CSHARP') != -1) {
url += CurrentPath + 'action/csharp-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('VBNET') != -1) {
url += CurrentPath + 'action/vbnet-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('PHP') != -1) {
url += CurrentPath + 'action/php-mysql.php?imgID=' + imgIndexInDB;
}
else if (info.indexOf('JSP') != -1) {
url += CurrentPath + 'action/jsp-oracle.jsp?imgID=' + imgIndexInDB;
}
}
else {
url += CurrentPath + 'action/UploadedImages/' + encodeURI(fileName);
}
var newTR = document.createElement('tr');
_str = "<td class='tc'><a class='bluelink'" + ' href="' + url + '" target="_blank">' + fileName + "</a></td>"
+ "<td class='tc'>" + fileSize + '</td>';
if (info.indexOf("FieldsTrue:") != -1)
_str += "<td class='tc'><a class='bluelink'" + '" href="' + url.substring(0, url.length - 4) + '_1.txt' + '" target="_blank">Fields</td>';
else {
_str += "<td class='tc'>No Fields</td>";
}
newTR.innerHTML = _str;
document.getElementById('div-uploadedFile').appendChild(newTR);
}
}
function upload_preparation(_name) {
DWObject.IfShowCancelDialogWhenImageTransfer = !document.getElementById('quietScan').checked;
strActionPage = CurrentPath + 'action/';
switch (document.getElementById("ddlLanguages").options.selectedIndex) {
case 0: strActionPage += "php.php"; break;
case 2: strActionPage += "csharp.aspx"; break;
case 6: strActionPage += "jsp.jsp"; break;
case 4: strActionPage += "vbnet.aspx"; break;
case 8: strActionPage += "asp.asp"; break;
case 10: strActionPage += "cfm.cfm"; break;
case 1: strActionPage += "php-mysql.php?imgID=new"; break;
case 7: strActionPage += "jsp-oracle.jsp?imgID=new"; break;
case 3: strActionPage += "csharp-db.aspx?imgID=new"; break;
case 5: strActionPage += "vbnet-db.aspx?imgID=new"; break;
case 9: strActionPage += "asp-db.asp"; break;
case 11: preparetoUploadtoAzure(_name); break;
default: break;
}
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
var _strPort = location.port == "" ? 80 : location.port;
if (Dynamsoft.Lib.detect.ssl == true)
_strPort = location.port == "" ? 443 : location.port;
DWObject.HTTPPort = _strPort;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) != -1) {
/* Add Fields to the Post */
var fields = document.getElementsByClassName('div-fields-item');
DWObject.ClearAllHTTPFormField();
for (var n = 0; n < fields.length; n++) {
var o = fields[n];
if (o.children[0].value != '')
DWObject.SetHTTPFormField(o.children[0].value, o.children[1].value);
}
}
}
function UploadImage_inner() {
if (DWObject.HowManyImagesInBuffer == 0)
return;
var Digital = new Date();
var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name
upload_preparation(uploadfilename);
// Upload the image(s) to the server asynchronously
if (document.getElementById("ddlLanguages").options.selectedIndex == 11 /*Azure*/) return;
if (document.getElementsByName('ImageType')[0].checked) {
var uploadIndexes = [];
for (var i = DWObject.HowManyImagesInBuffer - 1; i > -1 ; i--) {
uploadIndexes.push(i);
}
var uploadJPGsOneByOne = function (errorCode, errorString, sHttpResponse) {
if (upload_returnSth)
_printUploadedFiles(sHttpResponse);
if (uploadIndexes.length > 0) {
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
}
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[1].checked) {
DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF(strHTTPServer, strActionPage, uploadfilename + ".tif", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[2].checked) {
DWObject.HTTPUploadAllThroughPostAsPDF(strHTTPServer, strActionPage, uploadfilename + ".pdf", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
}
function UploadImage() {
if (DWObject) {
var nCount = 0, nCountUpLoaded = 0, aryFilePaths = [];
if (document.getElementById('uploadDirectly').checked) {
DWObject.IfShowCancelDialogWhenImageTransfer = false;
function ds_load_file_to_upload_directly(bSave, filesCount, index, path, filename) {
nCount = filesCount;
var filePath = path + "\\" + filename;
aryFilePaths.push(filePath);
if (aryFilePaths.length == nCount) {
upload_preparation();
var i = 0;
function uploadFileOneByOne() {
DWObject.HTTPUploadThroughPostDirectly(strHTTPServer, filePath, strActionPage, filename,
function () {
console.log('Upload Image:' + aryFilePaths[i] + ' -- successful');
i++;
if (i != nCount)
uploadFileOneByOne();
else
DWObject.UnregisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
},
OnHttpServerReturnedSomething
);
}
uploadFileOneByOne();
}
}
DWObject.RegisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
DWObject.ShowFileDialog(false, "Any File | *.*", 0, "", "", true, true, 0);
}
else {
UploadImage_inner();
}
}
}
/*******************/
/* Upload to Azure */
var Base64Binary = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
decode: function (input, arrayBuffer) {
//get last chars to see if are valid
var lkey1 = this._keyStr.indexOf(input.charAt(input.length - 1));
var lkey2 = this._keyStr.indexOf(input.charAt(input.length - 2));
var bytes = (input.length / 4) * 3;
if (lkey1 == 64) bytes--; //padding chars, so skip
if (lkey2 == 64) bytes--; //padding chars, so skip
var uarray;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var j = 0;
if (arrayBuffer)
uarray = new Uint8Array(arrayBuffer);
else
uarray = new Uint8Array(bytes);
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < bytes; i += 3) {
//get the 3 octects in 4 ascii chars
enc1 = this._keyStr.indexOf(input.charAt(j++));
enc2 = this._keyStr.indexOf(input.charAt(j++));
enc3 = this._keyStr.indexOf(input.charAt(j++));
enc4 = this._keyStr.indexOf(input.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 != 64) uarray[i + 1] = chr2;
if (enc4 != 64) uarray[i + 2] = chr3;
}
return uarray;
}
}
function uploadImageInner_azure(blobSasUrl, fileDataAsArrayBuffer) {
var ajaxRequest = new XMLHttpRequest();
try {
ajaxRequest.open('PUT', blobSasUrl, true);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(fileDataAsArrayBuffer);
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
console.log('Upload image to azure server successfully.');
}
}
}
catch (e) {
console.log("can't upload the image to server.\n" + e.toString());
}
}
function preparetoUploadtoAzure(__name) {
var uploadfilename = '';
//For JPEG, upload the current image
if (document.getElementsByName('ImageType')[0].checked) {
DWObject.SelectedImagesCount = 1;
DWObject.SetSelectedImageIndex(0, DWObject.CurrentImageIndexInBuffer);
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_JPG);
uploadfilename = __name + '.jpg';
}
else { //For TIFF, PDF, upload all images
var count = DWObject.HowManyImagesInBuffer;
DWObject.SelectedImagesCount = count;
for (var i = 0; i < count; i++) {
DWObject.SetSelectedImageIndex(i, i);
}
if (document.getElementsByName('ImageType')[1].checked) {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_TIF);
uploadfilename = __name + '.tif';
}
else {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_PDF);
uploadfilename = __name + '.pdf';
}
}
var strImg, aryImg, _uint8_STR, _bin_ARR, _blobImg;
strImg = DWObject.SaveSelectedImagesToBase64Binary();
// convert base64 to Uint8Array
var bytes = (strImg.length / 4) * 3;
var _temp = new ArrayBuffer(bytes);
_uint8_STR = Base64Binary.decode(strImg, _temp);
// convert Uint8Array to blob
_blobImg = new Blob([_uint8_STR]);
// upload to Azure server
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
uploadImageInner_azure(xhr.responseText, _blobImg);
}
}
var actionPageFullPath = CurrentPath + 'action/' + 'azure.aspx?imageName=' + uploadfilename;
xhr.open('GET', actionPageFullPath, true);
xhr.send();
}
/*******************/

Related

Max File Size in roxy fileman

Is there any way to set the max file limit.
I already searched google and found this code (this code isnt working):
function addFile() {
clickFirstOnEnter('dlgAddFile');
var dialogButtons = {};
dialogButtons[t('Upload')] = function () {
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
if (!$('#fileUploads').val())
alert(t('E_SelectFiles'));
else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t('E_ActionDisabled'));
//$('#dlgAddFile').dialog('close');
}
else {
var files = $('#fileUploads')[0].files;
for (var i = 0; i < files.length; i++) {
//alert(files[i].name);
totalsize += files[i].size;
if ((files[i].size / 1024) > maxfilesize) {
fileoversize = files[i].name + '\n';
}
}
if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
}
else if (fileoversize != "") {
alert("Max total upload : "+ maxfilesize +"KB. Oversized files:\n" + fileoversize);
}
else {
document.forms['addfile'].action = RoxyFilemanConf.UPLOAD;
document.forms['addfile'].submit();
}
}
}
};
dialogButtons[t('Cancel')] = function () { $('#dlgAddFile').dialog('close'); };
$('#dlgAddFile').dialog({ title: t('T_AddFile'), modal: true, buttons: dialogButtons });
}
Adding 2 variables to conf.json
MAXTOTAL and MAXFILESIZE.
but this doesnt work at all..
Anyone who got any suggestions/solution for this problem?
As OP has already discovered, this is a configuration setting. For people searching for a solution in .Net, two changes are required in the web.config for IIS 7.0+. Check the link for more complete details.
I added the elements to my root web.config.
<system.web>
<!-- Max int value of 2gb -->
<httpRuntime maxRequestLength="2097151" appRequestQueueLimit="100000" requestLengthDiskThreshold="2097151" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength, for IIS, in bytes -->
<requestLimits maxAllowedContentLength="104857600" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
Sause:
How to increase the max upload file size in ASP.NET?
I've also updated the code to work as intended with version 1.4.5. Make sure you apply this to the main.js/main.min.js files.
function addFile() {
clickFirstOnEnter("dlgAddFile");
$("#uploadResult").html("");
clearFileField();
var a = {};
a[t("Upload")] = {
id: "btnUpload",
text: t("Upload"),
disabled: true,
click: function () {
if (!$("#fileUploads").val() && (!uploadFileList || uploadFileList.length == 0)) {
alert(t("E_SelectFiles"))
} else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t("E_ActionDisabled"))
} else {
// start of change
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
for (var i = 0; i < uploadFileList.length; i++) {
totalsize += uploadFileList[i].size;
if ((uploadFileList[i].size / 1024) > maxfilesize) {
fileoversize = fileoversize + uploadFileList[i].name + '\n';
}
}
if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
} else if (fileoversize != "") {
alert("Max total upload : " + maxfilesize + "KB. Oversized files:\n" + fileoversize);
} else // end of change
if (window.FormData && window.XMLHttpRequest && window.FileList && uploadFileList && uploadFileList.length > 0)
{
for (i = 0; i < uploadFileList.length; i++) {
fileUpload(uploadFileList[i], i)
}
} else {
document.forms.addfile.action = RoxyFilemanConf.UPLOAD;
document.forms.addfile.submit()
}
}
}
}
};
a[t("Cancel")] = function () {
$("#dlgAddFile").dialog("close")
};
$("#dlgAddFile").dialog({
title: t("T_AddFile"),
modal: true,
buttons: a,
width: 400
})
}
(Posted on behalf of the OP).
This is fixed. I found out that the max file is going through the php.ini.
upload_max_filesize=4M

Running multiple functions javascript

I currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}

Redirect to homepage from splash page magento

I am trying to redirect to my homepage from a splash (age verification) page, and it just keeps popping up the same age verification page.
I have the ageVerify.php script in the root folder and I have the other script at the top of my template file page. I just need to find the correct file structure format to redirect too after someone hits "yes i'm 18"
The code below doesn't work when added to the top of my column1.phtml file - it just keeps going back and recalling the verify.php script. Any ideas would be very helpful!
<?php
function verified()
{
$redirect_url='http://www.johnsoncreeksmokejuice.com.vhost.zerolag.com/verify.php';
$expires=-1;
session_start();
$validated=false;
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
if ($validated) {
return;
}
else {
$redirect_url=$redirect_url."?return=index.php&x=".$expires;
Header('Location: '.$redirect_url);
exit(0);
}
}
verified();
?>
If $_SESSION is not set always will evaluate this
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
Just fix it and should work.
Assuming that everything else is fine, I would replace
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
By:
if ( (isset($_COOKIE["verified"] && !empty($_COOKIE["verified"])) OR isset($_SESSION['verified']) ) {
$validated=true;
}
So, if user has a non-empty "verified" cookie or a "verified" session set, it assumes he is validated.
Chose to use a javascript alternative. Worked out much easier for me:
function writeCookie(key,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
}
function readCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function ageGate() {
var monthDays = {
1: 31,
2: 29,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
var months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
};
var monthOptions = [];
var dayOptions = {};
var yearOptions = [];
for (var month in monthDays) {
var days = monthDays[month];
monthOptions.push('<option value="' + month + '">' + months[month] + '</option>');
dayOptions[month] = [];
for (var i=1; i <= days; i++) {
var day = i;
dayOptions[month].push('<option value="' + day + '">' + day + '</option>');
}
}
var currentYear = new Date();
currentYear = currentYear.getFullYear();
var startYear = currentYear - 120;
for (var y=currentYear; y > startYear; y--) {
yearOptions.push('<option value="' + y + '">' + y + '</option>');
}
$s(document).ready(function(){
var monthHtml = '';
for (var j=0; j < monthOptions.length; j++) {
var html = monthOptions[j];
monthHtml += html;
}
$s('#ageMonth').html(monthHtml);
var yearHtml = '';
for (var i=0; i < yearOptions.length; i++) {
yearHtml += yearOptions[i];
}
$s('#ageYear').html(yearHtml);
$s('#ageMonth').bind('change', function(){
var dayHtml = '';
var month = $s(this).val();
for (var i=0; i < dayOptions[month].length; i++) {
dayHtml += dayOptions[month][i];
}
$s('#ageDay').html(dayHtml);
});
$s('#ageEnterSite').click(function(e){
e.preventDefault();
var date = new Date();
date.setMonth($s('#ageMonth').val() - 1);
date.setDate($s('#ageDay').val());
date.setYear($s('#ageYear').val());
var maxDate = new Date();
// alert(maxDate.getFullYear());
maxDate.setYear(maxDate.getFullYear() - 18);
if (date <= maxDate) {
writeCookie('jcsj_age_verified', '1', 30);
$s('#age-gate').fadeOut(function(){
$s(this).remove();
$s('body').removeClass('age-gate-visible');
});
}
else {
window.location.href = 'http://google.com';
}
});
$s('#ageMonth').change(); // load default month
// $s('#ageDay').prop('disabled', true);
setTimeout(function(){
$s('body').addClass('age-gate-visible');
$s('#age-gate').fadeIn();
}, 200);
});
}
if (readCookie('jcsj_age_verified')) {
} else {
ageGate();
}
</script>

Turning on BBCODES - Javascript

I'm using this chat http://tutorialzine.com/2010/10/ajax-web-chat-php-mysql/ and I tried to turn on the bbcodes but: http://imageshack.us/photo/my-images/827/bbcodes1.png/
I tried to replace in
scripts.js
text : text.replace(/</g,'<').replace(/>/g,'>')
with
text : text.replace(/</g,'<').
replace(/>/g,'>').
replace(/\[b\]((\s|.)+?)\[\/b\]/,'<b>\\1</b>')
This is my bbcode function, you can edit the codes variable to support more bbcode. For now, it support only [b], [i], [u], [url], [img].
[read] is my special bbcode for my website
function bbcode(text){
var codes = {};
codes['url'] = {
params : {
href : ''
},
html: "$text"
};
codes['b'] = {
params : {
},
html : "<b>$text</b>"
};
codes['i'] = {
params : {
},
html : "<i>$text</i>"
};
codes['u'] = {
params : {
},
html : "<u>$text</u>"
};
codes['img'] = {
params : {
},
html : "<img src=\"$text\" />"
};
codes['read'] = {
params : {
},
text : function(text){
for(var x in codes){
text = text.replace(new RegExp('\\[' + x + '\\]','gi'), '').replace(new RegExp('\\[\\/' + x + '\\]','gi'), '');
}
return encodeURIComponent(text);
},
process: function(text){
return text;
},
html : "$text <object type=\"application/x-shockwave-flash\" data=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" width=\"200\" height=\"20\"><param name=\"movie\" value=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"mp3=http://api.ispeech.org/api/rest?apikey%3Ddeveloperdemokeydeveloperdemokey%26action%3Dconvert%26voice%3Dusenglishfemale1%26text%3D$TEXT&width=200&showslider=1\" /></object>"
};
text = text.replace(/\</g, '<').replace(/\>/g, '>');
var nomore = false;
while(!nomore){
var matches = text.match(/\[([^\]]+)\]/gi);
if(matches == null)
return text;
nomore = true;
for(var i = 0; i < matches.length; i++){
var code = matches[i].substring(1, matches[i].length - 1);
var parts = code.split(/\s+/);
if(typeof codes[parts[0]] == 'object'){
//is exist
var obj = {};
//get the params
for(var j = 1; j < parts.length; j++)
{
var temp = parts[j].split('=');
if(typeof codes[parts[0]].params[temp[0]] != 'undefined'){
obj[temp[0]] = (temp.length > 1) ? (temp[1].indexOf('"') == 0 ? temp[1].substring(1, temp[1].length - 1) : temp[1]) : '';
}
}
//find the text
var index = text.indexOf(matches[i]);
var index2 = text.indexOf('[/'+parts[0]+']', index);
if(index2 == -1)
index2 = text.length;
var t = text.substring(index + matches[i].length, index2);
if(typeof codes[parts[0]].process == 'function'){
t = codes[parts[0]].process(t);
}if(typeof codes[parts[0]].text == 'function'){
t2 = codes[parts[0]].text(t);
}
var html = codes[parts[0]].html;
for(var x in obj)
html = html.replace("$" + x, obj[x]);
html = html.replace(/\$text/g, t);
if(typeof codes[parts[0]].text == 'function'){
html = html.replace(/\$TEXT/g, t2);
}
text = text.substr(0, index) + html + text.substr(index2 + parts[0].length + 3);
nomore = false;
}
}
}
text = text.replace(/\n/g, "<br />");
return text;
}
You can use this by:
text: bbcode(text)

Actionscript Serialization Class

I have an actionscript class that serializes and unserializes data compatible with php's serialization functions. I expanded it to support binary data but now the unserialization does not seem to work.
For example, this data is not unserialized correctly:
a:2:{i:0;s:1:"õ";i:1;a:2:{i:0;s:32:"mÎiyl·T=doÁ°ýNd_¤ÁÝ`:AåÁˆ#";i:1;s:32:"ÿ^ò`d^|“T¶&JÐÞG[±iÏ*Ÿ!–Ü’IÍ";}}
Here is the class:
package pack
{
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.*;
use namespace mx_internal;
public class Serializer extends Object
{
public static const version:String = "3.0.0";
mx_internal static var c:uint;
mx_internal static var pattern:RegExp = /[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} \+|\-\d{4}/g
public static function serialize(data:*):ByteArray
{
var bas:ByteArray = new ByteArray();
var tmp:ByteArray = new ByteArray();
var i:int = 0;
var key:String;
if(data is Boolean){
bas.writeUTFBytes('b:');
bas.writeUnsignedInt(data);
bas.writeUTFBytes(';');
} else if(data is int){
bas.writeUTFBytes('i:');
bas.writeUTFBytes(data);
bas.writeUTFBytes(';');
} else if(data is Number){
bas.writeUTFBytes('d:');
bas.writeUTFBytes(data);
bas.writeUTFBytes(';');
} else if(data is ByteArray){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.length.toString());
bas.writeUTFBytes(':"');
bas.writeBytes(data);
bas.writeUTFBytes('";');
} else if(data is String){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.length.toString());
bas.writeUTFBytes(':"');
bas.writeUTFBytes(data);
bas.writeUTFBytes('";');
} else if(data is Date){
bas.writeUTFBytes('s:');
bas.writeUTFBytes(data.toString().length.toString());
bas.writeUTFBytes(':"');
bas.writeUTFBytes(data);
bas.writeUTFBytes('";');
} else if(data is ArrayCollection){
for(key in data){
tmp.writeBytes(Serializer.serialize(i));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('a:');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data is Array){
for(key in data){
tmp.writeBytes(Serializer.serialize(i));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('a:');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data is Object){
for(key in data){
tmp.writeBytes(Serializer.serialize(key));
tmp.writeBytes(Serializer.serialize(data[key]));
i += 1;
}
bas.writeUTFBytes('O:8:"stdClass":');
bas.writeUTFBytes(i.toString());
bas.writeUTFBytes(':{');
bas.writeBytes(tmp);
bas.writeUTFBytes('}');
} else if(data == null || data == undefined){
bas.writeUTFBytes('N;');
} else {
bas.writeUTFBytes('i:0;');
}
return bas;
}
public static function unserialize(data:ByteArray):*
{
Serializer.c = 0;
return Serializer.unserialize_internal(data);
}
mx_internal static function unserialize_internal(data:ByteArray):*
{
var result:*;
var tmpvar:*;
var tmp:Array = new Array();
var type:String = Serializer.charAt(data, Serializer.c);
var pos:uint = 0;
var islist:Boolean = true;
var i:uint;
switch(type){
case "N":
Serializer.c += 2;
break;
case "b":
result = Serializer.substr(data, Serializer.c+2, 1).toString() == '1'
//result = data.substr(Serializer.c+2, 1) == "1"
Serializer.c += 4
break;
case "i":
tmp.push(Serializer.indexOf(data, ';', Serializer.c));
//tmp.push(data.indexOf(";", Serializer.c))
pos = Serializer.c+2
Serializer.c = tmp[0]+1
result = int(Serializer.substring(data, pos, tmp[0]));
//result = int(data.substring(pos,tmp[0]))
break;
case "d":
tmp.push(Serializer.indexOf(data, ';', Serializer.c));
//tmp.push(data.indexOf(";", Serializer.c))
pos = Serializer.c + 2
Serializer.c = tmp[0]+1
result = Number(Serializer.substring(data, pos, tmp[0]));
//result = Number(data.substring(pos,tmp[0]))
break;
case "s":
tmp.push(int(Serializer.indexOf(data, ':', Serializer.c+2)));
//tmp.push(int(data.indexOf(":", Serializer.c+2)))
tmp.push(tmp[0]+2)
pos = Serializer.c+2
tmp.push(0)
tmp.push(int(Serializer.substring(data, pos, tmp[0])));
//tmp.push(int(data.substring(pos, tmp[0])));
if(tmp[3] == 0)
{
result = "";
Serializer.c = pos+5
} else {
var lenc:uint = Serializer.stringBCLenght(data, Serializer.c, tmp[3]);
if(lenc != tmp[3])
{
result = Serializer.substr(data, tmp[0]+2, lenc);
//result = data.substr(tmp[0]+2, lenc);
Serializer.c = tmp[0]+4+lenc;
} else {
result = Serializer.substr(data, tmp[0]+2, tmp[3]);
//result = data.substr(tmp[0]+2, tmp[3]);
Serializer.c = tmp[0]+4+tmp[3];
}
}
if(Serializer.pattern.test(result))
{
result = new Date(result)
}
break;
case "a":
//result:ByteArray;
pos = Serializer.c+2
tmp.push(int(Serializer.indexOf(data, ":", pos)))
tmp.push(int(Serializer.substring(data, pos, tmp[0])))
//tmp.push(int(data.indexOf(":", pos)))
//tmp.push(int(data.substring(pos, tmp[0])))
Serializer.c = tmp[0]+2
result = []
for(i = 0; i < tmp[1]; i++){
tmpvar = Serializer.unserialize_internal(data)
result[tmpvar] = Serializer.unserialize_internal(data)
if(!(tmpvar is int) || tmpvar < 0){
islist = false
}
}
if(islist){
tmp.push([])
for(var key:uint = 0; key < result.length; key++){
pos = tmp[2].length
while(key > pos){
tmp[2].push(null)
pos +=1
}
tmp[2].push(result[key])
}
result = tmp[2]
}
Serializer.c += 1
break;
case "O":
pos = Serializer.indexOf(data, "\"", Serializer.c)+1;
Serializer.c = Serializer.indexOf(data, "\"", pos);
tmp.push(Serializer.substring(data, pos, Serializer.c))
//pos = data.indexOf("\"", Serializer.c)+1;
//Serializer.c = data.indexOf("\"", pos);
//tmp.push(data.substring(pos, Serializer.c))
Serializer.c += 2
i = Serializer.c
Serializer.c = Serializer.indexOf(data, ":", i)
i = int(Serializer.substring(data, i, Serializer.c))
//Serializer.c = data.indexOf(":", i)
//i = int(data.substring(i, Serializer.c))
Serializer.c +=2;
result = {};
var tmps:*;
while(i > 0){
tmps = Serializer.unserialize_internal(data)
result[tmps] = Serializer.unserialize_internal(data)
i -= 1
}
break;
}
return result;
}
mx_internal static function stringCLenght(data:String, from:uint = 0, len:uint = 0):int
{
var i:uint;
var j:uint = len;
var startIndex:uint = from + 4 + len.toString().length;
for (i = 0; i < j; i++){
if (data.charCodeAt(i+startIndex) > 128)
{
j = j - 1
}
}
return j;
}
mx_internal static function stringBCLenght(data:ByteArray, from:uint = 0, len:uint = 0):int
{
var i:uint;
var j:uint = len;
var startIndex:uint = from + 4 + len.toString().length;
for (i = 0; i < j; i++){
if (Serializer.charCodeAt(data, i+startIndex) > 128)
{
j = j - 1
}
}
return j;
}
mx_internal static function stringLength(data:String):uint
{
var code:int = 0
var result:int = 0
var slen:int = data.length;
while(slen){
slen = slen - 1
try
{
code = data.charCodeAt(slen)
} catch(e:Error){
code = 65536
}
if(code < 128){
result = result + 1
} else if(code < 2048){
result = result + 2
} else if(code < 65536){
result = result + 3
} else {
result = result + 4
}
}
return result
}
public static function charAt(bytes:ByteArray, index:int):String {
if (bytes.length <= index) return null;
return String.fromCharCode(bytes[index]);
}
public static function charCodeAt(bytes:ByteArray, index:int):int {
if (bytes.length <= index) return -1;
return bytes[index];
}
public static function substr(bytes:ByteArray, start:int, length:int=0):ByteArray {
var res:ByteArray = new ByteArray();
bytes.position = start;
bytes.readBytes(res, 0, length);
return res;
}
public static function substring(bytes:ByteArray, start:int, end:int=0):ByteArray {
return substr(bytes, start, end-start);
}
public static function indexOf(bytes:ByteArray, str:String, startIndex:int):int {
var num:int = 0;
for (var i:int=0; i<bytes.length; i++) {
var strPos:int = 0;
while (bytes[i+strPos] == str.charCodeAt(strPos)) {
strPos++;
if (strPos == str.length) {
num++;
if(num == startIndex) {
return i;
}
}
}
}
return -1;
}
}
}
I resolved the issue, no need for answers.

Categories