first commit

This commit is contained in:
2025-02-24 22:33:42 +01:00
commit 737c037e85
18358 changed files with 5392983 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
/*function updateWhitelistInputValue() {
//var val = [];
document.getElementsByName('whitelist')[0].value = JSON.stringify(window.whitelist);
}
function setPassword(i) {
var password = window.prompt('Enter password' + i);
window.whitelist[i]['password_hashed'] = '';
window.whitelist[i]['new_password'] = password;
setWhitelistHTML();
}
*/
function setAuthorizedSitesHTML() {
var s = '';
if (window.authorizedSites && window.authorizedSites.length > 0) {
s+='<table class="authorized_sites_list" >';
s+='<tr>';
s+='<th>Site<span id="whitelist_site_helptext2"></span></th>'
//s+='<th>Salt<span id="salt_helptext2"></span></th>'
//s+='<th>Limit<span id="whitelist_quota_helptext2"></span></th>'
s+='</tr>';
s=='</th></tr>';
for (var i=0; i<window.authorizedSites.length; i++) {
s+='<tr><td>';
s+=window.authorizedSites[i]['id']
s+='</td></tr>';
}
} else {
s+='<i>No sites have been authorized to use this server yet.</i>';
}
s+='</table>';
s+='<button type="button" class="button button-secondary" id="server_listen_btn" onclick="whitelistAdd()">Connect website</button>';
/*
s+='<tr><td colspan="3" class="whitelist-add-site">';
s+='<button type="button" class="button button-secondary" id="whitelist_add" onclick="whitelistAdd()">+ Add site</button>';
s+='</td></tr>';
s+='</table>';*/
document.getElementById('authorized_sites_div').innerHTML = s;
}
/*
function whitelistAdd() {
window.whitelist.push({
site: '',
password_hashed: '',
new_password: '',
//quota: 60
});
setWhitelistHTML();
}
function whitelistRemoveRow(i) {
window.whitelist.splice(i, 1);
setWhitelistHTML();
}
*/
document.addEventListener('DOMContentLoaded', function() {
setAuthorizedSitesHTML();
});

View File

@@ -0,0 +1,378 @@
function openBulkConvertPopup() {
document.getElementById('bulkconvertlog').innerHTML = '';
document.getElementById('bulkconvertcontent').innerHTML = '<div>Receiving list of files to convert...</div>';
tb_show('Bulk Convert', '#TB_inline?inlineId=bulkconvertpopup');
var data = {
'action': 'list_unconverted_files',
'nonce' : window.webpExpress['ajax-nonces']['list-unconverted-files'],
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
dataType: 'text',
timeout: 30000,
error: function (jqXHR, status, errorThrown) {
html = '<h1>Error: ' + status + '</h1>';
html += errorThrown;
document.getElementById('bulkconvertcontent').innerHTML = html;
},
success: function(response) {
if ((typeof response == 'object') && (response['success'] == false)) {
html = '<h1>Error</h1>';
if (response['data'] && ((typeof response['data']) == 'string')) {
html += webpexpress_escapeHTML(response['data']);
}
document.getElementById('bulkconvertcontent').innerHTML = html;
return;
}
if (response == '') {
html = '<h1>Error</h1>';
html += '<p>Could not fetch list of files to convert. The server returned nothing (which is unexpected - ' +
'it is not simply because there are no files to convert.)</p>';
document.getElementById('bulkconvertcontent').innerHTML = html;
return;
}
var responseObj;
try {
responseObj = JSON.parse(response);
} catch (e) {
html = '<h1>Error</h1>';
html += '<p>The ajax call did not return valid JSON, as expected.</p>';
html += '<p>Check the javascript console to see what was returned.</p>';
console.log('The ajax call did not return valid JSON, as expected');
console.log('Here is what was received:');
console.log(response);
document.getElementById('bulkconvertcontent').innerHTML = html;
return;
}
var bulkInfo = {
'groups': responseObj,
'groupPointer': 0,
'filePointer': 0,
'paused': false,
'webpTotalFilesize': 0,
'orgTotalFilesize': 0,
};
window.webpexpress_bulkconvert = bulkInfo;
// count files
var numFiles = 0;
for (var i=0; i<bulkInfo.groups.length; i++) {
numFiles += bulkInfo.groups[i].files.length;
}
//console.log(JSON.parse(response));
var html = '';
if (numFiles == 0) {
html += '<p>There are no unconverted files</p>';
} else {
html += '<div>'
html += '<p>There are ' + numFiles + ' unconverted files.</p>';
html += '<p><i>Note that in a typical setup, you will have redirect rules which trigger conversion when needed, ' +
'and thus you have no need for bulk conversion. In fact, in that case, you should probably not bulk convert ' +
'because bulk conversion will also convert images and thumbnails which are not in use, and thus take up ' +
'more disk space than necessary. The bulk conversion feature was only added in order to make the plugin usable even when ' +
'there are problems with redirects (ie on Nginx in case you do not have access to the config or on Microsoft IIS). ' +
'</i></p><br>';
html += '<button onclick="startBulkConversion()" class="button button-primary" type="button">Start conversion</button>';
html += '</div>';
}
document.getElementById('bulkconvertcontent').innerHTML = html;
}
});
}
function pauseBulkConversion() {
var bulkInfo = window.webpexpress_bulkconvert;
bulkInfo.paused = true;
}
function pauseOrResumeBulkConversion() {
var bulkInfo = window.webpexpress_bulkconvert;
bulkInfo.paused = !bulkInfo.paused;
document.getElementById('bulkPauseResumeBtn').innerText = (bulkInfo.paused ? 'Resume' : 'Pause');
if (!bulkInfo.paused) {
convertNextInBulkQueue();
}
}
function startBulkConversion() {
var html = '<br>';
html += '<style>' +
'.has-tip {cursor:pointer; position:static;}\n' +
'.has-tip .tip {display: none}\n' +
'.has-tip:hover .tip {display: block}\n' +
'.tip{padding: 5px 10px; background-color:#ff9;min-width:310px; font-size:10px; color: black; border:1px solid black; max-width:90%;z-index:10}\n' +
'.reduction {float:right;}\n' +
'</style>';
html += '<button id="bulkPauseResumeBtn" onclick="pauseOrResumeBulkConversion()" class="button button-primary" type="button">Pause</button>';
//html += '<div id="conversionlog" class="das-popup">test</div>';
//html += '<div id="bulkconvertlog"></div>';
document.getElementById('bulkconvertcontent').innerHTML = html;
document.getElementById('bulkconvertlog').innerHTML = '';
convertNextInBulkQueue();
}
function convertDone() {
var bulkInfo = window.webpexpress_bulkconvert;
document.getElementById('bulkconvertlog').innerHTML += '<p><b>Done!</b></p>' +
'<p>Total reduction: ' + getReductionHtml(bulkInfo['orgTotalFilesize'], bulkInfo['webpTotalFilesize'], 'Total size of converted originals', 'Total size of converted webp files') + '</p>'
document.getElementById('bulkPauseResumeBtn').style.display = 'none';
}
function getPrintableSizeInfo(orgSize, webpSize) {
if (orgSize < 10000) {
return {
'org': orgSize + ' bytes',
'webp': webpSize + ' bytes'
};
} else {
return {
'org': Math.round(orgSize / 1024) + ' kb',
'webp': Math.round(webpSize / 1024) + ' kb'
};
}
}
function getReductionHtml(orgSize, webpSize, sizeOfOriginalText, sizeOfWebpText) {
var reduction = Math.round((orgSize - webpSize)/orgSize * 100);
var sizeInfo = getPrintableSizeInfo(orgSize, webpSize);
var hoverText = sizeOfOriginalText + ': ' + sizeInfo['org'] + '.<br>' + sizeOfWebpText + ': ' + sizeInfo['webp'];
// ps: this is all safe to print
return '<span class="has-tip reduction">' + reduction + '%' +
'<span class="tip">' + hoverText + '</span>' +
'</span><br>';
}
function logLn() {
var html = '';
for (i = 0; i < arguments.length; i++) {
html += arguments[i];
}
var spanEl = document.createElement('span');
spanEl.innerHTML = html;
document.getElementById('bulkconvertlog').appendChild(spanEl);
//document.getElementById('bulkconvertlog').innerHTML += html;
}
function webpexpress_viewLog(groupPointer, filePointer) {
/*
disabled until I am certain that security is in place.
var bulkInfo = window.webpexpress_bulkconvert;
var group = bulkInfo.groups[groupPointer];
var filename = group.files[filePointer];
var source = group.root + '/' + filename;
var w = Math.min(1200, Math.max(200, document.documentElement.clientWidth - 100));
var h = Math.max(250, document.documentElement.clientHeight - 80);
document.getElementById('conversionlog_content').innerHTML = 'loading log...'; // + source;
jQuery.ajax({
method: 'POST',
url: ajaxurl,
data: {
'action': 'webpexpress_view_log',
'nonce' : window.webpExpress['ajax-nonces']['view-log'],
'source': source
},
success: (response) => {
//alert(response);
if ((typeof response == 'object') && (response['success'] == false)) {
html = '<h1>Error</h1>';
if (response['data'] && ((typeof response['data']) == 'string')) {
html += webpexpress_escapeHTML(response['data']);
}
document.getElementById('conversionlog_content').innerHTML = html;
return;
}
var result = JSON.parse(response);
// the "log" result is a simply form of markdown, using just italic, bold and newlines.
// It ought not to return anything evil, but for good practice, let us encode.
result = webpexpress_escapeHTML(result);
var html = '<h1>Conversion log</h1><br>' + '<pre style="white-space:pre-wrap">' + result + '</pre>';
document.getElementById('conversionlog_content').innerHTML = html;
},
error: () => {
//responseCallback({requestError: true});
},
});
//<h1>Conversion log</h1>
//tb_show('Conversion log', '#TB_inline?inlineId=conversionlog');
openDasPopup('conversionlog', w, h);
*/
}
function convertNextInBulkQueue() {
var html;
var bulkInfo = window.webpexpress_bulkconvert;
//console.log('convertNextInBulkQueue', bulkInfo);
// Current group might contain 0, - skip if that is the case
while ((bulkInfo.groupPointer < bulkInfo.groups.length) && (bulkInfo.filePointer >= bulkInfo.groups[bulkInfo.groupPointer].files.length)) {
logLn(
'<h3>' + bulkInfo.groups[bulkInfo.groupPointer].groupName + '</h3>',
'<p>Nothing to convert</p>'
);
bulkInfo.groupPointer++;
bulkInfo.filePointer = 0;
}
if (bulkInfo.groupPointer >= bulkInfo.groups.length) {
convertDone();
return;
}
var group = bulkInfo.groups[bulkInfo.groupPointer];
var filename = group.files[bulkInfo.filePointer];
if (bulkInfo.filePointer == 0) {
logLn('<h3>' + group.groupName + '</h3>');
}
logLn('Converting <i>' + filename + '</i>');
var data = {
'action': 'convert_file',
'nonce' : window.webpExpress['ajax-nonces']['convert'],
'filename': group.root + '/' + filename
//'whatever': ajax_object.we_value // We pass php values differently!
};
function responseCallback(response){
if ((typeof response == 'object') && (response['success'] == false)) {
html = '<h1>Error</h1>';
if (response['data'] && ((typeof response['data']) == 'string')) {
// disabled. Need to check if it is secure
//html += webpexpress_escapeHTML(response['data']);
}
logLn(html);
return
}
var result = typeof response.requestError !== 'boolean' ? JSON.parse(response) : {
success: false,
msg: '',
log: '',
};
var bulkInfo = window.webpexpress_bulkconvert;
var group = bulkInfo.groups[bulkInfo.groupPointer];
var filename = group.files[bulkInfo.filePointer];
var result = JSON.parse(response); // TODO: An parse error has been experienced (perhaps when token expired?)
//console.log(result);
var html = '';
var htmlViewLog = '';
// uncommented until I'm certain that security is in place
//var htmlViewLog = '&nbsp;&nbsp;<a style="cursor:pointer" onclick="webpexpress_viewLog(' + bulkInfo.groupPointer + ',' + bulkInfo.filePointer + ')">view log</a>';
if (result['success']) {
//console.log('nonce tick:' + result['nonce-tick']);
if (result['new-convert-nonce']) {
//console.log('new convert nonce:' + result['new-convert-nonce']);
window.webpExpress['ajax-nonces']['convert'] = result['new-convert-nonce'];
}
var orgSize = result['filesize-original'];
var webpSize = result['filesize-webp'];
var orgSizePrint, webpSizePrint;
bulkInfo['orgTotalFilesize'] += orgSize;
bulkInfo['webpTotalFilesize'] += webpSize;
//'- Saved at: ' + result['destination-path'] +
/*
html += ' <span style="color:green">ok</span></span>' +
htmlViewLog +
getReductionHtml(orgSize, webpSize, 'Size of original', 'Size of webp')*/
html += ' <span style="color:green" class="has-tip">ok' +
'<span class="tip">' +
'<b>Destination:</b><br>' + result['destination-path'] + '<br><br>' +
'<b>Url:</b><br><a href="' + result['destination-url'] + '">' + result['destination-url'] + '<br>' +
'</span>' +
'</span>' +
getReductionHtml(orgSize, webpSize, 'Size of original', 'Size of webp')
} else {
html += ' <span style="color:red">failed</span>' + htmlViewLog;
if (result['msg']) {
logLn(html);
logLn('<br><br><span style="color:red; font-size:15px">' + webpexpress_escapeHTML(result['msg']) + '</span>');
}
if (result['stop']) {
return;
}
/*
if (result['msg'] != '') {
html += ' <span style="">' + result['msg'] + '</span>';
}
*/
html += '<br>';
/*if (result['log'] != '') {
html += ' <span style="font-size:10px">' + result['log'] + '</span>';
}*/
}
logLn(html);
// Get next
bulkInfo.filePointer++;
if (bulkInfo.filePointer == group.files.length) {
bulkInfo.filePointer = 0;
bulkInfo.groupPointer++;
}
if (bulkInfo.groupPointer == bulkInfo.groups.length) {
convertDone();
} else {
if (bulkInfo.paused) {
document.getElementById('bulkconvertlog').innerHTML += '<p><i>on pause</i><br>' +
'Reduction this far: ' + getReductionHtml(bulkInfo['orgTotalFilesize'], bulkInfo['webpTotalFilesize'], 'Total size of originals this far', 'Total size of webp files this far') + '</p>'
bulkInfo['orgTotalFilesize'] += orgSize;
bulkInfo['webpTotalFilesize'] += webpSize;
} else {
convertNextInBulkQueue();
}
}
}
// jQuery.post(ajaxurl, data, responseCallback);
jQuery.ajax({
method: 'POST',
url: ajaxurl,
data: data,
success: (response) => {
responseCallback(response);
},
error: () => {
responseCallback({requestError: true});
},
});
}

View File

@@ -0,0 +1,557 @@
// Map of converters (are updated with updateConvertersMap)
window.convertersMap = {};
window.currentlyEditing = '';
function getConversionMethodDescription(converterId) {
var descriptions = {
'cwebp': 'cwebp',
'wpc': 'Remote WebP Express',
'ewww': 'ewww cloud converter',
'gd': 'Gd extension',
'imagick': 'Imagick (PHP extension)',
'gmagick': 'Gmagick (PHP extension)',
'imagemagick': 'ImageMagick',
'graphicsmagick': 'GraphicsMagick',
'vips': 'Vips',
'ffmpeg': 'ffmpeg',
};
if (descriptions[converterId]) {
return descriptions[converterId];
}
return converterId;
}
function generateConverterHTML(converter) {
html = '<li data-id="' + converter['id'] + '" class="' + (converter.deactivated ? 'deactivated' : '') + ' ' + (converter.working ? 'operational' : 'not-operational') + ' ' + (converter.warnings ? 'has-warnings' : '') + '">';
//html += '<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="17px" height="17px" viewBox="0 0 100.000000 100.000000" preserveAspectRatio="xMidYMid meet"><g transform="translate(0.000000,100.000000) scale(0.100000,-0.100000)" fill="#444444" stroke="none"><path d="M415 920 l-80 -80 165 0 165 0 -80 80 c-44 44 -82 80 -85 80 -3 0 -41 -36 -85 -80z"/><path d="M0 695 l0 -45 500 0 500 0 0 45 0 45 -500 0 -500 0 0 -45z"/><path d="M0 500 l0 -40 500 0 500 0 0 40 0 40 -500 0 -500 0 0 -40z"/><path d="M0 305 l0 -45 500 0 500 0 0 45 0 45 -500 0 -500 0 0 -45z"/><path d="M418 78 l82 -83 82 83 83 82 -165 0 -165 0 83 -82z"/></g></svg>';
// html += '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/></svg>';
// html += '<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 100.000000 100.000000" preserveAspectRatio="xMidYMid meet"><g transform="translate(0.000000,100.000000) scale(0.100000,-0.100000)" fill="#888888" stroke="none"><path d="M415 920 l-80 -80 165 0 165 0 -80 80 c-44 44 -82 80 -85 80 -3 0 -41 -36 -85 -80z"/><path d="M0 695 l0 -45 500 0 500 0 0 45 0 45 -500 0 -500 0 0 -45z"/><path d="M0 500 l0 -40 500 0 500 0 0 40 0 40 -500 0 -500 0 0 -40z"/><path d="M0 305 l0 -45 500 0 500 0 0 45 0 45 -500 0 -500 0 0 -45z"/><path d="M418 78 l82 -83 82 83 83 82 -165 0 -165 0 83 -82z"/></g></svg>';
html += '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M2 13.5h14V12H2v1.5zm0-4h14V8H2v1.5zM2 4v1.5h14V4H2z"/></svg>';
html += '<div class="text">';
html += getConversionMethodDescription(converter['id']);
html += '</div>';
html += '<a class="configure-converter btn" onclick="configureConverter(\'' + converter['id'] + '\')">configure</a>';
html += '<a class="test-converter btn" onclick="testConverter(\'' + converter['id'] + '\')">test</a>';
if (converter.deactivated) {
html += '<a class="activate-converter btn" onclick=activateConverter(\'' + converter['id'] + '\')>activate</a>';
}
else {
html += '<a class="deactivate-converter btn" onclick=deactivateConverter(\'' + converter['id'] + '\')>deactivate</a>';
}
html += '<div class="status">';
if (converter['error']) {
html += '<svg id="status_not_ok" width="19" height="19" title="not operational" version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500.000000 500.000000" preserveAspectRatio="xMidYMid meet">';
html += '<g fill="currentcolor" stroke="none" transform="translate(0.000000,500.000000) scale(0.100000,-0.100000)"><path d="M2315 4800 c-479 -35 -928 -217 -1303 -527 -352 -293 -615 -702 -738 -1151 -104 -380 -104 -824 0 -1204 107 -389 302 -724 591 -1013 354 -354 785 -572 1279 -646 196 -30 476 -30 672 0 494 74 925 292 1279 646 354 354 571 784 646 1279 30 197 30 475 0 672 -75 495 -292 925 -646 1279 -289 289 -624 484 -1013 591 -228 62 -528 91 -767 74z m353 -511 c458 -50 874 -272 1170 -624 417 -497 536 -1174 308 -1763 -56 -145 -176 -367 -235 -434 -4 -4 -566 552 -1250 1236 l-1243 1243 94 60 c354 229 754 327 1156 282z m864 -3200 c-67 -59 -289 -179 -434 -235 -946 -366 -2024 172 -2322 1158 -47 155 -66 276 -73 453 -13 362 84 704 290 1023 l60 94 1243 -1243 c684 -684 1240 -1246 1236 -1250z"/></g></svg>';
html += '<div class="popup">';
html += webpexpress_escapeHTML(converter['error']);
html += '</div>';
} else if (converter['warnings']) {
/*html += '<svg id="status_warning" width="19" height="19" version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 478.125 478.125">';
html += '<g fill="currentcolor"">';
html += '<circle cx="239.904" cy="314.721" r="35.878"/>';
html += '<path d="M256.657,127.525h-31.9c-10.557,0-19.125,8.645-19.125,19.125v101.975c0,10.48,8.645,19.125,19.125,19.125h31.9c10.48,0,19.125-8.645,19.125-19.125V146.65C275.782,136.17,267.138,127.525,256.657,127.525z"/>';
html += '<path d="M239.062,0C106.947,0,0,106.947,0,239.062s106.947,239.062,239.062,239.062c132.115,0,239.062-106.947,239.062-239.062S371.178,0,239.062,0z M239.292,409.734c-94.171,0-170.595-76.348-170.595-170.596c0-94.248,76.347-170.595,170.595-170.595s170.595,76.347,170.595,170.595C409.887,333.387,333.464,409.734,239.292,409.734z"/>';
html += '</g></svg>';*/
html += '<svg id="status_warning" width="19" height="19" version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 123.996 123.996">';
html += '<circle cx="62" cy="67" r="35" color="black"/>';
html += '<g fill="currentcolor">';
html += '<path d="M9.821,118.048h104.4c7.3,0,12-7.7,8.7-14.2l-52.2-92.5c-3.601-7.199-13.9-7.199-17.5,0l-52.2,92.5C-2.179,110.348,2.521,118.048,9.821,118.048z M70.222,96.548c0,4.8-3.5,8.5-8.5,8.5s-8.5-3.7-8.5-8.5v-0.2c0-4.8,3.5-8.5,8.5-8.5s8.5,3.7,8.5,8.5V96.548z M57.121,34.048h9.801c2.699,0,4.3,2.3,4,5.2l-4.301,37.6c-0.3,2.7-2.1,4.4-4.6,4.4s-4.3-1.7-4.6-4.4l-4.301-37.6C52.821,36.348,54.422,34.048,57.121,34.048z"/>';
html += '</g></svg>';
html += '<div class="popup">';
if (converter['warnings'].join) {
if (converter['warnings'].filter) {
// remove duplicate warnings
converter['warnings'] = converter['warnings'].filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
}
html += '<p>Warnings were issued:</p>';
for (var i = 0; i<converter['warnings'].length; i++) {
html += '<p>' + webpexpress_escapeHTML(converter['warnings'][i]) + '</p>';
}
// TODO: Tell him to deactivate the converter - or perhaps do it automatically?
html += '<p>check conversion log for more insight (ie by clicking the "test" link a little left of this warning triangle)</p>';
}
html += '</div>';
} else if (converter.working) {
html += '<svg id="status_ok" width="19" height="19" version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256.000000 256.000000" preserveAspectRatio="xMidYMid meet">';
html += '<g fill="currentcolor" stroke="none" transform="translate(0.000000,256.000000) scale(0.100000,-0.100000)"><path d="M1064 2545 c-406 -72 -744 -324 -927 -690 -96 -193 -127 -333 -127 -575 0 -243 33 -387 133 -585 177 -351 518 -606 907 -676 118 -22 393 -17 511 8 110 24 252 78 356 136 327 183 569 525 628 887 19 122 19 338 0 460 -81 498 -483 914 -990 1025 -101 22 -389 28 -491 10z m814 -745 c39 -27 73 -59 77 -70 9 -27 10 -25 -372 -590 -345 -510 -357 -524 -420 -512 -19 4 -98 74 -250 225 -123 121 -225 228 -228 238 -3 10 1 31 9 47 20 40 125 132 149 132 11 0 79 -59 162 -140 79 -77 146 -140 149 -140 3 0 38 48 78 108 95 143 465 678 496 720 35 46 64 42 150 -18z"/></g></svg>';
//html += '<div class="popup">' + converter['id'] + ' is operational</div>';
html += '<div class="popup">Operational</div>';
}
html += '</div>';
html += '</li>';
return html;
}
/* Set ids on global converters object */
function setTemporaryIdsOnConverters() {
if (window.converters == undefined) {
console.log('window.converters is undefined. Strange. Please report!');
return;
}
var numConverterInstances = [];
for (var i=0; i<window.converters.length; i++) {
var converter = converters[i]['converter'];
if (numConverterInstances[converter]) {
numConverterInstances[converter]++;
window.converters[i]['id'] = converter + '-' + numConverterInstances[converter];
}
else {
numConverterInstances[converter] = 1;
window.converters[i]['id'] = converter;
}
}
//alert(JSON.stringify(window.converters));
updateConvertersMap();
}
function updateConvertersMap() {
var map = {};
for (var i=0; i<window.converters.length; i++) {
var converter = window.converters[i];
map[converter['id']] = converter;
}
window.convertersMap = map;
}
function reorderConverters(order) {
// Create new converter array
var result = [];
for (var i=0; i<order.length; i++) {
result.push(window.convertersMap[order[i]]);
}
//alert(JSON.stringify(result));
window.converters = result;
updateInputValue();
}
/* Update the hidden input containing all the data */
function updateInputValue() {
document.getElementsByName('converters')[0].value = JSON.stringify(window.converters);
}
function setConvertersHTML() {
var html = '';
setTemporaryIdsOnConverters();
if (document.getElementById('converters') == null) {
alert('document.getElementById("converters") returns null. Strange! Please report.');
return;
}
for (var i=0; i<window.converters.length; i++) {
var converter = converters[i];
html += generateConverterHTML(converter);
}
var el = document.getElementById('converters');
el.innerHTML = html;
var sortable = Sortable.create(el, {
onChoose: function() {
document.getElementById('converters').className = 'dragging';
},
onUnchoose: function() {
document.getElementById('converters').className = '';
},
store: {
get: function() {
var order = [];
for (var i=0; i<window.converters.length; i++) {
order.push(window.converters[i]['id']);
}
return order;
},
set: function(sortable) {
var order = sortable.toArray();
reorderConverters(order);
}
}
});
updateInputValue();
}
document.addEventListener('DOMContentLoaded', function() {
setConvertersHTML();
});
function wpe_addCloudConverter(converter) {
}
function isConverterOptionSet(converter, optionName) {
if ((converter['options'] == undefined) || (converter['options'][optionName] == undefined)) {
return false;
}
return true;
}
function getConverterOption(converter, optionName, defaultValue) {
if ((converter['options'] == undefined) || (converter['options'][optionName] == undefined)) {
return defaultValue;
}
return converter['options'][optionName];
}
function setConverterOption(converter, optionName, value) {
if (converter['options'] == undefined) {
converter['options'] = {};
}
converter['options'][optionName] = value;
}
function deleteConverterOption(converter, optionName) {
if (converter['options'] == undefined) {
converter['options'] = {};
}
delete converter['options'][optionName];
}
function configureConverter(id) {
var converter = window.convertersMap[id];
window.currentlyEditing = id;
/*
Removed (#243)
var q = getConverterOption(converter, 'quality', 'auto');
if (document.getElementById(id + '_quality')) {
document.getElementById(id + '_quality').value = q;
document.getElementById(id + '_max_quality_div').style['display'] = (q == 'auto' ? 'block' : 'none');
document.getElementById(id + '_max_quality').value = getConverterOption(converter, 'max-quality', 85);
}
*/
switch (converter['converter']) {
case 'ewww':
document.getElementById('ewww_api_key').value = getConverterOption(converter, 'api-key', '');
document.getElementById('ewww_api_key_2').value = getConverterOption(converter, 'api-key-2', '');
break;
case 'wpc':
document.getElementById('wpc_api_url').value = getConverterOption(converter, 'api-url', '');
/* api key in configuration file can be:
- never set (null)
- set to be empty ('')
- set to be something.
If never set, we show a password input.
If set to empty, we also show a password input.
There is no need to differentiate. between never set and empty
If set to something, we show a link "Change"
In Config::getConfigForOptionsPage, we remove the api key from javascript array.
if api key is non-empty, a "_api-key-non-empty" field is set.
*/
document.getElementById('wpc_new_api_key').value = '';
if (getConverterOption(converter, '_api-key-non-empty', false)) {
// api key is set to something...
document.getElementById('wpc_change_api_key').style.display = 'inline';
document.getElementById('wpc_new_api_key').style.display = 'none';
} else {
// api key is empty (or not set)
document.getElementById('wpc_new_api_key').style.display = 'inline';
document.getElementById('wpc_change_api_key').style.display = 'none';
}
apiVersion = getConverterOption(converter, 'api-version', 0);
// if api version isn't set, then either
// - It is running on old api 0. In that case, URL is set
// - Wpc has never been configured. In that case, URL is not set,
// and we should not mention api 0 (we should set apiVersion to 1)
if (!isConverterOptionSet(converter, 'api-version')) {
if (getConverterOption(converter, 'api-url', '') == '') {
apiVersion = 1;
}
}
document.getElementById('wpc_api_version').value = apiVersion.toString();
if (apiVersion != 0) {
}
if (apiVersion == 0) {
document.getElementById('wpc_secret').value = getConverterOption(converter, 'secret', '');
} else {
// Only show api version dropdown if configured to run on old api
// There is no going back!
document.getElementById('wpc_api_version_div').style.display = 'none';
}
document.getElementById('wpc_crypt_api_key_in_transfer').checked = getConverterOption(converter, 'crypt-api-key-in-transfer', true);
// Hide/show the fields for the api version
wpcApiVersionChanged();
//document.getElementById('wpc_secret').value = getConverterOption(converter, 'secret', '');
//document.getElementById('wpc_url_2').value = getConverterOption(converter, 'url-2', '');
//document.getElementById('wpc_secret_2').value = getConverterOption(converter, 'secret-2', '');
//wpcUpdateWebServicesHTML();
break;
case 'gd':
document.getElementById('gd_skip_pngs').checked = getConverterOption(converter, 'skip-pngs', false);
break;
case 'cwebp':
document.getElementById('cwebp_use_nice').checked = getConverterOption(converter, 'use-nice', true);
document.getElementById('cwebp_method').value = getConverterOption(converter, 'method', '');
document.getElementById('cwebp_try_common_system_paths').checked = getConverterOption(converter, 'try-common-system-paths', '');
document.getElementById('cwebp_skip_these_precompiled_binaries').value = getConverterOption(converter, 'skip-these-precompiled-binaries', '');
document.getElementById('cwebp_try_supplied_binary').checked = getConverterOption(converter, 'try-supplied-binary-for-os', '');
document.getElementById('cwebp_set_size').checked = getConverterOption(converter, 'set-size', '');
document.getElementById('cwebp_size_in_percentage').value = getConverterOption(converter, 'size-in-percentage', '');
document.getElementById('cwebp_command_line_options').value = getConverterOption(converter, 'command-line-options', '');
break;
case 'imagemagick':
document.getElementById('imagemagick_use_nice').checked = getConverterOption(converter, 'use-nice', true);
break;
case 'graphicsmagick':
document.getElementById('graphicsmagick_use_nice').checked = getConverterOption(converter, 'use-nice', true);
break;
case 'vips':
document.getElementById('vips_smart_subsample').checked = getConverterOption(converter, 'smart-subsample', false);
document.getElementById('vips_preset').value = getConverterOption(converter, 'preset', 'disable');
break;
case 'ffmpeg':
document.getElementById('ffmpeg_use_nice').checked = getConverterOption(converter, 'use-nice', true);
document.getElementById('ffmpeg_method').value = getConverterOption(converter, 'method', '');
break;
}
tb_show("Configure " + converter['id'] + ' converter', '#TB_inline?inlineId=' + converter['converter']);
}
function updateConverterOptions() {
var id = window.currentlyEditing;
var converter = window.convertersMap[id];
/*
Removed (#243)
if (document.getElementById(id + '_quality')) {
var q = document.getElementById(id + '_quality').value;
if (q == 'auto') {
setConverterOption(converter, 'quality', 'auto');
setConverterOption(converter, 'max-quality', document.getElementById(id + '_max_quality').value);
} else {
setConverterOption(converter, 'quality', 'inherit');
deleteConverterOption(converter, 'max-quality');
}
} else {
deleteConverterOption(converter, 'quality');
deleteConverterOption(converter, 'max-quality');
}
*/
switch (converter['converter']) {
case 'ewww':
setConverterOption(converter, 'api-key', document.getElementById('ewww_api_key').value);
setConverterOption(converter, 'api-key-2', document.getElementById('ewww_api_key_2').value);
break;
case 'wpc':
setConverterOption(converter, 'api-url', document.getElementById('wpc_api_url').value);
//setConverterOption(converter, 'secret', document.getElementById('wpc_secret').value);
//setConverterOption(converter, 'url-2', document.getElementById('wpc_url_2').value);
//setConverterOption(converter, 'secret-2', document.getElementById('wpc_secret_2').value);*/
var apiVersion = parseInt(document.getElementById('wpc_api_version').value, 10);
setConverterOption(converter, 'api-version', apiVersion);
if (apiVersion == '0') {
setConverterOption(converter, 'secret', document.getElementById('wpc_secret').value);
} else {
deleteConverterOption(converter, 'secret');
setConverterOption(converter, 'crypt-api-key-in-transfer', document.getElementById('wpc_crypt_api_key_in_transfer').checked);
}
if (document.getElementById('wpc_new_api_key').style.display == 'inline') {
// password field is shown. Store the value
setConverterOption(converter, 'new-api-key', document.getElementById('wpc_new_api_key').value);
} else {
// password field is not shown. Remove "new-api-key" value, indicating there is no new value
//setConverterOption(converter, 'new-api-key', '');
deleteConverterOption(converter, 'new-api-key');
}
break;
case 'gd':
setConverterOption(converter, 'skip-pngs', document.getElementById('gd_skip_pngs').checked);
break;
case 'cwebp':
setConverterOption(converter, 'use-nice', document.getElementById('cwebp_use_nice').checked);
var methodString = document.getElementById('cwebp_method').value;
var methodNum = (methodString == '') ? 6 : parseInt(methodString, 10);
setConverterOption(converter, 'method', methodNum);
setConverterOption(converter, 'skip-these-precompiled-binaries', document.getElementById('cwebp_skip_these_precompiled_binaries').value);
setConverterOption(converter, 'try-common-system-paths', document.getElementById('cwebp_try_common_system_paths').checked);
setConverterOption(converter, 'try-supplied-binary-for-os', document.getElementById('cwebp_try_supplied_binary').checked);
setConverterOption(converter, 'set-size', document.getElementById('cwebp_set_size').checked);
var sizeInPercentageString = document.getElementById('cwebp_size_in_percentage').value;
var sizeInPercentageNumber = (sizeInPercentageString == '') ? '' : parseInt(sizeInPercentageString, 10);
setConverterOption(converter, 'size-in-percentage', sizeInPercentageNumber);
setConverterOption(converter, 'command-line-options', document.getElementById('cwebp_command_line_options').value);
break;
case 'imagemagick':
setConverterOption(converter, 'use-nice', document.getElementById('imagemagick_use_nice').checked);
break;
case 'graphicsmagick':
setConverterOption(converter, 'use-nice', document.getElementById('graphicsmagick_use_nice').checked);
break;
case 'vips':
setConverterOption(converter, 'smart-subsample', document.getElementById('vips_smart_subsample').checked);
var vipsPreset = document.getElementById('vips_preset').value;
if (vipsPreset == 'disable') {
deleteConverterOption(converter, 'preset');
} else {
setConverterOption(converter, 'preset', vipsPreset);
}
break;
case 'ffmpeg':
setConverterOption(converter, 'use-nice', document.getElementById('ffmpeg_use_nice').checked);
var methodString = document.getElementById('ffmpeg_method').value;
var methodNum = (methodString == '') ? 6 : parseInt(methodString, 10);
setConverterOption(converter, 'method', methodNum);
break;
}
updateInputValue();
tb_remove();
}
function updateConverterOptionsAndSave() {
updateConverterOptions();
document.getElementById('webpexpress_settings').submit();
}
/** Encode path before adding to querystring.
* Paths in querystring triggers LFI warning in Wordfence.
* By encoding it, Wordpfence will not detect our misdeed!
*
* see https://github.com/rosell-dk/webp-express/issues/87
*/
function encodePathforQS(path) {
return path.replace('/', '**');
}
function testConverter(id) {
openTestConvertPopup(id);
return;
}
/*
function removeConverter(id) {
for (var i=0; i<window.converters.length; i++) {
if (window.converters[i]['id'] == id) {
window.converters.splice(i, 1);
setConvertersHTML();
break;
}
}
}*/
function addConverter(id) {
window.converters.push({
converter: id
});
setConvertersHTML();
tb_remove();
}
function deactivateConverter(id) {
window.convertersMap[id].deactivated = true;
setConvertersHTML();
}
function activateConverter(id) {
delete window.convertersMap[id].deactivated
setConvertersHTML();
}
/* WPC */
/* ------------- */
/*
function converterQualityChanged(converterId) {
var q = document.getElementById(converterId + '_quality').value;
document.getElementById(converterId + '_max_quality_div').style['display'] = (q == 'auto' ? 'block' : 'none');
}*/
function wpcShowAwaitingApprovalPopup() {
closeDasPopup();
openDasPopup('wpc_awaiting_approval_popup', 500, 350);
/*
window.pollRequestApprovalTid = window.setInterval(function() {
//openDasPopup('wpc_successfully_connected_popup', 500, 350);
}, 1500);*/
}
function wpcRequestAccess() {
var url = document.getElementById('wpc_request_access_url').value;
url = 'http://we0/wordpress/webp-express-server';
jQuery.post(window.ajaxurl, {
'action': 'webpexpress_request_access',
}, function(response) {
if (response && (response.substr(0,1) == '{')) {
var r = JSON.parse(response);
if (r['success']) {
wpcShowAwaitingApprovalPopup()
} else {
alert(r['errorMessage']);
}
}
});
}
function openWpcConnectPopup() {
openDasPopup('wpc_connect_popup', 500, 350);
}
function wpcChangeApiKey() {
document.getElementById('wpc_new_api_key').style.display = 'inline';
document.getElementById('wpc_change_api_key').style.display = 'none';
}
function wpcApiVersionChanged() {
var apiVersion = parseInt(document.getElementById('wpc_api_version').value, 10);
if (apiVersion == 0) {
document.getElementById('wpc_crypt_api_key_in_transfer_div').style.display = 'none';
document.getElementById('wpc_api_key_label_1').style.display = 'inline-block';
document.getElementById('wpc_api_key_label_2').style.display = 'none';
document.getElementById('wpc_secret_div').style.display = 'block';
document.getElementById('wpc_api_key_div').style.display = 'none';
} else {
document.getElementById('wpc_crypt_api_key_in_transfer_div').style.display = 'block';
document.getElementById('wpc_api_key_label_1').style.display = 'none';
document.getElementById('wpc_api_key_label_2').style.display = 'inline-block';
document.getElementById('wpc_secret_div').style.display = 'none';
document.getElementById('wpc_api_key_div').style.display = 'block';
}
}

View File

@@ -0,0 +1,47 @@
function openDasPopup(id, w, h) {
// Create overlay, if it isn't already created
if (!document.getElementById('das_overlay')) {
var el = document.createElement('div');
el.setAttribute('id', 'das_overlay');
document.body.appendChild(el);
}
// Show overlay
document.getElementById('das_overlay').style['display'] = 'block';
// Set width and height on popup
var popupEl = document.getElementById(id);
popupEl.style['width'] = w + 'px';
popupEl.style['margin-left'] = -Math.floor(w/2) + 'px';
popupEl.style['height'] = h + 'px';
popupEl.style['margin-top'] = -Math.floor(h/2) + 'px';
// Show popup
popupEl.style['visibility'] = 'visible';
window.currentDasPopupId = id;
}
function closeDasPopup() {
if (document.getElementById('das_overlay')) {
document.getElementById('das_overlay').style['display'] = 'none';
}
if (window.currentDasPopupId) {
document.getElementById(window.currentDasPopupId).style['visibility'] = 'hidden';
}
}
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
if (isEscape) {
closeDasPopup();
}
};

View File

@@ -0,0 +1,34 @@
/*
function htmlEscape(str) {
return str
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
*/
function webpexpress_escapeHTML(s)
{
return s.replace(/./gm, function(s) {
var safe = /[0-9a-zA-Z\!]/;
if (safe.test(s.charAt(0))) {
return s.charAt(0);
}
switch (s.charAt(0)) {
case '*':
case '#':
case ' ':
case '{':
case '}':
case ':':
case '.':
case '`':
return s.charAt(0);
default:
return "&#" + s.charCodeAt(0) + ";";
}
});
}

View File

@@ -0,0 +1,68 @@
function initComparisonSlider($) {
//function to check if the .cd-image-container is in the viewport here
// ...
var w = $('.cd-image-container').width();
$('.cd-image-container img').each(function(){
$(this).css('max-width', w + 'px');
});
$('.cd-image-container img').first().on('load', function() {
$('.cd-image-container').width($(this).width());
})
//make the .cd-handle element draggable and modify .cd-resize-img width according to its position
$('.cd-image-container').each(function(){
var actual = $(this);
drags(actual.find('.cd-handle'), actual.find('.cd-resize-img'), actual);
});
//draggable funtionality - credits to http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
function drags(dragElement, resizeElement, container) {
dragElement.on("mousedown vmousedown", function(e) {
dragElement.addClass('draggable');
resizeElement.addClass('resizable');
var dragWidth = dragElement.outerWidth(),
xPosition = dragElement.offset().left + dragWidth - e.pageX,
containerOffset = container.offset().left,
containerWidth = container.outerWidth(),
minLeft = containerOffset + 10,
maxLeft = containerOffset + containerWidth - dragWidth - 10;
dragElement.parents().on("mousemove vmousemove", function(e) {
leftValue = e.pageX + xPosition - dragWidth;
//constrain the draggable element to move inside its container
if(leftValue < minLeft ) {
leftValue = minLeft;
} else if ( leftValue > maxLeft) {
leftValue = maxLeft;
}
widthValue = (leftValue + dragWidth/2 - containerOffset)*100/containerWidth+'%';
$('.draggable').css('left', widthValue).on("mouseup vmouseup", function() {
$(this).removeClass('draggable');
resizeElement.removeClass('resizable');
});
$('.resizable').css('width', widthValue);
//function to upadate images label visibility here
// ...
}).on("mouseup vmouseup", function(e){
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
e.preventDefault();
}).on("mouseup vmouseup", function(e) {
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
};
};

View File

@@ -0,0 +1,297 @@
function toggleVisibility(elmId, show) {
var elm = document.getElementById(elmId);
if (!elm) {
return;
}
elm.classList.add('toggler');
/*
if (!elm.style.maxHeight) {
elm.style['maxHeight'] = (elm.clientHeight + 40) + 'px';
}*/
if (show) {
elm.classList.remove('closed');
} else {
elm.classList.add('closed');
}
}
function updateAlterHTMLChartVisibility(show) {
function el(elmId) {
return document.getElementById(elmId);
}
var elm = el('alter_html_comparison_chart');
//elm.style['maxHeight'] = (elm.clientHeight + 40) + 'px';
//elm.style['maxHeight'] = '600px';
//elm.style.display = (show ? 'block' : 'none');
if (show) {
elm.classList.remove('closed');
} else {
elm.classList.add('closed');
}
el('hide_alterhtml_chart_btn').style.display = (show ? 'block' : 'none');
el('show_alterhtml_chart_btn').style.display = (show ? 'none' : 'inline-block');
el('ui_show_alter_html_chart').value = (show ? 'true' : 'false');
}
document.addEventListener('DOMContentLoaded', function() {
//resetToDefaultConverters();
function el(elmId) {
return document.getElementById(elmId);
}
if (el('cache_control_select') && el('cache_control_custom_div') && el('cache_control_set_div')) {
el('cache_control_custom_div').classList.add('effect-visibility');
el('cache_control_set_div').classList.add('effect-visibility');
function updateCacheControlCustomVisibility() {
var cacheControlValue = document.getElementById('cache_control_select').value;
/*
var customEl = document.getElementById('cache_control_custom');
if (cacheControlValue == 'custom') {
customEl.setAttribute('type', 'text');
} else {
customEl.setAttribute('type', 'hidden');
}*/
toggleVisibility('cache_control_custom_div', (cacheControlValue == 'custom'));
toggleVisibility('cache_control_set_div', (cacheControlValue == 'set'));
}
updateCacheControlCustomVisibility();
el('cache_control_select').addEventListener('change', function() {
updateCacheControlCustomVisibility();
});
}
// In "No conversion" and "CDN friendly" mode, toggle cache control div when redirect is enabled/disabled
if (el('operation_mode') && (el('operation_mode').value == 'no-conversion')) {
if (el('redirect_to_existing_in_htaccess') && el('cache_control_div')) {
el('cache_control_div').classList.add('effect-opacity');
function updateCacheControlHeaderVisibility() {
toggleVisibility('cache_control_div', el('redirect_to_existing_in_htaccess').checked);
}
updateCacheControlHeaderVisibility();
el('redirect_to_existing_in_htaccess').addEventListener('change', function() {
updateCacheControlHeaderVisibility();
});
}
}
if (el('only_redirect_to_converter_for_webp_enabled_browsers_row') && el('enable_redirection_to_converter')) {
el('only_redirect_to_converter_for_webp_enabled_browsers_row').classList.add('effect-opacity');
el('only_redirect_to_converter_on_cache_miss_row').classList.add('effect-opacity');
function updateRedirectionOnlyWebPVisibility() {
toggleVisibility('only_redirect_to_converter_for_webp_enabled_browsers_row', el('enable_redirection_to_converter').checked);
toggleVisibility('only_redirect_to_converter_on_cache_miss_row', el('enable_redirection_to_converter').checked);
}
updateRedirectionOnlyWebPVisibility();
el('enable_redirection_to_converter').addEventListener('change', function() {
updateRedirectionOnlyWebPVisibility();
});
}
// Toggle Quality (auto / specific)
if (el('quality_auto_select') && el('max_quality_div') && el('quality_specific_div')) {
function updateQualityVisibility() {
var qualityAutoValue = el('quality_auto_select').value;
toggleVisibility('max_quality_div', el('quality_auto_select').value == 'auto_on');
toggleVisibility('quality_specific_div', el('quality_auto_select').value != 'auto_on');
/*
if (qualityAutoValue == 'auto_on') {
el('max_quality_div').style['display'] = 'inline-block';
el('quality_specific_div').style['display'] = 'none';
} else {
el('max_quality_div').style['display'] = 'none';
el('quality_specific_div').style['display'] = 'inline-block';
}*/
}
updateQualityVisibility();
el('quality_auto_select').addEventListener('change', function() {
updateQualityVisibility();
});
}
// Jpeg encoding changing
if (el('jpeg_encoding_select') && el('jpeg_quality_lossless_div')) {
function updateJpgEncoding() {
toggleVisibility('jpeg_quality_lossless_div', el('jpeg_encoding_select').value != 'lossy');
}
updateJpgEncoding();
el('jpeg_encoding_select').addEventListener('change', function() {
updateJpgEncoding();
});
}
// Jpeg near-lossless toggling
if (el('jpeg_enable_near_lossless') && el('jpeg_near_lossless_div')) {
function updateNearLosslessVisibilityJpeg() {
toggleVisibility('jpeg_near_lossless_div', el('jpeg_enable_near_lossless').value == 'on');
}
updateNearLosslessVisibilityJpeg();
el('jpeg_enable_near_lossless').addEventListener('change', function() {
updateNearLosslessVisibilityJpeg();
});
}
// PNG encoding changing
if (el('image_types') && el('png_row')) {
function updatePngAndJpgRowVisibilities() {
var imageTypes = parseInt(el('image_types').value, 10);
var pngEnabled = (imageTypes & 2);
var jpegEnabled = (imageTypes & 1);
toggleVisibility('png_row', pngEnabled);
toggleVisibility('jpeg_row', jpegEnabled);
}
updatePngAndJpgRowVisibilities();
el('image_types').addEventListener('change', function() {
updatePngAndJpgRowVisibilities();
});
}
// PNG encoding changing
if (el('png_encoding_select') && el('png_quality_lossy_div')) {
function updatePngEncoding() {
toggleVisibility('png_quality_lossy_div', el('png_encoding_select').value != 'lossless');
}
updatePngEncoding();
el('png_encoding_select').addEventListener('change', function() {
updatePngEncoding();
});
}
// PNG near-lossless toggling
if (el('png_enable_near_lossless') && el('png_near_lossless_div')) {
function updateNearLosslessVisibilityPng() {
toggleVisibility('png_near_lossless_div', el('png_enable_near_lossless').value == 'on');
}
updateNearLosslessVisibilityPng();
el('png_enable_near_lossless').addEventListener('change', function() {
updateNearLosslessVisibilityPng();
});
}
// If "doc-root" cannot be used for structuring, disable the option and set to "image-roots"
if (!window.webpExpress['can-use-doc-root-for-structuring']) {
el('destination_structure').classList.add('effect-opacity');
toggleVisibility('destination_structure', false);
if (el('destination_structure').value == 'doc-root') {
el('destination_structure').value = 'image-roots';
}
}
// Toggle File Extension (only show when "mingled" is selected)
if (el('destination_folder') && el('destination_extension')) {
el('destination_extension').classList.add('effect-opacity');
function updateDestinationExtensionVisibility() {
toggleVisibility('destination_extension', el('destination_folder').value == 'mingled');
if (el('destination_folder').value == 'separate') {
el('destination_extension').value = 'append';
}
/*
if (document.getElementById('destination_folder').value == 'mingled') {
el('destination_extension_row').style['display'] = 'table-row';
} else {
el('destination_extension_row').style['display'] = 'none';
}*/
}
updateDestinationExtensionVisibility();
document.getElementById('destination_folder').addEventListener('change', function() {
updateDestinationExtensionVisibility();
});
}
// Toggle webservice
if (el('web_service_enabled') && el('whitelist_div')) {
el('whitelist_div').classList.add('effect-opacity');
function updateServerSettingsVisibility() {
toggleVisibility('whitelist_div', el('web_service_enabled').checked);
//document.getElementById('whitelist_div').style['display'] = (el('web_service_enabled').checked ? 'block' : 'none');
}
updateServerSettingsVisibility();
document.getElementById('web_service_enabled').addEventListener('change', function() {
updateServerSettingsVisibility();
});
}
// Toggle Alter HTML options
if (el('alter_html_enabled') && (el('alter_html_options_div'))) {
el('alter_html_options_div').classList.add('effect-opacity');
el('alter_html_comparison_chart').classList.add('effect-slider');
function updateAlterHTMLVisibility() {
toggleVisibility('alter_html_options_div', el('alter_html_enabled').checked);
// toggleVisibility('alter_html_comparison_chart', el('alter_html_enabled').checked);
}
updateAlterHTMLVisibility();
el('alter_html_enabled').addEventListener('change', function() {
updateAlterHTMLVisibility();
});
}
// Show/hide "Only do the replacements in webp enabled browsers" when "What to replace" is changed
if (el('alter_html_replacement_url') && el('alter_html_url_options_div')) {
el('alter_html_url_options_div').classList.add('effect-opacity');
el('alter_html_picture_options_div').classList.add('effect-opacity');
function updateAlterHTMLReplaceVisibility() {
toggleVisibility('alter_html_url_options_div', el('alter_html_replacement_url').checked);
toggleVisibility('alter_html_picture_options_div', el('alter_html_replacement_picture').checked);
}
updateAlterHTMLReplaceVisibility();
el('alter_html_replacement_url').addEventListener('change', function() {
updateAlterHTMLReplaceVisibility();
});
el('alter_html_replacement_picture').addEventListener('change', function() {
updateAlterHTMLReplaceVisibility();
});
}
if (el('ui_show_alter_html_chart') && el('alter_html_comparison_chart')) {
var elm = el('alter_html_comparison_chart');
elm.style['maxHeight'] = (elm.clientHeight + 80) + 'px';
updateAlterHTMLChartVisibility(el('ui_show_alter_html_chart').value == 'true');
}
document.getElementById('change_operation_mode').addEventListener('change', function() {
var msg;
if (document.getElementById('operation_mode').value == 'tweaked') {
msg = 'Save configuration and change mode? Any tweaks will be lost';
} else {
if (document.getElementById('change_operation_mode').value == 'tweaked') {
msg = 'Save configuration and change to tweaked mode? No options are lost when changing to tweaked mode (it will behave the same way as currently, until you start tweaking)';
} else {
msg = 'Save configuration and change mode?';
}
}
if (confirm(msg)) {
document.getElementById('webpexpress_settings').submit();
} else {
// undo select box change
document.getElementById('change_operation_mode').value = document.getElementById('operation_mode').value;
return;
}
});
});

View File

@@ -0,0 +1,50 @@
function openDeleteConvertedFilesPopup() {
var html = '';
html += '<p>To delete all converted files, click this button:<br>';
html += '<button onclick="purgeCache(false)" class="button button-secondary" type="button">Delete all converted files</button>';
html += '</p>';
html += '<p>Or perhaps, you only want to delete the converted <i>PNGs</i>? Then this button is for you:<br>';
html += '<button onclick="purgeCache(true)" class="button button-secondary" type="button">Delete converted PNGs</button>';
html += '</p>';
document.getElementById('purgecachecontent').innerHTML = html;
tb_show('Purge cache', '#TB_inline?inlineId=purgecachepopup');
// purgeCache();
}
function purgeCache(onlyPng) {
var data = {
'action': 'webpexpress_purge_cache',
'nonce' : window.webpExpress['ajax-nonces']['purge-cache'],
'only-png': onlyPng
};
jQuery.post(ajaxurl, data, function(response) {
if ((typeof response == 'object') && (response['success'] == false)) {
if (response['data'] && ((typeof response['data']) == 'string')) {
alert(response['data']);
} else {
alert('Something failed');
}
return;
}
var result = JSON.parse(response);
//console.log(result);
if (result['fail-count'] == 0) {
if (result['delete-count'] == 0) {
alert('No webp files were found, so none was deleted.');
} else {
alert('Successfully deleted ' + result['delete-count'] + ' webp files');
}
} else {
if (result['delete-count'] == 0) {
alert('Failed deleting ' + result['fail-count'] + ' webp files. None was deleted, in fact.');
} else {
alert('Deleted ' + result['delete-count'] + ' webp files. However, failed deleting ' + result['fail-count'] + ' webp files.');
}
}
});
}

View File

@@ -0,0 +1,74 @@
function openDeleteLogFilesPopup() {
var html = '';
html += '<p><b>Are you sure you want to do that?</b></p>';
html += '<p>' +
'The log files contain information about the conversion settings used for each webp and the libraries ' +
'used, and the versions. This information will be visible in the conversion manager in a not too far future. ' +
'The information might also be used to notify you if the libraries / version of a library you have is ' +
'significantly better than the one used for the conversion. ' +
'If you delete the log files, you will not benefit from this functionality. ' +
'</p>';
html += '<p>' +
'The log files are btw located in <i>wp-content/webp-express/log/</i>, if you want to have a closer look.' +
'</p>';
//html += '<p>In a not too far future, the log files will be used in the conversion manager.</p>'
//html += 'They could become handy.</p>'
/*
html += '<p>This action cannot be reversed. Your log files will be gone. '
html += 'Dead. Completely. Forever. '
html += '(Unless of course you have a backup. Or, of course, there are ways of recovery... Anyway...). '
html += 'Ok, sorry for the babbeling. The dialog seemed bare without text.</p>';*/
html += '<button onclick="purgeLog()" class="button button-secondary" type="button">Yes, delete!</button>';
document.getElementById('purgelogcontent').innerHTML = '<div>' + html + '</div>';
tb_show('Delete all log Files?', '#TB_inline?inlineId=purgelogpopup&height=320&width=450');
}
function closePurgeLogDialog() {
tb_remove();
}
function purgeLog() {
var data = {
'action': 'webpexpress_purge_log',
'nonce' : window.webpExpress['ajax-nonces']['purge-log'],
};
jQuery.post(ajaxurl, data, function(response) {
if ((typeof response == 'object') && (response['success'] == false)) {
if (response['data'] && ((typeof response['data']) == 'string')) {
alert(response['data']);
} else {
alert('Something failed');
}
return;
}
var result = JSON.parse(response);
//console.log(result);
var html = '<div><p>';
if (result['fail-count'] == 0) {
if (result['delete-count'] == 0) {
html += 'No log files were found, so none was deleted.';
} else {
html += 'Successfully deleted ' + result['delete-count'] + ' log files';
}
} else {
if (result['delete-count'] == 0) {
html += 'Failed deleting ' + result['fail-count'] + ' log files. None was deleted, in fact.';
} else {
html += 'Deleted ' + result['delete-count'] + ' log files. However, failed deleting ' + result['fail-count'] + ' log files.';
}
}
html += '</p>';
html += '<button onclick="closePurgeLogDialog()" class="button button-secondary" type="button">Ok</button>';
html += '</div>';
document.getElementById('purgelogcontent').innerHTML = html;
});
}

View File

@@ -0,0 +1,160 @@
if (typeof WebPExpress == 'undefined') {
WebPExpress = {};
}
WebPExpress.SelfTest = {
'clear': function() {
document.getElementById('webpexpress_test_redirection_content').innerHTML = '';
},
'write': function(html) {
//var el = document.getElementById('webpexpress_test_redirection_content');
//el.innerHTML += html;
var el = document.createElement('div');
el.innerHTML = html;
document.getElementById('webpexpress_test_redirection_content').appendChild(el);
},
'simpleMdToHtml': function(line) {
//return s.replace(/./gm, function(s) {
if (line.substr(0, 3) == '```') {
return '<pre>' + line.replace(/\`/gm, '') + '</pre>';
}
// Bold with inline attributtes (ie: "hi **bold**{: .red}")
line = line.replace(/\*\*([^\*]+)\*\*\{:\s([^}]+)\}/gm, function(s, g1, g2) {
// g2 is the inline attributes.
// right now we only support classes, and only ONE class.
// so it is easy.
var className = g2.substr(1);
return '<b class="' + className + '">' + g1 + '</b>';
//return '<b>' + s.substr(2, s.length - 4) + '</b>';
});
// Bold
line = line.replace(/(\*\*[^\*]+\*\*)/gm, function(s) {
return '<b>' + s.substr(2, s.length - 4) + '</b>';
});
// Italic
line = line.replace(/(\*[^\*]+\*)/gm, function(s) {
return '<i>' + s.substr(1, s.length - 2) + '</i>';
});
// Headline
if (line.substr(0, 2) == '# ') {
line = '<h1>' + line.substr(2) + '</h1>';
}
if (line.substr(0, 3) == '## ') {
line = '<h2>' + line.substr(3) + '</h2>';
}
if (line.substr(0, 4) == '### ') {
line = '<h3>' + line.substr(4) + '</h3>';
}
if (line.substr(0, 5) == '#### ') {
line = '<h4>' + line.substr(5) + '</h4>';
}
if (line.substr(0, 15) == '&#39;&#39;&#39;') {
line = '<pre>' + line.substr(15) + '</pre>';
}
// Empty line
if (line == '') {
line = '<br>';
}
// "ok!" green
line = line.replace(/ok\!/gmi, function(s) {
return '<span style="color:green; font-weight: bold;">ok</span>';
});
// "great" green
/*
line = line.replace(/great/gmi, function(s) {
return '<span style="color:green; font-weight: bold;">' + s + '</span>';
});*/
// "failed" red
line = line.replace(/failed/gmi, function(s) {
return '<span style="color:red; font-weight:bold">FAILED</span>';
});
return '<div class="webpexpress md">' + line + '</div>';
},
'responseHandler': function(response) {
if ((typeof response == 'object') && (response['success'] == false)) {
html = '<h1>Error</h1>';
if (response['data'] && ((typeof response['data']) == 'string')) {
html += webpexpress_escapeHTML(response['data']);
}
WebPExpress.SelfTest.write(html);
document.getElementById('bulkconvertcontent').innerHTML = html;
return;
}
var responseObj = JSON.parse(response);
var result = responseObj['result'];
if (typeof result == 'string') {
result = [result];
}
for (var i=0; i<result.length; i++) {
var line = result[i];
if (typeof line != 'string') {
continue;
}
line = webpexpress_escapeHTML(line);
line = WebPExpress.SelfTest.simpleMdToHtml(line);
WebPExpress.SelfTest.write(line);
}
//result = result.join('<br>');
var next = responseObj['next'];
if (next == 'done') {
//WebPExpress.SelfTest.write('<br>done');
} else if (next == 'break') {
WebPExpress.SelfTest.write('breaking');
} else {
WebPExpress.SelfTest.runTest(next);
}
},
'runTest': function(testId) {
var data = {
'action': 'webpexpress_self_test',
'testId': testId,
'nonce' : window.webpExpress['ajax-nonces']['self-test'],
};
jQuery.ajax({
method: 'POST',
url: ajaxurl,
data: data,
success: WebPExpress.SelfTest.responseHandler,
error: function() {
WebPExpress.SelfTest.write('PHP error. Check your debug.log for more info (make sure debugging is enabled)');
},
});
},
'openPopup': function(testId) {
WebPExpress.SelfTest.clear();
var w = Math.min(1000, Math.max(200, document.documentElement.clientWidth - 100));
var h = Math.max(250, document.documentElement.clientHeight - 80);
var title = 'Self testing';
if (testId == 'redirectToExisting') {
title = 'Testing redirection to existing webp';
}
tb_show(title, '#TB_inline?inlineId=webpexpress_test_redirection_popup&width=' + w + '&height=' + h);
WebPExpress.SelfTest.runTest(testId);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,294 @@
function openTestConvertPopup(converterId) {
var html = '<div id="tc_conversion_options">options</div><div><div id="tc_conversion_result"><h2>Result</h2>wait...</div></div>'
document.getElementById('tc_content').innerHTML = html;
var w = Math.min(1200, Math.max(200, document.documentElement.clientWidth - 100));
var h = Math.max(250, document.documentElement.clientHeight - 80);
tb_show('Testing conversion', '#TB_inline?inlineId=tc_popup&width=' + w + '&height=' + h);
webpexpress_createTCOptions(converterId);
}
function webpexpress_createTCOptions(converterId) {
var html = '';
html += '<h2>Options</h2>'
html += '<form>';
html += '<div style="display:inline-block; margin-right: 20px;"><label>Converter:</label><select id="converter" name="converter">';
for (var i=0; i<window.converters.length; i++) {
var c = window.converters[i];
var cid = c['converter'];
html += '<option value="' + cid + '"' + (cid == converterId ? ' selected' : '') + '>' + cid + '</option>';
}
html += '</select></div>'
html += '<div style="display:inline-block;"><label>Test image:</label><select id="test_image" name="image">';
//html += '<option value="dice.png">dice.png</option>';
html += '<option value="alphatest.png">alphatest.png</option>';
html += '<option value="test-pattern-tv.jpg">test-pattern-tv.jpg</option>';
html += '<option value="dice.png">dice.png</option>';
//html += '<option value="alphatest.png">alphatest.png</option>';
html += '<option value="palette-based-colors.png">palette-based-colors.png</option>';
//html += '<option value="test.png">test.png</option>';
html += '<option value="architecture-q85-w600.jpg">architecture-q85-w600.jpg</option>';
html += '</select></div>';
// html += '<h3>Conversion options</h3>'
html += '<div id="tc_png" class="toggler effect-visibility"><h3>Conversion options (PNG)</h3><div id="tc_png_options"></div></div>';
html += '<div id="tc_jpeg" class="toggler effect-visibility"><h3>Conversion options (JPEG)</h3><div id="tc_jpeg_options"></div></div>';
// html += '<div id="tc_jpeg_options" class="toggler effect-visibility"></div>';
html += '<div><label>Metadata:</label><div id="tc_metadata" style="display: inline-block"></div></div>';
html += '<button onclick="runTestConversion()" class="button button-primary" type="button" style="margin-top:25px">Convert</button>';
html += '</form>';
document.getElementById('tc_conversion_options').innerHTML = html;
// Append PNG
document.getElementById('tc_png_options').appendChild(
document.getElementById('png_td').cloneNode(true)
);
// Append Jpeg
document.getElementById('tc_jpeg_options').appendChild(
document.getElementById('jpeg_td').cloneNode(true)
);
// Append Metadata
document.getElementById('tc_metadata').appendChild(
document.getElementById('metadata').cloneNode(true)
);
// change ids. All id's will get appended "tc_" - unless they already have
document.querySelectorAll('#tc_conversion_options [id]').forEach(function(el) {
el.value = document.getElementById(el.id).value;
if (el.id.indexOf('tc_') != 0) {
el.id = 'tc_' + el.id;
}
});
// listen to all select box changes
document.querySelectorAll('#tc_conversion_options select').forEach(function(el) {
el.addEventListener('change', function() {
webpexpress_updateVisibilities();
});
});
webpexpress_updateVisibilities();
runTestConversion();
}
function webpexpress_updateVisibilities() {
// toggleVisibility('png_row', el('image_types').value != '1');
function el(elmId) {
return document.getElementById(elmId);
}
var testImage = el('tc_test_image').value;
var isPng = (testImage.toLowerCase().indexOf('.png') != -1);
toggleVisibility('tc_png', isPng);
toggleVisibility('tc_jpeg', !isPng);
toggleVisibility('tc_png_quality_lossy_div', el('tc_png_encoding_select').value != 'lossless');
toggleVisibility('tc_png_near_lossless_div', el('tc_png_enable_near_lossless').value == 'on');
console.log('value:' + el('tc_quality_auto_select').value);
toggleVisibility('tc_max_quality_div', el('tc_quality_auto_select').value == 'auto_on');
toggleVisibility('tc_quality_specific_div', el('tc_quality_auto_select').value != 'auto_on');
}
function runTestConversion() {
var html = '';
function elTxt(elmName) {
//var el = document.getElementById('tc_' + elmId);
var el = document.querySelector('#tc_conversion_options [name=' + elmName + ']');
if (!el) {
alert('Error: Could not find element with name: "' + elmName + '"');
}
return el.value;
}
function elInt(elmName) {
return parseInt(elTxt(elmName), 10);
}
var configOverrides = {
"jpeg-encoding": elTxt("jpeg-encoding"),
"jpeg-enable-near-lossless": (elTxt("jpeg-enable-near-lossless") == 'on'),
"jpeg-near-lossless": elInt('jpeg-near-lossless'),
"quality-auto": (elTxt("quality-auto") == 'auto_on'),
"max-quality": elInt('max-quality'),
"quality-specific": (elTxt("quality-auto") == 'auto_on' ? elInt('quality-fallback') : elInt('quality-specific')),
"png-encoding": elTxt("png-encoding"),
"png-enable-near-lossless": true,
"png-near-lossless": elInt("png-near-lossless"),
"png-quality": elInt("png-quality"),
"alpha-quality": elInt("alpha-quality"),
"metadata": elTxt('metadata'),
"log-call-arguments": true,
};
var data = {
'action': 'convert_file',
'nonce': window.webpExpress['ajax-nonces']['convert'],
'filename': window.webpExpressPaths['filePaths']['webpExpressRoot'] + '/test/' + elTxt('image'),
"converter": elTxt("converter"),
'config-overrides': JSON.stringify(configOverrides)
}
//html = JSON.stringify(data);
//html = 'Converting...';
document.getElementById('tc_conversion_result').innerHTML = html;
jQuery.ajax({
method: 'POST',
url: ajaxurl,
data: data,
//dataType: 'json',
success: (response) => {
convertResponseCallback(response);
},
error: () => {
convertResponseCallback({requestError: true});
},
});
}
function processLogMoveOptions(thelog) {
var pos1 = thelog.indexOf('Options:<br>---');
if (pos1 >= 0) {
var pos2 = thelog.indexOf('<br>', pos1 + 12) + 4;
//pos2+=8;
/*if (thelog.indexOf('<br>', pos2) < 2) {
pos2 = thelog.indexOf('<br>', pos2) + 4;
}*/
var pos3 = thelog.indexOf('----<br>', pos2) + 8;
// Remove empty line after "Conversion log:"
var pos4 = thelog.indexOf('<br>', pos3);
if (pos4-pos3 < 2) {
pos3 = pos4 + 4;
}
//pos3+=4;
return thelog.substr(0, pos1) +
thelog.substr(pos3) +
//'-------------------------------------------<br>' +
'<h3>Options:</h3>' +
thelog.substr(pos2, pos3-pos2);
}
return thelog;
/*
return thelog.substr(0, pos1) +
'Click to view options' +
'<div style="display:none">' + thelog.substr(pos1, pos2-pos1) + '</div>' +
thelog.substr(pos2);
*/
}
function convertResponseCallback(response){
if (typeof response.requestError == 'boolean') {
document.getElementById('tc_conversion_result').innerHTML = '<h1 style="color:red">An error occured!</h1>';
//console.log('response', response);
return;
}
if ((response['success'] === false) && response['data']) {
document.getElementById('tc_conversion_result').innerHTML = '<h1 style="color:red">An error occured</h1>' + response['data'];
return;
}
if ((typeof response == 'string') && (response[0] != '{')) {
document.getElementById('tc_conversion_result').innerHTML =
'<h1 style="color:red">Response was not JSON</h1><p>The following was returned:</p>' + response;
return;
}
var result = JSON.parse(response);
//result['log'] = processLogMoveOptions(result['log']);
//var html = document.getElementById('tc_conversion_result').innerHTML;
var html = '';
if (result['success'] === true) {
html += '<h2>Result: <span style="color:green;margin-bottom:2px">Success</span></h2>';
// sizes
var orgSize = result['filesize-original'];
var webpSize = result['filesize-webp'];
html += '<b>Reduction: ' + Math.round((orgSize - webpSize)/orgSize * 100) + '% ';
if (orgSize < 10000) {
orgSizeStr = orgSize + ' bytes';
webpSizeStr = webpSize + ' bytes';
} else {
orgSizeStr = Math.round(orgSize / 1024) + ' K';
webpSizeStr = Math.round(webpSize / 1024) + ' K';
}
html += '(from ' + orgSizeStr.replace('K', 'kb') + ' to ' + webpSizeStr.replace('K', 'kb') + ')';
html += '</b><br><br>'
if (window.canDisplayWebp) {
var filename = document.querySelector('#tc_conversion_options [name=image]').value;
var srcUrl = '/' + window.webpExpressPaths['urls']['webpExpressRoot'] + '/test/' + filename;
//html += '<img src="/' + srcUrl + '" style="width:100%">';
// TODO: THIS DOES NOT WORK. NEEDS ATTENTION!
/*
var webpUrl = '/' + window.webpExpressPaths['urls']['content'] +
'/webp-express/webp-images/doc-root/' +
window.webpExpressPaths['filePaths']['pluginRelToDocRoot'] + '/' +
'webp-express/' +
'test/' +
filename + '.webp';
*/
//html += '<img src="' + webpUrl + '" style="width:100%">';
var webpUrl = result['destination-url'];
html += '<div class="cd-image-container">';
html += ' <div class="cd-image-label webp">WebP: ' + webpSizeStr + '</div>';
html += ' <div class="cd-image-label original">' + (filename.toLowerCase().indexOf('png') > 0 ? 'PNG' : 'JPEG') + ': ' + orgSizeStr + '</div>';
html += ' <img src="' + webpUrl + '" alt="Converted Image" style="max-width:100%">';
html += ' <div class="cd-resize-img"> <!-- the resizable image on top -->';
html += ' <img src="' + srcUrl + '" alt="Original Image">';
html += ' </div>';
html += ' <span class="cd-handle"></span> <!-- slider handle -->';
html += '</div> <!-- cd-image-container -->';
html += '<i>Drag the slider above to compare original vs webp</i><br><br>'
}
html += '<h3>Conversion log:</h3>';
// the "log" result is a simple form of markdown, using just italic, bold and newlines.
// It ought not to return anything evil, but safety first
html += '<pre style="white-space:pre-wrap">' + webpexpress_escapeHTML(result['log']) + '</pre>';
document.getElementById('tc_conversion_result').innerHTML = html;
initComparisonSlider(jQuery);
} else {
html += '<h2>Result: <span style="color:red;margin-bottom:2px">Failure</span></h2>';
if (result['msg'] != '') {
html += ' <h3>Message: <span style="color:red; font-weight: bold">' + webpexpress_escapeHTML(result['msg']) + '</span></h3>';
}
if (result['log'] != '') {
html += '<h3>Conversion log:</h3>';
html += '<pre style="white-space:pre-wrap">' + webpexpress_escapeHTML(result['log']) + '</pre>';
}
document.getElementById('tc_conversion_result').innerHTML = html;
}
//html = result['log'];
}

View File

@@ -0,0 +1,203 @@
function updateWhitelistInputValue() {
if (document.getElementById('whitelist') == null) {
console.log('document.getElementById("whitelist") returns null. Strange! Please report.');
return;
}
document.getElementById('whitelist').value = JSON.stringify(window.whitelist);
}
function whitelistStartPolling() {
jQuery.post(window.ajaxurl, {
'action': 'webpexpress_start_listening',
}, function(response) {
window.whitelistTid = window.setInterval(function() {
jQuery.post(window.ajaxurl, {
'action': 'webpexpress_get_request',
}, function(response) {
if (response && (response.substr(0,1) == '{')) {
var r = JSON.parse(response);
window.webpexpress_incoming_request = r;
//console.log(r);
window.clearInterval(window.whitelistTid);
closeDasPopup();
// Show request
openDasPopup('whitelist_accept_request', 300, 200);
var s = '';
s += 'Website: ' + r['label'] + '<br>';
s += 'IP: ' + r['ip'] + '<br>';
document.getElementById('request_details').innerHTML = s;
} else {
console.log('Got this from the server: ' + response);
}
}
);
}, 2000);
}
);
}
function whitelistCancelListening() {
/*
jQuery.post(window.ajaxurl, {
'action': 'webpexpress_stop_listening',
}, function(response) {}
);
*/
}
function whitelistCreateUid() {
var timestamp = (new Date()).getTime();
var randomNumber = Math.floor(Math.random() * 10000);
return (timestamp * 10000 + randomNumber).toString(36);
}
/*
function whitelistAcceptRequest() {
whitelistCancelListening();
closeDasPopup();
var r = window.webpexpress_incoming_request;
window.whitelist.push({
uid: whitelistCreateUid(),
label: r['label'],
'new-api-key': r['api-key'],
ip: r['ip'],
// new_password: '',
//quota: 60
});
updateWhitelistInputValue();
whitelistSetHTML();
}
function whitelistDenyRequest() {
whitelistCancelListening();
closeDasPopup();
}*/
function whitelistAddSite() {
whitelistStartPolling();
openDasPopup('whitelist_listen_popup', 400, 300);
}
function whitelistRemoveEntry(i) {
window.whitelist.splice(i, 1);
whitelistSetHTML();
}
function whitelistSetHTML() {
updateWhitelistInputValue();
var s = '';
if (window.whitelist && window.whitelist.length > 0) {
s+='<br><i>Authorized web sites:</i>';
s+='<ul>';
for (var i=0; i<window.whitelist.length; i++) {
s+='<li>';
s+= webpexpress_escapeHTML(window.whitelist[i]['label']);
s+='<div class="whitelist-links">'
s+='<a href="javascript:whitelistEditEntry(' + i + ')">edit</a>';
s+='<a href="javascript:whitelistRemoveEntry(' + i + ')">remove</a>';
s+='</div>'
s+='</li>';
}
s+='</ul>';
} else {
s+='<p style="margin:12px 0"><i>No sites have been authorized to use the web service yet.</i></p>';
}
s+='<button type="button" class="button button-secondary" id="server_listen_btn" onclick="whitelistAddManually()">+ Authorize website</button>';
document.getElementById('whitelist_div').innerHTML = s;
}
function whitelistClearWhitelistEntryForm() {
document.getElementById('whitelist_label').value = '';
document.getElementById('whitelist_ip').value = '';
document.getElementById('whitelist_api_key').value = '';
document.getElementById('whitelist_require_api_key_to_be_crypted_in_transfer').checked = true;
}
function whitelistAddWhitelistEntry() {
if (document.getElementById('whitelist_label').value == '') {
alert('Label must be filled out');
return;
}
if (document.getElementById('whitelist_ip').value == '') {
alert('IP must be filled out. To allow any IP, enter "*"');
return;
}
// TODO: Validate IP syntax
if (document.getElementById('whitelist_api_key').value == '') {
alert('API key must be filled in');
return;
}
window.whitelist.push({
uid: whitelistCreateUid(),
label: document.getElementById('whitelist_label').value,
ip: document.getElementById('whitelist_ip').value,
'new-api-key': document.getElementById('whitelist_api_key').value,
'require-api-key-to-be-crypted-in-transfer': document.getElementById('whitelist_require_api_key_to_be_crypted_in_transfer').checked,
// new_password: '',
//quota: 60
});
updateWhitelistInputValue();
whitelistSetHTML();
closeDasPopup();
}
function whitelistAddManually() {
// alert('not implemented yet');
whitelistClearWhitelistEntryForm();
document.getElementById('whitelist_properties_popup').className = 'das-popup mode-add';
// whitelistCancelListening();
// closeDasPopup();
openDasPopup('whitelist_properties_popup', 400, 300);
}
function whitelistChangeApiKey() {
document.getElementById('whitelist_api_key').value = prompt('Enter new api key');
}
function whitelistUpdateWhitelistEntry() {
var i = parseInt(document.getElementById('whitelist_i').value, 10);
window.whitelist[i]['uid'] = document.getElementById('whitelist_uid').value;
window.whitelist[i]['label'] = document.getElementById('whitelist_label').value;
window.whitelist[i]['ip'] = document.getElementById('whitelist_ip').value;
if (document.getElementById('whitelist_api_key').value != '') {
window.whitelist[i]['new-api-key'] = document.getElementById('whitelist_api_key').value;
}
window.whitelist[i]['require-api-key-to-be-crypted-in-transfer'] = document.getElementById('whitelist_require_api_key_to_be_crypted_in_transfer').checked;
whitelistSetHTML();
closeDasPopup();
}
function whitelistEditEntry(i) {
var entry = window.whitelist[i];
whitelistClearWhitelistEntryForm();
document.getElementById('whitelist_properties_popup').className = 'das-popup mode-edit';
document.getElementById('whitelist_uid').value = entry['uid'];
document.getElementById('whitelist_i').value = i;
document.getElementById('whitelist_label').value = entry['label'];
document.getElementById('whitelist_ip').value = entry['ip'];
document.getElementById('whitelist_api_key').value = '';
document.getElementById('whitelist_require_api_key_to_be_crypted_in_transfer').checked = entry['require-api-key-to-be-crypted-in-transfer'];
openDasPopup('whitelist_properties_popup', 400, 300);
}
document.addEventListener('DOMContentLoaded', function() {
updateWhitelistInputValue();
whitelistSetHTML();
});