* @license GPL-3.0+ * @link https://puvox.software * @copyright 2018-2019 Puvox.software * */ if(!trait_exists('default_methods__Puvox_Software')) { trait default_methods__Puvox_Software { public function __construct($arg1=false) { $this->is_development = defined("_puvox_machine_") ; // set in devmachine (in "my_superglobals.php" and in "EnvVariables") if($this->is_development) $this->display_errors(); // #### Because this is a trait, we don't use "__FILE__" & "__DIR__" here, but "Reflection". #### $reflection = (new \ReflectionClass(__CLASS__)); $this->plugin_NAMESPACE = $reflection->getNamespaceName(); // get parent's namespace name $this->prefix = strtolower( preg_replace('![^A-Z]+!', '', $this->plugin_NAMESPACE) );// get prefix from current namespace initials (i.e. xyz) $this->prefix_ = $this->prefix .'_'; $this->plugin_FILE = $reflection->getFileName(); // set plugin's main file path $this->plugin_DIR = dirname($this->plugin_FILE); // set plugin's dir path $this->plugin_URL = plugin_dir_url($this->plugin_FILE); // get plugin's dir URL $this->wp_URL = network_home_url('/'); // WP installation home $this->wp_FOLDER = network_home_url('/', 'relative'); // WP folder $this->home_URL = home_url('/'); // current sub/site home url $this->home_FOLDER = home_url('/', 'relative'); // current sub/site home folder $this->is_https = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443); $this->httpsCurrent = $this->is_https ? 'https://' : 'http://'; $this->httpsReal = preg_replace('/(http(s|):\/\/)(.*)/i', '$1', $this->home_URL); $this->domainCurrent = $_SERVER['HTTP_HOST']; $this->domainReal = $this->getDomain($this->home_URL); $this->domain = $this->httpsReal.$this->domainReal; $this->siteslug = str_ireplace('.','_', $this->domainReal); $this->requestURI = $_SERVER["REQUEST_URI"]; $this->urlAfterHome = substr($this->requestURI, strlen($this->home_FOLDER) ); $this->pathAfterHome = parse_url($this->urlAfterHome, PHP_URL_PATH); $this->current_URL = $this->domain . $this->requestURI; $this->currentURL = $this->current_URL; //shortand $this->homeUrlStripped = $this->stripUrlPrefixes($this->home_URL); $this->is_localhost = (stripos($this->home_URL,'://127.0.0.1')!==false || stripos($this->home_URL,'://localhost')!==false ); $this->is_settings_page = false; $this->wpdb = $GLOBALS['wpdb']; $this->options_tabs = []; if ($this->old_version()){ register_activation_hook( $this->plugin_FILE, function(){ exit( __("Sorry, your PHP version ". phpversion() ." is very old. We suggest changing your hosting's PHP version.") ); } ); return; } // initial variables $this->my_plugin_vars(); $this->newtork_managed = is_multisite() && $this->getNetworkedState(); $this->opts = $this->refresh_options(); // Setup final variables $this->refresh_options_TimeGone(); $this->logs_table_name = $GLOBALS['wpdb']->base_prefix . $this->plugin_slug_u.'-error_logs'; $this->check_if_pro_plugin(); $this->__construct_my(); // All other custom construction hooks $pgnm = property_exists($this,'customOptsPageUrl') ? $this->customOptsPageUrl : $this->slug; $this->settingsPHP_page = ( array_key_exists('menu_button_level', $this->static_settings) && $this->static_settings['menu_button_level']=="mainmenu" ) ? 'admin.php' : (is_network_admin() || $this->newtork_managed ? 'settings.php' : 'options-general.php'); $this->plugin_page_url_current = ( is_network_admin() || $this->newtork_managed ? network_admin_url($this->settingsPHP_page) : admin_url($this->settingsPHP_page) ) .'?page='.$pgnm; $this->plugin_page_url_main = ( is_multisite() ? network_admin_url($this->settingsPHP_page) : admin_url($this->settingsPHP_page) ) .'?page='.$pgnm; $this->plugin_files = array_merge( (property_exists($this, 'plugin_files') ? $this->plugin_files : [] ), ['index.php'] ); $this->translation_phrases= $this->get_phrases(); $this->ip = $this->get_visitor_ip(); $this->isMobile = false; $this->is_in_customizer = (stripos($this->currentURL, admin_url('customize.php')) !== false); $this->myplugin_class = 'myplugin postbox version_'. (!$this->static_settings['has_pro_version'] ? "free" : ($this->is_pro_legal ? "pro" : "not_pro") ); $this->addon_namepart = 'puvox.software'; $this->define_option_tabs(); //activation & deactivation (empty hooks by default. all important things migrated into `refresh_options`) register_activation_hook( $this->plugin_FILE, [$this, 'activate'] ); register_deactivation_hook( $this->plugin_FILE, [$this, 'deactivate'] ); //translation hook add_action('init', [$this, 'load_textdomain'] ); //==== my other default hooks ===// $this->setupLinksAndMenus(); //shortcodes $this->shortcodes_initialize(); // if buttons needed $this->tinymce_funcs(); // for backend ajax add_action( 'wp_ajax_'.$this->plugin_slug_u.'_all', [$this, 'ajax_backend_call'] ); add_action( 'admin_head', [$this,'admin_head_func']); add_action( 'current_screen', function(){ $this->admin_scripts(null); } ); //add uninstaller file if(is_admin()) $this->add_default_uninstall(); //add_action( 'shutdown', [$this, 'my_shutdown_for_versioning']); add_action('wp', [$this, 'flush_checkpoint'], 999); // functions for PRO-ADDON upload // add_filter( 'pre_move_uploaded_file', function( $null, $file, $new_file, $type ){ return $path; }, 10, 4); $this->pro_file_part = 'puvox-software'; if($this->static_settings['has_pro_version']) { add_filter( 'upload_mimes', [$this,'upload_mimes_filter'], 1); add_filter( 'wp_handle_upload', [$this,'wp_handle_upload_filter'], 10, 2); } } public function setupLinksAndMenus() { // If plugin has options if($this->static_settings['show_opts']) { //add admin menu if (is_multisite()){ add_action('network_admin_menu', [$this, 'register_menus'] ); if (!$this->newtork_managed) add_action('admin_menu', [$this, 'register_menus'] ); } else { add_action('admin_menu', [$this, 'register_menus'] ); } //redirect to settings page after activation (if not bulk activation) add_action('activated_plugin', function($plugin) { if ($this->is_not_bulk_activation($plugin)) { exit( wp_redirect($this->plugin_page_url_main.'&isactivation') ); } } ); } // add Settings & Donate buttons in plugins list add_filter( (is_network_admin() ? 'network_admin_' : ''). 'plugin_action_links_'.plugin_basename($this->plugin_FILE), function($links){ if(!$this->static_settings['has_pro_version']) { $links[] = ''.$this->static_settings['menu_text']['donate'].''; } if($this->static_settings['show_opts']){ $links[] = ''.$this->static_settings['menu_text']['settings'].''; } if(isset($this->opts['custom_opts_page'])){ $links[] = ''.$this->static_settings['menu_text']['settings'].''; } //if(is_network_admin() && $this->initial_static_options['allowed_on'] =='singlesite'){ unset($links['activate']); $links[] = ''.$this->static_settings['menu_text']['deactivated_only_from'].' SUB-SITES'; } return $links; }); } public function register_menus() { $menu_button_name = (array_key_exists('menu_button_name', $this->static_settings) ? $this->static_settings['menu_button_name'] : $this->opts['name'] ); if( array_key_exists('menu_button_level', $this->static_settings) && $this->static_settings['menu_button_level']=="mainmenu" ) // icons: https://goo.gl/WXAYCi add_menu_page($menu_button_name, $menu_button_name, $this->static_settings['required_role'] , $this->slug, [$this, 'opts_page_output_parent'], $this->static_settings['menu_icon'] ); else add_submenu_page($this->settingsPHP_page, $menu_button_name, $menu_button_name, $this->static_settings['required_role'] , $this->slug, [$this, 'opts_page_output_parent'] ); // if target is custom link (not options page) if(array_key_exists('menu_button_link', $this->opts)){ add_action( 'admin_footer', function (){ ?> '.$this->opts['name'].': '. $this->static_settings['menu_text']['activated_only_from']. ' NETWORK DASHBOARD'; //$text .= ''; die($text); } //$this->plugin_updated_hook(); if(method_exists($this, 'activation_funcs') ) { $this->activation_funcs(); } } /* public function activate_old($network_wide){ $actKey = $this->slug.'_activat'; $show_die=isset($_GET['action']) && $_GET['action']=='error_scrape'; //if activation allowed from only on multisite or singlesite or Both? if(!$show_die) { if (get_site_option($actKey)) { $show_die=true; delete_site_option($actKey); } else { $show_die= ! $this->if_correct_activable($network_wide) ; if($show_die) { //update_site_option($actKey,true); } } } if($show_die) { $text= '

('.$this->opts['name'].') '. $this->static_settings['menu_text']['activated_only_from']. ' '.strtoupper($this->opts['allowed_on']).'

'; //$text .= ''; die($text); } //$this->plugin_updated_hook(); if(method_exists($this, 'activation_funcs') ) { $this->activation_funcs(); } } public function if_correct_activable($network_wide=false) { return !is_multisite() ? true : ( $this->initial_static_options['allowed_on'] == 'both' ? true : ( ($this->initial_static_options['allowed_on'] =='network' && is_network_admin() ) || ( $this->initial_static_options['allowed_on'] =='singlesite' && (!$network_wide && !is_network_admin()) ) ) ); } */ public function deactivate($network_wide){ if(method_exists($this, 'deactivation_funcs') ) { $this->deactivation_funcs($network_wide); } } //add my default values public function my_plugin_vars($step=0) { //get default plugin data: https://goo.gl/Z3z8FW include_once(ABSPATH . "wp-admin/includes/plugin.php"); $plugin_vars = $this->pluginvars(); $this->slug = sanitize_key($plugin_vars['TextDomain']); //same as foldername $this->plugin_slug = $this->slug; //same as foldername $this->plugin_slug_u= str_replace('-','_', $this->slug); $domain ='https://puvox.software' ; // $this->is_development && !property_exists($this,'avoid_localhost_development') ? 'https://puvox.software' ://https://127.0.0.1/wp/puvox.software $this->static_settings = $plugin_vars + array( 'menu_text' => array( 'donate' =>__('Donate'), 'settings' =>__('Settings'), 'open_settings' =>__('You can access settings from dashboard of:'), 'activated_only_from' =>__('Plugin activable only from'), 'deactivated_only_from' =>__('Plugin deactivable only from'), ), 'lang' => $this->get_locale__SANITIZED(), 'wp_rate_url' => 'https://wordpress.org/support/plugin/'.$this->slug.'/reviews/#new-post', 'public_assets_url' => 'https://ps.w.org/internal-functions-for-protectpages-com-users/trunk/', 'question_mark_icon'=> 'https://ps.w.org/internal-functions-for-protectpages-com-users/trunk/assets/question-mark-2.png', 'donate_url' => 'https://paypal.me/Puvox', // business: http://paypal.me/Puvox || personal : http://paypal.me/tazotodua 'mail_errors' => 'wp_plugin_errors@puvox.software', 'licenser_domain' => $domain, 'musthave_plugins' => $domain.'/blog/must-have-wordpress-plugins/', 'purchase_url' => $domain.'/?purchase_wp_plugin='.$this->slug, 'purchase_check' => $domain.'/?purchase_wp_act=', 'wp_tt_freelancers' => 'https://goo.gl/wZKANN', 'wp_fl_freelancers' => 'https://goo.gl/JSVy37', 'wp_pph_freelancers'=> 'https://goo.gl/vhrqiM' ); //enrich from main class $this->declare_settings(); $this->static_settings = $this->static_settings + $this->initial_static_options; } //load translation public function load_textdomain(){ load_plugin_textdomain( $this->slug, false, basename($this->plugin_DIR). '/languages/' ); } public function is_not_bulk_activation($plugin) { return ( $plugin == plugin_basename( $this->plugin_FILE ) && !((new WP_Plugins_List_Table())->current_action()=='activate-selected')); } public function pluginvars(){ /* [Name] => My Plugin Name [PluginURI] => https://example.com [Version] => 1.23 [Description] => Plugin Description. By [Author]. [Author] => myAuthorTitle [AuthorURI] => https://example.com/xyz [TextDomain] => my-plugin-name [DomainPath] => /languages [Network] => [Title] => My Plugin Name [AuthorName] => Author Name */ return get_plugin_data( $this->plugin_FILE, $markup = true, $translate = false); //dont $translate, otherwise you will get error of: https://core.trac.wordpress.org/ticket/43869 } //get latest options (in case there were updated,refresh them) public function refresh_options(){ $this->opts = $this->get_option_CHOSEN($this->slug, []); if(!is_array($this->opts)) $this->opts = $this->initial_user_options; foreach($this->initial_user_options as $name=>$value){ if (!array_key_exists($name, $this->opts)) { $this->opts[$name]=$value; $should_update=true; } } $this->opts = array_merge($this->opts, $this->initial_static_options); $this->opts['name'] =$this->static_settings['Name']; $this->opts['title'] =$this->static_settings['Title']; $this->opts['version'] =$this->static_settings['Version']; if(isset($should_update)) { $this->update_opts(); } return $this->opts; } public function refresh_options_TimeGone(){ //if never updated if(empty($this->opts['last_update_time'])) { $this->opts['last_update_time'] = time(); $should_update=true; } if(empty($this->opts['last_updates'])) { $this->opts['last_updates'] = []; $should_update=true; } if(empty($this->opts['fist_install_date'])) { $this->opts['fist_install_date'] = time(); $should_update=true; } //if plugin updated through hook or manually... to avoid complete break.. if( empty($this->opts['last_version']) || $this->opts['last_version'] != $this->opts['version'] ){ $this->opts['last_version'] = $this->opts['version']; $should_update=true; $reload_needed=true; } if(isset($should_update)) { $this->update_opts(); } if(isset($reload_needed)) { $this->plugin_updated_hook(true); } } public function reset_plugin_to_defaults() { $this->update_opts([]) ; $this->update_phrases([]) ; if(property_exists($this, 'plugin_reset_callback')) $this->plugin_reset_callback(); } //update library file on activation/update public function plugin_updated_hook($redirect=false) { return; } // quick method to update this plugin's opts public function optName($optname, $prefix=false){ if( substr($optname, 0, 1) == '`' ) { $prefix=true; $optname= substr($optname,1); } return ( !$prefix || stripos($optname, $this->slug) !== false ) ? $optname : $this->slug . '_' . $optname; } public function update_opts($opts=false){ return $this->update_option_CHOSEN($this->slug, ( $opts!==false ? $opts : $this->opts) ); } public function get_option_CHOSEN($optname, $default=false , $prefix=false){ return call_user_func("get_". ( $this->newtork_managed ? "site_" : "" ). "option", $this->optName($optname, $prefix), $default ); } public function update_option_CHOSEN($optname, $optvalue, $autoload=null , $prefix=false){ return call_user_func("update_". ( $this->newtork_managed ? "site_" : "" ). "option", $this->optName($optname, $prefix), $optvalue, $autoload ); } public function delete_option_CHOSEN($optname , $prefix=false){ return call_user_func("delete_". ( $this->newtork_managed ? "site_" : "" ). "option", $this->optName($optname, $prefix) ); } public function get_transient_CHOSEN($optname, $default=false , $prefix=false){ return call_user_func("get_". ( $this->newtork_managed ? "site_" : "" ). "transient", $this->optName($optname, $prefix), $default ); } public function update_transient_CHOSEN($optname, $optvalue, $autoload=null , $prefix=false){ return call_user_func("set_". ( $this->newtork_managed ? "site_" : "" ). "transient", $this->optName($optname, $prefix), $optvalue, $autoload ); } public function delete_transient_CHOSEN($optname , $prefix=false){ return call_user_func("delete_". ( $this->newtork_managed ? "site_" : "" ). "transient", $this->optName($optname, $prefix) ); } public function delete_transients_by_prefix_CHOSEN($myPrefix , $prefix=false){ global $wpdb; $myPrefix = sanitize_key($myPrefix); $table_name = $this->newtork_managed ? $wpdb->base_prefix.'sitemeta' : $wpdb->prefix .'options' ; $column_name = $this->newtork_managed ? 'meta_key' : 'option_name'; $sql = "delete from $table_name where $column_name like '%_transient_$myPrefix%' or $column_name like '%_transient_timeout_$myPrefix%'"; return $wpdb->query($sql); } public function get_prefix_CHOSEN(){ return ($this->newtork_managed ? $GLOBALS['wpdb']->base_prefix : $GLOBALS['wpdb']->prefix); } public function getNetworkedState(){ return get_site_option( $this->slug . '_network_managed', $this->initial_static_options['default_managed']=='network' ); } public function updateNetworkedState($value){ return update_site_option( $this->slug . '_network_managed', $value ); } //when is_admin or when page is unknown (for example, custom page or "wp-login.php" or etc... ) public function Is_Backend(){ $includes=get_included_files(); $path = str_replace( ['\\','/'], DIRECTORY_SEPARATOR, ABSPATH); return (is_admin() || in_array($path.'wp-login.php', $includes) || in_array($path.'wp-register.php', $includes) ); //return (!!array_intersect([$ABSPATH_MY.'wp-login.php',$ABSPATH_MY.'wp-register.php'] , get_included_files())) ; } public function is_gutenberg($active=true){ return ( function_exists( 'is_gutenberg_page' ) && (!$active || is_gutenberg_page() ) ); } public function is_gutenberg_page($active=true){ if (is_admin()) { global $current_screen; if (!isset($current_screen)) {$current_screen = get_current_screen();} if ( method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor() || $this->is_gutenberg(true) ) { return true; } } return false; } //Get Blog slug, i.e. "subdir" from "http://example.com/subdir/" public function get_blog_name(){ if(is_multisite()){ global $blog_id; $current_blog_details = !function_exists('get_blog_details') ? get_site($blog_id) : get_blog_details( ['blog_id' => $blog_id] ); $b_slug = basename($current_blog_details->path); return $b_slug; } return false; } //CHECK IF USER IS ADMIN public function is_administrator() { if (function_exists('current_user_can') || require_once(ABSPATH.'wp-includes/pluggable.php')) return (current_user_can('install_plugins')); return false; } public function phrase($key, $is_variable=false) { if($is_variable){ if (!isset($this->translation_phrases[$key])){ $this->translation_phrases[sanitize_title($key)] = sanitize_title($key); $this->update_phrases(); } } return ( isset($this->translation_phrases[$key]) ? $this->translation_phrases[$key] : $key ); } public function string_to_truefalse($string) { return ( $string ==='true' ? true : ($string ==='false' ? false : $string)); } public function truefalse_to_string($string) { return ( $string === true ? 'true' : ($string ===false ? 'false' : $string)); } public function string_to_array($string){ return array_map('trim', array_filter( explode(',', $string) ) ); } public function array_to_string($array) { return implode(",", array_map('trim',array_filter($array)) ); } //convert unsorted array (i.e. [ 'first'=>["a","b","c"], 'second'=>[1,2,3] , ] ) to associative [ "a"=>1, "b"=2 ] public function array_to_associative($array) { } public function add_prefix_to_array_keys($array, $prefix){ $new_array =[]; foreach ($array as $k => $v) { $new_array[$prefix.$k] = $v; } return $new_array; } public function get_visitor_ip() { $proxy_headers = array("CLIENT_IP", "FORWARDED", "FORWARDED_FOR", "FORWARDED_FOR_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED_FOR_IP", "HTTP_PC_REMOTE_ADDR", "HTTP_PROXY_CONNECTION", "HTTP_VIA", "HTTP_X_FORWARDED", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED_FOR_IP", "HTTP_X_IMFORWARDS", "HTTP_XROXY_CONNECTION", "VIA", "X_FORWARDED", "X_FORWARDED_FOR"); foreach($proxy_headers as $proxy_header) { if (isset($_SERVER[$proxy_header])) { if(preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $_SERVER[$proxy_header])) { return $_SERVER[$proxy_header]; } else if (stristr(",", $_SERVER[$proxy_header]) !== FALSE) { $proxy_header_temp = trim(array_shift(explode(",", $_SERVER[$proxy_header]))); if (($pos_temp = stripos($proxy_header_temp, ":")) !== FALSE) {$proxy_header_temp = substr($proxy_header_temp, 0, $pos_temp); } if (preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $proxy_header_temp)) { return $proxy_header_temp; } } } } return $_SERVER["REMOTE_ADDR"]; } public function arrayToObject($array) { return json_decode(json_encode($array)); } public function objectToArray($object){ return json_decode(json_encode($object), true); } public function mail_scrambler($email) { return str_replace('@', '@', $email);} /* public function shortcode_handler($atts, $content=false){ $d=debug_backtrace()[0]; if(!empty($d['args'])) { if(!empty($d['args'][2])) { $name = $d['args'][2]; $args = $this->shortcode_atts($name, $atts); return call_user_func( [$this, $name], $args, $content); } } } */ public function sqlResultsToArray($tableName, $first_key, $second_key=false, $data_key=false) { $array=$this->objectToArray($GLOBALS['wpdb']->get_results("SELECT * FROM ". $tableName)); $new_array=[]; foreach($array as $id=>$block) { if(array_key_exists($first_key, $block)) { if ($second_key) { if(array_key_exists($second_key, $block)) { $new_array[$block[$first_key]][$block[$second_key]] = $data_key ? json_decode($block[$data_key]) : $block; } } else { $new_array[$block[$first_key]] = $data_key ? json_decode($block[$data_key]) : $block; } } } return $new_array; } public function getDomain($url){ return preg_replace('/http(s|):\/\/(www.|)(.*?)(\/.*|$)/i', '$3', $url); } public function adjustedUrlPrefixes($url){ if(strpos($url, '://') !== false){ return preg_replace('/^(http(s|)|):\/\/(www.|)/i', 'https://www.', $url); } else{ return 'https://www.'.$url; } } public function stripUrlPrefixes($url){ return preg_replace('/http(s|):\/\/(www.|)/i', '', $url); } public function stripDomain($url){ return str_replace( $this->adjustedUrlPrefixes($this->domainReal), '', $this->adjustedUrlPrefixes($url) ); } public function safemode_basedir_set(){ return ( ini_get('open_basedir') || ini_get('safe_mode') ) ; } public function try_increase_exec_time($seconds){ if( ! $this-> safemode_basedir_set() ) { @set_time_limit($seconds); @ini_set('max_execution_time', $seconds); $this->try_increase_memory(512); return true; } return false; } public function try_increase_memory($limit=512){ if( ! $this-> safemode_basedir_set() ) { $limitBytes = $limit * 1048576; $currentLimit = (int) trim(ini_get('memory_limit')); $lastChar = strtolower($currentLimit[strlen($currentLimit)-1]); switch($lastChar) { case 'g': $currentLimit *= 1024; case 'm': $currentLimit *= 1024; case 'k': $currentLimit *= 1024; } if ($currentLimit < $limitBytes) return ini_set('memory_limit', $limit . 'M'); } return false; } public function convert_urls_in_text($text) { return preg_replace('@([^\"\']https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#][^<]*(\?\S+)?)?)?)@', '$1', $text); } public function randomString($length = 11) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1, $length); } public function OneSlash($url){ $prefix=''; if(substr($url,0,2)=='//'){ $prefix = '//'; $url=substr($url,2); } return $prefix.preg_replace( '/([^:])\/\//', '$1/', $url); } public function PlainString(&$text1=false,&$text2=false,&$text3=false,&$text4=false,&$text5=false,&$text6=false,&$text7=false,&$text8=false){ for($i=1; $i<=8; $i++){ if(${'text'.$i}) {${'text'.$i} = preg_replace('/\W/si','',${'text'.$i});} } return $text1; } public function get_locale__SANITIZED(){ return ( get_locale() ? "en" : preg_replace('/_(.*)/','',get_locale()) ); //i.e. 'en' //$x=$GLOBALS['wpdb']->get_var("SELECT lng FROM ".$this->options." WHERE `lang` = '".$lang."'"); return !empty($x); // preg_replace('/[^\w\d_\-]/', '', filter_var($input, FILTER_SANITIZE_STRING) ); } public function is_this_settings_page(){ return ( is_admin() && ( ( (stripos(get_current_screen()->base, $this->slug) !== false) && (isset($_GET['page']) && $_GET['page']==$this->slug) ) || ( property_exists($this,'customOptsPageUrl') && stripos($this->currentURL, $this->customOptsPageUrl) !==false ) ) ); } public function blog_prefix() { $blog_prefix = ''; if ( is_multisite() && ! is_subdomain_install() && is_main_site() && 0 === strpos( get_option( 'permalink_structure' ), '/blog/' ) ) { $blog_prefix = '/blog'; } $this->blog_prefix = $blog_prefix; return $blog_prefix; } public function path_after_blog() { $prf = $this->blog_prefix(); $path = $this->pathAfterHome; return ( ($prf=="/blog") ? str_replace('/blog/', '', '/'.$path) : $path ); } public function readUrl( $url){ return wp_remote_retrieve_body( wp_remote_get( $url ) ); } public function checkMyselfAgainstModification() { //if ($this->is_development) return; $name = '_puvox_default_lib_last_revision'; $opt= $this->get_option_CHOSEN($name, 0 ); $days=7; if( time() - $opt > $days* 86400 ) { //$wp_url =readUrl //https://plugins.trac.wordpress.org/browser/simple-post-views-count/trunk/default_library_puvox.php update_option_CHOSEN($name, time() ); } if(time() - $opt < 0 ){ update_option_CHOSEN($name, 0 ); } } public function set_cookie($name, $val, $time_length = 86400, $path=false, $domain=false, $httponly=true){ $site_urls = parse_url( (function_exists('home_url') ? home_url() : $_SERVER['SERVER_NAME']) ); $real_domain = $site_urls["host"]; $path = $path ? $path : ( (!empty($this) && property_exists($this,'home_FOLDER') ) ? $this->home_FOLDER : '/'); $domain = $domain ? $domain : (substr($real_domain, 0, 4) == "www.") ? substr($real_domain, 4) : $real_domain; setcookie ( $name , $val , time()+$time_length, $path = $path, $domain = $domain, $only_on_secure_https = FALSE, $httponly ); } public function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } public function MessageAgainstMaliciousAttempt(){ return 'Not allowed. Try again.';//'Well... I know that these words won\'t change you, but I\'ll do it again: Developers try to create a balance & harmony in internet, and some people like you try to steal things from other people. Even if you can it, please don\'t do that.'; } public function FullIframeScript(){ ?> $func]); } public function array_map_deep( $value, $callback ) { if ( is_array( $value ) ) { foreach ( $value as $index => $item ) { $value[ $index ] = $this->array_map_deep( $item, $callback ); } } elseif ( is_object( $value ) ) { $object_vars = get_object_vars( $value ); foreach ( $object_vars as $property_name => $property_value ) { $value->$property_name = $this->array_map_deep( $property_value, $callback ); } } else { $value = call_user_func( $callback, $value ); } return $value; } public function stripslashes_from_strings_only( $value ) { return is_string( $value ) ? stripslashes( $value ) : $value; } public function stripslashes_deep($value){ return $this->array_map_deep($value, [$this,'stripslashes_from_strings_only'] ); } // ================================================ public function cookieFuncs(){ ?> session_state(true); $_SESSION[$name] = $value; $this->session_state($id); } public function startSessionIfNotStarted(){ if(session_status() == PHP_SESSION_NONE) { $this->session_being_opened = true; session_start(); } } public function endSessionIfWasStarted( $method=2){ if(session_status() != PHP_SESSION_NONE && property_exists($this,"session_being_opened") ) { if($method==1) session_destroy(); elseif($method==2) session_write_close(); elseif($method==3) session_abort(); } } public function array_value($array, $key){ return (array_key_exists($key, $array) ? $array[$key] : ''); } public function nextKeyInArray($target_keyname, $array){ $keys = array_keys($array); $index_of_target_keyname = array_search($target_keyname, $keys , true); return (count($array) > $index_of_target_keyname+1 ) ? $keys[$index_of_target_keyname+1] : $keys[0]; } public function nextValueInArray($target_value, $array, $by_key=false){ $keys = array_keys($array); $target_keyname = $by_key ? $target_value : array_search($target_value, $array, true ); $index_of_target_keyname = array_search($target_keyname, $keys, true ); return (count($array) > $index_of_target_keyname+1 ) ? $array[ $keys[$index_of_target_keyname+1] ] : $array[ $keys[0] ]; } public function getIndexOfKey($array, $key){ return array_search($key, array_keys($array) ); } public function getMemberByIndex($array, $idx){ $keys= array_keys($array); return (!empty($keys) && !empty($array[$keys[$idx]])) ? $array[$keys[$idx]] : null ; } public function getIndexOfValue($array, $key){ return array_search($key, $array ); } public function resortArrayByKey($array, $key, $remove_current= false){ $remaining = array_splice ($array, $this->getIndexOfKey($array, $key) ); if($remove_current){ $array[$key]= $remaining[$key]; unset($remaining[$key] ); } return array_merge($remaining, $array); } public function insertValueAtPosition($arr, $insertedArray, $position) { $i = 0; $new_array=[]; foreach ($arr as $key => $value) { if ($i == $position) { foreach ($insertedArray as $ikey => $ivalue) { $new_array[$ikey] = $ivalue; } } $new_array[$key] = $value; $i++; } return $new_array; } //i.e. 123424235.325434645 public function decimal_outputer($input, $length=4, $only_dot=false){ $timeParts = explode('.', $input); return ($only_dot ? '' : $timeParts[0] . '.') . substr($timeParts[1], 0, $length); //sprintf('%.4F',$input); } public function arrayPhpToJs($array){ return '["'. implode('","', $array) .'"]'; } public function ListAllInDir($path, $only_files = false) { $all_list = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), ( $only_files ? \RecursiveIteratorIterator::LEAVES_ONLY : \RecursiveIteratorIterator::SELF_FIRST ) ); $files = []; foreach ($all_list as $file) $files[] = $file->getPathname(); return $files; } public function replace_occurences_in_dir($dir_base, $from, $to, $exts=array('php','shtml') ){ $dirIterator = $this->ListAllInDir($dir_base, true); foreach($dirIterator as $idx => $value) { $filext = pathinfo($value, PATHINFO_EXTENSION); if( in_array($filext, $exts ) ){ $cont = file_get_contents($value); if(stripos($cont, $from) !== false){ $new_cont = str_replace($from, $to, file_get_contents($value) ); file_put_contents($value, $new_cont); } } } } public function replace_in_file($file, $from_pattern, $to){ if(file_exists($file)) { $cont= file_get_contents($file); $new_cont= preg_replace($from_pattern, $to, $cont); file_put_contents($file, $new_cont); } } public function update_or_insert($tablename, $NewArray, $WhereArray=[]){ global $wpdb; $arrayNames= array_keys($WhereArray); //convert array to STRING $o=''; $i=1; foreach ($WhereArray as $key=>$value){ $o .= $key . ' = \''. $value .'\''; if ($i != count($WhereArray)) { $o .=' AND '; $i++;} } //check if already exist if(!empty($o)){ $CheckIfExists = $wpdb->get_var("SELECT ".$arrayNames[0]." FROM ".$tablename." WHERE ".$o); if ( $wpdb->update($tablename, $NewArray, $WhereArray ) ) return true; } if ( $wpdb->insert($tablename, array_merge($NewArray, $WhereArray) ) ) return true; return false; } public function startsWith($haystack, $needle) { return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false; } public function endsWith($haystack, $needle) { $length = strlen($needle); return $length === 0 || (substr($haystack, -$length) === $needle); } public function contains($content, $needle, $case_sens= true){ return ($case_sens ? strpos($content, $needle) : stripos($content, $needle)) !== false; } // ================ flash rules ================= // // unique func to flush rewrite rules when needed. if not hooked into wp_footer, hangs plugin options resaving public function flush_rules_if_needed($temp_key=false){ // lets check if refresh needed $key="b".get_current_blog_id()."_". md5( (empty($temp_key) ? "sample" : ( stripos($temp_key, basename($this->plugin_DIR)) !== false ? md5(filemtime($temp_key)) : $temp_key )) ); if( !array_key_exists($key, $this->opts['last_updates']) || $this->opts['last_updates'][$key] < $this->opts['last_update_time']){ $this->opts['last_updates'][$key] = $this->opts['last_update_time']; $this->update_opts(); add_action('wp_footer', function(){ $this->flush_rules("js"); } ); } } public function is_JSON_string($string){ return (is_string($string) && is_array(json_decode($string, true))); } public function arrayed_json($answer){ $result = []; if(!$this->is_JSON_string($answer)){ $result['error'] = $answer; } else{ $result = json_decode($answer, true); } return $result; } public function arrayed_answer($answer){ $result = []; if(!$this->is_JSON_string($answer)){ $result['error'] = $answer; } else{ $result = json_decode($answer, true); } return $result; } public function flush_rules($redirect=false){ flush_rewrite_rules(); if($redirect) { if ($redirect=="js"){ $this->js_redirect(); } else { $this->php_redirect(); } } } public function flush_rules_checkmark($redirect=false){ flush_rewrite_rules(); $this->opts['needs_flushing'] = true; $this->update_opts(); if($redirect) { if ($redirect=="js"){ $this->js_redirect(); } else { $this->php_redirect(); } } } public function flush_checkpoint(){ if(isset($this->opts['needs_flushing'])) { unset($this->opts['needs_flushing']); $this->update_opts(); $this->flush_rules(true); } } // TODO - handle $_POST public function disable_cache($hard=false, $file=false){ header("Expires: Mon, 4 Jan 1999 12:00:00 GMT"); // Expired already header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); header("Cache-Control: no-cache, must-revalidate"); // good for HTTP/1.1 header("Pragma: no-cache"); if($hard){ if(!isset($_GET['rand'])) $this->php_redirect( $this->AddStringToUrl($_SERVER['REQUEST_URI'], 'rand='.rand(1,9999999) ) ); } ini_set("opcache.enable", 0); if($file){ opcache_invalidate($file); } } public function AddStringToUrl($url, $string){ return $url .( stripos($url,'?')===false ? '?'.$string : '&'.$string); } public function js_redirect($url=false, $echo=true){ $str = ''; if($echo) { exit($str); } else { return $str; } } public function php_redirect($url=false, $code=302){ header("location: ". ( $url ?: $_SERVER['REQUEST_URI'] ), true, $code); exit; } public function js_redirect_message($message, $url=false){ echo ''; $this->js_redirect($url); } public function mkdir_recursive($dest, $permissions=0755, $create=true){ if(!is_dir($dest)){ //at first, recursively create directory if doesn't exist if(!is_dir(dirname($dest))){ $this->mkdir_recursive(dirname($dest), $permissions, $create); } mkdir($dest, $permissions, $create); } else{return true;} } public function mkdir($dest, $permissions=0755, $create=true){ return $this->mkdir_recursive($dest, $permissions, $create); } public function rmdir_recursive($path){ if(!empty($path) && is_dir($path) ){ $dir = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS); //upper dirs not included,otherwise DISASTER HAPPENS :) $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $f) {if (is_file($f)) {unlink($f);} else {$empty_dirs[] = $f;} } if (!empty($empty_dirs)) {foreach ($empty_dirs as $eachDir) {rmdir($eachDir);}} rmdir($path); return true; } return true; //include_once(ABSPATH.'/wp-admin/includes/class-wp-filesystem-base.php'); //\WP_Filesystem_Base::rmdir($fullPath, true); } public function file_put_contents($file, $content) { if(!empty($file)) { $this->mkdir(dirname($file)); file_put_contents($file,$content); } } // ================ flash rules ================= // public function add_prefix_to_object_keys($object, $prefix){ $new_object = new stdClass(); foreach ($object as $k => $v) { $new_object->{$prefix . $k} = $v; } return $new_object; } public function dieMessage($txt){ echo '
'. '

'.$txt.'

'. '
'; exit; } public function create_log_table() { return $GLOBALS['wpdb']->query("CREATE TABLE IF NOT EXISTS `". $this->logs_table_name ."` ( `id` int(50) NOT NULL AUTO_INCREMENT, `gmdate` datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, `function` longtext NOT NULL, `function_args` longtext NOT NULL, `message` longtext NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci AUTO_INCREMENT=1" // ) " . $wpdb->get_charset_collate() || DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci AUTO_INCREMENT=1 ); // or die("error_2345_". $wpdb->print_error()) //CHARACTER SET utf8mb4 } public function clear_errorslog(){ return $GLOBALS['wpdb']->query("TRUNCATE TABLE ".$this->logs_table_name ); } public function get_errorslog(){ return $GLOBALS['wpdb']->get_results("SELECT * from ".$this->logs_table_name); } //i.e. $this->log("couldnt get results", ''.print_r($response, true).'' ); public function log( $message ="", $exception="", $retrying=false) { global $wpdb; $prev = debug_backtrace()[1]; $final_msg = ($message ? print_r($message,true) : "") . "\r\n" . ($exception ? print_r($exception,true) : ""); //$res = $wpdb->insert( 'table', ['time'=>time(), 'function'=>$prev['function'], 'function'=>$prev['function'] ], ['%s', '%d' ] ); $res = $wpdb->insert( $this->logs_table_name, $arr=[ 'gmdate'=> gmdate("Y-m-d H:i:s"), 'function'=>$prev['function'], 'function_args'=>print_r($prev['args'],true), 'message'=>print_r($message, true). "\r\n".print_r($exception, true) ] ); if(!$res && !$retrying){ $this->create_log_table(); $this->log( $message, $exception, true); } return $res; } public function send_error_mail($error){ return wp_mail($this->static_settings['mail_errors'], 'wp plugin error at '. home_url(), (is_array($error) ? print_r($error, true) : $error) ); } public function sanitizer($text) { return preg_replace('/\W/si','',$text); } public function remove_double_slashes($input){$x=$input; $x=str_replace('//','/', $x); $x=str_replace('\\\\','\\', $x); return str_replace(':/','://',$x);} public function question_mark($text, $dialog=0) { $mouseover=''; $content = ''; if($dialog==0){ $content = $text; } else if($dialog==1){ $content = ''; $mouseover = ' onmouseover="jQuery(\'#\'+this.parentNode.id).tooltip({ items:this, content:\''.$text.'\', show: { effect: \'blind\', duration: 800 } }).tooltip(\'open\');"'; } else if($dialog==2){ $content = ''; $mouseover = ' onmouseover="jQuery(\'
'.$text.'
\').dialog({ modal:true, width:600 });"'; } return ''.$content.''; } public function serialize_argv($argvs) { if(empty($argvs) || !is_array($argvs)) return $argvs; $new_ar=[]; foreach($argvs as $key=>$value) { if(stripos($value,'=')===false) { $new_ar[$key] = $value; } else{ parse_str($argvs[$key], $params); $key1=array_keys($params)[0]; if(!empty($argvs) && is_array($params)) $new_ar[$key1] = $params[$key1]; } } return $new_ar; } // get_remote_data :: removed per WP Reviewer request ( code available at: https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php ) // ====================== tinymce buttons ==================== // public function tinymce_funcs() { // Add button in TinyMCE if( !empty($this->tinymce_buttons) ) { add_action( 'admin_init', function(){ add_filter( 'mce_external_plugins', [$this, 'tinymce_js'] ); add_filter( 'mce_buttons_2', [$this, 'register_buttons'] ); //add_filter( 'tiny_mce_version', function ( $ver ) { return $ver + 3;} ); } ); //tinymce buttons if needed $this->tinymce_buttons_body(); foreach($this->tinymce_buttons as $each_button){ if( !empty($each_button["shortcode"]) ){ add_shortcode($each_button["shortcode"], [$this, $each_button["shortcode"]] ); } } } } public function array_fields($array, $parent="plugin_slug[sample][sub]", $pairs=false) { echo '
'; if( empty($array) ){ $array = []; } echo '
'; if (is_array($array)) { if (!$pairs) { foreach ($array as $fieldKey=>$value) { echo $this->field_out_helper1($parent, $fieldKey, $value, $pairs) ; } } else { foreach ($array as $fieldKey=>$value) { echo $this->field_out_helper1($parent, $fieldKey, $value, $pairs) ; } } } $fieldKey= "abc_".rand(1,999999)*rand(1,999999); $sample_field = $this->field_out_helper1($parent, $fieldKey, "", $pairs, true); //echo $sample_field; echo '
'; ?> sanitizer($parent); ?> '; } public function field_out_helper1($parent, $key, $value, $pairs, $sample=false) { $output='
'; if (!$pairs) { $output .= ''; } else { $output .= ''; $output .= ''; } $output .='
'; return $output; } public function arrayFieldsResort($ar) { $new=[]; foreach($ar as $key=>$val) { $new[ sanitize_text_field($val["name"]) ] = sanitize_text_field($val["value"]); } return $new; } public function get_fb_name_regex($fb_url){ preg_match('/'.preg_quote('^(?:https?://)?(?:www.|m.|touch.)?(?:facebook.com|fb(?:.me|.com))/(?!$)(?:(?:\w)#!/)?(?:pages/)?(?:[\w-]/)?(?:/)?(?:profile.php?id=)?([^/?\s])(?:/|&|?)?.*$/'), $fb_url, $n); return $n[1]; } // public function NonceCheck($value, $action_name){if ( !isset($value) || !wp_verify_nonce($value, $action_name) ) { die("error_5151, Refresh the page");}} public function shortcode_alternative_message($name, $params_name=false) { ?>


<?php echo do_shortcode('[.....]'); ?>
or
<?php if (function_exists('')) { echo (["arg1"=>"value1", ...]); } ?>
slug . '_transl_lastvers'); if( ! $last_vers || $last_vers != $this->static_settings["Version"] ){ update_site_option('transl_lastvers', $this->static_settings["Version"]); $res = !empty($this->phrases_array()); update_site_option($this->slug . '_transl_exists', $res); return $res; } return get_site_option($this->slug . '_transl_exists'); } // settings page public function define_option_tabs(){ if(!is_admin()) return; $this->show_tabs = $this->static_settings['display_tabs']; $this->options_tabs = array_merge( ["Options"], $this->options_tabs, property_exists($this,'shortcodes') ? ['Shortcodes'] : [], ( $this->define_translations_exist() ? ["Translations & Phrases"] : [] ), ["Errors-Log & Reset"] //( ! property_exists($this, 'errors_tab') || $this->errors_tab ? ['Errors log'] : [] ) ); } public function options_tab($tabs_array =false){ if(!$tabs_array) $tabs_array = $this->options_tabs; $this->active_tab = $tabs_array[0]; foreach($tabs_array as $each_tab){ if (isset($_GET['tab']) && sanitize_key($each_tab)==$_GET['tab']) $this->active_tab=$each_tab; } echo ''; } public function opts_page_output_parent($args=false) { if(is_network_admin()) { if( !empty( $_POST["mng_nonce"] ) && check_admin_referer( "nonce_mng_" . $this->slug, "mng_nonce" ) ) { if(isset( $_POST[$this->slug]['managed_from_changer'] ) ){ $val = sanitize_key($_POST[$this->slug]['managed_from_site']) == "network"; $this->newtork_managed = $val; $this->updateNetworkedState($val); $this->js_redirect(); } } ?>

:newtork_managed);?> />     :newtork_managed);?> /> slug, "mng_nonce" ); ?>
newtork_managed) || (!is_network_admin() && !$this->newtork_managed) ) { $this->opts_page_output(); } else{ echo '

'.__("Plugin is set to be managed per: ". ($this->newtork_managed ? "Network": "Sub-sites") ).'

'; } } public function settings_page_part($type) { $this->is_settings_page = true; if($type=="start") { if( !empty( $_POST["_wpnonce"] ) && check_admin_referer( "nonce_" . $this->slug, "_wpnonce" ) ) { if(!empty($_POST[$this->slug]) ) { $this->opts['last_update_time'] = time(); $this->update_opts(); } if(isset( $_POST[$this->slug]['clear_error_logs'] ) ){ $this->clear_errorslog(); } if(isset( $_POST[$this->slug]['reset_plugin_defaults'] ) ){ $this->reset_plugin_to_defaults(); $this->js_redirect(); } if(isset( $_POST[$this->slug]['update_transl_phrases'] ) ){ $this->translation_phrases = array_map('sanitize_text_field', $_POST[$this->slug]['translation_phrases']); $this->update_phrases( $this->translation_phrases ) ; } } if( !empty( $_GET["_wpnonce"] ) && check_admin_referer( "nonce_" . $this->slug, "_wpnonce" ) ) { if(isset($_GET[$this->slug.'-remove-pro']) ) { delete_site_option($this->license_keyname()); $this->js_redirect(remove_query_arg($this->slug.'-remove-pro')); } } ?>

opts['name'];?>

options_tab(); ?>
active_tab == "Shortcodes") { echo '

'. __('Shortcodes Usage').'

'; foreach($this->shortcodes as $key=>$value) { $this->shortcodes_table($key, $value); $this->shortcode_alternative_message($key); } echo '
'; echo '

'. __('Available hooks (to modify from external functions)') .'

'; if ( property_exists($this, "hooks_examples") ) { foreach ($this->hooks_examples as $key=>$block){ echo '
'; if ($block['type']=='filter'){ echo '
'. __($block['description']) .':
'; echo 'add_filter("'.$key.'", "yourFunc", 10, '. count($block['parameters'] ) .' ); function yourFunc($'. implode(', $', $block['parameters'] ).') { ... return $'.$block['parameters'][0].';} '; } echo '
'; } } echo '
'; } if ($this->active_tab == "Translations & Phrases") { ?>
phrases_array(); $phrases = $this->translation_phrases; if(is_array($phrases_arr)){ foreach ($phrases_arr as $key=>$value){ $value = array_key_exists($key, $phrases) ? $phrases[$key] : $key; echo ''; echo ''; echo ''; } } ?>
'. $key.'
slug); submit_button( __( 'Save' ), 'button-secondary', '', true ); ?>
active_tab == "Errors-Log & Reset") { ?>
get_errorslog(); if(!empty($errors)){ rsort($errors); //reverse order, last added to top $column_count = count(array_keys( ((array)$errors[0]) )); foreach ($errors as $each_err ) { $each_err= (array) $each_err; echo ''; for($i=0; $i<$column_count; $i++){ $out=''; $current = $each_err[ array_keys($each_err)[$i]]; if (!empty($current) ) { $out = $current; } echo ''; } echo ''; } } ?>
'. htmlentities($out).'
slug); submit_button( __( 'Clear Errors Log' ), 'button-secondary red-button', '', true ); ?>
slug); submit_button( __( 'Reset plugin options to defaults' ), 'button-secondary red-button', '', true ); ?>
endStyles();?>
myplugin_class.'">'; } ?>

  • : $
  • Must have free plugins for everyone'), $this->static_settings['musthave_plugins'] ).'.'; ?>
static_settings['show_rating_message']) { ?> show_author_block) { ?>
purchase_pro_block(); ?>
'_save_button'] ); ?>
'; ?> slug ] = $this->home_URL . '?tinymce_buttons_'.$this->slug; return $plugin_array; } public function register_buttons( $buttons ) { $button_names = array_map( function($ar){ return $ar['button_name']; }, $this->tinymce_buttons ); return array_merge( $buttons, $button_names ); } public function replace_slashes($path){ return str_replace( ['/','\\',DIRECTORY_SEPARATOR], '/', $path); } public function remove_extra_slashes($path){ return str_replace( '//', '/', $path); } public function tinymce_buttons_body( ) { if( ! isset($_GET['tinymce_buttons_'. $this->slug] ) ) return; session_cache_limiter('none'); // http://stackoverflow.com/a/1385982/2377343 //Caching with "CACHE CONTROL" header('Cache-control: max-age='. ($year=60*60*24*365) .', public'); //Caching with "EXPIRES" (no need of EXPIRES when CACHE-CONTROL enabled) //header('Expires: '.gmdate(DATE_RFC1123,time()+$year)); //To get best cacheability, send Last-Modified header and ... header('Last-Modified: '.gmdate(DATE_RFC1123,filemtime(__file__))); //i.e. 1467220550 [it's 30 june,2016] //reply using: status 304 (with empty body) if browser sends If-Modified-Since header.... This is cheating a bit (doesn't verify the date), but remove if you dont want to be cached forever: // if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { header('HTTP/1.1 304 Not Modified'); die(); } header("Content-type: application/javascript; charset=utf-8"); ?> // ************ these useful scripts got from: https://github.com/tazotodua/useful-javascript/ ********** // " '; $out .= '['. $array['name'].''; foreach($array['atts'] as $key=>$value){ $out .= " ".$value[0].'="'. $this->truefalse_to_string($value[1]).'"';} $out .=']'; $out = ( $strip_tags ? strip_tags($out) : $out); $out = ( $htmlentities ? htmlentities($out) : $out); if( $ended ) $out .= "...[/".$array['name']."]"; $out .= ''; return $out; } public function shortcode_example($shortcode, $array, $ended=false){ $out="[$shortcode "; foreach($array as $key=>$value){ $out .= $key.'="'.$this->valueToString($value) .'" '; } $out = trim($out). "]"; if( $ended ) $out .= "...[/$shortcode]"; return $out; } public function shortcode_atts($shortcode, $atts){ $new_arr=[]; foreach($this->shortcodes[$shortcode]['atts'] as $x){ $new_arr[ $x[0] ] = $this->stringToValue($x[1]) ; } if (!empty($atts)) { $filtered_atts=[]; foreach($atts as $key=>$value){ $filtered_atts[$key] = $this->stringToValue($value) ; } $new_arr = array_merge($new_arr, $filtered_atts); } if (array_key_exists("...", $new_arr)) unset($new_arr["..."]); if (array_key_exists("___", $new_arr)) unset($new_arr["___"]); if (array_key_exists(0, $new_arr)) unset($new_arr[0]); $new_atts = shortcode_atts($new_arr, [] ); return $new_atts; } public function valueToString( $value ){ return is_bool($value) ? ($value ? 'true' : 'false' ) : strip_tags( $value ) ; } public function stringToValue( $value ){ return is_bool($value) ? $value : ( !is_string($value) ? $value : ( $value =='true' ? true : ( $value =='false' ? false : $value) ) ); } public function shortcodes_initialize(){ if(property_exists($this,'shortcodes')) { //enable shortcodes (if it's disabled) add_filter( 'widget_text', 'do_shortcode' ); foreach($this->shortcodes as $name=>$val) { //add "name" manually as name $this->shortcodes[$name]['name']=$name; add_shortcode($name, [$this, $name]); } } } public function get_phrases() { return $this->get_option_CHOSEN('`translated_phrases', []); } public function update_phrases($array=null) { if(!isset($array)) $array=$this->translation_phrases; return $this->update_option_CHOSEN('`translated_phrases', $array); } public function phrases_array() { $cont=''; foreach( $this->plugin_files as $each) { $cont .= file_get_contents(__DIR__.'/'.$this->slug.'/'.$each); } preg_match_all( '/\$this\-\>phrase\((.*?)\)/si', $cont, $matches ); $phrases_array = $this->get_phrases(); foreach($matches[1] as $value) { $value=trim($value); //if not variable if(substr($value, 0, 1) != '$') { $sanitized_value = preg_replace("/[\"\']/", "", $value); $phrases_array[$sanitized_value] = $sanitized_value; } } return $phrases_array; } public function shortcodes_table($name, $array) { /*======= example ======== $this->shortcodes_table( "breadcrumbs", [ [ 'id', '', __('Post ID (you can ignore that parameter if you want to get for current post)', 'breadcrumbs-shortcode') ], [ 'delimiter', 'hello', __('Your desired delimiter', 'breadcrumbs-shortcode') ], ]); */ ?>

shortcode_example_string($array, false,false, array_key_exists('ended', $array) );?>
$value) { ?>
truefalse_to_string($value[1]));?>
application/x-gzip // [rar] => application/rar // [7z] => application/x-7z-compressed return $mime_types; } //move uploaded addon to it's folder public function wp_handle_upload_filter( $array=['file' => 'path/to/wp-content/uploads/2018/12/example.ext', 'url' => 'https://.....example.ext', 'type' => 'application/zip'], $action= 'sideload|upload' ) { $file = $array['file']; if($array['type']=="application/zip" || $array['type']=="application/x-zip") { $filename = basename($file); $found = false; $found_files=[]; if (function_exists('zip_open')) { $zip = zip_open($file); if (is_resource($zip)) { while ($zip_entry = zip_read($zip)) { $found_files[]=zip_entry_name($zip_entry); //if (zip_entry_open($zip, $zip_entry)) //{ //echo zip_entry_read($zip_entry); //zip_entry_close($zip_entry); //} } zip_close($zip); } } elseif (class_exists('\ZipArchive')) { $za = new ZipArchive(); $za->open($file); for( $i = 0; $i < $za->numFiles; $i++ ){ $stat = $za->statIndex( $i ); $found_files[] = basename( $stat['name'] ) ; } } //elseif( stripos($filename, $this->pro_file_part) !== false) //{ // $found = true; //} //if contains if(!empty($found_files)) { foreach(array_filter($found_files) as $each) { if( stripos($each, $this->addon_namepart.'/'.$this->slug)!==false) { $found = true; } } } if($found) { $this->unzip($file, $this->addons_dir); $this->move_folder_contents($this->addons_dir.'/'. $this->addon_namepart, $this->addons_dir); $this->rmdir_recursive($this->addons_dir.'/'. $this->addon_namepart); $need_space = stripos($_SERVER['REQUEST_URI'], 'upload.php') !== false ? '        ' : ''; return ['error'=> $need_space."Thank You ⭐ Addon has been installed, you can activate it with the key !"]; } } return $array; } public function move_folder_contents($from, $to) { foreach( glob($from ."/*") as $each) { $target=$to."/".basename($each); if(is_dir($target)) { //$this->rmdir_recursive($target); } elseif(is_file($target)) { @unlink($target); //rename($each, $target); } } } public function ajax_backend_call() { if(isset($_POST['action']) && $_POST['action']==$this->plugin_slug_u .'_all') { if(isset($_POST['PRO_check_key'])){ echo $this->license_status($_POST['PRO_check_key'], "activate"); } elseif(isset($_POST['PRO_save_results'])){ } elseif(method_exists($this, 'backend_call')){ $this->backend_call( sanitize_key($_POST['act']) ); } wp_die(); } exit( __('Unknown-action') ); } public function insert_code_in_file($filepath, $replace_what, $replace_with) { if(is_admin()) { if(file_exists($filepath)) { $content= file_get_contents($filepath); if(stripos($content, $replace_with) === false) //if it doesnt contain { file_put_contents( $filepath, str_replace($replace_what, $replace_with, $content) ); } } } } public function admin_scripts($hook) //i.e. edit.php { if($this->is_this_settings_page()){ $this->admin_scripts_out($hook); } } public function admin_scripts_out($hook) //i.e. edit.php { $where='admin'; $this->register_stylescript($where, 'script', 'jquery'); //jquery ui $this->register_stylescript($where, 'style', 'wp-jquery-ui-core'); $this->register_stylescript($where, 'script', 'jquery-ui-core'); $this->register_stylescript($where, 'script', 'jquery-effects-core'); $this->register_stylescript($where, 'style', 'ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css', false, '1.1'); $this->register_stylescript($where, 'style', 'wp-jquery-ui-dialog'); $this->register_stylescript($where, 'script', 'jquery-ui-dialog'); $this->register_stylescript($where, 'script', 'jquery-ui-tooltip'); // spin.js //$this->register_stylescript($where, 'script', 'spin', 'https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js', ['jquery'], '2.3.2', true); // touch-punch.js //$this->register_stylescript($where, 'script', 'touch-punch', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js', ['jquery'], '0.2.3', true ); //add_action('admin_footer', function() { } ); } public function register_stylescript($admin_or_wp, $type, $handle=false, $url=false, $dependant=null, $version=false, $target=false) { add_action( $admin_or_wp.'_enqueue_scripts', function() use($type, $handle, $url, $dependant, $version, $target) { $this->enqueue($type, $handle, $url, $dependant, $version, $target); } ); } public function enqueue($type, $handle=false, $url=false, $dependant=null, $version=false, $target=false) { //lets allow shorthanded start $localstart = 'assets'; if( substr($url,0, strlen($localstart) ) == $localstart ) $url = $this->plugin_URL. $url; if ( ! call_user_func("wp_".$type."_is", $handle, "registered" ) ){ call_user_func("wp_register_".$type, $handle, $url, $dependant, $version, $target ); //,'jquery-migrate' } if ( ! call_user_func("wp_".$type."_is", $handle, "enqueued" ) ){ call_user_func("wp_enqueue_".$type, $handle); } } public function add_localscript($handle, $string){ $is_js = stripos($string,''; $this->reload_without_query(); } } public function add_default_uninstall(){ if( is_admin() && !$this->is_development) { $wp_uninstall_file = $this->plugin_DIR.'/uninstall.php'; if( !file_exists($wp_uninstall_file) ) { $content= '<'.'?php // If uninstall not called from WordPress, then exit if ( ! defined( "WP_UNINSTALL_PLUGIN" ) ) { exit; } $lib = dirname(__DIR__)."/'.basename(__FILE__).'"; if(file_exists($lib)){ //@unlink($lib); }'; file_put_contents($wp_uninstall_file, $content); } } } // ========= my functions for PRO plugins ========== // public function addon_path() { return WP_PLUGIN_DIR .'/_addons/'.$this->slug .'-addon/addon.php'; } public function addon_exists() { return (file_exists($this->addon_path())); } public function load_pro() { if ($this->is_pro) { if ($this->is_pro_legal) { $puvox_last_class = $this; if($this->addon_exists()) include_once($this->addon_path()); } } } public function check_if_pro_plugin() { $this->is_pro = null; $this->is_pro_legal = null; if( $this->static_settings['has_pro_version'] ){ //$this->has_pro_version = true; // it is price of plugin $ar= $this->get_license(); $this->is_pro = $ar['status']; $this->is_pro_legal = $ar['legal']; } if(is_admin()) { if ($this->is_pro) { if (!$this->is_pro_legal) { add_action('network_admin_notices', [$this, 'admin_error_notice_pro'] ); add_action('admin_notices', [$this, 'admin_error_notice_pro'] ); } else{ $this->pro_check_once_in_a_while(); } } } $this->addons_dir = WP_PLUGIN_DIR.'/_addons'; //wp_plugins_dir(); } public function license_keyname(){ return $this->plugin_slug_u ."_l_key"; } public function get_license($key=false){ $def_array = [ 'status' => false, 'legal' => false, 'key' => '', 'last_error'=>'' ]; $license_arr = get_site_option($this->license_keyname(), $def_array ); return ($key ? $license_arr[$key] : $license_arr); } public function update_license($val, $val1=false){ if(is_array($val)){ $array = $val; } else{ $array= $this->get_license(); $array[$val]=$val1; } update_site_option( $this->license_keyname(), $array ); } public function license_answer($key, $type="check/or/activate") { $this->info_arr = ['key' => $key] + ['siteurl'=>home_url(), 'plugin_slug'=>$this->slug ] + $this->pluginvars() + $this->opts; $answer = wp_remote_retrieve_body( wp_remote_post($this->static_settings['purchase_check'].$type, [ 'method' => 'POST', 'timeout' => 25, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => [], 'body' => $this->info_arr, 'cookies' => [] ] ) ); return $answer; } public function license_status($license, $type="check/or/activate") { $key = sanitize_text_field($license); $answer = $this->license_answer($key, $type); if(!$this->is_JSON_string($answer)){ $result = []; $result['error'] = $answer; } else{ $result = json_decode($answer, true); } // if(isset($result['valid'])){ if($result['valid']){ $ar['status']= true; $ar['legal']= true; $ar['key']= $key; $ar['last_error']= ''; $this->update_license($ar); } else { // $this->update_license( 'legal', false ); $this->update_license( 'last_error', json_encode($result['response']) ); $result['error'] = json_encode($result['response']); } } else{ $result['error'] = $answer; $this->log('Error while calling to vendor', $result['error']); } return json_encode($result); } public function pro_check_once_in_a_while( $time_length = 864000 ) { $name= '`_last_license_check'; $value= $this->get_transient_CHOSEN($name); if( !$value || time() - $value > $time_length ) { $lic = $this->get_license(); $res= $this->license_status($lic['key'], 'activate'); $this->update_transient_CHOSEN($name, time() ); } } public function unregistered_pro() { return $this->static_settings['has_pro_version'] && !$this->is_pro_legal; } public function admin_error_notice_pro(){ ?>

%s is invalidated, so it\'s PRO functionality has been disabled.', $this->static_settings['Name']) );?>

unregistered_pro()){ $res= 'data-pro-overlay="pro_overlay"'; if($echo) echo $res; else return $res; //echo ' '; } } public function purchase_pro_block(){ if ( !$this->static_settings['has_pro_version']) return; if ( $this->is_pro_legal ) return; ?>
is_pro ) { if ( !$this->addon_exists() ) { ?> ( ) is_pro_legal) { $need_to_enter_key=true; ?> ( . ( %s ', $this->get_license('last_error') ) ); ?> ) ) addon_exists()) { ?> static_settings['has_pro_version'];?>$ ( )
plugin_scripts(); } public function plugin_scripts(){ ?>