ip_method;
$pagelayer->ip_method = (int) $method;
if(isset($_SERVER["REMOTE_ADDR"])){
$ip = $_SERVER["REMOTE_ADDR"];
}
if(isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $method == 1){
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
if(isset($_SERVER["HTTP_CLIENT_IP"]) && $method == 2){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
// Hacking fix for X-Forwarded-For
if(!pagelayer_valid_ip($ip)){
return '';
}
return $ip;
}
// Execute a select query and return an array
function pagelayer_selectquery($query, $array = 0){
global $wpdb;
$result = $wpdb->get_results($query, 'ARRAY_A');
if(empty($array)){
return current($result);
}else{
return $result;
}
}
// Check if an IP is valid
function pagelayer_valid_ip($ip){
// IPv6
if(pagelayer_valid_ipv6($ip)){
return true;
}
// IPv4
if(!ip2long($ip)){
return false;
}
return true;
}
function pagelayer_valid_ipv6($ip){
$pattern = '/^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/';
if(!preg_match($pattern, $ip)){
return false;
}
return true;
}
// Check if a field is posted via POST else return default value
function pagelayer_optpost($name, $default = ''){
if(!empty($_POST[$name])){
return pagelayer_inputsec(pagelayer_htmlizer(trim($_POST[$name])));
}
return $default;
}
// Check if a field is posted via GET else return default value
function pagelayer_optget($name, $default = ''){
if(!empty($_GET[$name])){
return pagelayer_inputsec(pagelayer_htmlizer(trim($_GET[$name])));
}
return $default;
}
// Check if a field is posted via GET or POST else return default value
function pagelayer_optreq($name, $default = ''){
if(!empty($_REQUEST[$name])){
return pagelayer_inputsec(pagelayer_htmlizer(trim($_REQUEST[$name])));
}
return $default;
}
// For filling in posted values
function pagelayer_POSTval($name, $default = ''){
return (!empty($_POST) ? (!isset($_POST[$name]) ? '' : esc_html($_POST[$name])) : $default);
}
function pagelayer_POSTchecked($name, $default = false){
return (!empty($_POST) ? (isset($_POST[$name]) ? 'checked="checked"' : '') : (!empty($default) ? 'checked="checked"' : ''));
}
// For check isset value
function pagelayer_isset($var, $name, $default = ''){
return isset($var[$name]) ? $var[$name] : $default;
}
function pagelayer_POSTselect($name, $value, $default = false){
if(empty($_POST)){
if(!empty($default)){
return 'selected="selected"';
}
}else{
if(isset($_POST[$name])){
if(trim($_POST[$name]) == $value){
return 'selected="selected"';
}
}
}
}
function pagelayer_inputsec($string){
$string = addslashes($string);
// This is to replace ` which can cause the command to be executed in exec()
$string = str_replace('`', '\`', $string);
return $string;
}
function pagelayer_htmlizer($string){
$string = htmlentities($string, ENT_QUOTES, 'UTF-8');
preg_match_all('/(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)/', $string, $matches);//r_print($matches);
foreach($matches[1] as $mk => $mv){
$tmp_m = pagelayer_entity_check($matches[2][$mk]);
$string = str_replace($matches[1][$mk], $tmp_m, $string);
}
return $string;
}
function pagelayer_entity_check($string){
//Convert Hexadecimal to Decimal
$num = ((substr($string, 0, 1) === 'x') ? hexdec(substr($string, 1)) : (int) $string);
//Squares and Spaces - return nothing
$string = (($num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num < 0x20) ? '' : ''.$num.';');
return $string;
}
// Check if a checkbox is selected
function pagelayer_is_checked($post){
if(!empty($_POST[$post])){
return true;
}
return false;
}
// Report an error
function pagelayer_report_error($error = array()){
if(empty($error)){
return true;
}
$error_string = 'Please fix the below error(s) : ';
foreach($error as $ek => $ev){
$error_string .= '* '.$ev.' ';
}
echo '
'
. __pl($error_string)
. '
';
}
// Report a notice
function pagelayer_report_notice($notice = array()){
global $wp_version;
if(empty($notice)){
return true;
}
// Which class do we have to use ?
if(version_compare($wp_version, '3.8', '<')){
$notice_class = 'updated';
}else{
$notice_class = 'updated';
}
$notice_string = 'Please check the below notice(s) : ';
foreach($notice as $ek => $ev){
$notice_string .= '* '.$ev.' ';
}
echo ''
. __pl($notice_string)
. '
';
}
// Convert an objext to array
function pagelayer_objectToArray($d){
if(is_object($d)){
$d = get_object_vars($d);
}
if(is_array($d)){
return array_map(__FUNCTION__, $d); // recursive
}elseif(is_object($d)){
return pagelayer_objectToArray($d);
}else{
return $d;
}
}
// Sanitize variables
function pagelayer_sanitize_variables($variables = array()){
if(is_array($variables)){
foreach($variables as $k => $v){
$variables[$k] = trim($v);
$variables[$k] = escapeshellcmd($v);
}
}else{
$variables = escapeshellcmd(trim($variables));
}
return $variables;
}
// Is multisite ?
function pagelayer_is_multisite() {
if(function_exists('get_site_option') && function_exists('is_multisite') && is_multisite()){
return true;
}
return false;
}
// Generate a random string
function pagelayer_RandomString($length = 10){
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '';
for($i = 0; $i < $length; $i++){
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function pagelayer_print($array){
echo '';
print_r($array);
echo ' ';
}
function pagelayer_cleanpath($path){
$path = str_replace('\\\\', '/', $path);
$path = str_replace('\\', '/', $path);
$path = str_replace('//', '/', $path);
return rtrim($path, '/');
}
// Returns the Numeric Value of results Per Page
function pagelayer_get_page($get = 'page', $resperpage = 50){
$resperpage = (!empty($_REQUEST['reslen']) && is_numeric($_REQUEST['reslen']) ? (int) pagelayer_optreq('reslen') : $resperpage);
if(pagelayer_optget($get)){
$pg = (int) pagelayer_optget($get);
$pg = $pg - 1;
$page = ($pg * $resperpage);
$page = ($page <= 0 ? 0 : $page);
}else{
$page = 0;
}
return $page;
}
// Are we editing from the Admin panel ?
function pagelayer_is_editing($force = false){
global $post, $pagelayer;
if(!empty($force)){
return true;
}
if(!is_admin()){
return false;
}
$current_file = basename($_SERVER['PHP_SELF']);
$type = get_post_type();
//echo $type;return false;
//$page = pagelayer_optreq('page');
// Are we in the live editor mode OR is this a post which is supported
if((pagelayer_supported_type($type) && in_array($current_file, array('post.php', 'post-new.php'))) || pagelayer_is_live()){
return true;
}else{
return false;
}
}
// Is the given post type editable by us ?
function pagelayer_supported_type($type){
global $pagelayer;
$type = trim($type);
if(in_array($type, $pagelayer->settings['post_types'])){
return true;
}
if($type == $pagelayer->builder['name']){
return true;
}
return false;
}
function pagelayer_shortlink($id){
$post = get_post( $id );
if ( ! empty( $post->ID ) ) {
$post_id = $post->ID;
}
$post_type = get_post_type_object( $post->post_type );
if ( 'page' === $post->post_type && get_option( 'page_on_front' ) == $post->ID && 'page' === get_option( 'show_on_front' ) ) {
$link = home_url( '/' );
} elseif ( $post_type->public ) {
$link = home_url( '?p=' . $post_id );
}
if(function_exists('is_post_status_viewable') && !is_post_status_viewable($post_id)){
$link = get_permalink( $post->ID );
}
$link .= substr_count($link, '?') > 0 ? '' : '?';
return $link;
}
// Pagelayer live link
function pagelayer_livelink($id){
return pagelayer_shortlink($id).'&pagelayer-live=1';
}
// Are we in live mode ?
function pagelayer_is_live(&$error = array()){
global $post;
// Are we seeing the post ?
if(!isset($post) || !isset($post->ID) || empty($post->ID)){
$error[] = 'Post ID is missing or blank - '.@$post->ID;
return false;
}
$parID = $post->ID;
// Is revision?
if(wp_is_post_revision($post->ID) ){
$parID = wp_get_post_parent_id($post->ID);
}
// Are you allowed to edit ?
if(!pagelayer_user_can_edit($parID)){
$error[] = 'You dont have editing rights for this page - '.$parID;
return false;
}
// Is it the live mode ?
if(pagelayer_optreq('pagelayer-live')){
$error[] = 'pagelayer-live is missing';
return true;
}
return false;
}
// Are we in live IFRAME mode ?
function pagelayer_is_live_iframe(&$error = array()){
// Are we seeing the post ?
if(!pagelayer_is_live($error)){
return false;
}
// Is it the live mode ?
if(pagelayer_optreq('pagelayer-iframe')){
return true;
}
$error[] = 'pagelayer-iframe missing in GET';
return false;
}
// Are we editing a live template
function pagelayer_is_live_template($post = []){
// Are we seeing the post ?
if(!pagelayer_is_live()){
return false;
}
if(!$post){
$post = $GLOBALS['post'];
}
if($post->post_type == 'pagelayer-template'){
return true;
}
return false;
}
function pagelayer_has_blocks($post = null) {
if ( ! has_blocks( $post ) ) {
return false;
}
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( $wp_post instanceof WP_Post ) {
$post = $wp_post->post_content;
}
}
return false !== strpos( $post, '';
$content = str_replace($div, $div.$data_attr, $content);
}
}
return $content;
}
function pagelayer_create_id(){
return pagelayer_RandomString(3).rand(1000, 9999);
}
// Loads the shortcodes
function pagelayer_load_shortcodes(){
global $pagelayer, $post;
if(!empty($pagelayer->shortcode_loaded)){
return;
}
pagelayer_memory_limit(128);
// We have loaded
$pagelayer->shortcode_loaded = 1;
do_action('pagelayer_before_load_shortcodes');
// pQuery
include_once(PAGELAYER_DIR.'/lib/pquery/IQuery.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_formatter.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_node_html.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_tokenizer.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_parser_html.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_selector_html.php');
include_once(PAGELAYER_DIR.'/lib/pquery/gan_xml2array.php');
include_once(PAGELAYER_DIR.'/lib/pquery/pQuery.php');
include_once(PAGELAYER_DIR.'/main/shortcode_functions.php');
// Apply filter to load custom widgets functions
do_action('pagelayer_load_shortcode_functions');
include_once(PAGELAYER_DIR.'/main/shortcodes.php');
// Apply filter to load custom widgets
do_action('pagelayer_load_custom_widgets');
// Render Pagelayer element by blocks
add_action('pre_render_block', 'pagelayer_render_blocks', 10, 2);
// Add global widget data
if(defined('PAGELAYER_PREMIUM') && !pagelayer_is_gutenberg_editor()){
// Get global widget templates id by type
$args = [
'post_type' => $pagelayer->builder['name'],
'status' => 'publish',
'meta_key' => 'pagelayer_template_type',
'meta_value' => array('global_widget', 'section', 'global_section'),
'posts_per_page' => -1
];
$query = new WP_Query($args);
$tmp_list = [];
$global_widgets = array();
$global_widgets['global_widget'] = array();
$global_widgets['section'] = array();
$global_widgets['global_section'] = array();
foreach($query->posts as $template){
// The type
$pagelayer_template_type = get_post_meta($template->ID, 'pagelayer_template_type', true);
$global_data = [];
$global_data['post_id'] = $template->ID;
$global_data['title'] = $template->post_title;
$global_data['$'] = pagelayer_the_content($template->post_content, true);
$global_widgets[$pagelayer_template_type][$template->ID] = $global_data;
}
$pagelayer->global_widgets = $global_widgets['global_widget'];
$pagelayer->saved_sections = $global_widgets['section'];
$pagelayer->global_sections = $global_widgets['global_section'];
}
do_action('pagelayer_after_load_shortcodes');
}
// Add the shortcodes to the pagelayer list
function pagelayer_add_shortcode($tag, $params = array()){
global $pagelayer, $post;
if($tag == 'pl_row'){
$inner_tag = 'pl_inner_row';
add_shortcode($inner_tag, 'pagelayer_render_shortcode');
}
if($tag == 'pl_col'){
$inner_tag = 'pl_inner_col';
add_shortcode($inner_tag, 'pagelayer_render_shortcode');
}
add_shortcode($tag, 'pagelayer_render_shortcode');//$params['func']);
//unset($params['func']);
// Is there a group ?
if(empty($params['group'])){
$params['group'] = 'misc';
}
// Add the advanced styling group
$params['options'] = [
'ele_bg_styles' => __pl('ele_bg_styles'),
'ele_styles' => __pl('ele_styles'),
'border_styles' => __pl('border_styles'),
'font_style' => __pl('font_style'),
'position_styles' => __pl('position_styles'),
'animation_styles' => __pl('animation_styles'),
'motion_effects' => __pl('Motion Effects'),
'responsive_styles' => __pl('responsive_styles'),
'attributes' => __pl('attributes'),
'custom_styles' => __pl('custom_styles'),
];
if(!empty($params['skip_props_cat'])){
foreach($params['skip_props_cat'] as $k => $v){
unset($params['options'][$v]);
}
}
// Are the settings there which hold the params ?
if(empty($params['settings'])){
$params['settings'] = [
'params' => $params['name'],
];
}
// Disable the style options
if(!empty($params['styles'])){
$params['settings'] = array_merge($params['settings'], $params['styles']);
unset($params['styles']);
}
/*// The following is for testing only
$r = [];
foreach($pagelayer->styles as $k => $v){
foreach($v as $kk => $vv){
$r[$kk] = $kk;
}
}
//print_r($r);die();
foreach($params['settings'] as $k => $v){
if(empty($params[$k])) continue;
foreach($params[$k] as $kk => $vv){
if(!empty($r[$kk])){
echo 'Duplicate KEY '.$kk.' in Shortcode '.$tag." ";
}
}
}
//die();*/
$params = apply_filters( 'pagelayer_shortcode_params', $params, $tag );
// Insert the shortcode
$pagelayer->shortcodes[$tag] = $params;
$pagelayer->groups[$params['group']][] = $tag;
// Export the default values
foreach($pagelayer->tabs as $tab){
if(empty($pagelayer->shortcodes[$tag][$tab])){
continue;
}
foreach($pagelayer->shortcodes[$tag][$tab] as $section => $Lsection){
$props = empty($pagelayer->shortcodes[$tag][$section]) ? @$pagelayer->styles[$section] : @$pagelayer->shortcodes[$tag][$section];
//echo $tab.' - '.$section.' - ';
if(empty($props)){
continue;
}
// Save customizer params
if( $tag == 'pl_customizer' ){
$pagelayer->customizer_params = array_merge($pagelayer->customizer_params, $props);
}
foreach($props as $prop => $param){
// Set default values to export for JS
if(isset($param['export-def']) && isset($param['default']) && $param['export-def'] == 1){
$pagelayer->default_params[$tag][$prop] = $param['default'];
}
}
}
}
}
// Add a freemium shortcode i.e. available for render, but not to drag or edit
function pagelayer_freemium_shortcode($tag, $params = array()){
// If we are the free version, we just allow render and some edits
if(!defined('PAGELAYER_PREMIUM')){
$params['not_visible'] = 1;
$params['freemium'] = 1;
$cats = empty($params['styles']) ? array() : $params['styles'];
if(!empty($params['settings'])){
$cats = array_merge($cats, $params['settings']);
}
$cats['params'] = $params['name'];
//pagelayer_print($cats);
foreach($cats as $k => $v){
if(empty($params[$k])) continue;
foreach($params[$k] as $kk => $vv){
if(empty($params[$k][$kk]['np'])){
$params[$k][$kk]['pro'] = 1;
}
}
}
}
return pagelayer_add_shortcode($tag, $params);
}
// Returns the permalink values
function pagelayer_permalink($id){
if(is_numeric($id)){
$id = (int) @$id;
$perma = get_permalink($id);
if(!empty($perma)){
$id = $perma;
}
}
$id = apply_filters('pagelayer_permalink', $id);
return $id;
}
// Returns the Image values
function pagelayer_image($id = 0){
global $pagelayer;
$ret = [];
if(!empty($id) && is_array($id)){
foreach($id as $key => $image){
$attachment = pagelayer_image(@$image);
if(!empty($attachment)){
foreach($attachment as $k => $v){
if($key == 'retina'){
$ret['retina-'.$k] = $v;
}else if($key == 'retina_mobile'){
$ret['retina-mobile-'.$k] = $v;
}else{
$ret[$k] = $v;
}
}
}
}
return $ret;
}
// External image ?
if(pagelayer_is_external_img($id)){
$ret['url'] = $id;
// Attachment
}elseif(!empty($id)){
$id = (int) @$id;
$image = get_post($id);
// Is there an attachment which is an image ?
if(!empty($image) && $image->post_type == 'attachment' && wp_attachment_is_image($id)){
// Need to export necessary media
if(!empty($pagelayer->export_mode)){
$pagelayer->media_to_export[] = $id;
}
$sizes = get_intermediate_image_sizes();
array_unshift($sizes, 'full');
foreach($sizes as $size){
$src = wp_get_attachment_image_src($id, $size);
$ret[$size.'-url'] = $src[0];
}
// Title and Alt
$title = esc_attr($image->post_title);
$alt = get_post_meta($id, '_wp_attachment_image_alt', true);
$alt = empty($alt) ? $image->post_excerpt : $alt;
$alt = empty($alt) ? $image->post_title : $alt;
$alt = empty($alt) ? '' : esc_attr(trim(strip_tags($alt)));
$link = get_attachment_link($id);
$caption = wp_get_attachment_caption($id);
$caption = !empty($caption) ? esc_attr($caption) : '';
}
}
// First preference to full url
if(!empty($ret['full-url'])){
$ret['url'] = $ret['full-url'];
}
// No image
if(empty($ret['url'])){
$ret['url'] = PAGELAYER_URL.'/images/default-image.png';
}
$ret['alt'] = @$alt;
$ret['title'] = @$title;
$ret['link'] = @$link;
$ret['caption'] = @$caption;
$ret = apply_filters('pagelayer_image', $ret);
if(pagelayer_is_default_img($ret['url'])){
$ret['no-image-set'] = 1;
}
return $ret;
}
// Checks if the given parameter is an external link or a wp attachment id
function pagelayer_is_external_img($img = ''){
if(empty($img)){
return false;
}
if(preg_match('#http://#is', $img) || preg_match('#https://#is', $img) || preg_match('#^{{#is', $img)){
return true;
}
return false;
}
// Checks if the given parameter is the default image
function pagelayer_is_default_img($img){
if($img == PAGELAYER_URL.'/images/default-image.png'){
return true;
}
return false;
}
// Returns the attachment url
function pagelayer_attachment($id){
$ret = [];
// External url ?
if(pagelayer_is_external_img($id)){
$ret['url'] = $id;
// Attachment
}elseif(!empty($id)){
// Need to export necessary media
if(!empty($pagelayer->export_mode)){
$pagelayer->media_to_export[] = $id;
}
$ret['url'] = wp_get_attachment_url($id);
}
$ret = apply_filters('pagelayer_attachment', $ret);
return $ret;
}
// Convert the regular URL of a Video to a Embed URL
// Todo : Check
function pagelayer_video_url($source, $no_url = false){
global $pagelayer;
if (!empty($source)) {
$source = esc_url( $source );
$source = str_replace('&', '&', $source);
$url = parse_url($source);
$videoSite ='';
$videoId ='';
$vid_atts = [];
$youtubeRegExp = '/youtube\.com|youtu\.be/is';
$vimeoRegExp = '/vimeo\.com/is';
if (preg_match($youtubeRegExp, $source)) {
$videoSite = 'youtube';
} else if (preg_match($vimeoRegExp, $source)) {
$videoSite = 'vimeo';
}
switch ($videoSite) {
case 'youtube':
$pagelayer->append_yt_api = true;
if (preg_match('/youtube\.com/is', $source)) {
if (preg_match('/watch/is', $source)) {
parse_str($url['query'], $parameters);
if (isset($parameters['v']) && !empty($parameters['v'])) {
$videoId = $parameters['v'];
}
} else if (preg_match('/embed/is', $url['path'])) {
$path = explode('/', $url['path']);
if (isset($path[2]) && !empty($path[2])) {
$videoId = $path[2];
}
}
} else if (preg_match('/youtu\.be/is', $url['host'])) {
$path = explode('/', $url['path']);
if (isset($path[1]) && !empty($path[1])) {
$videoId = $path[1];
}
}
$vid_atts['type'] = 'youtube';
$vid_atts['src'] = '//www.youtube.com/embed/'.$videoId;
$vid_atts['id'] = $videoId;
break;
case 'vimeo':
if (preg_match('/player\.vimeo\.com/is', $url['host']) && preg_match('/video/is', $url['path'])) {
$path = explode('video/', $source);
} else if (preg_match('/vimeo\.com/is', $url['host'])) {
$path = explode('.com/', $source);
}
if(isset($path[1]) && !empty($path[1])) {
$videoId = $path[1];
}
$vid_atts['type'] = 'vimeo';
$vid_atts['src'] = '//player.vimeo.com/video/'.$videoId;
$vid_atts['id'] = $videoId;
break;
default:
$vid_atts['type'] = 'local';
$vid_atts['src'] = $source;
$vid_atts['id'] = $videoId;
}
if(!$no_url){
return $vid_atts['src'];
}
return $vid_atts;
}
}
// As per the JS specification
function pagelayer_escapeHTML($str){
$replace = [
']' => ']',
'[' => '[',
//'=' => '=',
'<' => '<',
'>' => '>',
'"' => '"',
//'&' => '&',
'\'' => ''',
'\\' => '\'
];
$str = str_replace(array_keys($replace), array_values($replace), $str);
return $str;
}
// As per the JS specification
function pagelayer_unescapeHTML($str){
$replace = [
'#93' => ']',
'#91' => '[',
//'#61' => '=',
'lt' => '<',
'gt' => '>',
'quot' => '"',
//'amp' => '&',
'#39' => '\'',
'#92' => '\\'
];
foreach($replace as $k => $v){
$str = str_replace('&'.$k.';', $v, $str);
}
return $str;
}
// Converts a Unicode code point to its UTF-8 encoded string.
function pagelayer_codepoint_to_utf8($num) {
if ($num < 0x80) {
return chr($num);
} elseif ($num < 0x800) {
return chr(0xC0 | ($num >> 6))
. chr(0x80 | ($num & 0x3F));
} elseif ($num < 0x10000) {
return chr(0xE0 | ($num >> 12))
. chr(0x80 | (($num >> 6) & 0x3F))
. chr(0x80 | ($num & 0x3F));
} elseif ($num < 0x110000) {
return chr(0xF0 | ($num >> 18))
. chr(0x80 | (($num >> 12) & 0x3F))
. chr(0x80 | (($num >> 6) & 0x3F))
. chr(0x80 | ($num & 0x3F));
}
return '';
}
// To make decode entities faster
function pagelayer_optimized_decode_entities($string, $req = true) {
// Fast replace common HTML entities
$common_entities_map = [
']' => ']', '[' => '[', '<' => '<', '>' => '>', '&' => '&', '"' => '"', ''' => "'",
'©' => '©', '®' => '®', '–' => '–', '—' => '—', '•' => '•',
'…' => '…', '‘' => '‘', '’' => '’', '“' => '“', '”' => '”'
];
// Replace common entities first for performance
$string = str_replace(array_keys($common_entities_map), array_values($common_entities_map), $string);
// Return early if no encoded entities exist
if(!preg_match('/\\\\u[0-9a-fA-F]{4}|[0-9a-fA-F]+;|\d+;/', $string)) {
return $string;
}
$string = preg_replace_callback(
'/\\\\u([0-9a-fA-F]{4})|([0-9a-fA-F]+);|([0-9]+);/',
function ($matches) {
if (!empty($matches[1])) {
// Decode \uXXXX Unicode sequences
return pagelayer_codepoint_to_utf8( hexdec($matches[1]) );
}elseif (!empty($matches[2])) {
// Decode hexadecimal HTML entities (j → j)
return pagelayer_codepoint_to_utf8( hexdec($matches[2]) );
} elseif (!empty($matches[3])) {
// Decode decimal HTML entities (j → j)
return pagelayer_codepoint_to_utf8( (int)$matches[3] );
}
return $matches[0];
},
$string
);
// Additional decoding to cover remaining cases
if($req){
$string = pagelayer_optimized_decode_entities($string, false);
}
return $string;
}
// Return true if user can add js content
function pagelayer_user_can_add_js_content(){
// Unfiltered_html cap needs to be checked for multisite
if(current_user_can('unfiltered_html')){
return true;
}
$pagelayer_js_permission = get_option('pagelayer_js_permission');
$current_user = wp_get_current_user();
// If not allowed any role by admin
if(empty($pagelayer_js_permission) || empty($current_user->roles)){
return false;
}
foreach($current_user->roles as $role){
if(in_array($role, $pagelayer_js_permission)){
return true;
}
}
return false;
}
// Check for XSS codes in our shortcodes submitted
function pagelayer_xss_content($data){
$data = pagelayer_optimized_decode_entities($data);
$data = preg_split('/\s/', $data);
$data = implode('', $data);
//echo $data;
if(preg_match('/["\']javascript\:/is', $data)){
return 'javascript';
}
if(preg_match('/["\']vbscript\:/is', $data)){
return 'vbscript';
}
if(preg_match('/\-moz\-binding\:/is', $data)){
return '-moz-binding';
}
if(preg_match('/expression\(/is', $data)){
return 'expression';
}
if(preg_match('/\<(iframe|frame|script|style|link|applet|embed|xml|svg|object|layer|ilayer|meta)/is', $data, $matches)){
return $matches[1];
}
// These events not start with on
$not_allowed = array('click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'load', 'unload', 'change', 'submit', 'reset', 'select', 'blur', 'focus', 'keydown', 'keypress', 'keyup', 'afterprint', 'beforeprint', 'beforeunload', 'error', 'hashchange', 'message', 'offline', 'online', 'pagehide', 'pageshow', 'popstate', 'resize', 'storage', 'contextmenu', 'input', 'invalid', 'search', 'mousewheel', 'wheel', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop', 'scroll', 'copy', 'cut', 'paste', 'abort', 'canplay', 'canplaythrough', 'cuechange', 'durationchange', 'emptied', 'ended', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting', 'toggle', 'animationstart', 'animationcancel', 'animationend', 'animationiteration', 'auxclick', 'beforeinput', 'beforematch', 'beforexrselect', 'compositionend', 'compositionstart', 'compositionupdate', 'contentvisibilityautostatechange', 'focusout', 'focusin', 'fullscreenchange', 'fullscreenerror', 'gotpointercapture', 'lostpointercapture', 'mouseenter', 'mouseleave', 'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave', 'pointermove', 'pointerout', 'pointerover', 'pointerrawupdate', 'pointerup', 'scrollend', 'securitypolicyviolation', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'transitioncancel', 'transitionend', 'transitionrun', 'transitionstart', 'MozMousePixelScroll', 'DOMActivate', 'afterscriptexecute', 'beforescriptexecute', 'DOMMouseScroll', 'willreveal', 'gesturechange', 'gestureend', 'gesturestart', 'mouseforcechanged', 'mouseforcedown', 'mouseforceup', 'mouseforceup');
$not_allowed = implode('|', $not_allowed);
if(preg_match('/(on|onwebkit)+('.($not_allowed).')=/is', $data, $matches)){
return $matches[1].$matches[2];
}
return;
}
// Check for XSS codes in our blocks array
function pagelayer_sanitize_blocks_save_pre($block){
foreach($block as $k => $v){
// Recurse on arrays
if(is_array($v)){
$block[$k] = pagelayer_sanitize_blocks_save_pre($v);
// We dont support objects !
}elseif(is_object($v)){
$block[$k] = null;
// Strings
}else{
if(is_string($v)){
$v = wp_filter_post_kses($v);
while(true){
$str = '"'.($v);
$found = pagelayer_xss_content($str);
//echo (string)$v.'--'.$found."\n";
if(strlen($found) > 0){
// There is htmlentities?
if(strpos($v, $found) === false){
$v = '';
break;
}
$v = str_replace($found, '', $v);
}else{
break;
}
}
}
$block[$k] = $v;
}
}
return $block;
}
// Check for XSS codes in our shortcode attributes
function pagelayer_sanitize_shortcode_atts($content){
// Do we have something suspicious ?
$tmp_check = pagelayer_xss_content($content);
if(empty($tmp_check)){
return $content;
}
pagelayer_load_shortcodes();
preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
$prefixes = ['pl_'];
$prefixes = apply_filters( 'pagelayer_valid_shortcode_tag', $prefixes);
foreach ($matches as $shortcode) {
$shortcode_name = $shortcode[2];
$vailid = false;
foreach($prefixes as $prefix) {
if (strpos($shortcode_name, $prefix) === 0) {
$vailid = true;
break;
}
}
if(!$vailid){
continue;
}
$attrs = shortcode_parse_atts( $shortcode[3] );
$atts = ' ';
foreach($attrs as $key => $value){
// Skip if key contains XSS
if (!is_numeric($key) && strlen(pagelayer_xss_content($key . '=')) > 0) continue;
$value = wp_filter_post_kses($value);
// Skip if value contains XSS
if (strlen(pagelayer_xss_content('"' . $value)) > 0) continue;
$atts .= is_numeric($key) ? $value . ' ' : $key . '="' . $value . '" ';
}
$new_shortcode = '[' . $shortcode_name . $atts . ']';
if(!empty($shortcode[5])){
$new_shortcode .= $shortcode[5].'[/' . $shortcode_name .']';
}
// Replace the original shortcode with sanitized attributes
$content = str_replace($shortcode[0], $new_shortcode, $content);
}
return $content;
}
function pagelayer_getting_started_notice(){
// Is Sitepad setup done?
$setup_done = get_option('sp_setup_done');
if(defined('SITEPAD') && empty($setup_done)){
return;
}
// If SitePad used custom BRAND SM
if(defined('BRAND_SM_CUSTOM')){
return;
}
echo '
';
if(defined('SITEPAD')){
echo ' '.__('Thanks for choosing '.BRAND_SM .'. We recommend that you see the short and sweet Getting Started Video to know the basics of '.BRAND_SM.'.');
}else{
echo ' '.__('Thanks for choosing Pagelayer. We recommend that you see the short and sweet Getting Started Video to know the basics of Pagelayer.', 'pagelayer');
}
echo '
';
}
// Show Changelog promo
function pagelayer_show_changelog_notice(){
// Is Sitepad setup done?
if(defined('SITEPAD')){
return;
}
echo '
'.__('Empower Your Designs: Pagelayer 1.8.1 - Unleashing Seamless Integration with Gutenberg for Enhanced Website Creation! Read More .', 'pagelayer') .'
';
}
// Show promo notice on dashboard
function pagelayer_show_promo(){
global $pagelayer_promo_opts;
$opts = $pagelayer_promo_opts;
echo '
Dismiss
';
if(!empty($opts['image'])){
echo '
';
}
echo '
We are glad you like Pagelayer and have been using it since the past few days. It is time to take the next step !
'.(empty($opts['pro_url']) ? '' : 'Buy Pagelayer Pro ').'
'.(empty($opts['rating']) ? '' : 'Rate it 5★\'s ').'
'.(empty($opts['facebook']) ? '' : ' Facebook ').'
'.(empty($opts['twitter']) ? '' : ' Tweet ').'
'.(empty($opts['website']) ? '' : 'Visit our website ').'
Pagelayer Pro has many more features like 60+ widgets, 400+ sections, Theme Builder, WooCommerce Builder, Theme Creator and Exporter, Form Builder, Popup Builder, etc.';
if(date('Ymd') <= 20200331){
echo 'Promotional Offer : If you buy Pagelayer Pro before 31st March, 2020 then you will get an additional year free and your license will expire on 31st March, 2022 .';
}
echo '
';
}
// Are we to show a promo ?
function pagelayer_maybe_promo($opts){
global $pagelayer_promo_opts;
// There must be an interval
if(!current_user_can('activate_plugins')){
return false;
}
// There must be an interval
if(empty($opts['interval'])){
return false;
}
// Are we to show a promo
$opt_name = 'pagelayer_promo_time';
$promo_time = get_option($opt_name);
// First time access
if(empty($promo_time)){
update_option($opt_name, time() + (!empty($opts['after']) ? $opts['after'] * 86400 : 0));
$promo_time = get_option($opt_name);
}
// Is there interval elapsed
if(time() > $promo_time){
$pagelayer_promo_opts = $opts;
add_action('admin_notices', 'pagelayer_show_promo');
}
// Are we to disable the promo
if(isset($_GET['pagelayer_promo']) && (int)$_GET['pagelayer_promo'] == 0){
update_option($opt_name, time() + ($opts['interval'] * 86400));
die('DONE');
}
}
// Show the Pro notice
function pagelayer_show_pro_notice(){
if(defined('PAGELAYER_PREMIUM')){
return;
}
echo ''.__('This feature is a part of
Pagelayer Pro . You will need to purchase
Pagelayer Pro to use this feature.').'
';
}
// Show the Pro Div
function pagelayer_show_pro_div($head = '', $message = '', $admin_css = 1){
if(defined('PAGELAYER_PREMIUM')){
return;
}
if(basename(get_template_directory()) == 'popularfx'){
$pro_url = 'https://popularfx.com/pricing?from=pagelayer-plugin';
$pro_txt = 'PopularFX Pro';
}else{
$pro_url = PAGELAYER_PRO_PRICE_URL;
$pro_txt = 'Pagelayer Pro';
}
if(!empty($admin_css)){
wp_enqueue_style( 'pagelayer-admin', PAGELAYER_CSS.'/pagelayer-admin.css', array(), PAGELAYER_VERSION);
}
echo '';
if(!empty($head)){
echo '
'.$head.' ';
}
echo '
';
if(empty($message)){
echo __('This feature is a part of
'.$pro_txt.' . You will need to purchase
'.$pro_txt.' to use this feature.');
}else{
echo $message;
echo ' '.__('This feature is a part of
'.$pro_txt.' .');
}
echo '
Get '.$pro_txt.'
';
}
// Bread Crumbs with links
function pagelayer_get_breadcrumb(){
global $post;
// Home page
$ret = '{{home}} ';
// Is Front page
if(is_front_page()){
return $ret;
// Is search query
}elseif(is_search()){
$ret .= '{{separator}} {{search_prefix}} ';
$ret .= '';
$ret .= ''.get_search_query().' ';
$ret .= ' ';
//Is category or single post
}elseif(is_category() || is_single()){
$ret .= '{{separator}} ';
$categories = get_the_category();
$separator = ' ';
$output = '';
if(!empty($categories)){
$ret .= get_category_parents($categories[0], true, ' {{separator}} ');
}
if(is_single()) {
/* if (empty($categories)){
$ret .= ' {{separator}} ';
} */
$ret .= ''.get_the_title().' ';
}
// Is page
}elseif(is_page() ){
if(!empty($post->post_parent)){
$ancestors = array_reverse(get_post_ancestors( $post->ID ));
$page_on_front = get_option('page_on_front');
foreach( $ancestors as $ancestor ){
if($page_on_front == $ancestor){
continue;
}
$ret .= '{{separator}} '.get_the_title($ancestor).' ';
}
$ret .=' {{separator}} '.get_the_title().' ';
}else{
$ret .= '{{separator}} ';
$ret .= ''.get_the_title().' ';
}
}else{
$ret .= '{{separator}} ';
$ret .= ''.wp_title('', false ).' ';
}
// wooCommerce Integration left
return $ret;
}
// Portfolio Posts
function pagelayer_widget_posts($args){
$r = new \WP_Query($args);
$ret = '';
if ( $r->have_posts() ){
if($args['filter_by'] != 'none' && $args['post_type'] == 'post'){
$ret .= '';
$data_filter = ( $args['filter_by'] == 'category' ? get_categories() : get_tags() );
if(!empty($data_filter)){
$ret .= '
'.__pl('All').'
';
foreach($data_filter as $filter) {
$ret .= '
' . $filter->name . '
';
}
}
$ret .= '
';
}
$ret .= '';
while ( $r->have_posts() ) : $r->the_post();
$post_meta = ( $args['filter_by'] == 'category' ? get_the_category() : get_the_tags() );
$meta_attr = '';
if($post_meta){
$meta_array = array();
foreach( $post_meta as $meta ){
$meta_array[] = $meta->name;
}
$meta_attr .= ' data-category="'.implode(' ', $meta_array).'"';
}
$ret .= '
';
endwhile;
$ret .= '
';
}
return $ret;
}
// List all available sizes of images registered on WordPress
function pagelayer_image_sizes(){
$sizes = array();
$sizes = get_intermediate_image_sizes();
$ret = array();
foreach($sizes as $size){
$ret[$size] = __pl($size);
}
return $ret;
}
function pagelayer_remove_excerpt_more($more){
return '';
}
function pagelayer_posts($params, $args = []){
global $post, $wp_query;
if(isset($params['exc_length'])){
$exc_length = (int) $params['exc_length'];
add_filter( 'excerpt_length', function($length) use($exc_length){
return $exc_length;
}, 999 );
}
add_filter('excerpt_more', 'pagelayer_remove_excerpt_more', 999);
// If args is empty
if(empty($args)){
$args = array(
'post_type' => $params['post_type'],
'posts_per_page' => $params['posts_per_page'],
'order' => $params['order']
);
if(!empty($params['paged'])){
$args['paged'] = $params['paged'];
}
if (!empty($params['term']) || !empty($params['exc_term'])) {
$tax_query = [];
if (!empty($params['term'])) {
$terms = explode(',', $params['term']);
$include = array_reduce($terms, function ($carry, $term) {
list($taxonomy, $slug, $id) = explode(':', $term);
$carry[$taxonomy][] = $slug;
return $carry;
}, []);
$filters = array_filter([
isset($include['category']) ? [
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $include['category'],
'include_children' => false,
] : null,
isset($include['post_tag']) ? [
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $include['post_tag'],
'include_children' => false,
] : null,
]);
if(!empty($filters)){
$tax_query[] = array_merge(['relation' => 'OR'], $filters);
}
}
// Handle exclusions
if (!empty($params['exc_term'])) {
$terms = explode(',', $params['exc_term']);
$include = array_reduce($terms, function ($carry, $term) {
list($taxonomy, $slug, $id) = explode(':', $term);
$carry[$taxonomy][] = $slug;
return $carry;
}, []);
$filters = array_filter([
isset($include['category']) ? [
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $include['category'],
'operator' => 'NOT IN',
'include_children' => false,
] : null,
isset($include['post_tag']) ? [
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $include['post_tag'],
'operator' => 'NOT IN',
'include_children' => false,
] : null,
]);
if(!empty($filters)){
$tax_query[] = array_merge(['relation' => 'AND'], $filters);
}
}
// Apply the combined tax_query
if(!empty($tax_query)){
$args['tax_query'] = array_merge(['relation' => 'AND'], $tax_query);
}
}
if(!empty($params['author_name'])){
$author_name = explode(':', $params['author_name']);
$args['author_name'] = $author_name[0];
}
if(!empty($params['exc_author'])){
$exc_author = explode(':', $params['exc_author']);
$args['author'] = '-'.$exc_author[1];
}
if (!empty($params['offset'])) {
$args['offset'] = (int) $params['offset'];
// Make Compatible for Infinite load
if(!empty($params['infinite_types']) && !empty($params['paged']) && $params['paged'] > 1 ){
$args['offset'] = $args['offset'] + (($params['paged'] - 1) * $params['posts_per_page']);
}
}
if(!empty($params['ignore_sticky'])){
$args['ignore_sticky_posts'] = $params['ignore_sticky'];
}
if(!empty($params['orderby'])){
$args['orderby'] = $params['orderby'];
}
if(!empty($params['by_period'])){
$date_arg = array();
switch($params['by_period']){
case 'last_day':
$date_arg['day'] = date('j')-1;
break;
case 'last_week':
$date_arg['week'] = date('W')-1;
break;
case 'last_month':
$date_arg['month'] = date('n')-1;
break;
case 'last_year':
$date_arg['year'] = date('Y')-1;
break;
case 'custom':
$date_arg['before'] = $params['before_date'];
$date_arg['after'] = $params['after_date'];
break;
}
$args['date_query'] = array(
$date_arg
);
}
}
//pagelayer_print($args);
// Only see published posts
$args['post_status'] = 'publish';
$postsquery = new WP_Query($args);
$data = '';
if(!wp_doing_ajax() && !empty($params['infinite_types'])){
$data.='
';
}
if(!$postsquery->have_posts()){
return 'No posts found! ';
}
// To reset the post when the $wp_query->post is empty
$orig_post = $post;
while($postsquery->have_posts()) : $postsquery->the_post();
$data .= '
';
if(!empty($params['show_title'])){
$data .= '
'. get_the_title().'
';
}
$data .= '
';
$sep = '';
if(!empty($params['meta_sep'])){
$sep = '
'.$params['meta_sep'].' ';
}
if(!empty($params['author'])){
$data .= '
By '.esc_html(get_the_author()).' '.$sep;
}
if(!empty($params['date'])){
$data .= '
'.get_the_date('j').' '.get_the_date('M, y').' '.$sep;
}
if(!empty($params['category'])){
$category = get_the_category();
$singlecategory = '';
foreach( $category as $cat ){
$singlecategory .= '
'. $cat->name .' ';
}
if(!empty($singlecategory)){
$data .= '
' . $singlecategory . ' '.$sep;
}
}
if(!empty($params['tags'])){
$tags = get_the_tags();
$singletag = '';
if(!empty($tags)){
foreach( $tags as $tag ){
$singletag .= '
'. $tag->name .' ';
}
if(!empty($singletag)){
$data .= '
'.$singletag.' '.$sep;
}
}
}
if(!empty($params['comments']) && comments_open($postsquery->ID)){
$data .= ''.$sep;
}
$data .= '
';
if(!empty($params['show_content'])){
$data .= '
';
if($params['show_content'] == 'excerpt'){
$data .= pagelayer_the_content(get_the_excerpt());
}elseif($params['show_content'] == 'full'){
$data .= pagelayer_the_content(get_the_content());
}
$data .= '
';
}
if(!empty($params['show_more'])){
$data .= '
';
//$data .= '
'.$params['more'].' ';
}
//$data .= '
';
$data .= '
';
endwhile;
// In the Gutenberg while adding new page the $wp_query->post was empty
if ( !isset( $wp_query ) || empty($wp_query->post) ) {
$GLOBALS['post'] = $orig_post;
}else{
wp_reset_postdata();
}
return $data;
}
// Get Post Revision
function pagelayer_get_post_revision_by_id($postID){
// Insert the post revision into the database
$post_revisions = array();
$reviews = wp_get_post_revisions($postID);
foreach($reviews as $values){
$date_format = date_i18n('j-M @ H:i', strtotime( $values->post_modified ) );
$user_meta = get_userdata($values->post_author);
if ( false !== strpos( $values->post_name, 'autosave' ) ) {
$type = 'autosave';
} else {
$type = 'revision';
}
$post_tmp_data = array(
'ID' => $values->ID,
'post_author_name' => $user_meta->data->display_name,
'post_author_url' => get_avatar_url($values->post_author),
'post_date' => $date_format,
'post_date_ago' => human_time_diff(strtotime($values->post_modified), current_time( 'timestamp' )) . ' ago ',
'post_type' => $type,
);
$post_revisions[] = $post_tmp_data;
}
return $post_revisions;
}
// Gets author data
function pagelayer_author_data($postID){
$authorID = get_post_field('post_author', $postID);
$data['display_name'] = get_the_author_meta( 'display_name' , $authorID );
$data['description'] = get_the_author_meta( 'description' , $authorID );
$data['user_url'] = get_author_posts_url( $authorID , '' );
$data['avatar'] = get_avatar_url( $authorID );
return $data;
}
// Posts Slider
function pagelayer_posts_slider($params){
$args = array();
if(isset($params['post']['post_type'])){
$args['post_type'] = $params['post']['post_type'];
}
if(isset($params['post']['category'])){
$args['category_name'] = $params['post']['category'];
}
if(isset($params['post']['tags'])){
$args['tag'] = $params['post']['tags'];
}
if(isset($params['post']['order_by'])){
$args['orderby'] = $params['post']['order_by'];
}
if(isset($params['post']['sort_order'])){
$args['order'] = $params['post']['sort_order'];
}
if(isset($params['post']['post_count'])){
$args['posts_per_page'] = $params['post']['post_count'];
}
$data = '';
$postsquery = new WP_Query($args);
if ( $postsquery->have_posts() ){
while ( $postsquery->have_posts() ) : $postsquery->the_post();
$data .= '
';
$data .= '
'. get_the_title().'
';
$data .= '
';
if($params['post']['show_excerpt'] == "true"){
if(has_excerpt()){
$excerpt = get_the_excerpt();
$data .= pagelayer_the_content($excerpt);
}
}
$data .= '
';
$data .= '
Read More ';
$data .= '
';
$data .= '
';
endwhile;
}
return $data;
}
// Gets the site logo URLs
function pagelayer_site_logo(){
if(get_theme_mod('custom_logo')){
$logo_id = get_theme_mod('custom_logo');
return pagelayer_image($logo_id);
}
return NULL;
}
// Create select options
function pagelayer_create_sel_options( $opt_array , $selected = ''){
$options = '';
foreach($opt_array as $x => $val){
// Single item
if(is_string($opt_array[$x])){
$options .= pagelayer_sel_option($x, $val, $selected);
// Groups
}else{
if(array_key_exists('hide_drop', $opt_array[$x]) && !empty($opt_array[$x]['hide_drop'])){
continue;
}
// If Label is there, then its a normal option
if(array_key_exists('label', $opt_array[$x])){
$options .= pagelayer_sel_option($x, $opt_array[$x]['label'], $selected);
// Optgroups
} else{
$options .= '';
$options .= pagelayer_create_sel_options($opt_array[$x], $selected);
$options .= ' ';
}
}
}
return $options;
}
// Create option HTML
function pagelayer_sel_option($val, $lang, $selected){
return ''. $lang .' ';
}
// Get values from multi-dimensional array by key
function pagelayer_multi_array_search(&$array, $key){
if(!is_array($array)){
return false;
}
foreach ($array as $k => $v) {
if($k == $key){
return $v;
}
if (is_array($v)) {
$found = pagelayer_multi_array_search($v, $key);
if(!empty($found)){
return $found;
}
}
}
return false;
}
function pagelayer_get_post_term(){
$args = [
'taxonomy' => array('category','post_tag'),
'hide_empty' => false,
];
$terms = get_terms( $args );
$ret = array();
foreach ( $terms as $term ) {
$ret[$term->taxonomy.':'.$term->slug.':'.$term->term_taxonomy_id] = $term->taxonomy .': '. $term->name;
}
//pagelayer_print($terms);die();
return $ret;
}
function pagelayer_get_post_author(){
$args = [
'capability' => array( 'edit_posts' ),
'fields' => [
'ID',
'display_name',
'user_nicename',
]
];
// Capability queries were only introduced in WP 5.9.
if( version_compare( $GLOBALS['wp_version'], '5.9-alpha', '<' ) ){
$args['who'] = 'authors';
unset( $args['capability'] );
}
$authors = new \WP_User_Query( $args );
$ret = array();
foreach ( $authors->get_results() as $author ) {
$ret[$author->user_nicename.':'.$author->ID] = $author->display_name;
}
//pagelayer_print($authors->get_results());die();
return $ret;
}
// Gets the registered post types
function pagelayer_get_public_post_types( $args = [] ) {
global $pagelayer;
$post_type_args = [
'public' => true,
];
$post_type_args = wp_parse_args( $post_type_args, $args );
$_post_types = get_post_types( $post_type_args, 'objects' );
$post_types = array();
foreach ( $_post_types as $post_type => $object ) {
if($post_type == $pagelayer->builder['name']){
continue;
}
$post_types[ $post_type ] = $object->label;
}
//print_r($post_types);
return $post_types;
}
// Simply echo and dir
function pagelayer_json_output(&$done){
echo json_encode($done);
wp_die();
}
// Get the current query for render the product
function pagelayer_shortcode_current_query($query_args, $atts, $type){
global $wp_query;
if($type == 'pagelayer_current_query'){
if ( ! is_page( wc_get_page_id( 'shop' ) ) ) {
$query_args = $wp_query->query_vars;
}
add_action( "woocommerce_shortcode_before_{$type}_loop", function () {
wc_set_loop_prop( 'is_shortcode', false );
} );
if(!empty($atts['paginate'])){
$page = get_query_var( 'paged', 1 );
if( 1 < $page ) {
$query_args['paged'] = $page;
}
}
// Always query only IDs
$query_args['fields'] = 'ids';
}
return $query_args;
}
// Loads the tags which have parameters of a particular type
function pagelayer_get_prop_type($types){
global $pagelayer;
if(!is_array($types)){
$types = [$types];
}
$ret = [];
// Loop thru all shortcodes
foreach($pagelayer->shortcodes as $tag => $vvv){
// Lets create the CSS, Classes, Attr. Also clean the dependent atts
foreach($pagelayer->tabs as $tab){
if(empty($pagelayer->shortcodes[$tag][$tab])){
continue;
}
foreach($pagelayer->shortcodes[$tag][$tab] as $section => $Lsection){
$props = empty($pagelayer->shortcodes[$tag][$section]) ? @$pagelayer->styles[$section] : @$pagelayer->shortcodes[$tag][$section];
//echo $tab.' - '.$section.' - ';
if(empty($props)){
continue;
}
// Loop all props
foreach($props as $prop => $param){
// Load any attachment values
if(!in_array($param['type'], $types)){
continue;
}
$ret[$tag][$prop] = $param['type'];
}
}
}
}
//r_print($ret);die();
return $ret;
}
function pagelayer_export_content($content){
global $pagelayer;
// Just call do_shortcode so we can get list of media files to export
//do_shortcode($content);
$theme_url = preg_replace('/http(s?):\/\//is', '', get_stylesheet_directory_uri());
$content = preg_replace('/http(s?):\/\/'.preg_quote($theme_url, '/').'/is', '{{theme_url}}', $content);
// Remove unnecessary spaces
$content = preg_replace('/--\>\s*(?!', $content);
// Replace links of the theme for images
$content = pagelayer_export_theme_links($content, get_stylesheet_directory_uri());
////////////////////
// Handle Link IDs
////////////////////
if(empty($pagelayer->e['link_tags'])){
$pagelayer->e['link_tags'] = pagelayer_get_prop_type('link');
//r_print($pagelayer->e['link_tags']);die();
}
if(empty($pagelayer->e['media_tags'])){
$pagelayer->e['media_tags'] = pagelayer_get_prop_type(['image', 'video', 'audio', 'media', 'multi_image']);
//r_print($pagelayer->e['media_tags']);die();
}
$parsed = parse_blocks($content);
//r_print($parsed);//die();
$parsed = pagelayer_export_link_ids($parsed);
// Export the media as well
$parsed = pagelayer_export_media($parsed);
// Reserialize
$content = serialize_blocks($parsed);
// We store in SP format
$content = str_replace(').)*+)?}\s+)?(?P\/)?-->/s', $content, $matches);
if(!empty($matches['attrs'])){
foreach($matches['attrs'] as $k => $v){
preg_match('/nav_list"\s*:\s*"(\d*)"/is', $v, $vmatch);
if(!empty($vmatch[1])){
$vmatch[1] = (int)$vmatch[1];
$pagelayer->export_menus[$vmatch[1]] = $vmatch[1];
//r_print($pagelayer->export_menus);
}
}
}
return $content;
}
function pagelayer_export_link_ids($parsed){
global $pagelayer;
foreach($parsed as $k => $v){
if(!empty($v['innerBlocks'])){
$parsed[$k]['innerBlocks'] = pagelayer_export_link_ids($v['innerBlocks']);
}
if(!preg_match('/pagelayer/is', $v['blockName'])){
continue;
}
$tag = str_replace('pagelayer/', '', $v['blockName']);
//echo $tag;//die();
// Is there a tag having a link prop
if(empty($pagelayer->e['link_tags'][$tag])){
continue;
}
//echo $tag;die();
foreach($pagelayer->e['link_tags'][$tag] as $kk => $vv){
if(!empty($v['attrs'][$kk]) && is_numeric($v['attrs'][$kk])){
$linked = get_post($v['attrs'][$kk]);
if(!empty($linked->post_name)){
$parsed[$k]['attrs'][$kk] = '||link_id|'.$linked->post_type.'|'.$linked->post_name.'||';
}
//echo $tag;echo '-'.$kk;r_print($parsed[$k]['attrs']);die();
}
}
}
return $parsed;
}
// Replace theme links with theme_url
function pagelayer_export_theme_links($content, $link){
global $sitepad;
// Theme URL correction code
$theme_url = preg_replace('/http(s?):\/\//is', '', $link);
$theme_urls[0] = 'http://'.$theme_url;
$theme_urls[1] = 'https://'.$theme_url;
$theme_urls[2] = $theme_url;
$theme_urls[3] = str_replace('/', '\\/', $theme_urls[0]);
$theme_urls[4] = str_replace('/', '\\/', $theme_urls[1]);
$theme_urls[5] = str_replace('/', '\\/', $theme_url);
foreach($theme_urls as $k => $v){
$content = preg_replace_callback('/'.preg_quote($v, '/').'([^"]*)/is', 'pagelayer_export_theme_links_replacer', $content);
}
$content = str_ireplace($theme_urls, '{{theme_url}}', $content);
return $content;
}
// This function is a part of pagelayer_export_theme_links
function pagelayer_export_theme_links_replacer($matches){
return '{{theme_url}}'.str_replace('\\/', '/', $matches[1]);
}
// Export media
function pagelayer_export_media($parsed){
global $pagelayer;
foreach($parsed as $k => $v){
if(!empty($v['innerBlocks'])){
$parsed[$k]['innerBlocks'] = pagelayer_export_media($v['innerBlocks']);
}
if(!preg_match('/pagelayer/is', $v['blockName'])){
continue;
}
$tag = str_replace('pagelayer/', '', $v['blockName']);
//echo $tag;//die();
// Is there a tag having a link prop
if(empty($pagelayer->e['media_tags'][$tag])){
continue;
}
//echo $tag;die();
foreach($pagelayer->e['media_tags'][$tag] as $kk => $vv){
if(empty($v['attrs'][$kk])){
continue;
}
$is_array = 0;
// Is it an array
if(is_array($v['attrs'][$kk])){
$ids = $v['attrs'][$kk];
$is_array = 1;
// Is it of the format 1,2,3
}elseif(preg_match('/^((\d*)(,?))*$/is', $v['attrs'][$kk])){
$ids = pagelayer_maybe_explode(',', $v['attrs'][$kk]);
// Its a number or string
}else{
// Is it our default image ?
if(preg_match('/pagelayer-pro\/images\/default-image.png$/is', $v['attrs'][$kk])){
$parsed[$k]['attrs'][$kk] = '';
continue;
}
// It should be a number
if(!is_numeric($v['attrs'][$kk])){
continue;
}
$ids = [$v['attrs'][$kk]];
}
$ret = [];
foreach($ids as $id){
$file = pagelayer_export_media_files($id, $exp_img_url);
// Did it export ?
if(empty($file) || !file_exists($file)){
continue;
}
$ret[] = $exp_img_url;
}
$parsed[$k]['attrs'][$kk] = $is_array ? $ret : implode(',', $ret);
//echo $tag;echo '-'.$kk;r_print($parsed[$k]['attrs']);die();
}
}
return $parsed;
}
// Exports the media to the images folder of the current theme
function pagelayer_export_media_files($id, &$url = ''){
$theme_dir = get_stylesheet_directory();
$image_dir = $theme_dir.'/images/';
@mkdir($image_dir);
// Get the file path
$file = get_attached_file($id);
if(empty($file) || !file_exists($file)){
return false;
}
$dest_file = $image_dir.basename($file);
// Copy the file
copy($file, $dest_file);
// Replace the text
$url = '{{theme_url}}/images/'.basename($file);
return $dest_file;
//echo $content;
}
// Insert a post which is a Pagelayer Post
function pagelayer_sanitize_content($content){
// Replace Vars
$template_vars = pagelayer_template_vars();
foreach($template_vars as $key => $val){
$content = str_replace($key, $val, $content);
}
if(defined('PAGELAYER_BLOCK_PREFIX') && PAGELAYER_BLOCK_PREFIX == 'wp'){
$content = str_replace('