-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
1532 lines (1316 loc) · 39.7 KB
/
Copy pathfunctions.php
File metadata and controls
1532 lines (1316 loc) · 39.7 KB
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
require_once get_template_directory() . '/includes/start.php';
/**
* Append table name in $wpdb.
*
* @since 1.0.0
*/
function ap_append_table_names() {
global $wpdb;
$wpdb->ap_qameta = $wpdb->prefix . 'ap_qameta';
$wpdb->ap_votes = $wpdb->prefix . 'ap_votes';
$wpdb->ap_views = $wpdb->prefix . 'ap_views';
$wpdb->ap_reputations = $wpdb->prefix . 'ap_reputations';
}
ap_append_table_names(); // we should call this
/**
* To retrieve AnsPress option.
*
* @param string $key Name of option to retrieve or keep it blank to get all options of AnsPress.
* @param string $value Enter value to update existing option.
* @return string
* @since 0.1
*/
function ap_opt( $key = false, $value = null ) {
$settings = wp_cache_get( 'anspress_opt', 'ap' );
if ( false === $settings ) {
$settings = get_option( 'anspress_opt' );
if ( ! $settings ) {
$settings = array();
}
wp_cache_set( 'anspress_opt', $settings, 'ap' );
}
$settings = $settings + ap_default_options();
if ( ! is_null( $value ) ) {
$settings[ $key ] = $value;
update_option( 'anspress_opt', $settings );
// Clear cache if option updated.
wp_cache_delete( 'anspress_opt', 'ap' );
return;
}
if ( false === $key ) {
return $settings;
}
if ( isset( $settings[ $key ] ) ) {
return $settings[ $key ];
}
return null;
}
/**
* Create base page for AnsPress.
*
* This function is called in plugin activation. This function checks if base page already exists,
* if not then it create a new one and update the option.
*
* @see anspress_activate
* @since 1.0.0
*/
function ap_create_base_page() {
$opt = ap_opt();
$pages = ap_main_pages();
foreach ( $pages as $slug => $page ) {
// Check if page already exists.
$_post = get_page( ap_opt( $slug ) );
if ( ! $_post || 'trash' === $_post->post_status ) {
$args = wp_parse_args(
$page, array(
'post_type' => 'page',
'post_content' => '[anspress]',
'post_status' => 'publish',
'comment_status' => 'closed',
)
);
if ( 'base_page' !== $slug ) {
$args['post_parent'] = ap_opt( 'base_page' );
}
// Now create post.
$new_page_id = wp_insert_post( $args );
if ( $new_page_id ) {
$page = get_page( $new_page_id );
ap_opt( $slug, $page->ID );
ap_opt( $slug . '_id', $page->post_name );
}
}
} // End foreach().
}
/**
* All pages required of AnsPress.
*
* @return array
* @since 4.1.0
*/
function ap_main_pages() {
$pages = array(
'base_page' => array(
'label' => __( 'Archives page', 'anspress-question-answer' ),
'desc' => __( 'Page used to display question archive (list). Sometimes this page is used for displaying other subpages of AnsPress.<br/>This page is also referred as <b>Base Page</b> in AnsPress documentations and support forum.', 'anspress-question-answer' ),
'post_title' => __( 'Questions', 'anspress-question-answer' ),
'post_name' => 'questions',
),
'ask_page' => array(
'label' => __( 'Ask page', 'anspress-question-answer' ),
'desc' => __( 'Page used to display ask form.', 'anspress-question-answer' ),
'post_title' => __( 'Ask a question', 'anspress-question-answer' ),
'post_name' => 'ask',
),
'user_page' => array(
'label' => __( 'User page', 'anspress-question-answer' ),
'desc' => __( 'Page used to display user profile.', 'anspress-question-answer' ),
'post_title' => __( 'Profile', 'anspress-question-answer' ),
'post_name' => 'profile',
),
'categories_page' => array(
'label' => __( 'Categories page', 'anspress-question-answer' ),
'desc' => __( 'Page used to display question categories. NOTE: Categories addon must be enabled to render this page.', 'anspress-question-answer' ),
'post_title' => __( 'Categories', 'anspress-question-answer' ),
'post_name' => 'categories',
),
);
/**
* Hook for filtering main pages of AnsPress. Custom main pages
* can be registered using this hook.
*
* @param array $pages Array of pages.
* @since 4.1.5
*/
return apply_filters( 'ap_main_pages', $pages );
}
function ap_has_base_page() {
$base_page = ap_opt( 'base_page' );
if ( $base_page ) {
return true;
}
return false;
}
/**
* Return the total numbers of post.
*
* @param string $post_type Post type.
* @param boolean|string $ap_type ap_meta type.
* @return array
* @since 2.0.0
* @TODO use new qameta table.
*/
function ap_total_posts_count( $post_type = 'question', $ap_type = false, $user_id = false ) {
global $wpdb;
if ( 'question' === $post_type ) {
$type = "p.post_type = 'question'";
} elseif ( 'answer' === $post_type ) {
$type = "p.post_type = 'answer'";
} else {
$type = "(p.post_type = 'question' OR p.post_type = 'answer')";
}
$meta = '';
$join = '';
if ( 'unanswered' === $ap_type ) {
$meta = 'AND qameta.answers = 0';
$join = "INNER JOIN {$wpdb->ap_qameta} qameta ON p.ID = qameta.post_id";
} elseif ( 'best_answer' === $ap_type ) {
$meta = 'AND qameta.selected > 0';
$join = "INNER JOIN {$wpdb->ap_qameta} qameta ON p.ID = qameta.post_id";
}
$where = "WHERE p.post_status NOT IN ('trash', 'draft', 'private') AND $type $meta";
if ( false !== $user_id && (int) $user_id > 0 ) {
$where .= ' AND p.post_author = ' . (int) $user_id;
}
$where = apply_filters( 'ap_total_posts_count', $where );
$query = "SELECT count(*) as count, p.post_status FROM $wpdb->posts p $join $where GROUP BY p.post_status";
$cache_key = md5( $query );
$count = wp_cache_get( $cache_key, 'counts' );
if ( false !== $count ) {
return $count;
}
$count = $wpdb->get_results( $query, ARRAY_A ); // @codingStandardsIgnoreLine
$counts = array();
foreach ( (array) get_post_stati() as $state ) {
$counts[ $state ] = 0;
}
$counts['total'] = 0;
if ( ! empty( $count ) ) {
foreach ( $count as $row ) {
$counts[ $row['post_status'] ] = (int) $row['count'];
$counts['total'] += (int) $row['count'];
}
}
wp_cache_set( $cache_key, (object) $counts, 'counts' );
return (object) $counts;
}
/**
* Echo anspress links.
*
* @param string|array $sub Sub page.
* @since 2.1
*/
function ap_link_to( $sub ) {
echo ap_get_link_to( $sub ); // xss ok.
}
/**
* Return link to AnsPress pages.
*
* @param string|array $sub Sub pages/s.
* @return string
*/
function ap_get_link_to( $sub ) {
$url = false;
if ( 'ask' === $sub ) {
$url = get_permalink( ap_opt( 'ask_page' ) );
}
if ( false === $url ) {
/**
* Define default AnsPress page slugs.
*
* @var array
*/
$default_pages = array(
'question' => ap_opt( 'question_page_slug' ),
);
$default_pages = apply_filters( 'ap_default_page_slugs', $default_pages );
if ( is_array( $sub ) && isset( $sub['ap_page'] ) && isset( $default_pages[ $sub['ap_page'] ] ) ) {
$sub['ap_page'] = $default_pages[ $sub['ap_page'] ];
} elseif ( ! is_array( $sub ) && ! empty( $sub ) && isset( $default_pages[ $sub ] ) ) {
$sub = $default_pages[ $sub ];
}
$base = rtrim( ap_base_page_link(), '/' );
$args = '';
if ( get_option( 'permalink_structure' ) !== '' ) {
if ( ! is_array( $sub ) && 'base' !== $sub ) {
$args = $sub ? '/' . $sub : '';
} elseif ( is_array( $sub ) ) {
$args = '/';
if ( ! empty( $sub ) ) {
foreach ( (array) $sub as $s ) {
$args .= $s . '/';
}
}
}
$args = rtrim( $args, '/' ) . '/';
} else {
if ( ! is_array( $sub ) ) {
$args = $sub ? '&ap_page=' . $sub : '';
} elseif ( is_array( $sub ) ) {
$args = '';
if ( ! empty( $sub ) ) {
foreach ( $sub as $k => $s ) {
$args .= '&' . $k . '=' . $s;
}
}
}
}
$url = $base . $args;
} // End if().
/**
* Allows filtering anspress links.
*
* @param string $url Generated url.
* @param string|array $sub AnsPress sub pages.
*
* @since unknown
*/
return apply_filters( 'ap_link_to', $url, $sub );
}
/**
* Retrieve permalink to base page.
*
* @return string URL to AnsPress base page
* @since 2.0.0
* @since 3.0.0 Return link to questions page if base page not selected.
*/
function ap_base_page_link() {
if ( empty( ap_opt( 'base_page' ) ) ) {
return home_url( '/questions/' );
}
return get_permalink( ap_opt( 'base_page' ) );
}
/**
* Get slug of base page.
*
* @return string
* @since 2.0.0
* @since 3.0.0 Return `questions` if base page is not selected.
* @since 4.1.6 Make sure always `questions` is returned if no base page is set.
*/
function ap_base_page_slug() {
$slug = 'questions';
if ( ! empty( ap_opt( 'base_page' ) ) ) {
$base_page = get_post( ap_opt( 'base_page' ) );
if ( $base_page ) {
$slug = $base_page->post_name;
if ( $base_page->post_parent > 0 ) {
$parent_page = get_post( $base_page->post_parent );
$slug = $parent_page->post_name . '/' . $slug;
}
}
}
return apply_filters( 'ap_base_page_slug', $slug );
}
/**
* Get current question ID in single question page.
*
* @return integer|false
* @since unknown
* @since 4.1.0 Remove `question_name` query var check. Get question ID from queried object.
*/
function get_question_id() {
if ( is_question() && get_query_var( 'question_id' ) ) {
return (int) get_query_var( 'question_id' );
}
if ( is_question() ) {
return get_queried_object_id();
}
if ( get_query_var( 'edit_q' ) ) {
return get_query_var( 'edit_q' );
}
return false;
}
/**
* Pre fetch users and update cache.
*
* @param array $ids User ids.
* @since 4.0.0
*/
function ap_post_author_pre_fetch( $ids ) {
$users = get_users(
[
'include' => $ids,
'fields' => array( 'ID', 'user_login', 'user_nicename', 'user_email', 'display_name' ),
]
);
foreach ( (array) $users as $user ) {
update_user_caches( $user );
}
update_meta_cache( 'user', $ids );
}
/**
* Check if current page is question page.
*
* @return boolean
* @since 0.0.1
* @since 4.1.0 Also check and return true if singular question.
*/
function is_question() {
if ( is_singular( 'question' ) ) {
return true;
}
return false;
}
/**
* Return or echo user display name.
*
* Get display name from comments if WP_Comment object is passed. Else
* fetch name form user profile. If anonymous user then fetch name from
* current question, answer or comment.
*
* @param WP_Comment|array|integer $args {
* Arguments or `WP_Comment` or user ID.
*
* @type integer $user_id User ID.
* @type boolean $html Shall return just text name or name with html markup.
* @type boolean $echo Return or echo.
* @type string $anonymous_label A placeholder name for anonymous user if no name found in post or comment.
* }
*
* @return string|void If `$echo` argument is tru then it will echo name.
* @since 0.1
* @since 4.1.2 Improved args and PHPDoc.
*/
function ap_user_display_name( $args = [] ) {
global $post;
$defaults = array(
'user_id' => get_the_author_meta( 'ID' ),
'html' => false,
'echo' => false,
);
// When only user id passed.
if ( is_numeric( $args ) ) {
$defaults['user_id'] = $args;
$args = $defaults;
} else {
$args = wp_parse_args( $args, $defaults );
}
extract( $args ); // @codingStandardsIgnoreLine
$user = get_userdata( $user_id );
$return = ! $html ? $user->display_name : '<a href="' . ap_user_link( $user_id ) . '" itemprop="url"><span itemprop="name">' . $user->display_name . '</span></a>';
/**
* Filter AnsPress user display name.
*
* Filter can be used to alter user display name or
* appending some extra information of user, like: rank, reputation etc.
* Make sure to return plain text when `$args['html']` is true.
*
* @param string $return Name of user to return.
* @param array $args Arguments.
*
* @since 2.0.1
*/
$return = apply_filters( 'ap_user_display_name', $return, $args );
if ( ! $args['echo'] ) {
return $return;
}
echo $return; // xss okay.
}
function ap_user_display_meta( $args = [] ) {
global $post;
$defaults = array(
'user_id' => get_the_author_meta( 'ID' ),
);
// When only user id passed.
if ( is_numeric( $args ) ) {
$defaults['user_id'] = $args;
$args = $defaults;
} else {
$args = wp_parse_args( $args, $defaults );
}
$return = '';
$return = apply_filters( 'ap_user_display_meta', $return, $args );
echo $return;
}
/**
* Verify the __nonce field.
*
* @param string $action Action.
* @return bool
* @since 2.4
*/
function ap_verify_nonce( $action ) {
return wp_verify_nonce( ap_sanitize_unslash( '__nonce', 'p' ), $action );
}
/**
* Sanitize and unslash string or array or post/get value at the same time.
*
* @param string|array $str String or array to sanitize. Or post/get key name.
* @param boolean|string $from Get value from `$_REQUEST` or `query_var`. Valid values: request, query_var.
* @param mixed $default Default value if variable not found.
* @return array|string
* @since 3.0.0
*/
function ap_sanitize_unslash( $str, $from = false, $default = '' ) {
// If not false then get from $_REQUEST or query_var.
if ( false !== $from ) {
if ( in_array( strtolower( $from ), [ 'request', 'post', 'get', 'p', 'g', 'r' ], true ) ) {
$str = ap_isset_post_value( $str, $default );
} elseif ( 'query_var' === $from ) {
$str = get_query_var( $str );
}
}
// Return default if empty.
if ( empty( $str ) ) {
return $default;
}
if ( is_array( $str ) ) {
$str = wp_unslash( $str );
return array_map( 'sanitize_text_field', $str );
}
return sanitize_text_field( wp_unslash( $str ) );
}
/**
* Check if $_REQUEST var exists and get value. If not return default.
*
* @param string $var Variable name.
* @param mixed $default Default value.
* @return mixed
* @since 3.0.0
*/
function ap_isset_post_value( $var, $default = '' ) {
if ( isset( $_REQUEST[ $var ] ) ) { // input var okay.
return wp_unslash( $_REQUEST[ $var ] ); // input var okay, xss ok, sanitization ok.
}
return $default;
}
/**
* Sort array by order value. Group array which have same order number and then sort them.
*
* @param array $array Array to order.
* @return array
* @since 2.0.0
* @since 4.1.0 Use `WP_List_Util` class for sorting.
*/
function ap_sort_array_by_order( $array ) {
$new_array = [];
if ( ! empty( $array ) && is_array( $array ) ) {
$i = 1;
foreach ( $array as $k => $a ) {
if ( is_array( $a ) ) {
$array[ $k ]['order'] = isset( $a['order'] ) ? $a['order'] : $i;
}
$i += 2;
}
$util = new WP_List_Util( $array );
return $util->sort( 'order', 'ASC', true );
}
}
/**
* Convert array notation (string, not real array) to dot notation.
*
* @param boolean|string $path Path name.
* @return string Path separated by dot notation.
*/
function ap_to_dot_notation( $path = false ) {
$parsed = rtrim( str_replace( '..', '.', str_replace( [ ']', '[' ], '.', $path ) ), '.' );
return $parsed;
}
/**
* Send properly formatted AnsPress json string.
*
* @param array|string $response Response array or string.
*/
function ap_ajax_json( $response ) {
ap_send_json( ap_ajax_responce( $response ) );
}
/**
* Send a array as a JSON.
*
* @param array $result Results.
*/
function ap_send_json( $result = array() ) {
header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
$result['is_ap_ajax'] = true;
$json = '<div id="ap-response">' . wp_json_encode( $result, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP ) . '</div>';
wp_die( $json ); // xss ok.
}
/**
* Format an array as valid AnsPress ajax response.
*
* @param array|string $results Response to send.
* @return array
* @since unknown
* @since 4.1.0 Removed `template` variable. Send `snackbar` for default message.
*/
function ap_ajax_responce( $results ) {
if ( ! is_array( $results ) ) {
$message_id = $results;
$results = array();
$results['message'] = $message_id;
}
$results['ap_responce'] = true;
if ( isset( $results['message'] ) ) {
$error_message = ap_responce_message( $results['message'] );
if ( false !== $error_message ) {
$results['snackbar'] = array(
'message' => $error_message['message'],
'message_type' => $error_message['type'],
);
$results['success'] = 'error' === $error_message['type'] ? false : true;
}
}
/**
* Filter AnsPress ajax response body.
*
* @param array $results Results.
* @since 2.0.1
*/
$results = apply_filters( 'ap_ajax_responce', $results );
return $results;
}
/**
* Check if user answered on a question.
*
* @param integer $question_id Question ID.
* @param integer $user_id User ID.
* @return boolean
*
* @since unknown
* @since 4.1.6 Changed cache group to `counts`.
* @todo clear cache after answer.
*/
function ap_is_user_answered( $question_id, $user_id ) {
global $wpdb;
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts where post_parent = %d AND ( post_author = %d AND post_type = 'answer') AND ( post_status = 'publish' )", $question_id, $user_id ) ); // db call ok.
return $count > 0 ? true : false;
}
/**
* Truncate string but preserve full word.
*
* @param string $text String.
* @param int $limit Limit string to.
* @param string $ellipsis Ellipsis.
* @return string
*
* @since 4.1.8 Strip tags.
*/
function ap_truncate_chars( $text, $limit = 40, $ellipsis = '...' ) {
$text = strip_tags( $text );
$text = str_replace( array( "\r\n", "\r", "\n", "\t" ), ' ', $text );
if ( strlen( $text ) > $limit ) {
$endpos = strpos( $text, ' ', (string) $limit );
if ( false !== $endpos ) {
$text = trim( substr( $text, 0, $endpos ) ) . $ellipsis;
}
}
return $text;
}
/**
* Remove white space from string.
*
* @param string $contents String.
* @return string
*/
function ap_trim_traling_space( $contents ) {
$contents = preg_replace( '#(^( |\s)+|( |\s)+$)#', '', $contents );
return $contents;
}
/**
* Search array by key and value.
*
* @param array $array Array to search.
* @param string $key Array key to search.
* @param mixed $value Value of key supplied.
* @return array
* @since 4.0.0
*/
function ap_search_array( $array, $key, $value ) {
$results = array();
if ( is_array( $array ) ) {
if ( isset( $array[ $key ] ) && $array[ $key ] == $value ) {
$results[] = $array;
}
foreach ( $array as $subarray ) {
$results = array_merge( $results, ap_search_array( $subarray, $key, $value ) );
}
}
return $results;
}
/**
* Return question title with solved prefix if answer is accepted.
*
* @param boolean|integer $question_id Question ID.
* @return string
*
* @since 2.3 @see `ap_page_title`
*/
function ap_question_title_with_solved_prefix( $question_id = false ) {
if ( false === $question_id ) {
$question_id = get_question_id();
}
$solved = ap_have_answer_selected( $question_id );
if ( ap_opt( 'show_solved_prefix' ) ) {
return get_the_title( $question_id ) . ' ' . ( $solved ? __( '[Solved] ', 'anspress-question-answer' ) : '' );
}
return get_the_title( $question_id );
}
/**
* Return edit link for question and answer.
*
* @param mixed $_post Post.
* @return string
* @since 2.0.1
*/
function ap_post_edit_link( $_post ) {
$_post = ap_get_post( $_post );
$nonce = wp_create_nonce( 'edit-post-' . $_post->ID );
$base_page = 'question' === $_post->post_type ? ap_get_link_to( 'ask' ) : ap_get_link_to( 'edit' );
$edit_link = add_query_arg(
array(
'id' => $_post->ID,
'__nonce' => $nonce,
), $base_page
);
/**
* Allows filtering post edit link.
*
* @param string $edit_link Url to edit post.
* @since unknown
*/
return apply_filters( 'ap_post_edit_link', $edit_link );
}
/**
* Return post status based on AnsPress options.
*
* @param boolean|integer $user_id ID of user creating question.
* @param string $post_type Post type, question or answer.
* @param boolean $edit Is editing post.
* @return string
* @since 3.0.0
*/
function ap_new_edit_post_status( $user_id = false, $post_type = 'question', $edit = false ) {
if ( false === $user_id ) {
$user_id = get_current_user_id();
}
$new_edit = $edit ? 'edit' : 'new';
$option_key = $new_edit . '_' . $post_type . '_status';
$status = 'publish';
return $status;
}
/**
* Send ajax response after posting an answer.
*
* @param integer|object $question_id Question ID or object.
* @param integer|object $answer_id Answer ID or object.
* @return void
* @since 4.0.0
* @since 4.1.0 Moved from includes\answer-form.php.
*/
function ap_answer_post_ajax_response( $question_id, $answer_id ) {
$question = ap_get_post( $question_id );
// Get existing answer count.
$current_ans = ap_count_published_answers( $question_id );
global $post;
$post = ap_get_post( $answer_id );
setup_postdata( $post );
ob_start();
global $withcomments;
$withcomments = true;
ap_template_part( 'answer' );
$html = ob_get_clean();
$count_label = sprintf( _n( '%d Answer', '%d Answers', $current_ans, 'anspress-question-answer' ), $current_ans );
$result = array(
'success' => true,
'ID' => $answer_id,
'form' => 'answer',
'div_id' => '#post-' . get_the_ID(),
'can_answer' => ap_user_can_answer( $post->ID ),
'html' => $html,
'snackbar' => [ 'message' => __( 'Answer submitted successfully', 'anspress-question-answer' ) ],
'answersCount' => [
'text' => $count_label,
'number' => $current_ans,
],
);
ap_ajax_json( $result );
}
/**
* Return Link to user pages.
*
* @param boolean|integer $user_id user id.
* @param string|array $sub page slug.
* @return string
* @since unknown
* @since 4.1.1 Profile link not linking to BuddyPress when active.
* @since 4.1.2 User user nicename in url as author_name query var gets user by nicename.
*/
function ap_user_link( $user_id = false, $sub = false ) {
$link = '';
if ( false === $user_id ) {
$user_id = get_the_author_meta( 'ID' );
}
if ( empty( $user_id ) && is_author() ) {
$user_id = get_queried_object_id();
}
$user = get_user_by( 'id', $user_id );
if ( $user ) {
$slug = get_option( 'ap_user_path' );
$link = home_url( $slug ) . '/' . $user->user_nicename . '/';
// Append sub.
if ( ! empty( $sub ) ) {
if ( is_array( $sub ) ) {
$link = rtrim( $link, '/' ) . implode( '/', $sub ) . '/';
} else {
$link = $link . rtrim( $sub, '/' ) . '/';
}
}
return apply_filters( 'ap_user_link', $link, $user_id, $sub );
}
return '';
}
/**
* Return link to answers.
*
* @param boolean|integer $question_id Question ID.
* @return string
*/
function ap_answers_link( $question_id = false ) {
if ( ! $question_id ) {
return get_permalink() . '#answers';
}
return get_permalink( $question_id ) . '#answers';
}
/**
* Convert number to 1K, 1M etc.
*
* @param integer $num Number to convert.
* @param integer $precision Precision.
* @return string
*/
function ap_short_num( $num, $precision = 2 ) {
if ( $num >= 1000 && $num < 1000000 ) {
$n_format = number_format( $num / 1000, $precision ) . 'K';
} elseif ( $num >= 1000000 && $num < 1000000000 ) {
$n_format = number_format( $num / 1000000, $precision ) . 'M';
} elseif ( $num >= 1000000000 ) {
$n_format = number_format( $num / 1000000000, $precision ) . 'B';
} else {
$n_format = $num;
}
return $n_format;
}
/**
* Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended
* to the end of the array.
*
* @param array $array
* @param string $key
* @param array $new
*
* @return array
*/
function ap_array_insert_after( $array = [], $key, $new ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys );
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}
/**
* Check if current page is AnsPress. Also check if showing question or
* answer page in BuddyPress.
*
* @return boolean
* @since 4.1.0 Improved check. Check for main pages.
* @since 4.1.1 Check for @see ap_current_page().
* @since 4.1.8 Added filter `is_anspress`.
*/
function is_anspress() {
$ret = false;
$page_slug = array_keys( ap_main_pages() );
$queried_object = get_queried_object();
// Check if main pages.
if ( $queried_object instanceof WP_Post ) {
$page_ids = [];
foreach ( $page_slug as $slug ) {
$page_ids[] = ap_opt( $slug );
}
if ( in_array( $queried_object->ID, $page_ids ) ) {
$ret = true;
}
}
// Check if ap_page.
if ( is_search() && 'question' === get_query_var( 'post_type' ) ) {
$ret = true;
} elseif ( '' !== ap_current_page() ) {
$ret = true;
}
/**
* Filter for overriding is_anspress() return value.
*
* @param boolean $ret True or false.
* @since 4.1.8
*/
return apply_filters( 'is_anspress', $ret );
}
/**
* Sanitize comma delimited strings.
*
* @param string|array $str Comma delimited string.
* @param string $pieces_type Type of piece, string or number.
* @return string
*/
function sanitize_comma_delimited( $str, $pieces_type = 'int' ) {
$str = ! is_array( $str ) ? explode( ',', $str ) : $str;
if ( ! empty( $str ) ) {
$str = wp_unslash( $str );
$glue = 'int' !== $pieces_type ? '","' : ',';
$sanitized = [];
foreach ( $str as $s ) {
if ( '0' == $s || ! empty( $s ) ) {
$sanitized[] = 'int' === $pieces_type ? intval( $s ) : str_replace( [ "'", '"', ',' ], '', sanitize_text_field( $s ) );