-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary_wp.php
3591 lines (3143 loc) · 138 KB
/
library_wp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ################################################################################
* ############################## Our WP Library ##############################
* ##### Here we collect frequently used methods across our WP applications. #####
* ################################################################################
*
* ### Example usage: ###
* $helpers = new \Puvox\library_wp();
* $helpers-> remove_admin_bar ();
* -> disable_emojis ();
* -> delete_transients_by_prefix ('something');
* -> unzip ('file.zip');
* ...
*
* Note: This file also contains additional 'wp_plugin' class. example use: https://bit.ly/puvox_wp_plugin
*/
namespace Puvox;
if (!class_exists('\\Puvox\\library_wp')) {
#[\AllowDynamicProperties]
class library_wp extends library
{
public function __construct()
{
parent::__construct();
}
public $logs_table_maxnum=100;
public $logs_table_name ='_default_table_ERRORS_LOGS';
public function init_module($args=[])
{
parent::init_module($args);
//get blog-slug
if(is_multisite()){
global $blog_id; if(empty($blog_id)) $blog_id = get_current_blog_id();
$current_blog_details = function_exists('get_sites') ? get_site($blog_id) : get_blog_details( array( 'blog_id' => $blog_id ) );
$b_slug = basename($current_blog_details->path);
}
$this->BLOGSLUG = (!empty($b_slug)? $b_slug : basename($this->homeFOLDER) );
// others
$this->this_file_link= '';//$this->baseURL . $this->urlify( explode( basename($this->baseURL), __FILE__ )[1] );
$this->PHP_customCALL= '';//$this->this_file_link .'?custom_php_load=scripts_load&actionn=';
if ($this->is_development)
{
$this->js_debugmode("debugmode");
}
}
public function is_home_path($path){
return trailingslashit($path)==trailingslashit(str_replace( trailingslashit(network_site_url()), '', trailingslashit(home_url())) );
} //return in_array(home_url(), ["http://$site","https://$site"]) || home_url('', 'relative')==$site; }
public function home_url(){ return trailingslashit(home_url());}
public function blog_slug(){
$blogname = str_replace(basename(get_site_url()),'', basename( get_site($GLOBALS['blog_id'])->path));
return ($blogname !=='' ? $blogname : str_replace('www','',$_SERVER['HTTP_HOST']));
}
public function load_scripts_styles()
{
//load desired scripts
add_action( 'wp_enqueue_scripts', [$this, 'my_styles_hook'], 9);
add_action( 'admin_enqueue_scripts', [$this, 'my_styles_hook'], 9);
}
public function init_properties()
{
}
//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 || $this->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;
// global $current_blog;
// $blog_path = explode('/',$current_blog->path);
// if(isset($blog_path[2])) {
// return $blog_path[2];
// }
//if(!get_blog_name()) { header("Location: http://www.mydomain.com/", true, 301); exit; }
}
return false;
}
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);
}
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 disable_metabox_folding()
{
add_action('admin_footer', function ()
{ ?><script>
jQuery(window).load(function() {
jQuery('.postbox .hndle').css('pointer-events', 'none');
jQuery('.postbox .hndle input, .postbox .hndle select').css('pointer-events', 'all');
{ jQuery('.postbox .hndle').unbind('click.postboxes'); jQuery('.postbox .handlediv').remove(); jQuery('.postbox').removeClass('closed'); }
});
</script><?php
} );
}
public function disable_php_in_wpcontent()
{
if (last_checkpoint('uploads_htaccess', 500000))
add_action('init', function() {
$uploads_dir = defined('UPLOADS') ? UPLOAD : get_option('upload_path');
$uploads_dir = !empty($uploads_dir) ? $uploads_dir : WP_CONTENT_DIR.'/uploads';
$file=$uploads_dir.'/.htaccess';
if(!file_exists($file)) {
$this->file_put_contents($file, '<Files ~ "\.php">'."\r\n".
'Order allow,deny'."\r\n".
'Deny from all'."\r\n".
'</Files>'
);
}
});
}
public function my_site_variables__secret($var_name=false, $value=false){
$final= $this->SITE_VARIABLES = get_site_option('site_variables_my_secret',[]);
if ($var_name) {
if(array_key_exists($var_name, $this->SITE_VARIABLES)){
$final = $this->SITE_VARIABLES[$var_name];
}
elseif($value) {
$final = $this->SITE_VARIABLES[$var_name]=$value;
update_site_option('site_variables_my_secret', $this->SITE_VARIABLES);
}
else{
$final = '';
}
return $final;
}
else{ return $this->SITE_VARIABLES; }
}
public function dashicon_styled($name, $style){
return '//" class="dashicons-before '.$name.'" style="opacity:0.91; '.$style;
}
// ====================== tinymce buttons ==================== //
// $this->my_default_buttons= array('superscript', 'subscript') + array( "|", "youtube_video","audioo", "add_spacee_button", "removeline_button", "abzac_button","videomovie", "lists", "script");
public function tinymce_funcs()
{
// Add button in TinyMCE
add_action( 'admin_init', function(){
if ( get_user_option('rich_editing') == 'true') {
add_filter( 'mce_external_plugins', function ( $plugin_array ) { return array_merge($plugin_array, ["button_handle_" . $this->slug=> $this->homeURL . '?tinymce_buttons_'.$this->slug] ); } );
add_filter( 'mce_buttons_2', function ( $button_names ) { return array_merge( $button_names, array_map( function($ar){ return $ar['button_name']; }, $this->tinymce_buttons )); } );
//this is must for REFRESHING!
add_filter( 'tiny_mce_version', function ( $ver ) { $ver += 3; return $ver;} );
}
} );
//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 compress_php_header($isWP=false)
{
ob_start('ob_gzhandler'); //similar as: ini_set('zlib.output_compression', '1');
if ($isWP){
add_action('wp', (function (){ if (!is_admin()) ob_start('ob_gzhandler'); } ) ,1);
remove_action( 'shutdown', 'wp_ob_end_flush_all', 1 );
}
}
//add_action( 'pre_get_posts', 'querymodify_2322',77);
// public function querymodify_2322($query) { $q=$query;
// if( $q->is_main_query() && !is_admin() ) {
// if($q->is_home){
// $q->init();
// $q->set('post_type',LNG);
// $q->set('category__not_in', 64);
// $q->set_query_vars('category__not_in',array(64) );
// }
// }
// return $q;
// }
public function referrer_is_external_domain()
{
return $this->get_domain(wp_get_referer()) !== $this->get_domain(home_url());
}
public function inprogress_flag_cache($flagname, $max_seconds=999999999){
$flagname_final = "inprogress_$flagname";
$start_time = $this->cache_get($flagname_final,null);
if($start_time && time()<$start_time+$max_seconds) {
return true;
}
else{
$this->cache_set($flagname_final, time(), $max_seconds);
register_shutdown_function(function() use($flagname_final){ $this->cache_set($flagname_final,null); });
return false;
}
}
public function inprogress_flag($flagname, $max_seconds=60){
$flagname_final = "inprogress_$flagname";
$start_time = $this->get_transient($flagname_final,null);
if($start_time && time()<$start_time+$max_seconds) {
return true;
}
else{
$this->set_transient($flagname_final, time(), $max_seconds);
register_shutdown_function(function() use($flagname_final){ $this->inprogress_flag_reset($flagname_final); });
return false;
}
}
public function inprogress_flag_reset($flagname_final){
$flagname_final = !$this->starts_with($flagname_final, 'inprogress_') ? "inprogress_$flagname_final" : $flagname_final;
if( !empty($this->get_transient($flagname_final) ) ) {
if( ! $this->set_transient($flagname_final,0,0) ) {
if( ! $this->set_transient($flagname_final,0,0) ) {
throw new \Exception("Cant update status: $flagname_final | ". $GLOBALS['wpdb']->last_error);
}
}
}
}
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);
}, 100);
}
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->moduleURL. $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);
}
}
//if used earlier than INIT
public function get_permalink_before_init($post=false){
global $wp_rewrite;
if (empty($wp_rewrite)){
if(is_object($post)) {$link=$post->guid; }
elseif(is_numeric($post)){ $post_obj=get_post($post, OBJECT); $link=get_permalink($post_obj->ID); }
}
else{
if(is_object($post)) { $link=get_permalink($post->ID);}
else { $link=get_permalink($post); }
}
return $link;
}
public function get_parent_slugs_path($post){
$final_SLUGG = '';
if (!empty($post->post_parent)){
$parent_post= get_post($post->post_parent);
while(!empty($parent_post)){
$final_SLUGG = $parent_post->post_name .'/'.$final_SLUGG;
if (!empty($parent_post->post_parent) ) { $parent_post = get_post( $parent_post->post_parent); } else{ break ;}
}
}
return $final_SLUGG;
}
// https://stackoverflow.com/questions/18401236/custom-category-tree-in-wordpress
//foreach (get_terms($allTermSlugs, array('hide_empty'=>0, 'orderby'=>'id', 'parent'=>0) ) as $category) echo my_Categ_tree($category->taxonomy,$category->term_id);
public function my_categ_tree($TermName='', $termID=null, $separator='', $parent_shown=true ){
$args = 'hierarchical=1&taxonomy='.$TermName.'&hide_empty=0&orderby=id&parent=';
if ($parent_shown) {$term=get_term($termID , $TermName); $output=$separator.$term->name.'('.$term->term_id.')<br/>'; $parent_shown=false;}
$separator .= '-';
$terms = get_terms($TermName, $args . $termID);
if(count($terms)>0){
foreach ($terms as $term) {
//$selected = ($cat->term_id=="22") ? " selected": "";
//$output .= '<option value="'.$category->term_id.'" '.$selected .'>'.$separator.$category->cat_name.'</option>';
$output .= $separator.$term->name.'('.$term->term_id.')<br/>';
$output .= my_Categ_tree($TermName, $term->term_id, $separator, $parent_shown);
}
}
return $output;
}
public function recount_categories($tax_name='category')
{
$terms_ids = get_terms( ['taxonomy' => $tax_name, 'fields' => 'ids','hide_empty' => false]);
wp_update_term_count_now( $terms_ids, $tax_name);
}
public function random_val_for_site($name){
$randoms = get_site_option('randoms_for_main_site', array());
if(empty($randoms) || empty($randoms[$name])){
$randoms[$name]= random_stringg(16);
update_site_option('randoms_for_main_site', $randoms);
}
return $randoms[$name];
}
// https://pastebin_com/sPb1qvJ0
public function delete_transients_by_prefix($myPrefix, $table_name, $column_name, $prefix=false){
global $wpdb;
$myPrefix = sanitize_key($myPrefix);
$sql = $wpdb->prepare("delete from %s where %s like '%s' or %s like '%s'", $table_name, $column_name, '%_transient_$myPrefix%', $column_name, "%_transient_timeout_$myPrefix%" );
return $wpdb->query($sql);
}
// NONCES
public function default_nonce_action($actionName=null){ return ($actionName!=null? $actionName : "_nonceAction"."_".$this->slug); }
public function default_nonce_slug($slugName=null){ return ($slugName!=null? $slugName : "_wpnonce"."_".$this->slug); }
public function check_form_submission($action=null, $slug=null)
{
$action = $this->default_nonce_action($action);
$slug = $this->default_nonce_slug($slug);
$result = isset($_POST[$slug]) && check_admin_referer($action, $slug);
return $result;
}
public function checkSubmission($action=null, $slug=null){
return $this->check_form_submission($action, $slug);
}
public function nonce($action=null, $slug=null, $echo=true)
{
$out = wp_nonce_field( $this->default_nonce_action($action), $this->default_nonce_slug($slug), true, false );
if ($echo) echo $out; else return $out;
}
public function nonceSubmit($text=null, $action=null, $slug=null, $centeredFloat=false, $echo=true)
{
$btn = $this->submit_button($text, $action, $slug, $centeredFloat);
if ($echo) echo $btn; else return $btn;
}
public function submit_button($text=null, $action=null, $slug=null, $centeredFloat=false, $echo=false)
{
$out = '';
$out .= $this->nonce( $this->default_nonce_action($action), $this->default_nonce_slug($slug), false );
if ($centeredFloat) $out .= '<div class="centered-float submitbutton">';
$out .= get_submit_button( $text, $type='button-primary', $name='', $wrap=true, $other_attributes= ['id'=>'mainsubmit-button'] );
if ($centeredFloat) $out .= '</div>';
if ($echo) echo $out; else return $out;
}
// old
public function nonce_check($value, $action_name){
if ( !isset($value) || !wp_verify_nonce($value, $action_name) ) { die("not allowed. error_5151, Refresh the page");}
}
public function nonce_check2($name='nonce_input_name', $action_name='blabla') {
return ( wp_verify_nonce($_POST[$name], $action_name) ? true : die("not allowed, refresh page!") );
}
public function nonce_field($name='nonce_input_name', $action_name='blabla') { return '<input type="hidden" name="'.$name.'" value="'.wp_create_nonce($action_name).'" />';}
// backend
private function default_nonce_action_key($actName){ return 'puvox_backend_call_'.$this->slug. "_".sanitize_key($actName); }
public function add_action_backend_call($actName, $callback){
add_action( $this->default_nonce_action_key($actName), $callback );
}
public function register_backend_call_actions(){
add_action( 'wp_ajax_'.$this->plugin_slug_u.'_all', [$this, 'ajax_backend_call'] );
add_action( 'wp_ajax_nopriv_'.$this->plugin_slug_u.'_all', [$this, 'ajax_backend_call_nopriv'] );
}
public function ajax_backend_call()
{
if(isset($_POST['action']) && $_POST['action']==$this->plugin_slug_u .'_all')
{
if( empty( $_POST["_wpnonce"] ) || !wp_verify_nonce( $_POST["_wpnonce"], "Puvox_BackendCallJS") )
{
exit( __('Incorrect nonce. Refresh page and try again.') );
}
if(isset($_POST['PRO_check_key'])){
echo $this->license_status( sanitize_text_field($_POST['PRO_check_key']), "activate");
}
elseif(isset($_POST['PRO_save_results'])){
}
else{
do_action($this->default_nonce_action_key($_POST['act']));
}
wp_die();
}
exit( __('Unknown-action') );
}
public function ajax_backend_call_nopriv(){
}
public function unzip_url($url, $where)
{
$zipLoc = $where.'/temp_'.rand(1,999999). "_". (basename($url)).'.zip';
wp_remote_get
(
$url,
[
'timeout' => 300,
'stream' => true,
'filename' => $zipLoc
]
);
$this->unzip($zipLoc, $where);
@unlink($zipLoc);
}
public function unzip($path, $where)
{
$this->file->create_directory($where);
require_once(ABSPATH . 'wp-admin/includes/file.php');
\WP_Filesystem();
\unzip_file($path, $where);
$this->sleep(300);
}
public function unzip_in_dir($dir, $rewrite=true)
{
$this->temp_unziped_folders = [];
foreach( array_filter(glob($dir.'/*.zip'), 'is_file') as $each_zip)
{
$uniqueTag = md5($each_zip);
$each_dir = substr($each_zip, 0, -4); //trim .zip
if (empty($each_dir)) return; // ! must have, to avoid empty directory threat
// remove if previous unpack was partial.
if( is_dir($each_dir) && $rewrite )
{
if( !array_key_exists($uniqueTag, $this->temp_unziped_folders) || $this->temp_unziped_folders[$uniqueTag]==false )
{
$this->file->delete_directory($each_dir);
$this->sleep(500);
//$this->create_directory($pathh);
}
}
elseif( !is_dir($each_dir) )
{
$this->temp_unziped_folders[$uniqueTag] = false;
$this->unzip($each_zip, dirname($each_zip));
$this->temp_unziped_folders[$uniqueTag] = true;
}
}
}
public function is_plugin_active($name) //i.e. woocommerce/woocommerce.php
{
return in_array($name, get_option('active_plugins') );
}
public function woocommerce_products_to_array($products)
{
$new = [];
foreach($products as $p) $new[] =$p->get_data();
return $new;
}
public function shortcode_handler_old($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);
}
}
}
//Advanced custom fields alternative
public function acf_getfield_detect(){
add_action('plugins_loaded', function(){
if (!function_exists('get_field')){
function get_field(){
return 'Advanced Custom Fields plugin is not installed';
}
}
}, 1);
}
// ================ flash rules ================= //
public function flush_rules_double(){ add_action('wp', [$this, 'my_flush__rewrite'] ); }
public function my_flush__rewrite($RedirectFlushToo=false){
$GLOBALS['wp_rewrite']->flush_rules();
flush_rewrite_rules();
//DUE TO WORDPRESS BUG ( https://core.trac.wordpress.org/ticket/32023 ) , i use this: (//USE ECHO ONLY! because code maybe executed before other PHP functions.. so, we shouldnt stop&redirect, but we should redirect from already executed PHP output )
if($RedirectFlushToo) {echo '<form name="mlss_frForm" method="POST" action="" style="display:none;"> <input type="text" name="mlss_FRRULES_AGAIN" value="ok" /> <input type="submit"> </form> <script type="text/javascript"> document.forms["mlss_frForm"].submit(); </script>';}
}
public function flush_rules($redirect=false){
flush_rewrite_rules();
if($redirect) {
if ($redirect=="js"){ $this->js_redirect(); } else { $this->php_redirect(); }
}
}
public function output_js_categories_ids()
{
if( ! ($out = get_transient('termids_for_js'))) {
$terms= get_terms();
foreach($terms as $term){
$cats[$term->term_id] = urldecode($term->slug);
}
$out = json_encode($cats, JSON_UNESCAPED_UNICODE);
set_transient('termids_for_js', $out , 60*60);
}
echo "<script>cat_term_ids = $out;</script>";
}
// ==================== shortcodes =======================
public function shortcode_atts($shortcode, $predefined_atts, $passed_atts){
$new_arr=[];
foreach($predefined_atts as $x){
$new_arr[ $x[0] ] = $this->string_to_value($x[1]) ;
}
if (!empty($passed_atts)) {
$filtered_atts=[];
foreach($passed_atts as $key=>$value){
$filtered_atts[$key] = $this->string_to_value($value) ;
}
$new_arr = array_merge($new_arr, $filtered_atts);
}
$new_arr = $this->sanitize_shortcode_empty_defaults_pre($new_arr);
$new_atts = shortcode_atts($new_arr, [] );
return $new_atts;
}
public function sanitize_shortcode_empty_defaults_pre($atts){
$ar= ["...","___", 0];
foreach($ar as $e) { if (array_key_exists($e, $atts)) unset($atts[$e]); }
return $atts;
}
public function sanitize_shortcode_empty_defaults($attsArray){
$new_arr = [];
foreach($attsArray as $eachAttArr)
{
if ( empty($eachAttArr[0]) || in_array($eachAttArr[0], ["...","___"] ) ) continue;
$new_arr[] = $eachAttArr;
}
return $new_arr;
}
public function shortcode_alternative_message($name, $params_name=false)
{
?>
<div class="alertnative_to_shortcodes">
<h2><?php _e('(Alternatives to shortcode)'); ?></h2>
<?php _e('Note, you can always use programatical approach using:'); ?>
<br/> <code><?php echo do_shortcode('[.....]'); ?></code>
<br/> or
<br/> <code><?php if (function_exists('<?php echo esc_attr($name);?>')) { echo <?php echo esc_attr($name);?>(["arg1"=>"value1", ...]); } ?></code>
</div>
<?php
}
public function shortcode_example_string($array, $strip_tags=false, $htmlentities=false, $ended=false){
$out = '<code>';
$out .= '['. $array['name'].'<span class="shortcode_atts">'; $atts = $this->sanitize_shortcode_empty_defaults($array['atts']); foreach( $atts as $key=>$value){ $out .= " ".$value[0].'="'. htmlentities($this->truefalse_to_string($value[1])).'"';} $out .='</span>]';
$out = ( $strip_tags ? strip_tags($out) : $out);
$out = ( $htmlentities ? htmlentities($out) : $out);
if( $ended )
$out .= "...[/".$array['name']."]";
$out .= '</code>';
return $out;
}
public function shortcode_example($shortcode, $array, $ended=false){
$out="[$shortcode "; foreach($array as $key=>$value){ $out .= $key.'="'.$this->value_to_string($value) .'" '; } $out = trim($out). "]";
if( $ended )
$out .= "...[/$shortcode]";
return $out;
}
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') ],
// ] );
?>
<div class="shortcodes_block">
<h3><?php echo $array['description'];?></h3>
<table class="form-table shortcodes">
<tr>
<td><?php _e('Example:');?></td>
<td>
<?php echo $this->shortcode_example_string($array, false,false, array_key_exists('ended', $array) );?>
</td>
</tr>
<tr>
<td><?php _e('Parameters:');?></td>
<td>
<table>
<tr class="shortcode_tr_descr">
<td><?php _e('name');?></td><td><?php _e('default value');?></td><td><?php _e('description');?></td>
<tr>
<?php
foreach($array['atts'] as $key=>$value)
{ ?>
<tr>
<td><code><?php echo htmlentities($value[0]);?></code></td><td><code><?php echo htmlentities($this->truefalse_to_string($value[1]));?></code></td><td><?php echo wp_kses_post($value[2]);?></td><?php //todo :kses ?>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
</div>
<?php
}
public function get_template_filename($post_id=false){
if(is_page()){
$name= get_post_meta( $post_id ?: $GLOBALS['post']->ID, '_wp_page_template', true); // page-templates/my_homepage_1.php
return basename($name);
}
return false;
}
// disable georgian russian slugs: https://pastebin_com/UmvhEmuz
// example to dump: add_action('save_post', function () { var_dump($_POST); exit; }, 99, 11);
public function debug_actions() { add_action( 'wp_footer', function (){ var_dump( $GLOBALS['wp_filter']); } ); }
public function called_script() { return $_SERVER["SCRIPT_FILENAME"];}
public function is_subscriber() { return $this->is_helper_('read'); }
public function is_contributor() { return $this->is_helper_('edit_posts'); }
public function is_author() { return $this->is_helper_('upload_files'); }
public function is_editor() { return $this->is_helper_('edit_others_posts'); }
public function is_administrator(){ return $this->is_helper_('install_plugins'); }
private function is_helper_($what){ return (function_exists('current_user_can') || require_once(ABSPATH.'wp-includes/pluggable.php')) && current_user_can($what); }
public function user_id(){return (function_exists('current_user_can') || require_once(ABSPATH.'wp-includes/pluggable.php')) ? get_current_user_id() : -1; }
public function init_if_editor($func, $initPriority=1){
add_action('init', function() use ($func) {
if ($this->is_editor())
call_user_func($func);
}, $initPriority);
}
public function get_user_role( $user_id = 0 ) {
$user = ( $user_id ) ? get_userdata( $user_id ) : wp_get_current_user();
return current( $user->roles );
}
// ##############
public function get_transient($transientName, $default=''){
if( ($value = get_transient($transientName))===false ) {
$value = $default;
}
return $value;
}
public function set_transient($transientName, $value, $seconds=8640000){
return set_transient($transientName, $value, $seconds);
}
public function append_transient_array($transientName, $key=null, $valueToAddInArray=null, $seconds=8640000, $autoreset_if_array_above=999){
$current_arr= $this->get_transient($transientName, []);
if( count($current_arr) > $autoreset_if_array_above )
$current_arr = $this->array_part( $current_arr, $autoreset_if_array_above, 'end');
if ($key) $current_arr[$key] = $valueToAddInArray;
else $current_arr[] = $valueToAddInArray;
return $this->set_transient($transientName,$current_arr, $seconds);
}
public function timer_remains( $uniqueActionId, $cache_seconds=9999999999, $reset=false ){
return $this->check_timer_remains($uniqueActionId, $cache_seconds, $reset );
}
public function check_timer_remains($uniqueActionId, $cache_seconds=9999999999, $reset=false ){
$remains = 0;
if ( $cache_seconds>0 )
{
$transientName = $this->slug ."_px_timer_flag_".$uniqueActionId;
$last_time = $this->get_transient($transientName,0);
if( $last_time > 0 ) {
$remains = ($last_time + $cache_seconds) - time();
if ($reset)
$this->set_transient($transientName, time(), $cache_seconds);
}
else{
$this->set_transient($transientName, time(), $cache_seconds);
}
}
return $remains;
}
public function check_timer_remains_function($uniqueActionId, $callback, $cache_seconds=9999999999){
$remains = 0;
if ( $cache_seconds>0 )
{
$transientName = $this->slug ."_px_timer_flag_".$uniqueActionId;
$last_time = $this->get_transient($transientName,0);
if( $last_time > 0 ) {
$remains = ($last_time + $cache_seconds) - time();
}
else{
call_user_func($callback);
$this->set_transient($transientName, time(), $cache_seconds);
}
}
return $remains;
}
//delete all transients:
public function delete_all_transients(){
global $wpdb;
$wpdb->query("DELETE FROM `{$wpdb->prefix}options` WHERE `option_name` LIKE ('_transient_%');");
$wpdb->query("DELETE FROM `{$wpdb->prefix}options` WHERE `option_name` LIKE ('_site_transient_%');");
}
public function option_exists($name, $site_wide=false){
global $wpdb;
$tablename = ($site_wide ? $wpdb->base_prefix : $wpdb->prefix).'options';
$sql = $wpdb->prepare("SELECT * FROM " . $tablename . " WHERE option_name ='%s' LIMIT 1", $name);
return $wpdb->query($sql);
}
public function transient_exists ($transientName, $site_wide = false) {
// get_option('_transient_timeout_' . $your_transient); gets timestamp of expiration, but is heavier than below line
return $this->option_exists('_transient_timeout_'.$transientName, $site_wide);
}
// ################################
public function post_is_in_descendant_category($cat, $postttId) {
$descendants = array_merge( array($cat,''), get_term_children((int) $cat, 'category') );
return (in_category($descendants, $postttId)) ? true : false;
}
//if post is ansector of category //is_category(4)
public function post_or_cat_is_in_ansector($upper_category_id){
$truee_fals =false; global $post;
//for categories
if (is_archive()) { $cur_cat_id = get_query_var('cat');
if ($cur_cat_id == $upper_category_id || cat_is_ancestor_of($upper_category_id, $cur_cat_id)) {return true;}
}
else {
if (in_category( $upper_category_id, $post->ID )) { return true;}
}
//$curr_post = get_post($post->ID); $truee_fals=cat_is_ancestor_of($upper_category_id, $curr_post->$post_category) ? true : $truee_fals;
}
public function get_metas_by_metakv($key, $value=null, $what=false) {
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare( "SELECT %s FROM ".$wpdb->postmeta." WHERE meta_key=%s %s", ($what ?: "*"), $key, ($value ? " AND meta_value=$value" : "") )
);
if (!empty($results)) {
if ($what){
$array= array();
foreach($results as $index => $result) { $array[$index] = $result->{$what}; }
return $array;
}
return $results;
}
return false;
}
// metaboxes, meta-box, media-uploaders: https://pastebin_com/ePszrRWb
public function error_mail($subject, $text){
return wp_mail(get_option('admin_email'), $subject, $text );
}
public function myframe_center($content){
if(is_singular() && stripos($content,'<iframe') !==false){
$content= preg_replace('/\<iframe (.*?)\>/si','<div class="frame_parentt" style="text-align:center;">$0</div>', $content);
}
return $content;
}
public function change_output()
{
add_action('wp_loaded', function() { ob_start( function ($buffer) {
// modify buffer here, and then return the updated code
$buffer = str_replace('MERCEDES','FERRARIIII',$buffer);
return $buffer;
}); } );
add_action('shutdown', function() { ob_end_flush(); } );
}
#region DATABASE FUNCTIONS
// name, columns (included), excluded
public function output_table_from_db_table($opts)
{
$opts['excluded'] = $this->array_value($opts,'excluded',[]);
$opts['reverse'] = $this->array_value($opts,'reverse',true);
$opts['limit'] = $this->array_value($opts,'limit',9999);
$opts['datetime_key'] = $this->array_value($opts,'datetime_key', 'time');
$results = $this->db_get_results( $opts['name'], '*');
if ($opts['reverse'])
$results = array_reverse($results); //reverse chronologically
$results = array_slice($results, 0, $opts['limit']);
$out = '';
$out .= '
<style>
.typicalTable {border: 1px solid black;}
.typicalTable td {border: 1px solid black;}
</style>
';
$out .=
'<table class="typicalTable"><thead>';
if (!empty($results))
{
$headrows = array_keys((array)$results[0]);
$out .= '<tr>';
foreach($headrows as $key){
if (!in_array($key, $opts['excluded']))
$out .= "<th>$key</th>";
}
$out .= '</tr>';
}
$out .=
'</thead><tbody>';
foreach($results as $eachBlock)
{
$out .= '<tr>';
foreach($eachBlock as $key=>$value){
if (!in_array($key, $opts['excluded'])) {
if ($key===$opts['datetime_key']){
$value = date('Y-m-d H:i:s', $value);
}
$out .= "<td>$value</td>";
}
}
$out .= '</tr>';
}
$out .=
'</tbody></table>';
return $out;
}
// $this->create_table_my( 'myTable1', [ '`gmdate` datetime', '`function_args` longtext NOT NULL' ] );
public function create_table_my($table_name, $array, $auto_increment_ID=true){
global $wpdb;
// `meta_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
// ................................. NULL DEFAULT '0',
// `meta_key` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
// varchar(255) | longtext |
// PRIMARY KEY (`meta_id`),
// KEY `post_id` (`post_id`),
// KEY `meta_key` (`meta_key`(191))
//)
$sql ="(";
if ($auto_increment_ID===true)
$sql .="`ID` bigint NOT NULL AUTO_INCREMENT,";
foreach( $array as $key=>$val){
$sql .= $val . ',' ;//' NOT NULL,';
}
if ($auto_increment_ID===true)
$sql .= "PRIMARY KEY (`ID`), UNIQUE KEY `ID` (`ID`) ";
elseif (is_string($auto_increment_ID))
$sql .= "PRIMARY KEY (`$auto_increment_ID`), UNIQUE KEY `$auto_increment_ID` (`$auto_increment_ID`) ";
else
$sql = $this->remove_chars_from_start_end($sql,0,1);
$sql .=") ";
if ($auto_increment_ID===true)
$sql .=" AUTO_INCREMENT=1 ";
// text text NOT NULL, name tinytext NOT NULL, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, id mediumint(9) NOT NULL AUTO_INCREMENT,
return $this->create_table_command($table_name, $sql);
}
public function create_table_command($table_name, $sql_inner){
global $wpdb;
$sql = "CREATE TABLE IF NOT EXISTS `%s`";
$sql .= $sql_inner;
$sql .=" %s;";
$charset = $wpdb->get_charset_collate();
//$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci';
$sql = $wpdb->prepare( $sql, $table_name, $charset );
$sql = $this->unquote($sql);
$x= $wpdb->query($sql );
//require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
//dbDelta( $sql );
return $x;
}
public function update_or_insert($tablename, $NewArray, $WhereArray=[]){
return $this->db_update_or_insert($tablename, $NewArray, $WhereArray);
}
public function db_update_or_insert($tablename, $NewArray, $WhereArray=[]){
global $wpdb;
// if string (i.e. key), then grab it from $NewArray[key]
if (is_string($WhereArray)) $WhereArray=[$WhereArray=>$NewArray[$WhereArray]];
elseif (!$this->array_is_associative($WhereArray) ) { foreach($WhereArray as $key) $WhereArray[$key]=$NewArray[$key]; }
//check if already exist
if(!empty($WhereArray)){
// ### now check, if it exists, and it was not updated, then return false ###
$whereStr=''; $i=1; foreach ($WhereArray as $key=>$value){ $whereStr .= $wpdb->prepare( sanitize_key($key) . " = '%s'", $value); if ($i != count($WhereArray)) { $whereStr .=' AND '; $i++;} }
$sql = ("SELECT * FROM `".sanitize_key($tablename)."` WHERE $whereStr");
$CheckIfExists = $wpdb->get_results($sql);
if (!empty($CheckIfExists)){
$result_Update = $wpdb->update($tablename, $NewArray, $WhereArray );
return $result_Update;
}
}
if ( $wpdb->insert($tablename, array_merge($NewArray, $WhereArray) ) ) return true;
return false;
}
public function db_update_or_insert_OLD($tablename, $NewArray, $WhereArray=[]){
global $wpdb;
// if string (i.e. key), then grab it from $NewArray[key]
if (is_string($WhereArray)) $WhereArray=[$WhereArray=>$NewArray[$WhereArray]];
elseif (!$this->array_is_associative($WhereArray) ) { foreach($WhereArray as $key) $WhereArray[$key]=$NewArray[$key]; }
//check if already exist
if(!empty($WhereArray)){
$result_Update = $wpdb->update($tablename, $NewArray, $WhereArray );
if ($result_Update) {
return true;
}