/
functions.php
4148 lines (3702 loc) · 206 KB
/
functions.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
/** Acoes iniciais ** */
//define('ALTERNATE_WP_CRON', true);
add_action('init', 'wpdbfix');
add_action('init', 'register_post_types');
add_action('init', 'register_taxonomies');
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
include_once( dirname(__FILE__) . "/config/config.php" );
require_once (dirname(__FILE__) . '/libraries/php/OfficeToPlainText/OfficeDocumentToPlainText.php');
require_once('wp_bootstrap_navwalker.php');
include_once("models/log/log_model.php");
$tainacan_widgets = ["contact", "social_media", "site_map", "teaser", "news", "collections", "spot"];
foreach ($tainacan_widgets as $wg)
include_once("views/widgets/widget_$wg.php");
show_admin_bar(false);
add_theme_support( 'post-thumbnails' );
/*
AUTO LOAD DE CLASSES
*/
function AutoLoad() {
spl_autoload_register("MyAutoLoad");
}
function MyAutoLoad($Class) {
$Matches = array();
preg_match_all('/((?:^|[A-Z])[a-z]+)/', $Class, $Matches);
if (!empty($Matches)):
$ArrClass = $Matches[0];
$Folder = strtolower(end($ArrClass));
$File = strtolower(implode('_', $ArrClass));
$iDir = null;
if ($Folder == 'api'):
if (!$iDir && file_exists(__DIR__ . '/' . $Folder . '/' . $File . '.php') && !is_dir(__DIR__ . '/' . $Folder . '/' . $File . '.php')):
include_once (__DIR__ . '/' . $Folder . '/' . $File . '.php');
$iDir = true;
endif;
else:
$cDir = ['controllers', 'models'];
foreach ($cDir as $dirName):
$subDir = array_diff(scandir(__DIR__ . '/' . $dirName), array('..', '.'));
foreach ($subDir as $subDirName):
if (!$iDir && file_exists(__DIR__ . '/' . $dirName . '/' . $subDirName . '/' . $File . '.php') && !is_dir(__DIR__ . '/' . $dirName . '/' . $subDirName . '/' . $File . '.php')):
include_once (__DIR__ . '/' . $dirName . '/' . $subDirName . '/' . $File . '.php');
$iDir = true;
endif;
endforeach;
endforeach;
endif;
endif;
//excecoes
if(is_null($iDir)){
if($File === 'query_model')
include_once (__DIR__ . '/models/wp_query/wp_' .$File . '.php');
if($File === 'object_file_model')
include_once (__DIR__ . '/models/object/objectfile_model.php');
}
}
add_action('init', 'AutoLoad');
#### Desativar Widgets Padrões do Wordpress ####
/*
* @author Weryques
* */
function unregister_default_wp_widgets() {
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Links');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Text');
unregister_widget('WP_Widget_Categories');
unregister_widget('WP_Widget_Recent_Posts');
unregister_widget('WP_Widget_Recent_Comments');
unregister_widget('WP_Widget_RSS');
unregister_widget('WP_Widget_Tag_Cloud');
unregister_widget('WP_Nav_Menu_Widget');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);
#### WIDGETS AREAS #####
/*
* Função que carrega as áreas para widgets padrões e ativa o menu de widgets em wp-admin.
* @author Weryques
* */
function tainacan_widgets_init() {
register_sidebar(array(
'name' => __('Footer A', 'tainacan'),
'id' => 'footer-a',
'description' => __('Add widgets here to appear in your footer.', 'tainacan'),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>',
));
register_sidebar(array(
'name' => __('Footer B', 'tainacan'),
'id' => 'footer-b',
'description' => __('Add widgets here to appear in your footer.', 'tainacan'),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>',
));
register_sidebar(array(
'name' => __('Footer C', 'tainacan'),
'id' => 'footer-c',
'description' => __('Add widgets here to appear in your footer.', 'tainacan'),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>',
));
}
add_action('widgets_init', 'tainacan_widgets_init');
#### LOAD DEFAULT WIDGETS ###
/*
* Função que carrega os widgets padrões
* @author Weryques
* */
function activate_widgets() {
$active_widgets = get_option('sidebars_widgets');
$sidebars = array('a' => 'footer-a', 'b' => 'footer-b', 'c' => 'footer-c');
if (!empty($active_widgets[$sidebars['a']]) or ! empty($active_widgets[$sidebars['b']]) or ! empty($active_widgets[$sidebars['c']])) {
return;
}
$counter = 1;
$site_map_content = get_option('widget_site_map');
$social_media_content = get_option('widget_social_media');
$contact_content = get_option('widget_contact');
$site_map_content[$counter] = array(
'title' => _t('Site map'), 'handbook' => '',
'option1_title' => '', 'option1_url' => '', 'option1_new_page' => '',
'option2_title' => '', 'option2_url' => '', 'option2_new_page' => '',
'option3_title' => '', 'option3_url' => '', 'option3_new_page' => '',
'option4_title' => '', 'option4_url' => '', 'option4_new_page' => '',
);
$social_media_content[$counter] = array(
'title' => _t('Social Media'), 'facebook_url' => '',
'youtube_url' => '', 'twitter_url' => '',
'googleplus_url' => '', 'github_url' => ''
);
$contact_content[$counter] = array(
'title' => __('Contatos'), 'institution' => '', 'cnpj' => '',
'street' => '', 'address_number' => '', 'complement' => '', 'cep' => '',
'city' => '', 'state' => '', 'country' => '', 'email' => '', 'phone' => '',
);
$active_widgets[$sidebars['a']][] = 'site_map-' . $counter;
$active_widgets[$sidebars['b']][] = 'contact-' . $counter;
$active_widgets[$sidebars['c']][] = 'social_media-' . $counter;
update_option('sidebars_widgets', $active_widgets);
update_option('widget_site_map', $site_map_content);
update_option('widget_contact', $contact_content);
update_option('widget_social_media', $social_media_content);
}
add_action('widgets_init', 'activate_widgets');
/**
* Criando tabela taxonomymeta
*
*/
function setup_taxonomymeta() {
global $wpdb;
$charset_collate = '';
if (!empty($wpdb->charset))
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if (!empty($wpdb->collate))
$charset_collate .= " COLLATE $wpdb->collate";
$tables_taxonomymeta = $wpdb->get_results("show tables like '{$wpdb->prefix}taxonomymeta'");
if (count($tables_taxonomymeta)) {
$wpdb->query("ALTER TABLE {$wpdb->prefix}taxonomymeta
CHANGE taxonomy_id term_id bigint(20);");
$wpdb->query("ALTER TABLE {$wpdb->prefix}taxonomymeta
RENAME TO {$wpdb->prefix}termmeta;");
}
$tables_termeta = $wpdb->get_results("show tables like '{$wpdb->prefix}termmeta'");
if (!count($tables_termeta))
$wpdb->query("CREATE TABLE {$wpdb->prefix}termmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
term_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY term_id (term_id),
KEY meta_key (meta_key)
) $charset_collate;");
}
function createRepoStatPage() {
$_page_id = wp_insert_post([
'post_title' => __('Statistics', 'tainacan'),
'post_status' => 'publish',
'post_content' => __('Repository Statistics', 'tainacan'),
'post_type' => 'page',
'comment_status' => 'closed',
]);
if ($_page_id && $_page_id != 0) {
update_post_meta($_page_id, '_wp_page_template', 'page-statistics.php');
}
}
function setup_statisticsLog() {
global $wpdb;
//$curret_blog_ID = get_current_blog_id();
//$statistics_page_= get_page_by_title('Statistics');
//$statistics_ID = $statistics_ID->ID;
//if(is_null(get_blog_post($current_blog_ID, $statistics_ID))){
createRepoStatPage();
//}
$charset_collate = '';
if (!empty($wpdb->charset))
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if (!empty($wpdb->collate))
$charset_collate .= " COLLATE $wpdb->collate";
if (is_multisite()) {
$_sites_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
foreach ($_sites_ids as $siteID) {
switch_to_blog($siteID);
$_log_table_name = Log::_table();
$stats_table_sql = prepareRepoStatSQL($_log_table_name, $charset_collate);
$wpdb->query($stats_table_sql);
restore_current_blog();
}
} else {
$_log_table_name = Log::_table();
$stats_table_sql = prepareRepoStatSQL($_log_table_name, $charset_collate);
$wpdb->query($stats_table_sql);
}
}
function prepareRepoStatSQL($_TABLE_NAME_, $_CHARSET_COLLATE_) {
$_SQL_string = "CREATE TABLE IF NOT EXISTS {$_TABLE_NAME_} (
id INT UNSIGNED NOT NULL auto_increment,
collection_id BIGINT(20) UNSIGNED NOT NULL,
user_id BIGINT(20) UNSIGNED NOT NULL,
item_id BIGINT(20) UNSIGNED NOT NULL,
resource_id BIGINT(20) UNSIGNED NOT NULL,
ip VARCHAR(39) DEFAULT NULL,
event_type VARCHAR(20) NOT NULL,
event VARCHAR(50) NOT NULL,
event_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id) ) $_CHARSET_COLLATE_";
return $_SQL_string;
}
/*
* Quick touchup to wpdb
*/
function wpdbfix() {
global $wpdb;
if (!isset($wpdb->termmeta)) {
$wpdb->termmeta = "{$wpdb->prefix}termmeta";
}
}
//
// Term Meta funtions para Wordpress inferiores ao 4.4
//
/**
* Update term meta field based on term ID.
*
* Use the $prev_value parameter to differentiate between meta fields with the
* same key and term ID.
*
* If the meta field for the term does not exist, it will be added.
*
* @param int $term_id Term ID.
* @param string $key Metadata key.
* @param mixed $value Metadata value.
* @param mixed $prev_value Optional. Previous value to check before removing.
* @return bool False on failure, true if success.
*/
if (!function_exists('update_term_meta')) {
function update_term_meta($term_id, $meta_key, $meta_value, $prev_value = '') {
return update_metadata('term', $term_id, $meta_key, $meta_value, $prev_value);
}
}
/**
* Add meta data field to a term.
*
* @param int $term_id Post ID.
* @param string $key Metadata name.
* @param mixed $value Metadata value.
* @param bool $unique Optional, default is false. Whether the same key should not be added.
* @return bool False for failure. True for success.
*/
if (!function_exists('add_term_meta')) {
function add_term_meta($term_id, $meta_key, $meta_value, $unique = false) {
return add_metadata('term', $term_id, $meta_key, $meta_value, $unique);
}
}
/**
* Remove metadata matching criteria from a term.
*
* You can match based on the key, or key and value. Removing based on key and
* value, will keep from removing duplicate metadata with the same key. It also
* allows removing all metadata matching key, if needed.
*
* @param int $term_id term ID
* @param string $meta_key Metadata name.
* @param mixed $meta_value Optional. Metadata value.
* @return bool False for failure. True for success.
*/
if (!function_exists('delete_term_meta')) {
function delete_term_meta($term_id, $meta_key, $meta_value = '') {
return delete_metadata('term', $term_id, $meta_key, $meta_value);
}
}
/**
* Retrieve term meta field for a term.
*
* @param int $term_id Term ID.
* @param string $key The meta key to retrieve.
* @param bool $single Whether to return a single value.
* @return mixed Will be an array if $single is false. Will be value of meta data field if $single
* is true.
*/
if (!function_exists('get_term_meta')) {
function get_term_meta($term_id, $key, $single = false) {
return get_metadata('term', $term_id, $key, $single);
}
}
/* * **************** MENU FUNCTION PARA O WORDPRESS ADMIN *********************** */
/**
* Registra o menu do Tainacan no Wordpress
*
* @return void Apenas insere o menu do tainacan no wordpress
*/
function register_my_menu() {
register_nav_menu('header-menu', __('Header Menu', 'tainacan'));
}
add_action('init', 'register_my_menu');
/* * **************** END MENU FUNCTION PARA O WORDPRESS ADMIN *********************** */
$conditional_scripts = array(
'html5shiv' => '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.js',
'html5shiv-printshiv' => '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv-printshiv.js',
'respond' => '//cdn.jsdelivr.net/respond/1.4.2/respond.min.js'
);
add_filter('script_loader_tag', function( $tag, $handle ) use ( $conditional_scripts ) {
if (array_key_exists($handle, $conditional_scripts)) {
$tag = "<!--[if lt IE 9]>$tag<![endif]-->";
}
return $tag;
}, 10, 2);
/* * * CONSTANTE PATH DO WORDPRESS * */
if (!defined('WORDPRESS_PATH')) {
$iroot = getcwd();
$folder = explode("/", $iroot);
if (count($folder) == 1) {
define('WORDPRESS_PATH', $folder[0]);
} else {
define('WORDPRESS_PATH', $iroot);
}
}
/**
* Retorna uma string com o tipo text/html.
*
* @return void retorna o tipo text/html.
*/
function set_html_content_type() {
return 'text/html';
}
function modify_attachment_link($markup) {
return preg_replace('/^<a([^>]+)>(.*)$/', '<a\\1 target="_blank">\\2', $markup);
}
add_filter('wp_get_attachment_link', 'modify_attachment_link', 10, 6);
/**
* Altera o link para os feeds
* * */
add_action('template_redirect', 'socialdb_catch_uri', 99);
function socialdb_catch_uri() {
global $wp_query;
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (get_query_var('collection_name')) {
$_GET['collection_id'] = get_post_by_name(get_query_var('collection_name'))->ID;
$_GET['operation'] = 'feed';
$_GET['by_function'] = true;
$get_privacity = wp_get_object_terms($_GET['collection_id'], 'socialdb_collection_type');
if ($get_privacity) {
foreach ($get_privacity as $privacity) {
$privacity_name = $privacity->name;
}
}
if ($privacity_name == 'socialdb_collection_public') {
require_once 'controllers/rss/rss_controller.php';
exit();
} else {
wp_redirect(get_the_permalink($_GET['collection_id']));
}
} else if (get_query_var('oaipmh')) {
$_GET['by_function'] = true;
//$template = locate_template('single-socialdb-oai.php', true);
require_once 'controllers/export/oaipmh_controller.php';
exit();
} else if (strpos($actual_link, '.rdf') !== false) {
require_once 'controllers/export/rdf_controller.php';
exit();
} else if ( get_query_var('add') || get_query_var('edit') ) {
require_once dirname(__FILE__) . '/partials/item/add.php';
exit();
}
}
add_filter('query_vars', 'my_queryvars');
function my_queryvars($qvars) {
$qvars[] = 'collection_name';
$qvars[] = 'oaipmh';
$qvars[] = 'item';
$qvars[] = 'log-in';
$qvars[] = 'metadata';
return $qvars;
}
function custom_rewrite_tag() {
add_rewrite_tag('%advancedSearch%', '([^&]+)');
add_rewrite_tag('%collection_name%', '([^&]+)');
add_rewrite_tag('%oaipmh%', '([^&]+)');
add_rewrite_tag('%item%', '([^&]+)');
add_rewrite_tag('%log-in%', '([^&]+)');
add_rewrite_tag('%metadata%', '([^&]+)');
add_rewrite_tag('%events%', '([^&]+)');
add_rewrite_tag('%configuration%', '([^&]+)');
add_rewrite_tag('%layout%', '([^&]+)');
add_rewrite_tag('%tags%', '([^&]+)');
add_rewrite_tag('%social%', '([^&]+)');
add_rewrite_tag('%licenses%', '([^&]+)');
add_rewrite_tag('%import%', '([^&]+)');
add_rewrite_tag('%export%', '([^&]+)');
add_rewrite_tag('%statistics%', '([^&]+)');
add_rewrite_tag('%email%', '([^&]+)');
add_rewrite_tag('%tools%', '([^&]+)');
add_rewrite_tag('%categories%', '([^&]+)');
add_rewrite_tag('%edit-item%', '([^&]+)');
add_rewrite_tag('%add-item%', '([^&]+)');
add_rewrite_tag('%add%', '([^&]+)');
add_rewrite_tag('%edit%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);
function custom_rewrite_basic() {
$collection = get_post(get_option('collection_root_id'));
$collection_base = ( get_option('collection_base_url_id') ) ? get_option('collection_base_url_id') : 'colecao';
add_rewrite_rule('^feed_collection/([^/]*)', 'index.php?collection_name=$matches[1]', 'top');
add_rewrite_rule('^oai', 'index.php?oaipmh=true', 'top');
add_rewrite_rule('^' . __('advanced-search', 'tainacan'), 'index.php?collection=' . $collection->post_name . '&advancedSearch=true', 'top');
// Paginas de admin da colecao
add_rewrite_rule('^([^/]*)/admin/'. __('metadata', 'tainacan'), 'index.php?collection=$matches[1]&metadata=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('layout', 'tainacan'), 'index.php?collection=$matches[1]&layout=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('events', 'tainacan'), 'index.php?collection=$matches[1]&events=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('configuration', 'tainacan'), 'index.php?collection=$matches[1]&configuration=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('tags', 'tainacan'), 'index.php?collection=$matches[1]&tags=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('social', 'tainacan'), 'index.php?collection=$matches[1]&social=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('licenses', 'tainacan'), 'index.php?collection=$matches[1]&licenses=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('import', 'tainacan'), 'index.php?collection=$matches[1]&import=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('export', 'tainacan'), 'index.php?collection=$matches[1]&export=true', 'top');
add_rewrite_rule('^([^/]*)/admin/'. __('statistics', 'tainacan'), 'index.php?collection=$matches[1]&statistics=true', 'top');
/* Páginas do Repositorio
add_rewrite_rule('^admin/'.__('metadata','tainacan'), 'index.php?collection='.$collection->post_name.'&metadata=true', 'top');
add_rewrite_rule('^admin/'.__('events','tainacan'), 'index.php?collection='.$collection->post_name.'&events=true', 'top');
add_rewrite_rule('^admin/'.__('configuration','tainacan'), 'index.php?collection='.$collection->post_name.'&configuration=true', 'top');
add_rewrite_rule('^admin/'.__('social','tainacan'), 'index.php?collection='.$collection->post_name.'&social=true', 'top');
add_rewrite_rule('^admin/'.__('tools','tainacan'), 'index.php?collection='.$collection->post_name.'&tools=true', 'top');
add_rewrite_rule('^admin/'.__('licenses','tainacan'), 'index.php?collection='.$collection->post_name.'&licenses=true', 'top');
add_rewrite_rule('^admin/'.__('welcome-email','tainacan'), 'index.php?collection='.$collection->post_name.'&email=true', 'top');
add_rewrite_rule('^admin/'.__('import','tainacan'), 'index.php?collection='.$collection->post_name.'&import=true', 'top');
add_rewrite_rule('^admin/'.__('export','tainacan'), 'index.php?collection='.$collection->post_name.'&export=true', 'top');
add_rewrite_rule('^admin/'.__('statistics','tainacan'), 'index.php?collection='.$collection->post_name.'&statistics=true', 'top');
add_rewrite_rule('^admin/'.__('categories','tainacan'), 'index.php?collection='.$collection->post_name.'&categories=true', 'top');
*/
//login
add_rewrite_rule('^log-in', 'index.php?log-in=true', 'top');
add_rewrite_rule('^'.__('signin','tainacan'), 'index.php?log-in=true', 'top');
/* add_rewrite_rule('^([^/]*)/([^/]*)/editar', 'index.php?collection=$matches[1]&item=$matches[2]&edit-item=true', 'top');
add_rewrite_rule('^colecao/([^/]*)/criar-item', 'index.php?collection=$matches[1]&add-item=true', 'top'); flush_rewrite_rules(); */
add_rewrite_rule("^$collection_base/([^/]*)/add", 'index.php?collection=$matches[1]&add=true', 'top');
add_rewrite_rule('^item/([^/]*)/edit', 'index.php?object=$matches[1]&edit=true', 'top');
}
add_action('init', 'custom_rewrite_basic', 10, 0);
/**
* Função responsavel por permitir zip
* * */
add_filter('upload_mimes', 'custom_upload_mimes');
function custom_upload_mimes($existing_mimes = array()) {
// add your extension to the mimes array as below
$existing_mimes['zip'] = 'application/zip';
$existing_mimes['csv'] = 'application/octet-stream';
$existing_mimes['csv2'] = 'application/vnd.ms-excel';
$existing_mimes['gz'] = 'application/x-gzip';
$existing_mimes['xml'] = 'application/xml';
$existing_mimes['xml2'] = 'text/xml';
return $existing_mimes;
}
/**
* Função responsavel pelas respostas dos comentários
* * */
function tainacan_comments($comment, $args, $depth) {
global $global_collection_id;
global $global_term_id;
$object = get_post(get_the_ID());
$is_from = get_comment_meta(get_comment_ID(), 'socialdb_is_comment_from', true);
// se nao pertencer a este termo item/propriedade/tag
if ($is_from != 'object' && $is_from != $global_term_id) {
return false;
}
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
if ('div' == $args['style']) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo $tag ?> <?php comment_class(empty($args['has_children']) ? '' : 'parent' ) ?> id="comment-<?php comment_ID() ?>">
<div class="col-md-12 comment-box-container">
<?php if ('div' != $args['style']) : ?> <div id="div-comment-<?php comment_ID() ?>" class="comment-body"> <?php endif; ?>
<div class="col-md-1 no-padding">
<?php if ($args['avatar_size'] != 0) echo get_avatar($comment, $args['avatar_size']); ?>
</div>
<div class="col-md-11">
<div class="row">
<div class="comment-author vcard" style="font-weight: bolder">
<?php printf(__('<span class="fn">%s</span>', 'tainacan'), get_comment_author_link()); ?>
</div>
<?php if ($comment->comment_approved == '0') : ?>
<em class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.', 'tainacan'); ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata">
<a href="javascript:void(0)"> <?php printf(__('%1$s at %2$s'), get_comment_date(), get_comment_time()); ?> </a>
<?php edit_comment_link(__('(Painel Edit )', 'tainacan'), ' ', ''); ?>
</div>
</div>
<div class="row">
<div id="comment_text_<?php comment_ID(); ?>">
<?php comment_text(); ?>
</div>
<div style="display:none" id="comment_edit_field_<?php comment_ID(); ?>">
<form class="form-inline">
<div class="form-group">
<textarea id="edit_field_value_<?php comment_ID(); ?>" class="form-control" id="exampleInputEmail3">
</textarea>
</div>
<button type="button" onclick="cancelEditComment('<?php comment_ID(); ?>')" class="btn btn-default"><?php _e('Cancel', 'tainacan') ?></button>
<button type="button" onclick="submitEditComment('<?php comment_ID(); ?>')" class="btn btn-default"><?php _e('Save', 'tainacan') ?></button>
</form>
</div>
</div>
<div class="row reply" id="reply_<?php comment_ID(); ?>">
<div class="col-md-12 left">
<div class="col-md-1 no-padding comment-item">
<a onclick="showModalReply('<?php comment_ID(); ?>');"><b><?php _e("Reply", 'tainacan'); ?></b></a>
</div>
<?php
/*Não é o dono da coleção e nem é o autor do comentario*/
$collection_moderator = verify_allowed_action($global_collection_id, 'socialdb_collection_permission_delete_comment');
$comment_autor = (get_userdata(get_current_user_id())->display_name === get_comment_author())? true : false;
$can_delete = verify_allowed_action($global_collection_id, 'socialdb_collection_permission_delete_comment');
$can_edit = verify_allowed_action($global_collection_id, 'socialdb_collection_permission_edit_comment');
if (!$collection_moderator && !$comment_autor ) { ?>
<div class="col-md-1 no-padding comment-item">
<a onclick="showModalReportAbuseComment('<?php comment_ID(); ?>');"><span class="glyphicon glyphicon-bullhorn"></span> <?php _e("Report Abuse", 'tainacan'); ?></a>
</div>
<?php
} else {
if($can_edit || $collection_moderator) {
?>
<div class="col-md-1 no-padding comment-item">
<a onclick="showEditComment('<?php comment_ID(); ?>');"><span class="glyphicon glyphicon-pencil"></span> <?php _e("Edit", 'tainacan'); ?></a>
</div>
<?php
}
if($can_delete || $collection_moderator) { ?>
<div class="col-md-1 no-padding comment-item">
<a onclick="showAlertDeleteComment('<?php comment_ID(); ?>', '<?php _e('Attention!') ?>', '<?php _e('Delete this comment?', 'tainacan') ?>', '<?php echo time(); ?>');">
<span class="glyphicon glyphicon-remove"></span> <?php _e("Delete", 'tainacan'); ?>
</a>
</div>
<?php
}
}
?>
</div>
</div>
</div>
<?php if ('div' != $args['style']) : ?> </div> <?php endif; ?>
</div>
<?php
}
/**
* Logout Redirect
* Automatically redirect to current page after user logout WordPress.
*/
function get_current_logout($logout_url) {
if (!is_admin()) {
$logout_url = add_query_arg('redirect_to', urlencode(( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), $logout_url);
}
return $logout_url;
}
add_filter('logout_url', 'get_current_logout');
//add_filter('login_url', 'get_current_logout');
/* * ************************************************************************************* */
/**
* SocialDB Theme Option Page
*/
function socialdb_theme_menu() {
add_theme_page('SocialDB Option', 'SocialDB Option', 'manage_options', 'socialdb_theme_options.php', 'socialdb_theme_page');
}
add_action('admin_menu', 'socialdb_theme_menu');
/**
* Callback function to the add_theme_page
* Will display the theme options page
*/
function socialdb_theme_page() {
?>
<div class="section panel">
<h1>Custom SocialDB Options</h1>
<form method="post" enctype="multipart/form-data" action="options.php">
<?php
settings_fields('socialdb_theme_options');
do_settings_sections('socialdb_theme_options.php');
?>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes', 'tainacan') ?>" />
</p>
</form>
</div>
<?php
}
/**
* Register the settings to use on the theme options page
*/
add_action('admin_init', 'socialdb_register_settings');
/**
* Function to register the settings
*/
function socialdb_register_settings() {
// Register the settings with Validation callback
register_setting('socialdb_theme_options', 'socialdb_theme_options', 'socialdb_validate_settings');
// Add settings section
add_settings_section('socialdb_fb_section', 'Facebook API Login', 'socialdb_display_section', 'socialdb_theme_options.php');
// Create textbox field
$field_args_fb_id = array(
'type' => 'text',
'id' => 'socialdb_fb_api_id',
'name' => 'socialdb_fb_api_id',
'desc' => 'Facebook API ID',
'std' => '',
'label_for' => 'socialdb_fb_api_id',
'class' => 'css_class'
);
$field_args_fb_secret = array(
'type' => 'text',
'id' => 'socialdb_fb_api_secret',
'name' => 'socialdb_fb_api_secret',
'desc' => 'Facebook API Secret',
'std' => '',
'label_for' => 'socialdb_fb_api_secret',
'class' => 'css_class'
);
add_settings_field('socialdb_fb_api_id', 'API ID', 'socialdb_display_setting', 'socialdb_theme_options.php', 'socialdb_fb_section', $field_args_fb_id);
add_settings_field('socialdb_fb_api_secret', 'API Secret', 'socialdb_display_setting', 'socialdb_theme_options.php', 'socialdb_fb_section', $field_args_fb_secret);
// Add settings section
add_settings_section('socialdb_embed_ly_section', 'Embed Ly API', 'socialdb_display_section_embed', 'socialdb_theme_options.php');
// Create textbox field
$field_args_embed_id = array(
'type' => 'text',
'id' => 'socialdb_embed_api_id',
'name' => 'socialdb_embed_api_id',
'desc' => 'API ID',
'std' => '',
'label_for' => 'socialdb_embed_api_id',
'class' => 'css_class'
);
add_settings_field('socialdb_embed_api_id', 'Embed Ly API ID', 'socialdb_display_setting', 'socialdb_theme_options.php', 'socialdb_embed_ly_section', $field_args_embed_id);
}
/**
* Function to add extra text to display on each section
*/
function socialdb_display_section($section) {
_e('Session responsible for the use of facebook API to login.', 'tainacan');
}
/**
* Function to add extra text to display on each section
*/
function socialdb_display_section_embed($section) {
_e('Session responsible for the use of Embed Ly API. (http://embed.ly/)', 'tainacan');
}
/**
* Function to display the settings on the page
* This is setup to be expandable by using a switch on the type variable.
* In future you can add multiple types to be display from this function,
* Such as checkboxes, select boxes, file upload boxes etc.
*/
function socialdb_display_setting($args) {
extract($args);
$option_name = 'socialdb_theme_options';
$options = get_option($option_name);
switch ($type) {
case 'text':
$options[$id] = stripslashes($options[$id]);
$options[$id] = esc_attr($options[$id]);
echo "<input class='regular-text$class' type='text' id='$id' name='" . $option_name . "[$id]' value='$options[$id]' />";
echo ($desc != '') ? "<br /><span class='description'>$desc</span>" : "";
break;
}
}
/**
* Callback function to the register_settings function will pass through an input variable
* You can then validate the values and the return variable will be the values stored in the database.
*/
function socialdb_validate_settings($input) {
foreach ($input as $k => $v) {
$newinput[$k] = trim($v);
// Check the input is a letter or a number
if (!preg_match('/^[A-Z0-9 _]*$/i', $v)) {
$newinput[$k] = '';
}
}
return $newinput;
}
function add_custom_caps() {
// gets the subscriber role
$role = get_role( 'subscriber' );
// This only works, because it accesses the class instance.
// would allow the subscriber to edit others' posts for current theme only
$role->add_cap( 'read' );;
$role->add_cap( 'read_private_post' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_others_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'delete_others_posts' );
$role->add_cap( 'delete_private_posts' );
$role->add_cap( 'delete_published_posts' );
}
//*****************************************************************************/
//*************** ELASTIC PRESS INTEGRATION ************************/
function elasticpress_improve_fields( $post_args, $post_id ) {
$allow = ['socialdb_object'];
if ( in_array( $post_args['post_type'], $allow ) ) {
//remove o array de busca geral
if(isset($post_args['post_meta']['socialdb_object_commom_values'])){
unset($post_args['post_meta']['socialdb_object_commom_values']);
unset($post_args['post_meta']['socialdb_object_commom_index']);
}
//getCollection
if(is_numeric($post_args['post_parent']) && $post_args['post_parent'] !== 0){
$post_args['collection'] = get_post($post_args['post_parent']);
}else if($post_args['post_parent'] === 0 && isset($post_args['terms']['socialdb_category_type'])){
foreach ($post_args['terms']['socialdb_category_type'] as $term) {
$id = (isset($term->term_id)) ? $term->term_id : $term['term_id'];
$collection = getCollectionByTermRoot($id);
if($collection){
$post_args['collection'] = $collection;
break;
}
}
}
//pego o valor atual dos metas do item
$metas = $post_args['post_meta'];
//iterando sobre os metas existen
foreach ($metas as $meta_key => $values) {
$isHelper = strpos($meta_key,'socialdb_property_helper_');
$isCat = strpos($meta_key,'_cat');
$isNormal = strpos($meta_key,'socialdb_property_');
if($isHelper === false && $isNormal !== false){
$id = str_replace('socialdb_property_','',$meta_key);
if($isCat !== false){
$id = str_replace('_cat','',$id);
}
$term = get_term_by('id',$id,'socialdb_property_type');
if($term){
$term->name = str_replace(' ','_', $term->name);
$parent = get_term_by('id',$term->parent,'socialdb_property_type');
$post_args['post_meta'][$term->name] = [];
foreach ($values as $value) {
if(!isset($value))
continue;
if($parent && $parent->name == 'socialdb_property_data'){
$post_args['post_meta'][$term->name][] = $value;
}else if($parent && $parent->name == 'socialdb_property_object' && is_numeric($value)){
$post_args['post_meta'][$term->name][] = get_post($value)->post_title;
}else if($parent && $parent->name == 'socialdb_property_term' && is_numeric($value)){
$post_args['post_meta'][$term->name][] = get_term_by('id',$value,'socialdb_category_type')->name;
}
}
$post_args['post_meta'][$term->name] = array_values( array_filter($post_args['post_meta'][$term->name]));
}
}
}
}else if($post_args['post_type'] === 'socialdb_collection'){
include_once(dirname(__FILE__) . '/models/property/property_model.php');
$property = new PropertyModel();
$post_args['metadata'] = [];
$category_root_id = $post_args['post_meta']['socialdb_collection_object_type'][0];
$root_properties = get_term_meta(get_term_by('name','socialdb_category','socialdb_category_type')->term_id,'socialdb_category_property_id');
$properties = get_term_meta($category_root_id,'socialdb_category_property_id');
$properties = array_merge($root_properties,$properties);
unset($post_args['post_meta']['properties-cached']);
if($properties){
$ids = [];
foreach ($properties as $property_id) {
$data = $property->get_all_property($property_id, true, $post_args['ID']); // pego todos os dados possiveis da propriedade;
if($data && !in_array($data['id'],$ids)){
$ids[] = $data['id'];
$post_args['metadata'][] = $data;
}
}
}
}
return $post_args;
}
add_filter('ep_post_sync_args', 'elasticpress_improve_fields', 10, 2);
function getCollectionByTermRoot($term_id){
global $wpdb;
$wp_posts = $wpdb->prefix . "posts";
$wp_postmeta = $wpdb->prefix . "postmeta";
$query = "
SELECT p.* FROM $wp_posts p
INNER JOIN $wp_postmeta pm ON p.ID = pm.post_id
WHERE pm.meta_key LIKE 'socialdb_collection_object_type' AND pm.meta_value LIKE '$term_id'
";
$result = $wpdb->get_results($query);
if ($result && is_array($result) && count($result) > 0) {
return $result[0];
}else if($result){
return $result;
}
return false;
}
//reindexo itens afetados pela atualizacao de seu metadado
function reindex_after_update_property($term_id, $taxonomy){
if (function_exists('ep_sync_post')) {
global $wpdb;
$wp_posts = $wpdb->prefix . "posts";
$wp_postmeta = $wpdb->prefix . "postmeta";
$query = "
SELECT p.* FROM $wp_posts p
INNER JOIN $wp_postmeta pm ON p.ID = pm.post_id
WHERE ( pm.meta_key LIKE 'socialdb_property_$term_id' || p.post_type = 'socialdb_collection') AND p.post_status LIKE 'publish'
";
$result = $wpdb->get_results($query);
if ($result && is_array($result) && count($result) > 0) {
foreach ($result as $item) {
ep_sync_post($item->ID);
}
}
}
}
add_action( 'edited_socialdb_property_type', 'reindex_after_update_property', 10, 2 );
//*****************************************************************************/
//**************************************** POST STATUS ************************/
/**
* funcao que cria os post status do tipo texto para rascunho
*/
function betatext_post_status() {
register_post_status('betatext', array(
'label' => __('Beta', 'post'),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop('Beta Text <span class="count">(%s)</span>', 'Beta <span class="count">(%s)</span>'),
));
}
add_action('init', 'betatext_post_status');
/**
* funcao que cria os post status do tipo arquivo para arquivos
*/
function betafile_post_status() {
register_post_status('betafile', array(
'label' => __('Beta File', 'post'),