Update API

This commit is contained in:
Hoang Huu 2019-10-12 09:42:33 +07:00
parent 68b955cdde
commit e7b240ef66
16 changed files with 1771 additions and 118 deletions

View File

@ -0,0 +1,619 @@
/*!
* jQuery blockUI plugin
* Version 2.70.0-2014.11.23
* Requires jQuery v1.7 or later
*
* Examples at: http://malsup.com/jquery/block/
* Copyright (c) 2007-2013 M. Alsup
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Thanks to Amir-Hossein Sobhi for some excellent contributions!
*/
;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";
function setup($) {
$.fn._fadeIn = $.fn.fadeIn;
var noOp = $.noop || function() {};
// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// confusing userAgent strings on Vista)
var msie = /MSIE/.test(navigator.userAgent);
var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
var mode = document.documentMode || 0;
var setExpr = $.isFunction( document.createElement('div').style.setExpression );
// global $ methods for blocking/unblocking the entire page
$.blockUI = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };
// convenience method for quick growl-like notifications (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
var $m = $('<div class="growlUI"></div>');
if (title) $m.append('<h1>'+title+'</h1>');
if (message) $m.append('<h2>'+message+'</h2>');
if (timeout === undefined) timeout = 3000;
// Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications
var callBlock = function(opts) {
opts = opts || {};
$.blockUI({
message: $m,
fadeIn : typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700,
fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
centerY: false,
showOverlay: false,
onUnblock: onClose,
css: $.blockUI.defaults.growlCSS
});
};
callBlock();
var nonmousedOpacity = $m.css('opacity');
$m.mouseover(function() {
callBlock({
fadeIn: 0,
timeout: 30000
});
var displayBlock = $('.blockMsg');
displayBlock.stop(); // cancel fadeout if it has started
displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency
}).mouseout(function() {
$('.blockMsg').fadeOut(1000);
});
// End konapun additions
};
// plugin method for blocking element content
$.fn.block = function(opts) {
if ( this[0] === window ) {
$.blockUI( opts );
return this;
}
var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
this.each(function() {
var $el = $(this);
if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
return;
$el.unblock({ fadeOut: 0 });
});
return this.each(function() {
if ($.css(this,'position') == 'static') {
this.style.position = 'relative';
$(this).data('blockUI.static', true);
}
this.style.zoom = 1; // force 'hasLayout' in ie
install(this, opts);
});
};
// plugin method for unblocking element content
$.fn.unblock = function(opts) {
if ( this[0] === window ) {
$.unblockUI( opts );
return this;
}
return this.each(function() {
remove(this, opts);
});
};
$.blockUI.version = 2.70; // 2nd generation blocking at no extra cost!
// override these in your code to change the default behavior and style
$.blockUI.defaults = {
// message displayed when blocking (use null for no message)
message: '<h1>Please wait...</h1>',
title: null, // title string; only used when theme == true
draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded)
theme: false, // set to true to use with jQuery UI themes
// styles for the message when blocking; if you wish to disable
// these and use an external stylesheet then do this in your code:
// $.blockUI.defaults.css = {};
css: {
padding: 0,
margin: 0,
width: '30%',
top: '40%',
left: '35%',
textAlign: 'center',
color: '#000',
border: '3px solid #aaa',
backgroundColor:'#fff',
cursor: 'wait'
},
// minimal style set used when themes are used
themedCSS: {
width: '30%',
top: '40%',
left: '35%'
},
// styles for the overlay
overlayCSS: {
backgroundColor: '#000',
opacity: 0.6,
cursor: 'wait'
},
// style to replace wait cursor before unblocking to correct issue
// of lingering wait cursor
cursorReset: 'default',
// styles applied when using $.growlUI
growlCSS: {
width: '350px',
top: '10px',
left: '',
right: '10px',
border: 'none',
padding: '5px',
opacity: 0.6,
cursor: 'default',
color: '#fff',
backgroundColor: '#000',
'-webkit-border-radius':'10px',
'-moz-border-radius': '10px',
'border-radius': '10px'
},
// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
// (hat tip to Jorge H. N. de Vasconcelos)
/*jshint scripturl:true */
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
// force usage of iframe in non-IE browsers (handy for blocking applets)
forceIframe: false,
// z-index for the blocking overlay
baseZ: 1000,
// set these to true to have the message automatically centered
centerX: true, // <-- only effects element blocking (page block controlled via css above)
centerY: true,
// allow body element to be stetched in ie6; this makes blocking look better
// on "short" pages. disable if you wish to prevent changes to the body height
allowBodyStretch: true,
// enable if you want key and mouse events to be disabled for content that is blocked
bindEvents: true,
// be default blockUI will supress tab navigation from leaving blocking content
// (if bindEvents is true)
constrainTabKey: true,
// fadeIn time in millis; set to 0 to disable fadeIn on block
fadeIn: 200,
// fadeOut time in millis; set to 0 to disable fadeOut on unblock
fadeOut: 400,
// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
timeout: 0,
// disable if you don't want to show the overlay
showOverlay: true,
// if true, focus will be placed in the first available input field when
// page blocking
focusInput: true,
// elements that can receive focus
focusableElements: ':input:enabled:visible',
// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
// no longer needed in 2012
// applyPlatformOpacityRules: true,
// callback method invoked when fadeIn has completed and blocking message is visible
onBlock: null,
// callback method invoked when unblocking has completed; the callback is
// passed the element that has been unblocked (which is the window object for page
// blocks) and the options that were passed to the unblock call:
// onUnblock(element, options)
onUnblock: null,
// callback method invoked when the overlay area is clicked.
// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
onOverlayClick: null,
// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
quirksmodeOffsetHack: 4,
// class name of the message block
blockMsgClass: 'blockMsg',
// if it is already blocked, then ignore it (don't unblock and reblock)
ignoreIfBlocked: false
};
// private data and functions follow...
var pageBlock = null;
var pageBlockEls = [];
function install(el, opts) {
var css, themedCSS;
var full = (el == window);
var msg = (opts && opts.message !== undefined ? opts.message : undefined);
opts = $.extend({}, $.blockUI.defaults, opts || {});
if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
return;
opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
if (opts.onOverlayClick)
opts.overlayCSS.cursor = 'pointer';
themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
msg = msg === undefined ? opts.message : msg;
// remove the current block (if there is one)
if (full && pageBlock)
remove(window, {fadeOut:0});
// if an existing element is being used as the blocking content then we capture
// its current place in the DOM (and current display style) so we can restore
// it when we unblock
if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
var node = msg.jquery ? msg[0] : msg;
var data = {};
$(el).data('blockUI.history', data);
data.el = node;
data.parent = node.parentNode;
data.display = node.style.display;
data.position = node.style.position;
if (data.parent)
data.parent.removeChild(node);
}
$(el).data('blockUI.onUnblock', opts.onUnblock);
var z = opts.baseZ;
// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
// layer1 is the iframe layer which is used to supress bleed through of underlying content
// layer2 is the overlay layer which has opacity and a wait cursor (by default)
// layer3 is the message content that is displayed while blocking
var lyr1, lyr2, lyr3, s;
if (msie || opts.forceIframe)
lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
else
lyr1 = $('<div class="blockUI" style="display:none"></div>');
if (opts.theme)
lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
else
lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
if (opts.theme && full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (opts.theme) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
}
else {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
}
lyr3 = $(s);
// if we have a message, style it
if (msg) {
if (opts.theme) {
lyr3.css(themedCSS);
lyr3.addClass('ui-widget-content');
}
else
lyr3.css(css);
}
// style the overlay
if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
lyr2.css(opts.overlayCSS);
lyr2.css('position', full ? 'fixed' : 'absolute');
// make iframe layer transparent in IE
if (msie || opts.forceIframe)
lyr1.css('opacity',0.0);
//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
$.each(layers, function() {
this.appendTo($par);
});
if (opts.theme && opts.draggable && $.fn.draggable) {
lyr3.draggable({
handle: '.ui-dialog-titlebar',
cancel: 'li'
});
}
// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
if (ie6 || expr) {
// give body 100% height
if (full && opts.allowBodyStretch && $.support.boxModel)
$('html,body').css('height','100%');
// fix ie6 issue when blocked element has a border width
if ((ie6 || !$.support.boxModel) && !full) {
var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
var fixT = t ? '(0 - '+t+')' : 0;
var fixL = l ? '(0 - '+l+')' : 0;
}
// simulate fixed position
$.each(layers, function(i,o) {
var s = o[0].style;
s.position = 'absolute';
if (i < 2) {
if (full)
s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
else
s.setExpression('height','this.parentNode.offsetHeight + "px"');
if (full)
s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
else
s.setExpression('width','this.parentNode.offsetWidth + "px"');
if (fixL) s.setExpression('left', fixL);
if (fixT) s.setExpression('top', fixT);
}
else if (opts.centerY) {
if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
s.marginTop = 0;
}
else if (!opts.centerY && full) {
var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
s.setExpression('top',expression);
}
});
}
// show the message
if (msg) {
if (opts.theme)
lyr3.find('.ui-widget-content').append(msg);
else
lyr3.append(msg);
if (msg.jquery || msg.nodeType)
$(msg).show();
}
if ((msie || opts.forceIframe) && opts.showOverlay)
lyr1.show(); // opacity is zero
if (opts.fadeIn) {
var cb = opts.onBlock ? opts.onBlock : noOp;
var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
var cb2 = msg ? cb : noOp;
if (opts.showOverlay)
lyr2._fadeIn(opts.fadeIn, cb1);
if (msg)
lyr3._fadeIn(opts.fadeIn, cb2);
}
else {
if (opts.showOverlay)
lyr2.show();
if (msg)
lyr3.show();
if (opts.onBlock)
opts.onBlock.bind(lyr3)();
}
// bind key and mouse events
bind(1, el, opts);
if (full) {
pageBlock = lyr3[0];
pageBlockEls = $(opts.focusableElements,pageBlock);
if (opts.focusInput)
setTimeout(focus, 20);
}
else
center(lyr3[0], opts.centerX, opts.centerY);
if (opts.timeout) {
// auto-unblock
var to = setTimeout(function() {
if (full)
$.unblockUI(opts);
else
$(el).unblock(opts);
}, opts.timeout);
$(el).data('blockUI.timeout', to);
}
}
// remove the block
function remove(el, opts) {
var count;
var full = (el == window);
var $el = $(el);
var data = $el.data('blockUI.history');
var to = $el.data('blockUI.timeout');
if (to) {
clearTimeout(to);
$el.removeData('blockUI.timeout');
}
opts = $.extend({}, $.blockUI.defaults, opts || {});
bind(0, el, opts); // unbind events
if (opts.onUnblock === null) {
opts.onUnblock = $el.data('blockUI.onUnblock');
$el.removeData('blockUI.onUnblock');
}
var els;
if (full) // crazy selector to handle odd field errors in ie6/7
els = $(document.body).children().filter('.blockUI').add('body > .blockUI');
else
els = $el.find('>.blockUI');
// fix cursor issue
if ( opts.cursorReset ) {
if ( els.length > 1 )
els[1].style.cursor = opts.cursorReset;
if ( els.length > 2 )
els[2].style.cursor = opts.cursorReset;
}
if (full)
pageBlock = pageBlockEls = null;
if (opts.fadeOut) {
count = els.length;
els.stop().fadeOut(opts.fadeOut, function() {
if ( --count === 0)
reset(els,data,opts,el);
});
}
else
reset(els, data, opts, el);
}
// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
var $el = $(el);
if ( $el.data('blockUI.isBlocked') )
return;
els.each(function(i,o) {
// remove via DOM calls so we don't lose event handlers
if (this.parentNode)
this.parentNode.removeChild(this);
});
if (data && data.el) {
data.el.style.display = data.display;
data.el.style.position = data.position;
data.el.style.cursor = 'default'; // #59
if (data.parent)
data.parent.appendChild(data.el);
$el.removeData('blockUI.history');
}
if ($el.data('blockUI.static')) {
$el.css('position', 'static'); // #22
}
if (typeof opts.onUnblock == 'function')
opts.onUnblock(el,opts);
// fix issue in Safari 6 where block artifacts remain until reflow
var body = $(document.body), w = body.width(), cssW = body[0].style.width;
body.width(w-1).width(w);
body[0].style.width = cssW;
}
// bind/unbind the handler
function bind(b, el, opts) {
var full = el == window, $el = $(el);
// don't bother unbinding if there is nothing to unbind
if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
return;
$el.data('blockUI.isBlocked', b);
// don't bind events when overlay is not in use or if bindEvents is false
if (!full || !opts.bindEvents || (b && !opts.showOverlay))
return;
// bind anchors and inputs for mouse and key events
var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
if (b)
$(document).bind(events, opts, handler);
else
$(document).unbind(events, handler);
// former impl...
// var $e = $('a,:input');
// b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
}
// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
// allow tab navigation (conditionally)
if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
if (pageBlock && e.data.constrainTabKey) {
var els = pageBlockEls;
var fwd = !e.shiftKey && e.target === els[els.length-1];
var back = e.shiftKey && e.target === els[0];
if (fwd || back) {
setTimeout(function(){focus(back);},10);
return false;
}
}
}
var opts = e.data;
var target = $(e.target);
if (target.hasClass('blockOverlay') && opts.onOverlayClick)
opts.onOverlayClick(e);
// allow events within the message content
if (target.parents('div.' + opts.blockMsgClass).length > 0)
return true;
// allow events for content that is not being blocked
return target.parents().children().filter('div.blockUI').length === 0;
}
function focus(back) {
if (!pageBlockEls)
return;
var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
if (e)
e.focus();
}
function center(el, x, y) {
var p = el.parentNode, s = el.style;
var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
if (x) s.left = l > 0 ? (l+'px') : '0';
if (y) s.top = t > 0 ? (t+'px') : '0';
}
function sz(el, p) {
return parseInt($.css(el,p),10)||0;
}
}
/*global define:true */
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
define(['jquery'], setup);
} else {
setup(jQuery);
}
})();

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,36 @@
/**
* Simple text copy functions using native browser clipboard capabilities.
* @since 3.2.0
*/
/**
* Set the user's clipboard contents.
*
* @param string data: Text to copy to clipboard.
* @param object $el: jQuery element to trigger copy events on. (Default: document)
*/
function opalSetClipboard( data, $el ) {
if ( 'undefined' === typeof $el ) {
$el = jQuery( document );
}
var $temp_input = jQuery( '<textarea style="opacity:0">' );
jQuery( 'body' ).append( $temp_input );
$temp_input.val( data ).select();
$el.trigger( 'beforecopy' );
try {
document.execCommand( 'copy' );
$el.trigger( 'aftercopy' );
} catch ( err ) {
$el.trigger( 'aftercopyfailure' );
}
$temp_input.remove();
}
/**
* Clear the user's clipboard.
*/
function opalClearClipboard() {
opalSetClipboard( '' );
}

View File

@ -40,6 +40,7 @@ jQuery(document).ready(function($){
load_select2_member( '#opalestate_ppt_agent', 'opalestate_search_agents' ); load_select2_member( '#opalestate_ppt_agent', 'opalestate_search_agents' );
load_select2_member( '#opalestate_ppt_agency', 'opalestate_search_agencies' ); load_select2_member( '#opalestate_ppt_agency', 'opalestate_search_agencies' );
load_select2_member( '#p-assignment #post_author_override', 'opalestate_search_property_users' ); load_select2_member( '#p-assignment #post_author_override', 'opalestate_search_property_users' );
load_select2_member( '.opalestate-customer-search', 'opalestate_search_property_users' );
function formatRepo (repo) { function formatRepo (repo) {
if ( repo.loading ) { if ( repo.loading ) {

141
assets/js/api-keys.js Normal file
View File

@ -0,0 +1,141 @@
/*global jQuery, Backbone, _, opalestate_admin_api_keys, opalSetClipboard, opalClearClipboard */
(function( $ ) {
var APIView = Backbone.View.extend({
/**
* Element
*
* @param {Object} '#key-fields'
*/
el: $( '#key-fields' ),
/**
* Events
*
* @type {Object}
*/
events: {
'click input#update_api_key': 'saveKey'
},
/**
* Initialize actions
*/
initialize: function(){
_.bindAll( this, 'saveKey' );
},
/**
* Init jQuery.BlockUI
*/
block: function() {
$( this.el ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
/**
* Remove jQuery.BlockUI
*/
unblock: function() {
$( this.el ).unblock();
},
/**
* Init TipTip
*/
initTipTip: function( css_class ) {
$( document.body )
.on( 'click', css_class, function( evt ) {
evt.preventDefault();
if ( ! document.queryCommandSupported( 'copy' ) ) {
$( css_class ).parent().find( 'input' ).focus().select();
$( '#copy-error' ).text( opalestate_admin_api_keys.clipboard_failed );
} else {
$( '#copy-error' ).text( '' );
opalClearClipboard();
opalSetClipboard( $.trim( $( this ).prev( 'input' ).val() ), $( css_class ) );
}
} )
.on( 'aftercopy', css_class, function() {
$( '#copy-error' ).text( '' );
$( css_class ).tipTip( {
'attribute': 'data-tip',
'activation': 'focus',
'fadeIn': 50,
'fadeOut': 50,
'delay': 0
} ).focus();
} )
.on( 'aftercopyerror', css_class, function() {
$( css_class ).parent().find( 'input' ).focus().select();
$( '#copy-error' ).text( opalestate_admin_api_keys.clipboard_failed );
} );
},
/**
* Save API Key using ajax
*
* @param {Object} e
*/
saveKey: function( e ) {
e.preventDefault();
var self = this;
self.block();
Backbone.ajax({
method: 'POST',
dataType: 'json',
url: opalestate_admin_api_keys.ajax_url,
data: {
action: 'opalestate_update_api_key',
security: opalestate_admin_api_keys.update_api_nonce,
key_id: $( '#key_id', self.el ).val(),
description: $( '#key_description', self.el ).val(),
user: $( '#key_user', self.el ).val(),
permissions: $( '#key_permissions', self.el ).val()
},
success: function( response ) {
$( '.wc-api-message', self.el ).remove();
if ( response.success ) {
var data = response.data;
$( 'h2, h3', self.el ).first().append( '<div class="wc-api-message updated"><p>' + data.message + '</p></div>' );
if ( 0 < data.consumer_key.length && 0 < data.consumer_secret.length ) {
$( '#api-keys-options', self.el ).remove();
$( 'p.submit', self.el ).empty().append( data.revoke_url );
var template = wp.template( 'api-keys-template' );
$( 'p.submit', self.el ).before( template({
consumer_key: data.consumer_key,
consumer_secret: data.consumer_secret
}) );
self.initTipTip( '.copy-key' );
self.initTipTip( '.copy-secret' );
} else {
$( '#key_description', self.el ).val( data.description );
$( '#key_user', self.el ).val( data.user_id );
$( '#key_permissions', self.el ).val( data.permissions );
}
} else {
$( 'h2, h3', self.el ).first().append( '<div class="wc-api-message error"><p>' + response.data.message + '</p></div>' );
}
self.unblock();
}
});
}
});
new APIView();
})( jQuery );

View File

@ -33,14 +33,35 @@ class Opalestate_Admin {
* enqueue editor.js for edit mode * enqueue editor.js for edit mode
*/ */
public function enqueue_scripts() { public function enqueue_scripts() {
$screen = get_current_screen();
$screen_id = $screen ? $screen->id : '';
wp_enqueue_style( 'opalestate-admin', OPALESTATE_PLUGIN_URL . 'assets/admin.css', [], '3.0.3' ); wp_enqueue_style( 'opalestate-admin', OPALESTATE_PLUGIN_URL . 'assets/admin.css', [], '3.0.3' );
$suffix = ''; $suffix = '';
wp_enqueue_style( 'select2', OPALESTATE_PLUGIN_URL . 'assets/3rd/select2/css/select2.min.css', null, '1.3' ); wp_enqueue_style( 'select2', OPALESTATE_PLUGIN_URL . 'assets/3rd/select2/css/select2.min.css', null, '1.3' );
wp_enqueue_script( 'select2', OPALESTATE_PLUGIN_URL . 'assets/3rd/select2/js/select2.min.js', null, '1.3', true ); wp_enqueue_script( 'select2', OPALESTATE_PLUGIN_URL . 'assets/3rd/select2/js/select2.min.js', null, '1.3', true );
wp_enqueue_script( 'opalestate-country-select', OPALESTATE_PLUGIN_URL . 'assets/js/country-select.js', [ 'jquery' ], null, true ); wp_enqueue_script( 'opalestate-country-select', OPALESTATE_PLUGIN_URL . 'assets/js/country-select.js', [ 'jquery' ], OPALESTATE_VERSION, true );
wp_enqueue_script( 'opalestate-admin', OPALESTATE_PLUGIN_URL . 'assets/js/admin' . $suffix . '.js', [ 'jquery' ], null, true ); wp_enqueue_script( 'opalestate-admin', OPALESTATE_PLUGIN_URL . 'assets/js/admin' . $suffix . '.js', [ 'jquery' ], OPALESTATE_VERSION, true );
wp_register_script( 'jquery-blockui', OPALESTATE_PLUGIN_URL . 'assets/3rd/jquery-blockui/jquery.blockUI' . $suffix . '.js', array( 'jquery' ), '2.70', true );
wp_register_script( 'opal-clipboard', OPALESTATE_PLUGIN_URL . 'assets/3rd/opal-clipboard.js', array( 'jquery' ), OPALESTATE_VERSION, true );
// API settings.
if ( 'opalestate_property_page_opalestate-settings' === $screen_id && isset( $_GET['tab'] ) && 'api_keys' == $_GET['tab'] ) {
wp_register_script( 'opalestate-api-keys', OPALESTATE_PLUGIN_URL . 'assets/js/api-keys' . $suffix . '.js', array( 'jquery', 'opalestate-admin', 'underscore', 'backbone', 'wp-util', 'jquery-blockui', 'opal-clipboard' ),
OPALESTATE_VERSION, true );
wp_enqueue_script( 'opalestate-api-keys' );
wp_localize_script(
'opalestate-api-keys',
'opalestate_admin_api_keys',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'update_api_nonce' => wp_create_nonce( 'update-api-key' ),
'clipboard_failed' => esc_html__( 'Copying to clipboard failed. Please press Ctrl/Cmd+C to copy.', 'opalestate-pro' ),
)
);
}
} }
/** /**
@ -67,11 +88,8 @@ class Opalestate_Admin {
'settings/property.php', 'settings/property.php',
] ); ] );
//
// Get it started // Get it started
$Opalestate_Settings = new Opalestate_Plugin_Settings(); $Opalestate_Settings = new Opalestate_Plugin_Settings();
} }
/** /**

View File

@ -338,56 +338,6 @@ if ( ! function_exists( 'opalestate_license_key_callback' ) ) {
} }
} }
/**
* Display the API Keys
*
* @return void
* @since 2.0
*/
function opalestate_api_keys_callback() {
if ( ! current_user_can( 'manage_opalestate_settings' ) ) {
return;
}
do_action( 'opalestate_tools_api_keys_keys_before' );
require_once OPALESTATE_PLUGIN_DIR . 'inc/admin/class-api-keys-table.php';
$keys_table_list = new Opalestate_API_Keys_Table();
$keys_table_list->prepare_items();
echo '<input type="hidden" name="page" value="wc-settings" />';
echo '<input type="hidden" name="tab" value="api" />';
echo '<input type="hidden" name="section" value="keys" />';
$keys_table_list->views();
$keys_table_list->search_box( esc_html__( 'Search Key', 'opalestate-pro' ), 'key' );
$keys_table_list->display();
?>
<p>
<?php printf(
__( 'API keys allow users to use the <a href="%s">Opalestate REST API</a> to retrieve donation data in JSON or XML for external applications or devices, such as <a href="%s">Zapi_keyser</a>.',
'opalestate-pro' ),
'https://wpopal.com/opalestate/documentation/opalestate-api_keys-reference/',
'https://wpopal.com/addons/opalestate/'
); ?>
</p>
<style>
.opalestate_properties_page_opalestate-settings .opalestate-submit-wrap {
display: none; /* Hide Save settings button on System Info Tab (not needed) */
}
</style>
<?php
do_action( 'opalestate_tools_api_keys_keys_after' );
}
add_action( 'opalestate_settings_tab_api_keys_keys', 'opalestate_api_keys_callback' );
/** /**
* Hook Callback * Hook Callback
* *

View File

@ -46,9 +46,10 @@ class Opalestate_Plugin_Settings {
*/ */
protected $options_page = ''; protected $options_page = '';
protected $subtabs = array(); protected $subtabs = [];
protected $setting_object = [];
protected $setting_object = array();
/** /**
* Constructor * Constructor
* *
@ -67,23 +68,32 @@ class Opalestate_Plugin_Settings {
// add_action( 'cmb2_render_license_key', 'opalestate_license_key_callback', 10, 5 ); // add_action( 'cmb2_render_license_key', 'opalestate_license_key_callback', 10, 5 );
add_action( "cmb2_save_options-page_fields", [ $this, 'settings_notices' ], 10, 3 ); add_action( "cmb2_save_options-page_fields", [ $this, 'settings_notices' ], 10, 3 );
add_action( 'cmb2_render_api_keys', 'opalestate_api_keys_callback', 10, 5 );
// Include CMB CSS in the head to avoid FOUC // Include CMB CSS in the head to avoid FOUC
add_action( "admin_print_styles-opalestate_properties_page_opalestate-settings", [ 'CMB2_hookup', 'enqueue_cmb_css' ] ); add_action( "admin_print_styles-opalestate_properties_page_opalestate-settings", [ 'CMB2_hookup', 'enqueue_cmb_css' ] );
} }
public function admin_menu() { public function admin_menu() {
// Settings // Settings
$opalestate_settings_page = add_submenu_page( 'edit.php?post_type=opalestate_property', esc_html__( 'Settings', 'opalestate-pro' ), esc_html__( 'Settings', 'opalestate-pro' ), 'manage_opalestate_settings', $opalestate_settings_page = add_submenu_page(
'edit.php?post_type=opalestate_property',
esc_html__( 'Opalestate Settings', 'opalestate-pro' ),
esc_html__( 'Settings', 'opalestate-pro' ),
'manage_opalestate_settings',
'opalestate-settings', 'opalestate-settings',
[ $this, 'admin_page_display' ] ); [ $this, 'admin_page_display' ] );
// addons setting do_action( 'load-' . $opalestate_settings_page, $this );
$opalestate_settings_page = add_submenu_page( 'edit.php?post_type=opalestate_property', esc_html__( 'Addons', 'opalestate-pro' ), esc_html__( 'Addons', 'opalestate-pro' ), 'manage_options', 'opalestate-addons',
// Addons
$opalestate_addons_page = add_submenu_page(
'edit.php?post_type=opalestate_property',
esc_html__( 'Opalestate Addons', 'opalestate-pro' ),
esc_html__( 'Addons', 'opalestate-pro' ),
'manage_options',
'opalestate-addons',
[ $this, 'admin_addons_page_display' ] ); [ $this, 'admin_addons_page_display' ] );
do_action( 'load-' . $opalestate_addons_page, $this );
} }
/** /**
@ -93,7 +103,6 @@ class Opalestate_Plugin_Settings {
*/ */
public function init() { public function init() {
register_setting( $this->key, $this->key ); register_setting( $this->key, $this->key );
} }
/** /**
@ -133,11 +142,12 @@ class Opalestate_Plugin_Settings {
$tab_url = esc_url( add_query_arg( [ $tab_url = esc_url( add_query_arg( [
'settings-updated' => false, 'settings-updated' => false,
'tab' => $tab_id, 'tab' => $tab_id,
'subtab' => $stab_id 'subtab' => $stab_id,
] ) ); ] ) );
return $tab_url; return $tab_url;
} }
/** /**
* Admin page markup. Mostly handled by CMB2 * Admin page markup. Mostly handled by CMB2
* *
@ -150,7 +160,7 @@ class Opalestate_Plugin_Settings {
$sub_active_tab = isset( $_GET['subtab'] ) ? sanitize_text_field( $_GET['subtab'] ) : ''; $sub_active_tab = isset( $_GET['subtab'] ) ? sanitize_text_field( $_GET['subtab'] ) : '';
$tabs_fields = $this->opalestate_settings( $active_tab ); $tabs_fields = $this->opalestate_settings( $active_tab );
$sub_tabs_fields = array(); $sub_tabs_fields = [];
if ( empty( $sub_active_tab ) && $this->subtabs ) { if ( empty( $sub_active_tab ) && $this->subtabs ) {
$first = array_flip( $this->subtabs ); $first = array_flip( $this->subtabs );
@ -166,12 +176,11 @@ class Opalestate_Plugin_Settings {
<h2 class="nav-tab-wrapper"> <h2 class="nav-tab-wrapper">
<?php <?php
foreach ( $this->opalestate_get_settings_tabs() as $tab_id => $tab_name ) { foreach ( $this->opalestate_get_settings_tabs() as $tab_id => $tab_name ) {
$tab_url = esc_url( add_query_arg( [ $tab_url = esc_url( add_query_arg( [
'settings-updated' => false, 'settings-updated' => false,
'tab' => $tab_id, 'tab' => $tab_id,
'subtab' => false 'subtab' => false,
] ) ); ], admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings' ) ) );
$active = $active_tab == $tab_id ? ' nav-tab-active' : ''; $active = $active_tab == $tab_id ? ' nav-tab-active' : '';
@ -230,8 +239,8 @@ class Opalestate_Plugin_Settings {
'numberposts' => -1, 'numberposts' => -1,
] ); ] );
$general = array(); $general = [];
$opalestate_settings = array(); $opalestate_settings = [];
//Return all settings array if necessary //Return all settings array if necessary
@ -251,8 +260,10 @@ class Opalestate_Plugin_Settings {
return $tab->get_tab_content( $this->key ); return $tab->get_tab_content( $this->key );
} }
return array( $active_tab => array() );
return [ $active_tab => [] ];
} }
// Add other tabs and settings fields as needed // Add other tabs and settings fields as needed
return $output; return $output;

View File

@ -299,3 +299,105 @@ function opalestate_get_agent_property() {
wp_reset_postdata(); wp_reset_postdata();
exit; exit;
} }
function opalestate_update_api_key() {
ob_start();
global $wpdb;
check_ajax_referer( 'update-api-key', 'security' );
if ( ! current_user_can( 'manage_opalestate_settings' ) ) {
wp_die( -1 );
}
$response = [];
try {
if ( empty( $_POST['description'] ) ) {
throw new Exception( __( 'Description is missing.', 'opalestate-pro' ) );
}
if ( empty( $_POST['user'] ) ) {
throw new Exception( __( 'User is missing.', 'opalestate-pro' ) );
}
if ( empty( $_POST['permissions'] ) ) {
throw new Exception( __( 'Permissions is missing.', 'opalestate-pro' ) );
}
$key_id = isset( $_POST['key_id'] ) ? absint( $_POST['key_id'] ) : 0;
$description = sanitize_text_field( wp_unslash( $_POST['description'] ) );
$permissions = ( in_array( wp_unslash( $_POST['permissions'] ), [ 'read', 'write', 'read_write' ], true ) ) ? sanitize_text_field( wp_unslash( $_POST['permissions'] ) ) : 'read';
$user_id = absint( $_POST['user'] );
// Check if current user can edit other users.
if ( $user_id && ! current_user_can( 'edit_user', $user_id ) ) {
if ( get_current_user_id() !== $user_id ) {
throw new Exception( __( 'You do not have permission to assign API Keys to the selected user.', 'opalestate-pro' ) );
}
}
if ( 0 < $key_id ) {
$data = [
'user_id' => $user_id,
'description' => $description,
'permissions' => $permissions,
];
$wpdb->update(
$wpdb->prefix . 'opalestate_api_keys',
$data,
[ 'key_id' => $key_id ],
[
'%d',
'%s',
'%s',
],
[ '%d' ]
);
$response = $data;
$response['consumer_key'] = '';
$response['consumer_secret'] = '';
$response['message'] = __( 'API Key updated successfully.', 'opalestate-pro' );
} else {
$consumer_key = 'ck_' . wc_rand_hash();
$consumer_secret = 'cs_' . wc_rand_hash();
$data = [
'user_id' => $user_id,
'description' => $description,
'permissions' => $permissions,
'consumer_key' => wc_api_hash( $consumer_key ),
'consumer_secret' => $consumer_secret,
'truncated_key' => substr( $consumer_key, -7 ),
];
$wpdb->insert(
$wpdb->prefix . 'opalestate_api_keys',
$data,
[
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
]
);
$key_id = $wpdb->insert_id;
$response = $data;
$response['consumer_key'] = $consumer_key;
$response['consumer_secret'] = $consumer_secret;
$response['message'] = __( 'API Key generated successfully. Make sure to copy your new keys now as the secret key will be hidden once you leave this page.', 'opalestate-pro' );
$response['revoke_url'] = '<a style="color: #a00; text-decoration: none;" href="' . esc_url( wp_nonce_url( add_query_arg( [ 'revoke-key' => $key_id ],
admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys' ) ), 'revoke' ) ) . '">' . __( 'Revoke key', 'opalestate-pro' ) . '</a>';
}
} catch ( Exception $e ) {
wp_send_json_error( [ 'message' => $e->getMessage() ] );
}
// wp_send_json_success must be outside the try block not to break phpunit tests.
wp_send_json_success( $response );
}
add_action( 'wp_ajax_opalestate_update_api_key', 'opalestate_update_api_key' );

View File

@ -0,0 +1,272 @@
<?php
/**
* Opalestate API Keys Table List
*
* @package Opalestate\Admin
*/
defined( 'ABSPATH' ) || exit;
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}
/**
* API Keys table list class.
*/
class Opalestate_Admin_API_Keys_Table_List extends WP_List_Table {
/**
* Initialize the API key table list.
*/
public function __construct() {
parent::__construct(
[
'singular' => 'key',
'plural' => 'keys',
'ajax' => false,
]
);
}
/**
* No items found text.
*/
public function no_items() {
esc_html_e( 'No keys found.', 'opalestate-pro' );
}
/**
* Get list columns.
*
* @return array
*/
public function get_columns() {
return [
'cb' => '<input type="checkbox" />',
'title' => __( 'Description', 'opalestate-pro' ),
'truncated_key' => __( 'Consumer key ending in', 'opalestate-pro' ),
'user' => __( 'User', 'opalestate-pro' ),
'permissions' => __( 'Permissions', 'opalestate-pro' ),
'last_access' => __( 'Last access', 'opalestate-pro' ),
];
}
/**
* Column cb.
*
* @param array $key Key data.
* @return string
*/
public function column_cb( $key ) {
return sprintf( '<input type="checkbox" name="key[]" value="%1$s" />', $key['key_id'] );
}
/**
* Return title column.
*
* @param array $key Key data.
* @return string
*/
public function column_title( $key ) {
$url = admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys&edit-key=' . $key['key_id'] );
$user_id = absint( $key['user_id'] );
// Check if current user can edit other users or if it's the same user.
$can_edit = current_user_can( 'edit_user', $user_id ) || get_current_user_id() === $user_id;
$output = '<strong>';
if ( $can_edit ) {
$output .= '<a href="' . esc_url( $url ) . '" class="row-title">';
}
if ( empty( $key['description'] ) ) {
$output .= esc_html__( 'API key', 'opalestate-pro' );
} else {
$output .= esc_html( $key['description'] );
}
if ( $can_edit ) {
$output .= '</a>';
}
$output .= '</strong>';
// Get actions.
$actions = [
/* translators: %s: API key ID. */
'id' => sprintf( __( 'ID: %d', 'opalestate-pro' ), $key['key_id'] ),
];
if ( $can_edit ) {
$actions['edit'] = '<a href="' . esc_url( $url ) . '">' . __( 'View/Edit', 'opalestate-pro' ) . '</a>';
$actions['trash'] = '<a class="submitdelete" aria-label="' . esc_attr__( 'Revoke API key', 'opalestate-pro' ) . '" href="' . esc_url(
wp_nonce_url(
add_query_arg(
[
'revoke-key' => $key['key_id'],
], admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys' )
), 'revoke'
)
) . '">' . esc_html__( 'Revoke', 'opalestate-pro' ) . '</a>';
}
$row_actions = [];
foreach ( $actions as $action => $link ) {
$row_actions[] = '<span class="' . esc_attr( $action ) . '">' . $link . '</span>';
}
$output .= '<div class="row-actions">' . implode( ' | ', $row_actions ) . '</div>';
return $output;
}
/**
* Return truncated consumer key column.
*
* @param array $key Key data.
* @return string
*/
public function column_truncated_key( $key ) {
return '<code>&hellip;' . esc_html( $key['truncated_key'] ) . '</code>';
}
/**
* Return user column.
*
* @param array $key Key data.
* @return string
*/
public function column_user( $key ) {
$user = get_user_by( 'id', $key['user_id'] );
if ( ! $user ) {
return '';
}
if ( current_user_can( 'edit_user', $user->ID ) ) {
return '<a href="' . esc_url( add_query_arg( [ 'user_id' => $user->ID ], admin_url( 'user-edit.php' ) ) ) . '">' . esc_html( $user->display_name ) . '</a>';
}
return esc_html( $user->display_name );
}
/**
* Return permissions column.
*
* @param array $key Key data.
* @return string
*/
public function column_permissions( $key ) {
$permission_key = $key['permissions'];
$permissions = [
'read' => __( 'Read', 'opalestate-pro' ),
'write' => __( 'Write', 'opalestate-pro' ),
'read_write' => __( 'Read/Write', 'opalestate-pro' ),
];
if ( isset( $permissions[ $permission_key ] ) ) {
return esc_html( $permissions[ $permission_key ] );
} else {
return '';
}
}
/**
* Return last access column.
*
* @param array $key Key data.
* @return string
*/
public function column_last_access( $key ) {
if ( ! empty( $key['last_access'] ) ) {
/* translators: 1: last access date 2: last access time */
$date = sprintf( __( '%1$s at %2$s', 'opalestate-pro' ), date_i18n( wc_date_format(), strtotime( $key['last_access'] ) ),
date_i18n( get_option( 'time_format' ), strtotime( $key['last_access'] ) ) );
return apply_filters( 'opalestate_api_key_last_access_datetime', $date, $key['last_access'] );
}
return __( 'Unknown', 'opalestate-pro' );
}
/**
* Get bulk actions.
*
* @return array
*/
protected function get_bulk_actions() {
if ( ! current_user_can( 'remove_users' ) ) {
return [];
}
return [
'revoke' => __( 'Revoke', 'opalestate-pro' ),
];
}
/**
* Search box.
*
* @param string $text Button text.
* @param string $input_id Input ID.
*/
public function search_box( $text, $input_id ) {
if ( empty( $_REQUEST['s'] ) && ! $this->has_items() ) { // WPCS: input var okay, CSRF ok.
return;
}
$input_id = $input_id . '-search-input';
$search_query = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : ''; // WPCS: input var okay, CSRF ok.
echo '<p class="search-box">';
echo '<label class="screen-reader-text" for="' . esc_attr( $input_id ) . '">' . esc_html( $text ) . ':</label>';
echo '<input type="search" id="' . esc_attr( $input_id ) . '" name="s" value="' . esc_attr( $search_query ) . '" />';
submit_button(
$text, '', '', false,
[
'id' => 'search-submit',
]
);
echo '</p>';
}
/**
* Prepare table list items.
*/
public function prepare_items() {
global $wpdb;
$per_page = $this->get_items_per_page( 'opalestate_keys_per_page' );
$current_page = $this->get_pagenum();
if ( 1 < $current_page ) {
$offset = $per_page * ( $current_page - 1 );
} else {
$offset = 0;
}
$search = '';
if ( ! empty( $_REQUEST['s'] ) ) { // WPCS: input var okay, CSRF ok.
$search = "AND description LIKE '%" . esc_sql( $wpdb->esc_like( opalestate_clean( wp_unslash( $_REQUEST['s'] ) ) ) ) . "%' "; // WPCS: input var okay, CSRF ok.
}
// Get the API keys.
$keys = $wpdb->get_results(
"SELECT key_id, user_id, description, permissions, truncated_key, last_access FROM {$wpdb->prefix}opalestate_api_keys WHERE 1 = 1 {$search}" .
$wpdb->prepare( 'ORDER BY key_id DESC LIMIT %d OFFSET %d;', $per_page, $offset ), ARRAY_A
); // WPCS: unprepared SQL ok.
$count = $wpdb->get_var( "SELECT COUNT(key_id) FROM {$wpdb->prefix}opalestate_api_keys WHERE 1 = 1 {$search};" ); // WPCS: unprepared SQL ok.
$this->items = $keys;
// Set the pagination.
$this->set_pagination_args(
[
'total_items' => $count,
'per_page' => $per_page,
'total_pages' => ceil( $count / $per_page ),
]
);
}
}

View File

@ -0,0 +1,290 @@
<?php
/**
* Opalestate Admin API Keys Class
*
* @package Opalestate\API
*/
defined( 'ABSPATH' ) || exit;
/**
* Opalestate_Admin_API_Keys.
*/
class Opalestate_Admin_API_Keys {
/**
* Initialize the API Keys admin actions.
*/
public function __construct() {
add_action( 'admin_init', [ $this, 'actions' ] );
add_action( 'load-opalestate_property_page_opalestate-settings', [ $this, 'screen_option' ] );
add_action( 'cmb2_render_api_keys', [ $this, 'page_output' ] );
add_filter( 'opalestate_save_settings_advanced_keys', [ $this, 'allow_save_settings' ] );
}
/**
* Check if should allow save settings.
* This prevents "Your settings have been saved." notices on the table list.
*
* @param bool $allow If allow save settings.
* @return bool
*/
public function allow_save_settings( $allow ) {
if ( ! isset( $_GET['create-key'], $_GET['edit-key'] ) ) { // WPCS: input var okay, CSRF ok.
return false;
}
return $allow;
}
/**
* Check if is API Keys settings page.
*
* @return bool
*/
private function is_api_keys_settings_page() {
return isset( $_GET['page'], $_GET['tab'] ) && 'opalestate-settings' === $_GET['page'] && 'api_keys' === $_GET['tab']; // WPCS: input var okay, CSRF ok.
}
/**
* Page output.
*/
public static function page_output() {
if ( isset( $_GET['create-key'] ) || isset( $_GET['edit-key'] ) ) {
$key_id = isset( $_GET['edit-key'] ) ? absint( $_GET['edit-key'] ) : 0; // WPCS: input var okay, CSRF ok.
$key_data = static::get_key_data( $key_id );
$user_id = absint( $key_data['user_id'] );
if ( $key_id && $user_id && ! current_user_can( 'edit_user', $user_id ) ) {
if ( get_current_user_id() !== $user_id ) {
wp_die( esc_html__( 'You do not have permission to edit this API Key', 'opalestate-pro' ) );
}
}
include dirname( __FILE__ ) . '/html-keys-edit.php';
} else {
static::table_list_output();
}
}
/**
* Add screen option.
*/
public function screen_option() {
global $keys_table_list;
if ( ! isset( $_GET['create-key'] ) && ! isset( $_GET['edit-key'] ) && $this->is_api_keys_settings_page() ) { // WPCS: input var okay, CSRF ok.
$keys_table_list = new Opalestate_Admin_API_Keys_Table_List();
// Add screen option.
add_screen_option(
'per_page', [
'default' => 10,
'option' => 'opalestate_keys_per_page',
]
);
}
?>
<style>
input[name="submit-cmb"] {
display: none !important;
}
</style>
<?php
}
/**
* Table list output.
*/
private static function table_list_output() {
global $wpdb, $keys_table_list;
echo '<h2>' . esc_html__( 'REST API',
'opalestate-pro' ) . ' <a href="' . esc_url( admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys&create-key=1' ) ) . '" class="add-new-h2">' .
esc_html__( 'Add key', 'opalestate-pro' ) . '</a></h2>';
// Get the API keys count.
$count = $wpdb->get_var( "SELECT COUNT(key_id) FROM {$wpdb->prefix}opalestate_api_keys WHERE 1 = 1;" );
if ( absint( $count ) && $count > 0 ) {
$keys_table_list->prepare_items();
echo '<input type="hidden" name="page" value="wc-settings" />';
echo '<input type="hidden" name="tab" value="advanced" />';
echo '<input type="hidden" name="section" value="keys" />';
$keys_table_list->views();
$keys_table_list->search_box( __( 'Search key', 'opalestate-pro' ), 'key' );
$keys_table_list->display();
} else {
echo '<div class="opalestate-admin-api">';
?>
<h2 class="opalestate-admin-api-message">
<?php printf(
__( 'API keys allow users to use the <a href="%s">Opalestate REST API</a> to retrieve donation data in JSON or XML for external applications or devices, such as <a href="%s">Zapi_keyser</a>.',
'opalestate-pro' ),
'https://wpopal.com/opalestate/documentation/opalestate-api_keys-reference/',
'https://wpopal.com/addons/opalestate/'
); ?>
</h2>
<a class="button-primary button" href="<?php echo esc_url( admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys&create-key=1' ) ); ?>">
<?php esc_html_e( 'Create an API key', 'opalestate-pro' ); ?>
</a>
<style type="text/css">#posts-filter .wp-list-table, #posts-filter .tablenav.top, .tablenav.bottom .actions {
display: none;
}</style>
<?php
}
}
/**
* Get key data.
*
* @param int $key_id API Key ID.
* @return array
*/
private static function get_key_data( $key_id ) {
global $wpdb;
$empty = [
'key_id' => 0,
'user_id' => '',
'description' => '',
'permissions' => '',
'truncated_key' => '',
'last_access' => '',
];
if ( 0 === $key_id ) {
return $empty;
}
$key = $wpdb->get_row(
$wpdb->prepare(
"SELECT key_id, user_id, description, permissions, truncated_key, last_access
FROM {$wpdb->prefix}opalestate_api_keys
WHERE key_id = %d",
$key_id
), ARRAY_A
);
if ( is_null( $key ) ) {
return $empty;
}
return $key;
}
/**
* API Keys admin actions.
*/
public function actions() {
if ( $this->is_api_keys_settings_page() ) {
// Revoke key.
if ( isset( $_REQUEST['revoke-key'] ) ) { // WPCS: input var okay, CSRF ok.
$this->revoke_key();
}
// Bulk actions.
if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['key'] ) ) { // WPCS: input var okay, CSRF ok.
$this->bulk_actions();
}
}
}
/**
* Notices.
*/
public static function notices() {
if ( isset( $_GET['revoked'] ) ) { // WPCS: input var okay, CSRF ok.
$revoked = absint( $_GET['revoked'] ); // WPCS: input var okay, CSRF ok.
/* translators: %d: count */
Opalestate_Admin_Settings::add_message( sprintf( _n( '%d API key permanently revoked.', '%d API keys permanently revoked.', $revoked, 'opalestate-pro' ), $revoked ) );
}
}
/**
* Revoke key.
*/
private function revoke_key() {
global $wpdb;
check_admin_referer( 'revoke' );
if ( isset( $_REQUEST['revoke-key'] ) ) { // WPCS: input var okay, CSRF ok.
$key_id = absint( $_REQUEST['revoke-key'] ); // WPCS: input var okay, CSRF ok.
$user_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->prefix}opalestate_api_keys WHERE key_id = %d", $key_id ) );
if ( $key_id && $user_id && ( current_user_can( 'edit_user', $user_id ) || get_current_user_id() === $user_id ) ) {
$this->remove_key( $key_id );
} else {
wp_die( esc_html__( 'You do not have permission to revoke this API Key', 'opalestate-pro' ) );
}
}
wp_safe_redirect( esc_url_raw( add_query_arg( [ 'revoked' => 1 ], admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys' ) ) ) );
exit();
}
/**
* Bulk actions.
*/
private function bulk_actions() {
check_admin_referer( 'opalestate-settings' );
if ( ! current_user_can( 'manage_opalestate' ) ) {
wp_die( esc_html__( 'You do not have permission to edit API Keys', 'opalestate-pro' ) );
}
if ( isset( $_REQUEST['action'] ) ) { // WPCS: input var okay, CSRF ok.
$action = sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ); // WPCS: input var okay, CSRF ok.
$keys = isset( $_REQUEST['key'] ) ? array_map( 'absint', (array) $_REQUEST['key'] ) : []; // WPCS: input var okay, CSRF ok.
if ( 'revoke' === $action ) {
$this->bulk_revoke_key( $keys );
}
}
}
/**
* Bulk revoke key.
*
* @param array $keys API Keys.
*/
private function bulk_revoke_key( $keys ) {
if ( ! current_user_can( 'remove_users' ) ) {
wp_die( esc_html__( 'You do not have permission to revoke API Keys', 'opalestate-pro' ) );
}
$qty = 0;
foreach ( $keys as $key_id ) {
$result = $this->remove_key( $key_id );
if ( $result ) {
$qty++;
}
}
// Redirect to webhooks page.
wp_safe_redirect( esc_url_raw( add_query_arg( [ 'revoked' => $qty ], admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys' ) ) ) );
exit();
}
/**
* Remove key.
*
* @param int $key_id API Key ID.
* @return bool
*/
private function remove_key( $key_id ) {
global $wpdb;
$delete = $wpdb->delete( $wpdb->prefix . 'opalestate_api_keys', [ 'key_id' => $key_id ], [ '%d' ] );
return $delete;
}
}
new Opalestate_Admin_API_Keys();

View File

@ -40,6 +40,8 @@ class Opalestate_API {
*/ */
public function init() { public function init() {
$this->includes( [ $this->includes( [
'class-opalestate-admin-api-keys.php',
'class-opalestate-admin-api-keys-table-list.php',
'class-opalestate-api-admin.php', 'class-opalestate-api-admin.php',
'class-opalestate-base-api.php', 'class-opalestate-base-api.php',
'v1/property.php', 'v1/property.php',
@ -102,4 +104,35 @@ class Opalestate_API {
$api_class->register_routes(); $api_class->register_routes();
} }
} }
public static function install() {
try {
if ( ! function_exists( 'dbDelta' ) ) {
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
}
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql = 'CREATE TABLE IF NOT EXISTS ' . $wpdb->prefix . 'opalestate_api_keys' . ' (
key_id BIGINT UNSIGNED NOT NULL auto_increment,
user_id BIGINT UNSIGNED NOT NULL,
description varchar(200) NULL,
permissions varchar(10) NOT NULL,
consumer_key char(64) NOT NULL,
consumer_secret char(43) NOT NULL,
nonces longtext NULL,
truncated_key char(7) NOT NULL,
last_access datetime NULL default null,
PRIMARY KEY (key_id),
KEY consumer_key (consumer_key),
KEY consumer_secret (consumer_secret)
) ' . $charset_collate;
dbDelta( $sql );
} catch ( Exception $e ) {
}
}
} }

152
inc/api/html-keys-edit.php Normal file
View File

@ -0,0 +1,152 @@
<?php
/**
* Admin view: Edit API keys
*
* @package Opalestate/API/Settings
*/
defined( 'ABSPATH' ) || exit;
?>
<div id="key-fields" class="settings-panel">
<h2><?php esc_html_e( 'Key details', 'opalestate-pro' ); ?></h2>
<input type="hidden" id="key_id" value="<?php echo esc_attr( $key_id ); ?>" />
<table id="api-keys-options" class="form-table">
<tbody>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="key_description">
<?php esc_html_e( 'Description', 'opalestate-pro' ); ?>
</label>
</th>
<td class="forminp">
<input id="key_description" type="text" class="input-text regular-input" value="<?php echo esc_attr( $key_data['description'] ); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="key_user">
<?php esc_html_e( 'User', 'opalestate-pro' ); ?>
</label>
</th>
<td class="forminp">
<?php
$curent_user_id = get_current_user_id();
$user_id = ! empty( $key_data['user_id'] ) ? absint( $key_data['user_id'] ) : $curent_user_id;
$user = get_user_by( 'id', $user_id );
$user_string = sprintf(
/* translators: 1: user display name 2: user ID 3: user email */
esc_html__( '%1$s (#%2$s &ndash; %3$s)', 'opalestate-pro' ),
$user->display_name,
absint( $user->ID ),
$user->user_email
);
?>
<select class="opalestate-customer-search" id="key_user" data-placeholder="<?php esc_attr_e( 'Search for a user&hellip;', 'opalestate-pro' ); ?>" data-allow_clear="true">
<option value="<?php echo esc_attr( $user_id ); ?>" selected="selected"><?php echo htmlspecialchars( wp_kses_post( $user_string ) ); // htmlspecialchars to prevent XSS when rendered by selectWoo. ?></option>
</select>
</td>
</tr>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="key_permissions">
<?php esc_html_e( 'Permissions', 'opalestate-pro' ); ?>
</label>
</th>
<td class="forminp">
<select id="key_permissions" class="wc-enhanced-select">
<?php
$permissions = array(
'read' => __( 'Read', 'opalestate-pro' ),
'write' => __( 'Write', 'opalestate-pro' ),
'read_write' => __( 'Read/Write', 'opalestate-pro' ),
);
foreach ( $permissions as $permission_id => $permission_name ) :
?>
<option value="<?php echo esc_attr( $permission_id ); ?>" <?php selected( $key_data['permissions'], $permission_id, true ); ?>><?php echo esc_html( $permission_name ); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php if ( 0 !== $key_id ) : ?>
<tr valign="top">
<th scope="row" class="titledesc">
<?php esc_html_e( 'Consumer key ending in', 'opalestate-pro' ); ?>
</th>
<td class="forminp">
<code>&hellip;<?php echo esc_html( $key_data['truncated_key'] ); ?></code>
</td>
</tr>
<tr valign="top">
<th scope="row" class="titledesc">
<?php esc_html_e( 'Last access', 'opalestate-pro' ); ?>
</th>
<td class="forminp">
<span>
<?php
if ( ! empty( $key_data['last_access'] ) ) {
/* translators: 1: last access date 2: last access time */
$date = sprintf( __( '%1$s at %2$s', 'opalestate-pro' ), date_i18n( wc_date_format(), strtotime( $key_data['last_access'] ) ), date_i18n( wc_time_format(), strtotime(
$key_data['last_access'] ) ) );
echo esc_html( apply_filters( 'opalestate_api_key_last_access_datetime', $date, $key_data['last_access'] ) );
} else {
esc_html_e( 'Unknown', 'opalestate-pro' );
}
?>
</span>
</td>
</tr>
<?php endif ?>
</tbody>
</table>
<?php do_action( 'opalestate_admin_key_fields', $key_data ); ?>
<?php
if ( 0 === intval( $key_id ) ) {
submit_button( __( 'Generate API key', 'opalestate-pro' ), 'primary', 'update_api_key' );
} else {
?>
<p class="submit">
<?php submit_button( __( 'Save changes', 'opalestate-pro' ), 'primary', 'update_api_key', false ); ?>
<a style="color: #a00; text-decoration: none; margin-left: 10px;" href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'revoke-key' => $key_id ), admin_url( 'edit.php?post_type=opalestate_property&page=opalestate-settings&tab=api_keys' ) ), 'revoke' ) ); ?>">
<?php esc_html_e( 'Revoke key', 'opalestate-pro' ); ?>
</a>
</p>
<?php
}
?>
</div>
<script type="text/template" id="tmpl-api-keys-template">
<p id="copy-error"></p>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row" class="titledesc">
<?php esc_html_e( 'Consumer key', 'opalestate-pro' ); ?>
</th>
<td class="forminp">
<input id="key_consumer_key" type="text" value="{{ data.consumer_key }}" size="55" readonly="readonly"> <button type="button" class="button-secondary copy-key" data-tip="<?php
esc_attr_e( 'Copied!', 'opalestate-pro' ); ?>"><?php esc_html_e( 'Copy', 'opalestate-pro' ); ?></button>
</td>
</tr>
<tr valign="top">
<th scope="row" class="titledesc">
<?php esc_html_e( 'Consumer secret', 'opalestate-pro' ); ?>
</th>
<td class="forminp">
<input id="key_consumer_secret" type="text" value="{{ data.consumer_secret }}" size="55" readonly="readonly">
<button type="button" class="button-secondary copy-secret" data-tip="<?php esc_attr_e( 'Copied!', 'opalestate-pro' ); ?>">
<?php esc_html_e( 'Copy', 'opalestate-pro' ); ?>
</button>
</td>
</tr>
</tbody>
</table>
</script>

View File

@ -57,6 +57,7 @@ class Opalestate_Install {
OpalEstate_User_Search::install(); OpalEstate_User_Search::install();
OpalEstate_User_Message::install(); OpalEstate_User_Message::install();
OpalEstate_User_Request_Viewing::install(); OpalEstate_User_Request_Viewing::install();
Opalestate_API::install();
} }
/** /**

View File

@ -1232,3 +1232,18 @@ function opalestate_is_enable_price_field() {
function opalestate_is_enable_areasize_field() { function opalestate_is_enable_areasize_field() {
return 'on' == opalestate_get_option( 'opalestate_ppt_areasize_opt', 'on' ); return 'on' == opalestate_get_option( 'opalestate_ppt_areasize_opt', 'on' );
} }
/**
* Clean variables using sanitize_text_field. Arrays are cleaned recursively.
* Non-scalar values are ignored.
*
* @param string|array $var Data to sanitize.
* @return string|array
*/
function opalestate_clean( $var ) {
if ( is_array( $var ) ) {
return array_map( 'opalestate_clean', $var );
} else {
return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
}
}

View File

@ -25,9 +25,7 @@ The plugin will not make you disappointed with ease of use, friendly & flexible
1. *[ Housey - Real Estate WordPress Theme](https://bit.ly/2kHewkG "Housey - Real Estate WordPress Theme")* 1. *[ Housey - Real Estate WordPress Theme](https://bit.ly/2kHewkG "Housey - Real Estate WordPress Theme")*
2. *[ Latehome - Real Estate WordPress Theme](https://bit.ly/2M0rmp0 "Latehome - Real Estate WordPress Theme")* 2. *[ Latehome - Real Estate WordPress Theme](https://bit.ly/2M0rmp0 "Latehome - Real Estate WordPress Theme")*
3. *[ Latehome Free - Real Estate Free WordPress Theme](http://demo2.themelexus.com/latehome_free/ "Latehome Free - Real Estate Free WordPress Theme"). You can download free [here](https://bit 3. *[ Latehome Free - Real Estate Free WordPress Theme](http://demo2.themelexus.com/latehome_free/ "Latehome Free - Real Estate Free WordPress Theme"). You can download free [here](https://bit.ly/2nLTfHT "Latehome Free download").*
.ly/2nLTfHT "Latehome Free
download").*
* Please keep contact us at help@wpopal.com to send us your website, we will publish it our showcase * Please keep contact us at help@wpopal.com to send us your website, we will publish it our showcase