Gmedia Photo Gallery - Version 1.17.6

Version Description

Download this release

Release Info

Developer pasyuk
Plugin Icon 128x128 Gmedia Photo Gallery
Version 1.17.6
Comparing to
See all releases

Code changes from version 1.16.7 to 1.17.6

admin/admin.php CHANGED
@@ -1,1132 +1,1133 @@
1
- <?php
2
-
3
- /**
4
- * GmediaAdmin - Admin Section for GRAND Media
5
- */
6
- class GmediaAdmin {
7
- var $pages = array();
8
- var $body_classes = array();
9
-
10
- /**
11
- * constructor
12
- */
13
- function __construct() {
14
- global $pagenow;
15
-
16
- add_action( 'admin_head', array( &$this, 'admin_head' ) );
17
-
18
- // Add the admin menu
19
- add_action( 'admin_menu', array( &$this, 'add_menu' ) );
20
-
21
- // Add the script and style files
22
- add_action( 'admin_enqueue_scripts', array( &$this, 'load_scripts' ), 20 );
23
- add_action( 'admin_print_scripts-widgets.php', array( &$this, 'gmedia_widget_scripts' ) );
24
-
25
- add_action( 'enqueue_block_editor_assets', array( &$this, 'gutenberg_assets' ) );
26
-
27
- add_filter( 'screen_settings', array( &$this, 'screen_settings' ), 10, 2 );
28
- add_filter( 'set-screen-option', array( &$this, 'screen_settings_save' ), 11, 3 );
29
-
30
- if ( isset( $_GET['page'] ) && ( false !== strpos( $_GET['page'], 'GrandMedia' ) ) ) {
31
- $this->body_classes[] = 'grand-media-admin-page';
32
-
33
- if ( ! isset( $_GET['gmediablank'] ) || 'library' === $_GET['gmediablank'] ) {
34
- $this->body_classes[] = $_GET['page'];
35
- if ( ! empty( $_GET['mode'] ) ) {
36
- $this->body_classes[] = $_GET['page'] . '_' . $_GET['mode'];
37
- }
38
- if ( isset( $_GET['edit_term'] ) || isset( $_GET['gallery_module'] ) || isset( $_GET['preset'] ) ) {
39
- $this->body_classes[] = $_GET['page'] . '_edit';
40
- }
41
- }
42
-
43
- if ( ( 'admin.php' == $pagenow ) && isset( $_GET['gmediablank'] ) ) {
44
- add_action( 'admin_init', array( &$this, 'gmedia_blank_page' ) );
45
- }
46
-
47
- add_action( 'admin_footer', array( &$this, 'admin_footer' ) );
48
- }
49
-
50
- }
51
-
52
- /**
53
- * admin_head
54
- */
55
- function admin_head() {
56
- add_filter( 'admin_body_class', array( &$this, 'admin_body_class' ) );
57
-
58
- if ( isset( $_GET['page'] ) && ( false !== strpos( $_GET['page'], 'GrandMedia' ) ) ) {
59
- ?>
60
- <style type="text/css" id="gmedia_admin_css">html, body { background: <?php echo isset( $_GET['gmediablank'] )? 'transparent' : '#708090'; ?>; }</style>
61
- <?php
62
- }
63
- }
64
-
65
- /**
66
- * admin_body_class
67
- *
68
- * @param $classes_string
69
- *
70
- * @return string
71
- */
72
- function admin_body_class( $classes_string ) {
73
- $classes = $this->body_classes;
74
-
75
- $classes[] = $classes_string;
76
- if ( isset( $_GET["gmediablank"] ) ) {
77
- $classes[] = "gmedia-blank gmedia_{$_GET['gmediablank']}";
78
- }
79
- $classes = array_filter( $classes );
80
-
81
- return implode( ' ', $classes );
82
- }
83
-
84
- /**
85
- * Load gmedia pages in wpless interface
86
- */
87
- function gmedia_blank_page() {
88
- set_current_screen( 'GrandMedia_Settings' );
89
-
90
- global $gmCore, $gmProcessor;
91
- $gmediablank = $gmCore->_get( 'gmediablank', '' );
92
- define( 'IFRAME_REQUEST', true );
93
-
94
- iframe_header( 'GmediaGallery' );
95
-
96
- echo '<div id="gmedia-container">';
97
- switch ( $gmediablank ) {
98
- case 'update_plugin':
99
- require_once( dirname( dirname( __FILE__ ) ) . '/config/update.php' );
100
- gmedia_do_update();
101
- break;
102
- case 'image_editor':
103
- require_once( dirname( dirname( __FILE__ ) ) . '/inc/image-editor.php' );
104
- gmedia_image_editor();
105
- break;
106
- case 'map_editor':
107
- require_once( dirname( dirname( __FILE__ ) ) . '/inc/map-editor.php' );
108
- gmedia_map_editor();
109
- break;
110
- case 'library':
111
- echo '<div id="gmedia_iframe_content">';
112
- echo '<div id="gm-message">' . $gmCore->alert( 'success', $gmProcessor->msg ) . $gmCore->alert( 'danger', $gmProcessor->error ) . '</div>';
113
- include( GMEDIA_ABSPATH . 'admin/pages/library/library.php' );
114
- echo '</div>';
115
- break;
116
- case 'comments':
117
- require_once( dirname( __FILE__ ) . '/tpl/comments.php' );
118
- break;
119
- case 'module_preview':
120
- require_once( dirname( __FILE__ ) . '/tpl/module-preview.php' );
121
- break;
122
- }
123
- echo '</div>';
124
-
125
- iframe_footer();
126
- exit;
127
- }
128
-
129
- // integrate the menu
130
- function add_menu() {
131
-
132
- $count = '';
133
- if ( current_user_can( 'gmedia_module_manage' ) ) {
134
- global $gmGallery;
135
- if ( $gmGallery->options['modules_update'] ) {
136
- $count .= " <span class='update-plugins count-{$gmGallery->options['modules_update']}' style='background-color: #bb391b;'><span class='plugin-count gm-module-count gm-modules-update-count' title='" . __( 'Modules Updates', 'grand-media' ) . "'>{$gmGallery->options['modules_update']}</span></span>";
137
- }
138
- if ( $gmGallery->options['modules_new'] && !empty( $gmGallery->options['notify_new_modules'] ) ) {
139
- $count .= " <span class='update-plugins count-{$gmGallery->options['modules_new']}' style='background-color: #367236;'><span class='plugin-count gm-module-count gm-modules-new-count' title='" . __( 'New Modules', 'grand-media' ) . "'>{$gmGallery->options['modules_new']}</span></span>";
140
- }
141
- }
142
-
143
- $this->pages = array();
144
- $this->pages[] = add_menu_page( __( 'Gmedia Library', 'grand-media' ), "Gmedia{$count}", 'gmedia_library', 'GrandMedia', array(
145
- &$this,
146
- 'shell',
147
- ), 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIyMHB4IiBoZWlnaHQ9IjIwcHgiIHZpZXdCb3g9IjAgMCAyMCAyMCIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMjAgMjAiIHhtbDpzcGFjZT0icHJlc2VydmUiPiAgPGltYWdlIGlkPSJpbWFnZTAiIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgeD0iMCIgeT0iMCIKICAgIHhsaW5rOmhyZWY9ImRhdGE6aW1hZ2UvcG5nO2Jhc2U2NCxpVkJPUncwS0dnb0FBQUFOU1VoRVVnQUFBQlFBQUFBVUNBTUFBQUM2ViswL0FBQUFCR2RCVFVFQUFMR1BDL3hoQlFBQUFDQmpTRkpOCkFBQjZKZ0FBZ0lRQUFQb0FBQUNBNkFBQWRUQUFBT3BnQUFBNm1BQUFGM0NjdWxFOEFBQUJrbEJNVkVVeFpua3haM2d4WjNoQ2RJTnUKbEtBK2NZQnBrSjJRcmJhb3Y4YTV5OUdadEx5UnJyZG1qcHMzYTN4WmhKS0txYktPckxXcndjaW52c1dWc2JxM3l0Q1hzcnRWZ1k5UwpmNDZndWNGN25hZzdibjVFZFlWeGxxS01xclN3eGN1aHVzS2Z1TUMrejlSMm1xWTZibjZ1dzhyNy9QekYxTm0weU03dDh2UHo5dmVGCnBhL2Y1K3BiaHBSSWVJZCtvS3FOcTdTZHQ3OWhpcGN5YUhuSDF0clMzdUZIZDRiSzJOMzUrL3YzK2ZxOXp0UmFoWk5QZll5Qm9xeUMKbzYwOGIzOUdkb1poaTVoT2ZJdnE3L0dwdjhiLy8vLzIrUG45L2YzQjBkWkFjb0tZczd3emFIbSt6OVZxa1oxWGc1SFQzK0xZNHVaNgpuYWh3bGFGRGRJVFAzT0JLZVloTWU0bnc5UFhoNmV2eDlmYkwyZDFUZ0k1em1LTXphWHJUM3VLWXM3dlAyOS9WNE9PY3RyN2c2T3VVCnNMbE5mSXU0eTlEbzd2QkZkb1YzbTZibTdlODViWDNJMXR1RHBLN1EzT0JZaEpHUHJMWEMwdGVsdmNSSmVZamI1ZWpOMnQ1eWw2S1cKc3JyYjVPZUFvYXhqakpuZTUrbDJtcVhFMDlpSHByQnRrNTl5bDZOOG5xazRiSDNXNGVUVTMrUFIzZUdxd01jY1RNSnpBQUFBQW5SUwpUbE51MlhMaTRXRUFBQUFCWWt0SFJFVDV0SmpCQUFBQUNYQklXWE1BQUFzVEFBQUxFd0VBbXB3WUFBQUFCM1JKVFVVSDRBc0NDRGNJCmw0WXhCZ0FBQVIxSlJFRlVHTk5qWUdCa1FnT01ESmhpSUZFNGs1bUZGY2FFQzdLeGMzQnljZlB3SWd2eWNmRUxDQW9KYzRxSThvdEIKQmNVRkpDU2xtS1JsWklYbDVCVVVsVUNDeWlxcWF1b2FtbHJhT3N4TXVucjZCb1pBUVNOakUxTW1Kak56QzBzQkt5WW1hMTBiUHFDZwpyWWFkdllLRG81T3ppNnVidTRlOHA1QVhVTkJiMGNmWHo5OHVJRkNDS1VneE9NUk9DR2hScUdaWU9MTmRSR1JVZ0FFVGsxU0VYMVEwCkUwTk1ySGRjZklKVVlwSzdiRExRMHBUVXRIUW1ob3pNTEgzVGhPd2MzY3pjUExEelRMU1lHUElMbUR3S2k0cExtRXFUSWQ3Z0tHUmkKWUF1elk3SXJpeXV2cUlTSVNWVlZBeTJxQ2ErdERtU3BxMk1KckZkcXlNbjN5MjRFQ25weEp6UWxOUHZGeHBxMDVBWUh4N2Z5SW9VUwpNc0FleU5paUF3Q3FwalN3RnBqcGxnQUFBQ1YwUlZoMFpHRjBaVHBqY21WaGRHVUFNakF4TmkweE1TMHdNbFF3T0RvMU5Ub3dPQzB3Ck56b3dNSWl4dXBvQUFBQWxkRVZZZEdSaGRHVTZiVzlrYVdaNUFESXdNVFl0TVRFdE1ESlVNRGc2TlRVNk1EZ3RNRGM2TURENTdBSW0KQUFBQUFFbEZUa1N1UW1DQyIgLz4KPC9zdmc+Cg==', 11 );
148
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Library', 'grand-media' ), __( 'Gmedia Library', 'grand-media' ), 'gmedia_library', 'GrandMedia', array( &$this, 'shell' ) );
149
- if ( current_user_can( 'gmedia_library' ) ) {
150
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Add Media Files', 'grand-media' ), __( 'Add/Import Files', 'grand-media' ), 'gmedia_upload', 'GrandMedia_AddMedia', array( &$this, 'shell' ) );
151
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Tags', 'grand-media' ), __( 'Tags', 'grand-media' ), 'gmedia_tag_manage', 'GrandMedia_Tags', array( &$this, 'shell' ) );
152
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Categories', 'grand-media' ), __( 'Categories', 'grand-media' ), 'gmedia_category_manage', 'GrandMedia_Categories', array( &$this, 'shell' ) );
153
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Albums', 'grand-media' ), __( 'Albums', 'grand-media' ), 'gmedia_album_manage', 'GrandMedia_Albums', array( &$this, 'shell' ) );
154
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Galleries', 'grand-media' ), __( 'Galleries', 'grand-media' ), 'gmedia_gallery_manage', 'GrandMedia_Galleries', array( &$this, 'shell' ) );
155
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Modules', 'grand-media' ), __( 'Modules', 'grand-media' ), 'gmedia_gallery_manage', 'GrandMedia_Modules', array( &$this, 'shell' ) );
156
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Settings', 'grand-media' ), __( 'Settings', 'grand-media' ), 'manage_options', 'GrandMedia_Settings', array( &$this, 'shell' ) );
157
- //$this->pages[] = add_submenu_page( 'GrandMedia', __( 'iOS Application', 'grand-media' ), __( 'iOS Application', 'grand-media' ), 'gmedia_settings', 'GrandMedia_App', array( &$this, 'shell' ) );
158
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'WordPress Media Library', 'grand-media' ), __( 'WP Media Library', 'grand-media' ), 'gmedia_import', 'GrandMedia_WordpressLibrary', array( &$this, 'shell' ) );
159
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Logs', 'grand-media' ), __( 'Gmedia Logs', 'grand-media' ), 'manage_options', 'GrandMedia_Logs', array( &$this, 'shell' ) );
160
- $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Support', 'grand-media' ), __( 'Support', 'grand-media' ), 'manage_options', 'GrandMedia_Support', array( &$this, 'shell' ) );
161
- }
162
-
163
- foreach ( $this->pages as $page ) {
164
- add_action( "load-$page", array( &$this, 'screen_help' ) );
165
- }
166
- }
167
-
168
- /**
169
- * Load the script for the defined page and load only this code
170
- * Display shell of plugin
171
- */
172
- function shell() {
173
- global $gmCore, $gmProcessor, $gmGallery;
174
-
175
- $sideLinks = $this->sideLinks();
176
-
177
- // check for upgrade
178
- if ( get_option( 'gmediaDbVersion' ) != GMEDIA_DBVERSION ) {
179
- if ( get_transient( 'gmediaUpgrade' ) || ( isset( $_GET['do_update'] ) && ( 'gmedia' == $_GET['do_update'] ) ) ) {
180
- $sideLinks['grandTitle'] = __( 'Updating GmediaGallery Plugin', 'grand-media' );
181
- $sideLinks['sideLinks'] = '';
182
- $gmProcessor->page = 'GrandMedia_Update';
183
- } else {
184
- return;
185
- }
186
- }
187
-
188
- // global $wpdb;
189
- // $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gmedia_term");
190
- // foreach($query as $item){
191
- // $name = $gmCore->mb_convert_encoding_utf8($item->name);
192
- // $wpdb->update($wpdb->prefix . 'gmedia_term', array('name' => $name), array('term_id' => $item->term_id));
193
- // }
194
- // echo '<pre>' . print_r($query, true) . '</pre>';
195
-
196
- ?>
197
- <div id="gmedia-container" class="gmedia-admin">
198
- <?php
199
- if ( $gmProcessor->page !== 'GrandMedia_App' && ! isset( $gmGallery->options['gmedia_service'] ) && current_user_can( 'manage_options' ) ) {
200
- $this->collect_data_permission();
201
- }
202
- ?>
203
- <div id="gmedia-header" class="clearfix">
204
- <div id="gmedia-logo">Gmedia
205
- <small> by CodEasily.com</small>
206
- </div>
207
- <h2><?php echo $sideLinks['grandTitle']; ?></h2>
208
- <?php
209
- if ( ! is_plugin_active( 'woowbox/woowbox.php' ) && empty( $gmGallery->options['disable_ads'] ) ) {
210
- ?>
211
- <div class="promote-woowbox"><a href="https://bit.ly/woowbox" target="_blank"><img src="<?php echo plugins_url( '/grand-media/admin/assets/img/woowbox-promote.png' ) ?>" alt="Try WoowBox Gallery plugin"/></a></div>
212
- <?php
213
- }
214
- ?>
215
- </div>
216
- <div class="container-fluid">
217
- <div class="row row-fx180-fl">
218
- <div class="col-sm-2 hidden-xs" id="sidebar" role="navigation">
219
- <?php echo $sideLinks['sideLinks']; ?>
220
-
221
- <?php
222
- if ( (int) $gmGallery->options['feedback'] ) {
223
- $installDate = get_option( 'gmediaInstallDate' );
224
- if ( $installDate && ( strtotime( $installDate ) < strtotime( '2 weeks ago' ) ) ) { ?>
225
- <div class="row panel panel-default visible-lg-block">
226
- <div class="panel-heading" data-toggle="collapse" data-target="#support_div_collapse" aria-expanded="true" aria-controls="support_div_collapse" style="cursor:pointer;">
227
- <b><?php _e( 'Any feedback?', 'grand-media' ); ?></b>
228
- </div>
229
- <div class="collapse<?php if ( empty( $gmGallery->options['license_key'] ) ) {
230
- echo ' in';
231
- } ?>" id="support_div_collapse">
232
- <div class="panel-body">
233
- <p><?php _e( 'You can help me spread the word about GmediaGallery among the users striving to get awesome galleries on their WordPress sites.', 'grand-media' ); ?></p>
234
-
235
- <p>
236
- <a class="btn btn-primary" href="https://wordpress.org/support/view/plugin-reviews/grand-media?filter=5" target="_blank"><?php _e( 'Rate Gmedia Gallery', 'grand-media' ); ?></a>
237
- </p>
238
-
239
- <p><?php _e( 'Your reviews and ideas helps me to create new awesome modules and to improve plugin.', 'grand-media' ); ?></p>
240
- </div>
241
- </div>
242
- </div>
243
- <?php }
244
- }
245
- if ( (int) $gmGallery->options['twitter'] ) {
246
- ?>
247
- <div class="row panel visible-lg-block">
248
- <a class="twitter-timeline" data-height="600" href="https://twitter.com/CodEasily/timelines/648240437141086212?ref_src=twsrc%5Etfw">#GmediaGallery - Curated tweets by CodEasily</a>
249
- <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
250
- </div>
251
- <?php
252
- } ?>
253
- </div>
254
- <div class="col-sm-10 col-xs-12">
255
- <div id="gm-message"><?php
256
- echo $gmCore->alert( 'success', $gmProcessor->msg );
257
- echo $gmCore->alert( 'danger', $gmProcessor->error );
258
- ?></div>
259
-
260
- <?php $this->controller(); ?>
261
-
262
- </div>
263
- </div>
264
- </div>
265
- </div>
266
- <?php
267
- }
268
-
269
- function sideLinks() {
270
- global $submenu, $gmProcessor, $gmGallery;
271
- $content['sideLinks'] = '
272
- <div id="gmedia-navbar">
273
- <div class="row">
274
- <ul class="list-group"><li>';
275
- if ( empty( $gmGallery->options['license_key'] ) ) {
276
- $content['sideLinks'] .= "\n" . '<a class="list-group-item list-group-item-premium" target="_blank" href="https://codeasily.com/product/one-site-license/">' . __( 'Get Gmedia Premium', 'grand-media' ) . '</a></li><li>';
277
- }
278
- foreach ( $submenu['GrandMedia'] as $menuKey => $menuItem ) {
279
- if ( $menuItem[2] == $gmProcessor->page ) {
280
- $iscur = ' active';
281
- $content['grandTitle'] = $menuItem[3];
282
- } else {
283
- $iscur = '';
284
- }
285
- $menuData = '';
286
- if ( $menuItem[2] == 'GrandMedia_Modules' && gm_user_can( 'module_manage' ) ) {
287
- if ( !empty( $gmGallery->options['notify_new_modules'] ) ) {
288
- $menuData .= '<span class="badge badge-success pull-right gm-module-count-' . $gmGallery->options['modules_new'] . '" title="' . __( 'New Modules', 'grand-media' ) . '">' . $gmGallery->options['modules_new'] . '</span>';
289
- }
290
- $menuData .= '<span class="badge badge-error pull-right gm-module-count-' . $gmGallery->options['modules_update'] . '" title="' . __( 'Modules Updates', 'grand-media' ) . '">' . $gmGallery->options['modules_update'] . '</span>';
291
- }
292
-
293
- $content['sideLinks'] .= "\n" . '<a class="list-group-item' . $iscur . '" href="' . admin_url( 'admin.php?page=' . $menuItem[2] ) . '">' . $menuItem[0] . $menuData . '</a>';
294
- }
295
- $content['sideLinks'] .= '
296
- </li></ul>
297
- </div>
298
- </div>';
299
-
300
- return $content;
301
- }
302
-
303
- function collect_data_permission() {
304
- $current_user = wp_get_current_user();
305
- $nonce = wp_create_nonce( 'GmediaService' );
306
- ?>
307
- <div class="notice updated gm-message gmedia-service__message">
308
- <div class="gm-message-content">
309
- <div class="gm-plugin-icon">
310
- <img src="<?php echo plugins_url( '/grand-media/admin/assets/img/icon-128x128.png' ) ?>" width="90" height="90">
311
- </div>
312
- <?php printf( __( '<p>Hey %s,<br>Please help us improve <b>Gmedia Gallery</b>! If you opt-in, some data about your usage of <b>Gmedia Gallery</b> will be sent to <a href="https://codeasily.com/" target="_blank" tabindex="1">codeasily.com</a>.
313
- If you skip this, that\'s okay! <b>Gmedia Gallery</b> will still work just fine.</p>', 'grand-media' ), $current_user->display_name ); ?>
314
- </div>
315
- <div class="gm-message-actions">
316
- <button class="button button-secondary gm_service_action" data-action="skip" data-nonce="<?php echo $nonce; ?>"><?php _e( 'Skip', 'grand-media' ); ?></button>
317
- <button class="button button-primary gm_service_action" data-action="allow" data-nonce="<?php echo $nonce; ?>"><?php _e( 'Allow &amp; Continue', 'grand-media' ); ?></button>
318
- </div>
319
- <div class="gm-message-plus gm-closed">
320
- <a class="gm-mp-trigger" href="#" onclick="jQuery('.gm-message-plus').toggleClass('gm-closed gm-opened'); return false;"><?php _e( 'What permissions are being granted?', 'grand-media' ); ?></a>
321
- <ul>
322
- <li>
323
- <i class="dashicons dashicons-admin-users"></i>
324
-
325
- <div>
326
- <span><?php _e( 'Your Profile Overview', 'grand-media' ); ?></span>
327
-
328
- <p><?php _e( 'Name and email address', 'grand-media' ); ?></p>
329
- </div>
330
- </li>
331
- <li>
332
- <i class="dashicons dashicons-admin-settings"></i>
333
-
334
- <div>
335
- <span><?php _e( 'Your Site Overview', 'grand-media' ); ?></span>
336
-
337
- <p><?php _e( 'Site URL, WP version, PHP version, active theme &amp; plugins', 'grand-media' ); ?></p>
338
- </div>
339
- </li>
340
- </ul>
341
- </div>
342
- </div>
343
- <?php
344
- }
345
-
346
- function admin_footer() {
347
- $ajax_operations = get_option( 'gmedia_ajax_long_operations' );
348
- if ( empty( $ajax_operations ) || ! is_array( $ajax_operations ) ) {
349
- return;
350
- }
351
- reset( $ajax_operations );
352
- $ajax = key( $ajax_operations );
353
- if ( empty( $ajax ) ) {
354
- delete_option( 'gmedia_ajax_long_operations' );
355
-
356
- return;
357
- }
358
- $nonce = wp_create_nonce( 'gmedia_ajax_long_operations' );
359
- ?>
360
- <script type="text/javascript">
361
- jQuery(document).ready(function($) {
362
- var header = $('#gmedia-header');
363
- header.append('<div id="ajax-long-operation"><div class="progress"><div class="progress-bar progress-bar-info" style="width: 0%;"></div><div class="progress-bar-indicator">0%</div></div></div>');
364
- gmAjaxLongOperation = function() {
365
- jQuery.post(ajaxurl, {action: '<?php echo $ajax; ?>', _wpnonce_ajax_long_operations: '<?php echo $nonce; ?>'}, function(r) {
366
- if(r.data) {
367
- jQuery('.progress-bar-info', header).width(r.data.progress);
368
- var indicator = r.data.info ? r.data.info + ' ' + r.data.progress : r.data.progress;
369
- jQuery('.progress-bar-indicator', header).html(indicator);
370
-
371
- if(r.data.done) {
372
- return;
373
- }
374
- }
375
- gmAjaxLongOperation();
376
- });
377
- };
378
- gmAjaxLongOperation();
379
- });
380
- </script>
381
- <?php
382
- }
383
-
384
- function controller() {
385
-
386
- global $gmProcessor;
387
- switch ( $gmProcessor->page ) {
388
- case 'GrandMedia_AddMedia':
389
- include_once( dirname( __FILE__ ) . '/pages/addmedia/addmedia.php' );
390
- break;
391
- case 'GrandMedia_Albums':
392
- if ( isset( $_GET['edit_term'] ) ) {
393
- include_once( dirname( __FILE__ ) . '/pages/terms/edit-term.php' );
394
- } else {
395
- include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
396
- }
397
- break;
398
- case 'GrandMedia_Categories':
399
- if ( isset( $_GET['edit_term'] ) ) {
400
- include_once( dirname( __FILE__ ) . '/pages/terms/edit-term.php' );
401
- } else {
402
- include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
403
- }
404
- break;
405
- case 'GrandMedia_Tags':
406
- include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
407
- break;
408
- case 'GrandMedia_Galleries':
409
- if ( isset( $_GET['gallery_module'] ) || isset( $_GET['edit_term'] ) ) {
410
- include_once( dirname( __FILE__ ) . '/pages/galleries/edit-gallery.php' );
411
- } else {
412
- include_once( dirname( __FILE__ ) . '/pages/galleries/galleries.php' );
413
- }
414
- break;
415
- case 'GrandMedia_Modules':
416
- if ( isset( $_GET['preset_module'] ) || isset( $_GET['preset'] ) ) {
417
- include_once( dirname( __FILE__ ) . '/pages/modules/edit-preset.php' );
418
- } else {
419
- include_once( dirname( __FILE__ ) . '/pages/modules/modules.php' );
420
- }
421
- break;
422
- case 'GrandMedia_Settings':
423
- include_once( dirname( __FILE__ ) . '/pages/settings/settings.php' );
424
- break;
425
- case 'GrandMedia_App':
426
- include_once( dirname( __FILE__ ) . '/app.php' );
427
- gmediaApp();
428
- break;
429
- case 'GrandMedia_WordpressLibrary':
430
- include_once( dirname( __FILE__ ) . '/wpmedia.php' );
431
- grandWPMedia();
432
- break;
433
- case 'GrandMedia_Logs':
434
- include_once( dirname( __FILE__ ) . '/logs.php' );
435
- break;
436
- case 'GrandMedia_Support':
437
- include_once( dirname( __FILE__ ) . '/support.php' );
438
- gmediaSupport();
439
- break;
440
- case 'GrandMedia_Update':
441
- include_once( GMEDIA_ABSPATH . 'config/update.php' );
442
- gmedia_upgrade_progress_panel();
443
- break;
444
- case 'GrandMedia':
445
- include_once( dirname( __FILE__ ) . '/pages/library/library.php' );
446
- break;
447
- default:
448
- do_action( 'gmedia_admin_page-' . $gmProcessor->page );
449
- break;
450
- }
451
- }
452
-
453
- /**
454
- * @param $hook
455
- */
456
- function load_scripts( $hook ) {
457
- global $gmCore, $gmProcessor, $gmGallery;
458
- // no need to go on if it's not a plugin page
459
- if ( 'admin.php' != $hook && strpos( $gmCore->_get( 'page' ), 'GrandMedia' ) === false ) {
460
- return;
461
- }
462
-
463
- if ( $gmGallery->options['isolation_mode'] ) {
464
- global $wp_scripts, $wp_styles;
465
- foreach ( $wp_scripts->registered as $handle => $wp_script ) {
466
- if ( ( ( false !== strpos( $wp_script->src, '/plugins/' ) ) || ( false !== strpos( $wp_script->src, '/themes/' ) ) ) && ( false === strpos( $wp_script->src, GMEDIA_FOLDER ) ) ) {
467
- if ( in_array( $handle, $wp_scripts->queue ) ) {
468
- wp_dequeue_script( $handle );
469
- }
470
- wp_deregister_script( $handle );
471
- }
472
- }
473
- foreach ( $wp_styles->registered as $handle => $wp_style ) {
474
- if ( ( ( false !== strpos( $wp_style->src, '/plugins/' ) ) || ( false !== strpos( $wp_style->src, '/themes/' ) ) ) && ( false === strpos( $wp_style->src, GMEDIA_FOLDER ) ) ) {
475
- if ( in_array( $handle, $wp_styles->queue ) ) {
476
- wp_dequeue_style( $handle );
477
- }
478
- wp_deregister_style( $handle );
479
- }
480
- }
481
- }
482
-
483
- wp_enqueue_style( 'gmedia-bootstrap' );
484
- wp_enqueue_script( 'gmedia-bootstrap' );
485
-
486
- wp_register_script( 'selectize', $gmCore->gmedia_url . '/assets/selectize/selectize.min.js', array( 'jquery' ), '0.12.1' );
487
- wp_register_style( 'selectize', $gmCore->gmedia_url . '/assets/selectize/selectize.bootstrap3.css', array( 'gmedia-bootstrap' ), '0.12.1', 'screen' );
488
-
489
- wp_register_style( 'spectrum', $gmCore->gmedia_url . '/assets/spectrum/spectrum.min.css', array(), '1.8.0' );
490
- wp_register_script( 'spectrum', $gmCore->gmedia_url . '/assets/spectrum/spectrum.min.js', array( 'jquery' ), '1.8.0', true );
491
-
492
- if ( isset( $_GET['page'] ) ) {
493
- switch ( $_GET['page'] ) {
494
- case "GrandMedia" :
495
- if ( $gmCore->caps['gmedia_edit_media'] ) {
496
- if ( $gmCore->_get( 'gmediablank' ) == 'image_editor' ) {
497
- wp_enqueue_script( 'camanjs', $gmCore->gmedia_url . '/assets/image-editor/camanjs/caman.full.min.js', array(), '4.1.2' );
498
-
499
- wp_enqueue_style( 'nouislider', $gmCore->gmedia_url . '/assets/image-editor/js/jquery.nouislider.css', array( 'gmedia-bootstrap' ), '6.1.0' );
500
- wp_enqueue_script( 'nouislider', $gmCore->gmedia_url . '/assets/image-editor/js/jquery.nouislider.min.js', array( 'jquery' ), '6.1.0' );
501
-
502
- wp_enqueue_style( 'gmedia-image-editor', $gmCore->gmedia_url . '/assets/image-editor/style.css', array( 'gmedia-bootstrap' ), '0.9.16', 'screen' );
503
- wp_enqueue_script( 'gmedia-image-editor', $gmCore->gmedia_url . '/assets/image-editor/image-editor.js', array( 'jquery', 'camanjs' ), '0.9.16' );
504
- break;
505
- }
506
- if ( $gmProcessor->mode == 'edit' ) {
507
- wp_enqueue_script( 'alphanum', $gmCore->gmedia_url . '/assets/jq-plugins/jquery.alphanum.js', array( 'jquery' ), '1.0.16' );
508
-
509
- wp_enqueue_script( 'jquery-ui-sortable' );
510
-
511
- wp_enqueue_script( 'moment', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/moment.min.js', array( 'jquery' ), '2.22.2' );
512
- wp_enqueue_style( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css', array( 'gmedia-bootstrap' ), '4.17.47' );
513
- wp_enqueue_script( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js', array(
514
- 'jquery',
515
- 'moment',
516
- 'gmedia-bootstrap',
517
- ), '4.17.47' );
518
- }
519
- }
520
- wp_enqueue_script( 'wavesurfer', $gmCore->gmedia_url . '/assets/wavesurfer/wavesurfer.min.js', array( 'jquery' ), '1.1.5' );
521
- break;
522
- case "GrandMedia_WordpressLibrary" :
523
- break;
524
- case "GrandMedia_Albums" :
525
- if ( isset( $_GET['edit_term'] ) ) {
526
- if ( $gmCore->caps['gmedia_album_manage'] ) {
527
- wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
528
- wp_enqueue_script( 'jquery-ui-full', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js', array(), '1.10.2' );
529
- }
530
-
531
- wp_enqueue_script( 'moment', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/moment.min.js', array( 'jquery' ), '2.5.1' );
532
- wp_enqueue_style( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css', array( 'gmedia-bootstrap' ), '2.1.32' );
533
- wp_enqueue_script( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js', array(
534
- 'jquery',
535
- 'moment',
536
- 'gmedia-bootstrap',
537
- ), '2.1.32' );
538
- }
539
- break;
540
- case "GrandMedia_Categories" :
541
- break;
542
- case "GrandMedia_AddMedia" :
543
- if ( $gmCore->caps['gmedia_upload'] ) {
544
- $tab = $gmCore->_get( 'tab', 'upload' );
545
- if ( $tab == 'upload' ) {
546
- wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
547
- wp_enqueue_script( 'jquery-ui-full', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js', array(), '1.10.2' );
548
-
549
- wp_enqueue_script( 'gmedia-plupload', $gmCore->gmedia_url . '/assets/plupload/plupload.full.min.js', array( 'jquery', 'jquery-ui-full' ), '2.1.2' );
550
-
551
- wp_enqueue_style( 'jquery.ui.plupload', $gmCore->gmedia_url . '/assets/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css', array( 'jquery-ui-smoothness' ), '2.1.2', 'screen' );
552
- wp_enqueue_script( 'jquery.ui.plupload', $gmCore->gmedia_url . '/assets/plupload/jquery.ui.plupload/jquery.ui.plupload.min.js', array(
553
- 'gmedia-plupload',
554
- 'jquery-ui-full',
555
- ), '2.1.2' );
556
-
557
- }
558
- }
559
- break;
560
- case "GrandMedia_Settings" :
561
- case "GrandMedia_App" :
562
- // under construction
563
- break;
564
- case "GrandMedia_Galleries" :
565
- if ( $gmCore->caps['gmedia_gallery_manage'] && ( isset( $_GET['gallery_module'] ) || isset( $_GET['edit_term'] ) ) ) {
566
-
567
- wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
568
- wp_enqueue_script( 'jquery-ui-resizable' );
569
-
570
- wp_enqueue_script( 'jquery-ui-sortable' );
571
-
572
- wp_enqueue_style( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.css', array( 'gmedia-bootstrap' ), '0.9.13' );
573
- wp_enqueue_script( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.js', array( 'jquery' ), '0.9.13' );
574
-
575
- wp_enqueue_style( 'spectrum' );
576
- wp_enqueue_script( 'spectrum' );
577
- }
578
- break;
579
- case "GrandMedia_Modules" :
580
- if ( isset( $_GET['preset_module'] ) || isset( $_GET['preset'] ) ) {
581
-
582
- wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
583
- wp_enqueue_script( 'jquery-ui-resizable' );
584
-
585
- wp_enqueue_script( 'jquery-ui-sortable' );
586
-
587
- wp_enqueue_style( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.css', array( 'gmedia-bootstrap' ), '0.9.13' );
588
- wp_enqueue_script( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.js', array( 'jquery' ), '0.9.13' );
589
-
590
- wp_enqueue_style( 'spectrum' );
591
- wp_enqueue_script( 'spectrum' );
592
- }
593
- break;
594
- }
595
- }
596
- wp_enqueue_style( 'selectize' );
597
- wp_enqueue_script( 'selectize' );
598
-
599
- wp_enqueue_style( 'grand-media' );
600
- wp_enqueue_script( 'grand-media' );
601
-
602
- }
603
-
604
- function gmedia_widget_scripts() {
605
-
606
- }
607
-
608
- /**
609
- * Enqueue the block's assets for the gutenberg editor.
610
- */
611
- function gutenberg_assets() {
612
- global $gmGallery, $gmDB, $gmCore;
613
-
614
- wp_enqueue_style( 'gmedia-block-editor', $gmCore->gmedia_url . '/admin/assets/css/gmedia-block.css', array(), $gmGallery->version );
615
- wp_register_script(
616
- 'gmedia-block-editor',
617
- $gmCore->gmedia_url . '/admin/assets/js/gmedia-block.js',
618
- array( 'wp-blocks', 'wp-element' ),
619
- $gmGallery->version
620
- );
621
-
622
- $default_module = $gmGallery->options['default_gmedia_module'];
623
- $default_preset = $gmCore->getModulePreset( $default_module );
624
- $default_module = $default_preset['module'];
625
-
626
- $modules_data = get_gmedia_modules( false );
627
- $modules = array();
628
- $modules_options = array();
629
- if ( ! empty( $modules_data['in'] ) ) {
630
- foreach ( $modules_data['in'] as $module_name => $module_data ) {
631
-
632
- $presets = $gmDB->get_terms( 'gmedia_module', array( 'status' => $module_name ) );
633
- $option = array();
634
- $option[ $module_name ] = $module_data['title'] . ' - ' . __( 'Default Settings' );
635
- foreach ( $presets as $preset ) {
636
- if ( ! (int) $preset->global && '[' . $module_name . ']' === $preset->name ) {
637
- continue;
638
- }
639
- $by_author = '';
640
- if ( (int) $preset->global ) {
641
- $display_name = get_the_author_meta( 'display_name', $preset->global );
642
- $by_author = $display_name ? ' [' . $display_name . ']' : '';
643
- }
644
- if ( '[' . $module_name . ']' === $preset->name ) {
645
- $option[ $preset->term_id ] = $module_data['title'] . $by_author . ' - ' . __( 'Default Settings' );
646
- } else {
647
- $preset_name = str_replace( '[' . $module_name . '] ', '', $preset->name );
648
- $option[ $preset->term_id ] = $module_data['title'] . $by_author . ' - ' . $preset_name;
649
- }
650
- }
651
- $modules_options[ $module_name ] = array( 'title' => $module_data['title'], 'options' => $option );
652
-
653
- $modules[ $module_name ] = array(
654
- 'name' => $module_data['title'],
655
- 'screenshot' => $module_data['module_url'] . '/screenshot.png',
656
- );
657
- }
658
- }
659
-
660
- $gm_galleries = array();
661
- $gm_albums = array();
662
- $gm_categories = array();
663
- $gm_tags = array();
664
-
665
- $gm_terms = $gmDB->get_terms( 'gmedia_gallery' );
666
- if ( count( $gm_terms ) ) {
667
- foreach ( $gm_terms as $_term ) {
668
- unset( $_term->description );
669
- unset( $_term->taxonomy );
670
- $_term->module_name = $gmDB->get_metadata( 'gmedia_term', $_term->term_id, '_module', true );
671
- if ( $_term->global ) {
672
- $display_name = sprintf( __( 'by %s', 'grand-media' ), get_the_author_meta( 'display_name', $_term->global ) );
673
- $_term->name .= 'by ' === $display_name ? '' : ' ' . $display_name;
674
- }
675
- if ( $_term->status && 'publish' !== $_term->status ) {
676
- $_term->name .= " [{$_term->status}]";
677
- }
678
- $gm_galleries[ $_term->term_id ] = $_term;
679
- }
680
- }
681
- $gm_galleries = array(
682
- 0 => array(
683
- 'term_id' => 0,
684
- 'name' => __( ' - select gallery - ', 'grand-media' ),
685
- ),
686
- ) + $gm_galleries;
687
-
688
- $gm_terms = $gmDB->get_terms( 'gmedia_album' );
689
- if ( count( $gm_terms ) ) {
690
- foreach ( $gm_terms as $_term ) {
691
- unset( $_term->description );
692
- unset( $_term->taxonomy );
693
- $module_preset = $gmDB->get_metadata( 'gmedia_term', $_term->term_id, '_module_preset', true );
694
- if ( $module_preset ) {
695
- $preset = $gmCore->getModulePreset( $module_preset );
696
- $_term->module_name = $preset['module'];
697
- } else {
698
- $_term->module_name = '';
699
- }
700
- if ( $_term->global ) {
701
- $display_name = sprintf( __( 'by %s', 'grand-media' ), get_the_author_meta( 'display_name', $_term->global ) );
702
- $_term->name .= 'by ' === $display_name ? '' : ' ' . $display_name;
703
- }
704
- if ( $_term->status && 'publish' !== $_term->status ) {
705
- $_term->name .= " [{$_term->status}]";
706
- }
707
- $_term->name .= " ({$_term->count})";
708
- $gm_albums[ $_term->term_id ] = $_term;
709
- }
710
- }
711
- $gm_albums = array(
712
- 0 => array(
713
- 'term_id' => 0,
714
- 'name' => __( ' - select album - ', 'grand-media' ),
715
- ),
716
- ) + $gm_albums;
717
-
718
- $gm_terms = $gmDB->get_terms( 'gmedia_category' );
719
- if ( count( $gm_terms ) ) {
720
- foreach ( $gm_terms as $_term ) {
721
- unset( $_term->description );
722
- unset( $_term->taxonomy );
723
- unset( $_term->global );
724
- unset( $_term->status );
725
- $_term->name .= " ({$_term->count})";
726
- $gm_categories[ $_term->term_id ] = $_term;
727
- }
728
- }
729
- $gm_categories = array(
730
- 0 => array(
731
- 'term_id' => 0,
732
- 'name' => __( ' - select category - ', 'grand-media' ),
733
- ),
734
- ) + $gm_categories;
735
-
736
- $gm_terms = $gmDB->get_terms( 'gmedia_tag' );
737
- if ( count( $gm_terms ) ) {
738
- foreach ( $gm_terms as $_term ) {
739
- unset( $_term->description );
740
- unset( $_term->taxonomy );
741
- unset( $_term->global );
742
- unset( $_term->status );
743
- $_term->name .= " ({$_term->count})";
744
- $gm_tags[ $_term->term_id ] = $_term;
745
- }
746
- }
747
- $gm_tags = array(
748
- 0 => array(
749
- 'term_id' => 0,
750
- 'name' => __( ' - select tag - ', 'grand-media' ),
751
- ),
752
- ) + $gm_tags;
753
-
754
- $data = array(
755
- 'modules' => $modules,
756
- 'default_module' => $default_module,
757
- 'modules_options' => $modules_options,
758
- 'gmedia_image' => $gmCore->gmedia_url . '/admin/assets/img/gmedia-icon-320x240.png',
759
- 'galleries' => $gm_galleries,
760
- 'albums' => $gm_albums,
761
- 'categories' => $gm_categories,
762
- 'tags' => $gm_tags,
763
- );
764
-
765
- wp_localize_script( 'gmedia-block-editor', 'gmedia_data', $data );
766
- wp_enqueue_script( 'gmedia-block-editor' );
767
- }
768
-
769
- function screen_help() {
770
- $screen = get_current_screen();
771
- $screen_id = explode( 'page_', $screen->id, 2 );
772
- $screen_id = $screen_id[1];
773
-
774
- $screen->add_help_tab( array(
775
- 'id' => 'help_' . $screen_id . '_support',
776
- 'title' => __( 'Support' ),
777
- 'content' => __( '<h4>First steps</h4>
778
- <p>If you have any problems with displaying Gmedia Gallery in admin or on website. Before posting to the Forum try next:</p>
779
- <ul>
780
- <li>Exclude plugin conflicts: Disable other plugins one by one and check if it resolve problem</li>
781
- <li>Exclude theme conflict: Temporary switch to one of default themes and check if gallery works</li>
782
- </ul>
783
- <h4>Links</h4>', 'grand-media' )
784
- . '<p><a href="https://codeasily.com/community/forum/gmedia-gallery-wordpress-plugin/" target="_blank">' . __( 'Support Forum', 'grand-media' ) . '</a>
785
- | <a href="https://codeasily.com/contact/" target="_blank">' . __( 'Contact', 'grand-media' ) . '</a>
786
- | <a href="https://codeasily.com/portfolio/gmedia-gallery-modules/" target="_blank">' . __( 'Demo', 'grand-media' ) . '</a>
787
- | <a href="https://codeasily.com/product/one-site-license/" target="_blank">' . __( 'Premium', 'grand-media' ) . '</a>
788
- </p>',
789
- ) );
790
-
791
- switch ( $screen_id ) {
792
- case 'GrandMedia' :
793
- break;
794
- case 'GrandMedia_Settings' :
795
- if ( current_user_can( 'manage_options' ) ) {
796
- $screen->add_help_tab( array(
797
- 'id' => 'help_' . $screen_id . '_license',
798
- 'title' => __( 'License Key' ),
799
- 'content' => sprintf( __( '<h4>Should I buy it, to use plugin?</h4>
800
- <p>No, plugin is absolutely free and all modules for it are free to install.</p>
801
- <p>Even premium modules are fully functional and free to test, but have backlink labels. To remove baclink labels from premium modules you need license key.</p>
802
- <p>Note: License Key will remove backlinks from all current and future premium modules, so you can use all available modules on one website.</p>
803
- <p>Do not purchase license key before testing module you like. Only if everything works fine and you satisfied with functionality you are good to purchase license. Otherwise use <a href="%1$s" target="_blank">Gmedia Support Forum</a>.</p>
804
- <h4>I have license key but I can\'t activate it</h4>
805
- <p>Contact developer <a href="mailto:%2$s">%2$s</a> with your problem and wait for additional instructions and code for manual activation</p>', 'grand-media' ), 'https://codeasily.com/community/forum/gmedia-gallery-wordpress-plugin/', 'gmediafolder@gmail.com' )
806
- . '<div><a class="btn btn-default" href="' . admin_url( 'admin.php?page=' . $screen_id . '&license_activate=manual' ) . '">' . __( 'Manual Activation', 'grand-media' ) . '</a></div>',
807
- ) );
808
- }
809
- break;
810
- case 'GrandMedia_App' :
811
- $gm_options = get_option( 'gmediaOptions' );
812
- $nonce = wp_create_nonce( 'GmediaService' );
813
- if ( current_user_can( 'manage_options' ) && (int) $gm_options['mobile_app'] ) {
814
- $screen->add_help_tab( array(
815
- 'id' => 'help_' . $screen_id . '_optout',
816
- 'title' => __( 'Opt Out' ),
817
- 'content' => __( '<h4>We appreciate your help in making the plugin better by letting us track some usage data.</h4>
818
- <p>Usage tracking is done in the name of making <strong>Gmedia Gallery</strong> better. Making a better user experience, prioritizing new features, and more good things.</p>
819
- <p>By clicking "Opt Out", we will no longer be sending any data from <strong>Gmedia Gallery</strong> to <a href="https://codeasily.com" target="_blank">codeasily.com</a>.</p>
820
- <p>You\'ll also not be able to use Gmedia iOS application.</p>', 'grand-media' )
821
- . '<p><button class="button button-default gm_service_action" data-action="app_deactivate" data-nonce="' . $nonce . '">' . __( 'Opt Out', 'grand-media' ) . '</button><span class="spinner" style="float: none;"></span></p>'
822
- . '<div style="display:none;">Test:
823
- <button type="button" data-action="app_updateinfo" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Update</button>
824
- <button type="button" data-action="app_updatecron" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">CronJob</button> &nbsp;&nbsp;
825
- <button type="button" data-action="app_deactivateplugin" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Deactivate Plugin</button>
826
- <button type="button" data-action="app_uninstallplugin" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Uninstall Plugin</button>
827
- </div>
828
- ',
829
- ) );
830
- }
831
- break;
832
- }
833
- }
834
-
835
- /**
836
- * @param $current
837
- * @param $screen
838
- *
839
- * @return string
840
- */
841
- function screen_settings( $current, $screen ) {
842
- global $gmProcessor, $gmCore;
843
- if ( in_array( $screen->id, $this->pages ) ) {
844
-
845
- $gm_screen_options = $gmProcessor->user_options;
846
-
847
- $title = '<h5><strong>' . __( 'Settings', 'grand-media' ) . '</strong></h5>';
848
- $wp_screen_options = '<input type="hidden" name="wp_screen_options[option]" value="gm_screen_options" /><input type="hidden" name="wp_screen_options[value]" value="' . $screen->id . '" />';
849
- $button = get_submit_button( __( 'Apply', 'grand-media' ), 'button', 'screen-options-apply', false );
850
-
851
- $settings = false;
852
-
853
- $screen_id = explode( 'page_', $screen->id, 2 );
854
-
855
- switch ( $screen_id[1] ) {
856
- case 'GrandMedia' :
857
- $settings = '
858
- <div class="form-inline pull-left">
859
- <div class="form-group">
860
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
861
- </div>
862
- <div class="form-group">
863
- <select name="gm_screen_options[orderby_gmedia]" class="form-control input-sm">
864
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'ID', false ) . ' value="ID">' . __( 'ID', 'grand-media' ) . '</option>
865
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'title', false ) . ' value="title">' . __( 'Title', 'grand-media' ) . '</option>
866
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'gmuid', false ) . ' value="gmuid">' . __( 'Filename', 'grand-media' ) . '</option>
867
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'mime_type', false ) . ' value="mime_type">' . __( 'MIME Type', 'grand-media' ) . '</option>
868
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'author', false ) . ' value="author">' . __( 'Author', 'grand-media' ) . '</option>
869
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'date', false ) . ' value="date">' . __( 'Date', 'grand-media' ) . '</option>
870
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'modified', false ) . ' value="modified">' . __( 'Last Modified', 'grand-media' ) . '</option>
871
- <option' . selected( $gm_screen_options['orderby_gmedia'], '_created_timestamp', false ) . ' value="_created_timestamp">' . __( 'Created Timestamp', 'grand-media' ) . '</option>
872
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'comment_count', false ) . ' value="comment_count">' . __( 'Comment Count', 'grand-media' ) . '</option>
873
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'views', false ) . ' value="views">' . __( 'Views Count', 'grand-media' ) . '</option>
874
- <option' . selected( $gm_screen_options['orderby_gmedia'], 'likes', false ) . ' value="likes">' . __( 'Likes Count', 'grand-media' ) . '</option>
875
- <option' . selected( $gm_screen_options['orderby_gmedia'], '_size', false ) . ' value="_size">' . __( 'File Size', 'grand-media' ) . '</option>
876
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
877
- </div>
878
- <div class="form-group">
879
- <select name="gm_screen_options[sortorder_gmedia]" class="form-control input-sm">
880
- <option' . selected( $gm_screen_options['sortorder_gmedia'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
881
- <option' . selected( $gm_screen_options['sortorder_gmedia'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
882
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
883
- </div>
884
- ';
885
- if ( 'edit' == $gmCore->_get( 'mode' ) ) {
886
- $settings .= '
887
- <div class="form-group">
888
- <select name="gm_screen_options[library_edit_quicktags]" class="form-control input-sm">
889
- <option' . selected( $gm_screen_options['library_edit_quicktags'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
890
- <option' . selected( $gm_screen_options['library_edit_quicktags'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
891
- </select> <span>' . __( 'Quick Tags panel for Description field', 'grand-media' ) . '</span>
892
- </div>
893
- ';
894
- }
895
- $settings .= '
896
- </div>
897
- ';
898
- break;
899
- case 'GrandMedia_AddMedia' :
900
- $tab = $gmCore->_get( 'tab', 'upload' );
901
- if ( 'upload' == $tab ) {
902
- $html4_hide = ( 'html4' == $gm_screen_options['uploader_runtime'] ) ? ' hide' : '';
903
- $settings = '
904
- <div class="form-inline pull-left">
905
- <div id="uploader_runtime" class="form-group"><span>' . __( 'Uploader runtime:', 'grand-media' ) . ' </span>
906
- <select name="gm_screen_options[uploader_runtime]" class="form-control input-sm">
907
- <option' . selected( $gm_screen_options['uploader_runtime'], 'auto', false ) . ' value="auto">' . __( 'Auto', 'grand-media' ) . '</option>
908
- <option' . selected( $gm_screen_options['uploader_runtime'], 'html5', false ) . ' value="html5">' . __( 'HTML5 Uploader', 'grand-media' ) . '</option>
909
- <option' . selected( $gm_screen_options['uploader_runtime'], 'flash', false ) . ' value="flash">' . __( 'Flash Uploader', 'grand-media' ) . '</option>
910
- <option' . selected( $gm_screen_options['uploader_runtime'], 'html4', false ) . ' value="html4">' . __( 'HTML4 Uploader', 'grand-media' ) . '</option>
911
- </select>
912
- </div>
913
- <div id="uploader_chunking" class="form-group' . $html4_hide . '"><span>' . __( 'Chunking:', 'grand-media' ) . ' </span>
914
- <select name="gm_screen_options[uploader_chunking]" class="form-control input-sm">
915
- <option' . selected( $gm_screen_options['uploader_chunking'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
916
- <option' . selected( $gm_screen_options['uploader_chunking'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
917
- </select>
918
- </div>
919
- <div id="uploader_urlstream_upload" class="form-group' . $html4_hide . '"><span>' . __( 'URL streem upload:', 'grand-media' ) . ' </span>
920
- <select name="gm_screen_options[uploader_urlstream_upload]" class="form-control input-sm">
921
- <option' . selected( $gm_screen_options['uploader_urlstream_upload'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
922
- <option' . selected( $gm_screen_options['uploader_urlstream_upload'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
923
- </select>
924
- </div>
925
- </div>
926
- ';
927
- }
928
- break;
929
- case 'GrandMedia_Albums' :
930
- if ( isset( $_GET['edit_term'] ) ) {
931
- $settings = '
932
- <div class="form-inline pull-left">
933
- <div class="form-group">
934
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_album_edit]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_album_edit'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
935
- </div>
936
- </div>
937
- ';
938
- } else {
939
- $settings = '
940
- <div class="form-inline pull-left">
941
- <div class="form-group">
942
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_album]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_album'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
943
- </div>
944
- <div class="form-group">
945
- <select name="gm_screen_options[orderby_gmedia_album]" class="form-control input-sm">
946
- <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
947
- <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
948
- <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
949
- <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'global', false ) . ' value="global">' . __( 'Author ID', 'grand-media' ) . '</option>
950
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
951
- </div>
952
- <div class="form-group">
953
- <select name="gm_screen_options[sortorder_gmedia_album]" class="form-control input-sm">
954
- <option' . selected( $gm_screen_options['sortorder_gmedia_album'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
955
- <option' . selected( $gm_screen_options['sortorder_gmedia_album'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
956
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
957
- </div>
958
- </div>
959
- ';
960
- }
961
- break;
962
- case 'GrandMedia_Categories' :
963
- if ( isset( $_GET['edit_term'] ) ) {
964
- $settings = '
965
- <div class="form-inline pull-left">
966
- <div class="form-group">
967
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_category_edit]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_category_edit'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
968
- </div>
969
- </div>
970
- ';
971
- } else {
972
- $settings = '
973
- <div class="form-inline pull-left">
974
- <div class="form-group">
975
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_category]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_category'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
976
- </div>
977
- <div class="form-group">
978
- <select name="gm_screen_options[orderby_gmedia_category]" class="form-control input-sm">
979
- <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
980
- <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
981
- <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
982
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
983
- </div>
984
- <div class="form-group">
985
- <select name="gm_screen_options[sortorder_gmedia_category]" class="form-control input-sm">
986
- <option' . selected( $gm_screen_options['sortorder_gmedia_category'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
987
- <option' . selected( $gm_screen_options['sortorder_gmedia_category'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
988
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
989
- </div>
990
- </div>
991
- ';
992
- }
993
- break;
994
- case 'GrandMedia_Tags' :
995
- $settings = '
996
- <div class="form-inline pull-left">
997
- <div class="form-group">
998
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_tag]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_tag'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
999
- </div>
1000
- <div class="form-group">
1001
- <select name="gm_screen_options[orderby_gmedia_tag]" class="form-control input-sm">
1002
- <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
1003
- <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
1004
- <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
1005
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1006
- </div>
1007
- <div class="form-group">
1008
- <select name="gm_screen_options[sortorder_gmedia_tag]" class="form-control input-sm">
1009
- <option' . selected( $gm_screen_options['sortorder_gmedia_tag'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1010
- <option' . selected( $gm_screen_options['sortorder_gmedia_tag'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1011
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1012
- </div>
1013
- </div>
1014
- ';
1015
- break;
1016
- case 'GrandMedia_Galleries' :
1017
- if ( ! $gmCore->_get( 'edit_term' ) && ! $gmCore->_get( 'gallery_module' ) ) {
1018
- $settings = '
1019
- <div class="form-inline pull-left">
1020
- <div class="form-group">
1021
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_gallery]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_gallery'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1022
- </div>
1023
- <div class="form-group">
1024
- <select name="gm_screen_options[orderby_gmedia_gallery]" class="form-control input-sm">
1025
- <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
1026
- <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
1027
- <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'global', false ) . ' value="global">' . __( 'Author ID', 'grand-media' ) . '</option>
1028
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1029
- </div>
1030
- <div class="form-group">
1031
- <select name="gm_screen_options[sortorder_gmedia_gallery]" class="form-control input-sm">
1032
- <option' . selected( $gm_screen_options['sortorder_gmedia_gallery'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1033
- <option' . selected( $gm_screen_options['sortorder_gmedia_gallery'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1034
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1035
- </div>
1036
- </div>
1037
- ';
1038
- }
1039
- break;
1040
- case 'GrandMedia_WordpressLibrary' :
1041
- $settings = '<p>' . __( 'Set query options for this page to be loaded by default.', 'grand-media' ) . '</p>
1042
- <div class="form-inline pull-left">
1043
- <div class="form-group">
1044
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_wpmedia]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_wpmedia'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1045
- </div>
1046
- <div class="form-group">
1047
- <select name="gm_screen_options[orderby_wpmedia]" class="form-control input-sm">
1048
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'ID', false ) . ' value="ID">' . __( 'ID', 'grand-media' ) . '</option>
1049
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'title', false ) . ' value="title">' . __( 'Title', 'grand-media' ) . '</option>
1050
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'filename', false ) . ' value="filename">' . __( 'Filename', 'grand-media' ) . '</option>
1051
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'date', false ) . ' value="date">' . __( 'Date', 'grand-media' ) . '</option>
1052
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'modified', false ) . ' value="modified">' . __( 'Last Modified', 'grand-media' ) . '</option>
1053
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'mime_type', false ) . ' value="mime_type">' . __( 'MIME Type', 'grand-media' ) . '</option>
1054
- <option' . selected( $gm_screen_options['orderby_wpmedia'], 'author', false ) . ' value="author">' . __( 'Author', 'grand-media' ) . '</option>
1055
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1056
- </div>
1057
- <div class="form-group">
1058
- <select name="gm_screen_options[sortorder_wpmedia]" class="form-control input-sm">
1059
- <option' . selected( $gm_screen_options['sortorder_wpmedia'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1060
- <option' . selected( $gm_screen_options['sortorder_wpmedia'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1061
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1062
- </div>
1063
- </div>
1064
- ';
1065
- break;
1066
- case 'GrandMedia_Logs' :
1067
- $settings = '
1068
- <div class="form-inline pull-left">
1069
- <div class="form-group">
1070
- <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_log]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_log'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1071
- </div>
1072
- <div class="form-group">
1073
- <select name="gm_screen_options[orderby_gmedia_log]" class="form-control input-sm">
1074
- <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'log_date', false ) . ' value="log_date">' . __( 'Date', 'grand-media' ) . '</option>
1075
- <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'ID', false ) . ' value="ID">' . __( 'Gmedia ID', 'grand-media' ) . '</option>
1076
- <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'author', false ) . ' value="author">' . __( 'Author ID', 'grand-media' ) . '</option>
1077
- </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1078
- </div>
1079
- <div class="form-group">
1080
- <select name="gm_screen_options[sortorder_gmedia_log]" class="form-control input-sm">
1081
- <option' . selected( $gm_screen_options['sortorder_gmedia_log'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1082
- <option' . selected( $gm_screen_options['sortorder_gmedia_log'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1083
- </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1084
- </div>
1085
- </div>
1086
- ';
1087
- break;
1088
- }
1089
-
1090
- if ( $settings ) {
1091
- $current = $title . $settings . $wp_screen_options . $button;
1092
- }
1093
-
1094
- }
1095
-
1096
- return $current;
1097
- }
1098
-
1099
- /**
1100
- * @param $status
1101
- * @param $option
1102
- * @param $value
1103
- *
1104
- * @return array
1105
- */
1106
- function screen_settings_save( $status, $option, $value ) {
1107
- global $user_ID;
1108
- if ( 'gm_screen_options' == $option ) {
1109
- /*
1110
- global $gmGallery;
1111
- foreach ( $_POST['gm_screen_options'] as $key => $val ) {
1112
- $gmGallery->options['gm_screen_options'][$key] = $val;
1113
- }
1114
- update_option( 'gmediaOptions', $gmGallery->options );
1115
- */
1116
- $gm_screen_options = get_user_meta( $user_ID, 'gm_screen_options', true );
1117
- if ( ! is_array( $gm_screen_options ) ) {
1118
- $gm_screen_options = array();
1119
- }
1120
- $value = array_merge( $gm_screen_options, $_POST['gm_screen_options'] );
1121
-
1122
- return $value;
1123
- }
1124
-
1125
- return $status;
1126
- }
1127
-
1128
- }
1129
-
1130
- global $gmAdmin;
1131
- // Start GmediaAdmin
1132
- $gmAdmin = new GmediaAdmin();
 
1
+ <?php
2
+
3
+ /**
4
+ * GmediaAdmin - Admin Section for GRAND Media
5
+ */
6
+ class GmediaAdmin {
7
+ var $pages = array();
8
+ var $body_classes = array();
9
+
10
+ /**
11
+ * constructor
12
+ */
13
+ function __construct() {
14
+ global $pagenow;
15
+
16
+ add_action( 'admin_head', array( &$this, 'admin_head' ) );
17
+
18
+ // Add the admin menu
19
+ add_action( 'admin_menu', array( &$this, 'add_menu' ) );
20
+
21
+ // Add the script and style files
22
+ add_action( 'admin_enqueue_scripts', array( &$this, 'load_scripts' ), 20 );
23
+ add_action( 'admin_print_scripts-widgets.php', array( &$this, 'gmedia_widget_scripts' ) );
24
+
25
+ add_action( 'enqueue_block_editor_assets', array( &$this, 'gutenberg_assets' ) );
26
+
27
+ add_filter( 'screen_settings', array( &$this, 'screen_settings' ), 10, 2 );
28
+ add_filter( 'set-screen-option', array( &$this, 'screen_settings_save' ), 11, 3 );
29
+
30
+ if ( isset( $_GET['page'] ) && ( false !== strpos( $_GET['page'], 'GrandMedia' ) ) ) {
31
+ $this->body_classes[] = 'grand-media-admin-page';
32
+
33
+ if ( ! isset( $_GET['gmediablank'] ) || 'library' === $_GET['gmediablank'] ) {
34
+ $this->body_classes[] = $_GET['page'];
35
+ if ( ! empty( $_GET['mode'] ) ) {
36
+ $this->body_classes[] = $_GET['page'] . '_' . $_GET['mode'];
37
+ }
38
+ if ( isset( $_GET['edit_term'] ) || isset( $_GET['gallery_module'] ) || isset( $_GET['preset'] ) ) {
39
+ $this->body_classes[] = $_GET['page'] . '_edit';
40
+ }
41
+ }
42
+
43
+ if ( ( 'admin.php' == $pagenow ) && isset( $_GET['gmediablank'] ) ) {
44
+ add_action( 'admin_init', array( &$this, 'gmedia_blank_page' ) );
45
+ }
46
+
47
+ add_action( 'admin_footer', array( &$this, 'admin_footer' ) );
48
+ }
49
+
50
+ }
51
+
52
+ /**
53
+ * admin_head
54
+ */
55
+ function admin_head() {
56
+ add_filter( 'admin_body_class', array( &$this, 'admin_body_class' ) );
57
+
58
+ if ( isset( $_GET['page'] ) && ( false !== strpos( $_GET['page'], 'GrandMedia' ) ) ) {
59
+ ?>
60
+ <style type="text/css" id="gmedia_admin_css">html, body { background: <?php echo isset( $_GET['gmediablank'] )? 'transparent' : '#708090'; ?>; }</style>
61
+ <?php
62
+ }
63
+ }
64
+
65
+ /**
66
+ * admin_body_class
67
+ *
68
+ * @param $classes_string
69
+ *
70
+ * @return string
71
+ */
72
+ function admin_body_class( $classes_string ) {
73
+ $classes = $this->body_classes;
74
+
75
+ $classes[] = $classes_string;
76
+ if ( isset( $_GET["gmediablank"] ) ) {
77
+ $classes[] = "gmedia-blank gmedia_{$_GET['gmediablank']}";
78
+ }
79
+ $classes = array_filter( $classes );
80
+
81
+ return implode( ' ', $classes );
82
+ }
83
+
84
+ /**
85
+ * Load gmedia pages in wpless interface
86
+ */
87
+ function gmedia_blank_page() {
88
+ set_current_screen( 'GrandMedia_Settings' );
89
+
90
+ global $gmCore, $gmProcessor;
91
+ $gmediablank = $gmCore->_get( 'gmediablank', '' );
92
+ define( 'IFRAME_REQUEST', true );
93
+
94
+ iframe_header( 'GmediaGallery' );
95
+
96
+ echo '<div id="gmedia-container">';
97
+ switch ( $gmediablank ) {
98
+ case 'update_plugin':
99
+ require_once( dirname( dirname( __FILE__ ) ) . '/config/update.php' );
100
+ gmedia_do_update();
101
+ break;
102
+ case 'image_editor':
103
+ require_once( dirname( dirname( __FILE__ ) ) . '/inc/image-editor.php' );
104
+ gmedia_image_editor();
105
+ break;
106
+ case 'map_editor':
107
+ require_once( dirname( dirname( __FILE__ ) ) . '/inc/map-editor.php' );
108
+ gmedia_map_editor();
109
+ break;
110
+ case 'library':
111
+ echo '<div id="gmedia_iframe_content">';
112
+ echo '<div id="gm-message">' . $gmCore->alert( 'success', $gmProcessor->msg ) . $gmCore->alert( 'danger', $gmProcessor->error ) . '</div>';
113
+ include( GMEDIA_ABSPATH . 'admin/pages/library/library.php' );
114
+ echo '</div>';
115
+ break;
116
+ case 'comments':
117
+ require_once( dirname( __FILE__ ) . '/tpl/comments.php' );
118
+ break;
119
+ case 'module_preview':
120
+ require_once( dirname( __FILE__ ) . '/tpl/module-preview.php' );
121
+ break;
122
+ }
123
+ echo '</div>';
124
+
125
+ iframe_footer();
126
+ exit;
127
+ }
128
+
129
+ // integrate the menu
130
+ function add_menu() {
131
+
132
+ $count = '';
133
+ if ( current_user_can( 'gmedia_module_manage' ) ) {
134
+ global $gmGallery;
135
+ if ( $gmGallery->options['modules_update'] ) {
136
+ $count .= " <span class='update-plugins count-{$gmGallery->options['modules_update']}' style='background-color: #bb391b;'><span class='plugin-count gm-module-count gm-modules-update-count' title='" . __( 'Modules Updates', 'grand-media' ) . "'>{$gmGallery->options['modules_update']}</span></span>";
137
+ }
138
+ if ( $gmGallery->options['modules_new'] && !empty( $gmGallery->options['notify_new_modules'] ) ) {
139
+ $count .= " <span class='update-plugins count-{$gmGallery->options['modules_new']}' style='background-color: #367236;'><span class='plugin-count gm-module-count gm-modules-new-count' title='" . __( 'New Modules', 'grand-media' ) . "'>{$gmGallery->options['modules_new']}</span></span>";
140
+ }
141
+ }
142
+
143
+ $this->pages = array();
144
+ $this->pages[] = add_menu_page( __( 'Gmedia Library', 'grand-media' ), "Gmedia{$count}", 'gmedia_library', 'GrandMedia', array(
145
+ &$this,
146
+ 'shell',
147
+ ), 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIyMHB4IiBoZWlnaHQ9IjIwcHgiIHZpZXdCb3g9IjAgMCAyMCAyMCIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMjAgMjAiIHhtbDpzcGFjZT0icHJlc2VydmUiPiAgPGltYWdlIGlkPSJpbWFnZTAiIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgeD0iMCIgeT0iMCIKICAgIHhsaW5rOmhyZWY9ImRhdGE6aW1hZ2UvcG5nO2Jhc2U2NCxpVkJPUncwS0dnb0FBQUFOU1VoRVVnQUFBQlFBQUFBVUNBTUFBQUM2ViswL0FBQUFCR2RCVFVFQUFMR1BDL3hoQlFBQUFDQmpTRkpOCkFBQjZKZ0FBZ0lRQUFQb0FBQUNBNkFBQWRUQUFBT3BnQUFBNm1BQUFGM0NjdWxFOEFBQUJrbEJNVkVVeFpua3haM2d4WjNoQ2RJTnUKbEtBK2NZQnBrSjJRcmJhb3Y4YTV5OUdadEx5UnJyZG1qcHMzYTN4WmhKS0txYktPckxXcndjaW52c1dWc2JxM3l0Q1hzcnRWZ1k5UwpmNDZndWNGN25hZzdibjVFZFlWeGxxS01xclN3eGN1aHVzS2Z1TUMrejlSMm1xWTZibjZ1dzhyNy9QekYxTm0weU03dDh2UHo5dmVGCnBhL2Y1K3BiaHBSSWVJZCtvS3FOcTdTZHQ3OWhpcGN5YUhuSDF0clMzdUZIZDRiSzJOMzUrL3YzK2ZxOXp0UmFoWk5QZll5Qm9xeUMKbzYwOGIzOUdkb1poaTVoT2ZJdnE3L0dwdjhiLy8vLzIrUG45L2YzQjBkWkFjb0tZczd3emFIbSt6OVZxa1oxWGc1SFQzK0xZNHVaNgpuYWh3bGFGRGRJVFAzT0JLZVloTWU0bnc5UFhoNmV2eDlmYkwyZDFUZ0k1em1LTXphWHJUM3VLWXM3dlAyOS9WNE9PY3RyN2c2T3VVCnNMbE5mSXU0eTlEbzd2QkZkb1YzbTZibTdlODViWDNJMXR1RHBLN1EzT0JZaEpHUHJMWEMwdGVsdmNSSmVZamI1ZWpOMnQ1eWw2S1cKc3JyYjVPZUFvYXhqakpuZTUrbDJtcVhFMDlpSHByQnRrNTl5bDZOOG5xazRiSDNXNGVUVTMrUFIzZUdxd01jY1RNSnpBQUFBQW5SUwpUbE51MlhMaTRXRUFBQUFCWWt0SFJFVDV0SmpCQUFBQUNYQklXWE1BQUFzVEFBQUxFd0VBbXB3WUFBQUFCM1JKVFVVSDRBc0NDRGNJCmw0WXhCZ0FBQVIxSlJFRlVHTk5qWUdCa1FnT01ESmhpSUZFNGs1bUZGY2FFQzdLeGMzQnljZlB3SWd2eWNmRUxDQW9KYzRxSThvdEIKQmNVRkpDU2xtS1JsWklYbDVCVVVsVUNDeWlxcWF1b2FtbHJhT3N4TXVucjZCb1pBUVNOakUxTW1Kak56QzBzQkt5WW1hMTBiUHFDZwpyWWFkdllLRG81T3ppNnVidTRlOHA1QVhVTkJiMGNmWHo5OHVJRkNDS1VneE9NUk9DR2hScUdaWU9MTmRSR1JVZ0FFVGsxU0VYMVEwCkUwTk1ySGRjZklKVVlwSzdiRExRMHBUVXRIUW1ob3pNTEgzVGhPd2MzY3pjUExEelRMU1lHUElMbUR3S2k0cExtRXFUSWQ3Z0tHUmkKWUF1elk3SXJpeXV2cUlTSVNWVlZBeTJxQ2ErdERtU3BxMk1KckZkcXlNbjN5MjRFQ25weEp6UWxOUHZGeHBxMDVBWUh4N2Z5SW9VUwpNc0FleU5paUF3Q3FwalN3RnBqcGxnQUFBQ1YwUlZoMFpHRjBaVHBqY21WaGRHVUFNakF4TmkweE1TMHdNbFF3T0RvMU5Ub3dPQzB3Ck56b3dNSWl4dXBvQUFBQWxkRVZZZEdSaGRHVTZiVzlrYVdaNUFESXdNVFl0TVRFdE1ESlVNRGc2TlRVNk1EZ3RNRGM2TURENTdBSW0KQUFBQUFFbEZUa1N1UW1DQyIgLz4KPC9zdmc+Cg==', 11 );
148
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Library', 'grand-media' ), __( 'Gmedia Library', 'grand-media' ), 'gmedia_library', 'GrandMedia', array( &$this, 'shell' ) );
149
+ if ( current_user_can( 'gmedia_library' ) ) {
150
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Add Media Files', 'grand-media' ), __( 'Add/Import Files', 'grand-media' ), 'gmedia_upload', 'GrandMedia_AddMedia', array( &$this, 'shell' ) );
151
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Tags', 'grand-media' ), __( 'Tags', 'grand-media' ), 'gmedia_tag_manage', 'GrandMedia_Tags', array( &$this, 'shell' ) );
152
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Categories', 'grand-media' ), __( 'Categories', 'grand-media' ), 'gmedia_category_manage', 'GrandMedia_Categories', array( &$this, 'shell' ) );
153
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Albums', 'grand-media' ), __( 'Albums', 'grand-media' ), 'gmedia_album_manage', 'GrandMedia_Albums', array( &$this, 'shell' ) );
154
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Galleries', 'grand-media' ), __( 'Galleries', 'grand-media' ), 'gmedia_gallery_manage', 'GrandMedia_Galleries', array( &$this, 'shell' ) );
155
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Modules', 'grand-media' ), __( 'Modules', 'grand-media' ), 'gmedia_gallery_manage', 'GrandMedia_Modules', array( &$this, 'shell' ) );
156
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Settings', 'grand-media' ), __( 'Settings', 'grand-media' ), 'manage_options', 'GrandMedia_Settings', array( &$this, 'shell' ) );
157
+ //$this->pages[] = add_submenu_page( 'GrandMedia', __( 'iOS Application', 'grand-media' ), __( 'iOS Application', 'grand-media' ), 'gmedia_settings', 'GrandMedia_App', array( &$this, 'shell' ) );
158
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'WordPress Media Library', 'grand-media' ), __( 'WP Media Library', 'grand-media' ), 'gmedia_import', 'GrandMedia_WordpressLibrary', array( &$this, 'shell' ) );
159
+ $this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Logs', 'grand-media' ), __( 'Gmedia Logs', 'grand-media' ), 'manage_options', 'GrandMedia_Logs', array( &$this, 'shell' ) );
160
+ //$this->pages[] = add_submenu_page( 'GrandMedia', __( 'Gmedia Support', 'grand-media' ), __( 'Support', 'grand-media' ), 'manage_options', 'GrandMedia_Support', array( &$this, 'shell' ) );
161
+ }
162
+
163
+ foreach ( $this->pages as $page ) {
164
+ add_action( "load-$page", array( &$this, 'screen_help' ) );
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Load the script for the defined page and load only this code
170
+ * Display shell of plugin
171
+ */
172
+ function shell() {
173
+ global $gmCore, $gmProcessor, $gmGallery;
174
+
175
+ $sideLinks = $this->sideLinks();
176
+
177
+ // check for upgrade
178
+ if ( get_option( 'gmediaDbVersion' ) != GMEDIA_DBVERSION ) {
179
+ if ( get_transient( 'gmediaUpgrade' ) || ( isset( $_GET['do_update'] ) && ( 'gmedia' == $_GET['do_update'] ) ) ) {
180
+ $sideLinks['grandTitle'] = __( 'Updating GmediaGallery Plugin', 'grand-media' );
181
+ $sideLinks['sideLinks'] = '';
182
+ $gmProcessor->page = 'GrandMedia_Update';
183
+ } else {
184
+ return;
185
+ }
186
+ }
187
+
188
+ // global $wpdb;
189
+ // $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gmedia_term");
190
+ // foreach($query as $item){
191
+ // $name = $gmCore->mb_convert_encoding_utf8($item->name);
192
+ // $wpdb->update($wpdb->prefix . 'gmedia_term', array('name' => $name), array('term_id' => $item->term_id));
193
+ // }
194
+ // echo '<pre>' . print_r($query, true) . '</pre>';
195
+
196
+ ?>
197
+ <div id="gmedia-container" class="gmedia-admin">
198
+ <?php
199
+ if ( $gmProcessor->page !== 'GrandMedia_App' && ! isset( $gmGallery->options['gmedia_service'] ) && current_user_can( 'manage_options' ) ) {
200
+ $this->collect_data_permission();
201
+ }
202
+ ?>
203
+ <div id="gmedia-header" class="clearfix">
204
+ <div id="gmedia-logo">Gmedia
205
+ <small> by CodEasily.com</small>
206
+ </div>
207
+ <h2><?php echo $sideLinks['grandTitle']; ?></h2>
208
+ <?php
209
+ if ( ! is_plugin_active( 'woowbox/woowbox.php' ) && empty( $gmGallery->options['disable_ads'] ) ) {
210
+ ?>
211
+ <div class="promote-woowbox"><a href="https://bit.ly/woowbox" target="_blank"><img src="<?php echo plugins_url( '/grand-media/admin/assets/img/woowbox-promote.png' ) ?>" alt="Try WoowBox Gallery plugin"/></a></div>
212
+ <?php
213
+ }
214
+ ?>
215
+ </div>
216
+ <div class="container-fluid">
217
+ <div class="row row-fx180-fl">
218
+ <div class="col-sm-2 hidden-xs" id="sidebar" role="navigation">
219
+ <?php echo $sideLinks['sideLinks']; ?>
220
+
221
+ <?php
222
+ if ( (int) $gmGallery->options['feedback'] ) {
223
+ $installDate = get_option( 'gmediaInstallDate' );
224
+ if ( $installDate && ( strtotime( $installDate ) < strtotime( '2 weeks ago' ) ) ) { ?>
225
+ <div class="row panel panel-default visible-lg-block">
226
+ <div class="panel-heading" data-toggle="collapse" data-target="#support_div_collapse" aria-expanded="true" aria-controls="support_div_collapse" style="cursor:pointer;">
227
+ <b><?php _e( 'Any feedback?', 'grand-media' ); ?></b>
228
+ </div>
229
+ <div class="collapse<?php if ( empty( $gmGallery->options['license_key'] ) ) {
230
+ echo ' in';
231
+ } ?>" id="support_div_collapse">
232
+ <div class="panel-body">
233
+ <p><?php _e( 'You can help me spread the word about GmediaGallery among the users striving to get awesome galleries on their WordPress sites.', 'grand-media' ); ?></p>
234
+
235
+ <p>
236
+ <a class="btn btn-primary" href="https://wordpress.org/support/view/plugin-reviews/grand-media?filter=5" target="_blank"><?php _e( 'Rate Gmedia Gallery', 'grand-media' ); ?></a>
237
+ </p>
238
+
239
+ <p><?php _e( 'Your reviews and ideas helps me to create new awesome modules and to improve plugin.', 'grand-media' ); ?></p>
240
+ </div>
241
+ </div>
242
+ </div>
243
+ <?php }
244
+ }
245
+ if ( (int) $gmGallery->options['twitter'] ) {
246
+ ?>
247
+ <div class="row panel visible-lg-block">
248
+ <a class="twitter-timeline" data-height="600" href="https://twitter.com/CodEasily/timelines/648240437141086212?ref_src=twsrc%5Etfw">#GmediaGallery - Curated tweets by CodEasily</a>
249
+ <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
250
+ </div>
251
+ <?php
252
+ } ?>
253
+ </div>
254
+ <div class="col-sm-10 col-xs-12">
255
+ <div id="gm-message"><?php
256
+ echo $gmCore->alert( 'success', $gmProcessor->msg );
257
+ echo $gmCore->alert( 'danger', $gmProcessor->error );
258
+ ?></div>
259
+
260
+ <?php $this->controller(); ?>
261
+
262
+ </div>
263
+ </div>
264
+ </div>
265
+ </div>
266
+ <?php
267
+ }
268
+
269
+ function sideLinks() {
270
+ global $submenu, $gmProcessor, $gmGallery;
271
+ $content['sideLinks'] = '
272
+ <div id="gmedia-navbar">
273
+ <div class="row">
274
+ <ul class="list-group"><li>';
275
+ if ( empty( $gmGallery->options['license_key'] ) ) {
276
+ $content['sideLinks'] .= "\n" . '<a class="list-group-item list-group-item-premium" target="_blank" href="https://codeasily.com/product/one-site-license/">' . __( 'Get Gmedia Premium', 'grand-media' ) . '</a></li><li>';
277
+ }
278
+ foreach ( $submenu['GrandMedia'] as $menuKey => $menuItem ) {
279
+ if ( $menuItem[2] == $gmProcessor->page ) {
280
+ $iscur = ' active';
281
+ $content['grandTitle'] = $menuItem[3];
282
+ } else {
283
+ $iscur = '';
284
+ }
285
+ $menuData = '';
286
+ if ( $menuItem[2] == 'GrandMedia_Modules' && gm_user_can( 'module_manage' ) ) {
287
+ if ( !empty( $gmGallery->options['notify_new_modules'] ) ) {
288
+ $menuData .= '<span class="badge badge-success pull-right gm-module-count-' . $gmGallery->options['modules_new'] . '" title="' . __( 'New Modules', 'grand-media' ) . '">' . $gmGallery->options['modules_new'] . '</span>';
289
+ }
290
+ $menuData .= '<span class="badge badge-error pull-right gm-module-count-' . $gmGallery->options['modules_update'] . '" title="' . __( 'Modules Updates', 'grand-media' ) . '">' . $gmGallery->options['modules_update'] . '</span>';
291
+ }
292
+
293
+ $content['sideLinks'] .= "\n" . '<a class="list-group-item' . $iscur . '" href="' . admin_url( 'admin.php?page=' . $menuItem[2] ) . '">' . $menuItem[0] . $menuData . '</a>';
294
+ }
295
+ $content['sideLinks'] .= "\n" . '<a class="list-group-item" target="_blank" href="https://wordpress.org/support/plugin/grand-media/">' . __( 'Support', 'grand-media' ) . '</a>';
296
+ $content['sideLinks'] .= '
297
+ </li></ul>
298
+ </div>
299
+ </div>';
300
+
301
+ return $content;
302
+ }
303
+
304
+ function collect_data_permission() {
305
+ $current_user = wp_get_current_user();
306
+ $nonce = wp_create_nonce( 'GmediaService' );
307
+ ?>
308
+ <div class="notice updated gm-message gmedia-service__message">
309
+ <div class="gm-message-content">
310
+ <div class="gm-plugin-icon">
311
+ <img src="<?php echo plugins_url( '/grand-media/admin/assets/img/icon-128x128.png' ) ?>" width="90" height="90">
312
+ </div>
313
+ <?php printf( __( '<p>Hey %s,<br>Please help us improve <b>Gmedia Gallery</b>! If you opt-in, some data about your usage of <b>Gmedia Gallery</b> will be sent to <a href="https://codeasily.com/" target="_blank" tabindex="1">codeasily.com</a>.
314
+ If you skip this, that\'s okay! <b>Gmedia Gallery</b> will still work just fine.</p>', 'grand-media' ), $current_user->display_name ); ?>
315
+ </div>
316
+ <div class="gm-message-actions">
317
+ <button class="button button-secondary gm_service_action" data-action="skip" data-nonce="<?php echo $nonce; ?>"><?php _e( 'Skip', 'grand-media' ); ?></button>
318
+ <button class="button button-primary gm_service_action" data-action="allow" data-nonce="<?php echo $nonce; ?>"><?php _e( 'Allow &amp; Continue', 'grand-media' ); ?></button>
319
+ </div>
320
+ <div class="gm-message-plus gm-closed">
321
+ <a class="gm-mp-trigger" href="#" onclick="jQuery('.gm-message-plus').toggleClass('gm-closed gm-opened'); return false;"><?php _e( 'What permissions are being granted?', 'grand-media' ); ?></a>
322
+ <ul>
323
+ <li>
324
+ <i class="dashicons dashicons-admin-users"></i>
325
+
326
+ <div>
327
+ <span><?php _e( 'Your Profile Overview', 'grand-media' ); ?></span>
328
+
329
+ <p><?php _e( 'Name and email address', 'grand-media' ); ?></p>
330
+ </div>
331
+ </li>
332
+ <li>
333
+ <i class="dashicons dashicons-admin-settings"></i>
334
+
335
+ <div>
336
+ <span><?php _e( 'Your Site Overview', 'grand-media' ); ?></span>
337
+
338
+ <p><?php _e( 'Site URL, WP version, PHP version, active theme &amp; plugins', 'grand-media' ); ?></p>
339
+ </div>
340
+ </li>
341
+ </ul>
342
+ </div>
343
+ </div>
344
+ <?php
345
+ }
346
+
347
+ function admin_footer() {
348
+ $ajax_operations = get_option( 'gmedia_ajax_long_operations' );
349
+ if ( empty( $ajax_operations ) || ! is_array( $ajax_operations ) ) {
350
+ return;
351
+ }
352
+ reset( $ajax_operations );
353
+ $ajax = key( $ajax_operations );
354
+ if ( empty( $ajax ) ) {
355
+ delete_option( 'gmedia_ajax_long_operations' );
356
+
357
+ return;
358
+ }
359
+ $nonce = wp_create_nonce( 'gmedia_ajax_long_operations' );
360
+ ?>
361
+ <script type="text/javascript">
362
+ jQuery(document).ready(function($) {
363
+ var header = $('#gmedia-header');
364
+ header.append('<div id="ajax-long-operation"><div class="progress"><div class="progress-bar progress-bar-info" style="width: 0%;"></div><div class="progress-bar-indicator">0%</div></div></div>');
365
+ gmAjaxLongOperation = function() {
366
+ jQuery.post(ajaxurl, {action: '<?php echo $ajax; ?>', _wpnonce_ajax_long_operations: '<?php echo $nonce; ?>'}, function(r) {
367
+ if(r.data) {
368
+ jQuery('.progress-bar-info', header).width(r.data.progress);
369
+ var indicator = r.data.info ? r.data.info + ' ' + r.data.progress : r.data.progress;
370
+ jQuery('.progress-bar-indicator', header).html(indicator);
371
+
372
+ if(r.data.done) {
373
+ return;
374
+ }
375
+ }
376
+ gmAjaxLongOperation();
377
+ });
378
+ };
379
+ gmAjaxLongOperation();
380
+ });
381
+ </script>
382
+ <?php
383
+ }
384
+
385
+ function controller() {
386
+
387
+ global $gmProcessor;
388
+ switch ( $gmProcessor->page ) {
389
+ case 'GrandMedia_AddMedia':
390
+ include_once( dirname( __FILE__ ) . '/pages/addmedia/addmedia.php' );
391
+ break;
392
+ case 'GrandMedia_Albums':
393
+ if ( isset( $_GET['edit_term'] ) ) {
394
+ include_once( dirname( __FILE__ ) . '/pages/terms/edit-term.php' );
395
+ } else {
396
+ include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
397
+ }
398
+ break;
399
+ case 'GrandMedia_Categories':
400
+ if ( isset( $_GET['edit_term'] ) ) {
401
+ include_once( dirname( __FILE__ ) . '/pages/terms/edit-term.php' );
402
+ } else {
403
+ include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
404
+ }
405
+ break;
406
+ case 'GrandMedia_Tags':
407
+ include_once( dirname( __FILE__ ) . '/pages/terms/terms.php' );
408
+ break;
409
+ case 'GrandMedia_Galleries':
410
+ if ( isset( $_GET['gallery_module'] ) || isset( $_GET['edit_term'] ) ) {
411
+ include_once( dirname( __FILE__ ) . '/pages/galleries/edit-gallery.php' );
412
+ } else {
413
+ include_once( dirname( __FILE__ ) . '/pages/galleries/galleries.php' );
414
+ }
415
+ break;
416
+ case 'GrandMedia_Modules':
417
+ if ( isset( $_GET['preset_module'] ) || isset( $_GET['preset'] ) ) {
418
+ include_once( dirname( __FILE__ ) . '/pages/modules/edit-preset.php' );
419
+ } else {
420
+ include_once( dirname( __FILE__ ) . '/pages/modules/modules.php' );
421
+ }
422
+ break;
423
+ case 'GrandMedia_Settings':
424
+ include_once( dirname( __FILE__ ) . '/pages/settings/settings.php' );
425
+ break;
426
+ case 'GrandMedia_App':
427
+ include_once( dirname( __FILE__ ) . '/app.php' );
428
+ gmediaApp();
429
+ break;
430
+ case 'GrandMedia_WordpressLibrary':
431
+ include_once( dirname( __FILE__ ) . '/wpmedia.php' );
432
+ grandWPMedia();
433
+ break;
434
+ case 'GrandMedia_Logs':
435
+ include_once( dirname( __FILE__ ) . '/logs.php' );
436
+ break;
437
+ case 'GrandMedia_Support':
438
+ include_once( dirname( __FILE__ ) . '/support.php' );
439
+ gmediaSupport();
440
+ break;
441
+ case 'GrandMedia_Update':
442
+ include_once( GMEDIA_ABSPATH . 'config/update.php' );
443
+ gmedia_upgrade_progress_panel();
444
+ break;
445
+ case 'GrandMedia':
446
+ include_once( dirname( __FILE__ ) . '/pages/library/library.php' );
447
+ break;
448
+ default:
449
+ do_action( 'gmedia_admin_page-' . $gmProcessor->page );
450
+ break;
451
+ }
452
+ }
453
+
454
+ /**
455
+ * @param $hook
456
+ */
457
+ function load_scripts( $hook ) {
458
+ global $gmCore, $gmProcessor, $gmGallery;
459
+ // no need to go on if it's not a plugin page
460
+ if ( 'admin.php' != $hook && strpos( $gmCore->_get( 'page' ), 'GrandMedia' ) === false ) {
461
+ return;
462
+ }
463
+
464
+ if ( $gmGallery->options['isolation_mode'] ) {
465
+ global $wp_scripts, $wp_styles;
466
+ foreach ( $wp_scripts->registered as $handle => $wp_script ) {
467
+ if ( ( ( false !== strpos( $wp_script->src, '/plugins/' ) ) || ( false !== strpos( $wp_script->src, '/themes/' ) ) ) && ( false === strpos( $wp_script->src, GMEDIA_FOLDER ) ) ) {
468
+ if ( in_array( $handle, $wp_scripts->queue ) ) {
469
+ wp_dequeue_script( $handle );
470
+ }
471
+ wp_deregister_script( $handle );
472
+ }
473
+ }
474
+ foreach ( $wp_styles->registered as $handle => $wp_style ) {
475
+ if ( ( ( false !== strpos( $wp_style->src, '/plugins/' ) ) || ( false !== strpos( $wp_style->src, '/themes/' ) ) ) && ( false === strpos( $wp_style->src, GMEDIA_FOLDER ) ) ) {
476
+ if ( in_array( $handle, $wp_styles->queue ) ) {
477
+ wp_dequeue_style( $handle );
478
+ }
479
+ wp_deregister_style( $handle );
480
+ }
481
+ }
482
+ }
483
+
484
+ wp_enqueue_style( 'gmedia-bootstrap' );
485
+ wp_enqueue_script( 'gmedia-bootstrap' );
486
+
487
+ wp_register_script( 'selectize', $gmCore->gmedia_url . '/assets/selectize/selectize.min.js', array( 'jquery' ), '0.12.1' );
488
+ wp_register_style( 'selectize', $gmCore->gmedia_url . '/assets/selectize/selectize.bootstrap3.css', array( 'gmedia-bootstrap' ), '0.12.1', 'screen' );
489
+
490
+ wp_register_style( 'spectrum', $gmCore->gmedia_url . '/assets/spectrum/spectrum.min.css', array(), '1.8.0' );
491
+ wp_register_script( 'spectrum', $gmCore->gmedia_url . '/assets/spectrum/spectrum.min.js', array( 'jquery' ), '1.8.0', true );
492
+
493
+ if ( isset( $_GET['page'] ) ) {
494
+ switch ( $_GET['page'] ) {
495
+ case "GrandMedia" :
496
+ if ( $gmCore->caps['gmedia_edit_media'] ) {
497
+ if ( $gmCore->_get( 'gmediablank' ) == 'image_editor' ) {
498
+ wp_enqueue_script( 'camanjs', $gmCore->gmedia_url . '/assets/image-editor/camanjs/caman.full.min.js', array(), '4.1.2' );
499
+
500
+ wp_enqueue_style( 'nouislider', $gmCore->gmedia_url . '/assets/image-editor/js/jquery.nouislider.css', array( 'gmedia-bootstrap' ), '6.1.0' );
501
+ wp_enqueue_script( 'nouislider', $gmCore->gmedia_url . '/assets/image-editor/js/jquery.nouislider.min.js', array( 'jquery' ), '6.1.0' );
502
+
503
+ wp_enqueue_style( 'gmedia-image-editor', $gmCore->gmedia_url . '/assets/image-editor/style.css', array( 'gmedia-bootstrap' ), '0.9.16', 'screen' );
504
+ wp_enqueue_script( 'gmedia-image-editor', $gmCore->gmedia_url . '/assets/image-editor/image-editor.js', array( 'jquery', 'camanjs' ), '0.9.16' );
505
+ break;
506
+ }
507
+ if ( $gmProcessor->mode == 'edit' ) {
508
+ wp_enqueue_script( 'alphanum', $gmCore->gmedia_url . '/assets/jq-plugins/jquery.alphanum.js', array( 'jquery' ), '1.0.16' );
509
+
510
+ wp_enqueue_script( 'jquery-ui-sortable' );
511
+
512
+ wp_enqueue_script( 'moment', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/moment.min.js', array( 'jquery' ), '2.22.2' );
513
+ wp_enqueue_style( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css', array( 'gmedia-bootstrap' ), '4.17.47' );
514
+ wp_enqueue_script( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js', array(
515
+ 'jquery',
516
+ 'moment',
517
+ 'gmedia-bootstrap',
518
+ ), '4.17.47' );
519
+ }
520
+ }
521
+ wp_enqueue_script( 'wavesurfer', $gmCore->gmedia_url . '/assets/wavesurfer/wavesurfer.min.js', array( 'jquery' ), '1.1.5' );
522
+ break;
523
+ case "GrandMedia_WordpressLibrary" :
524
+ break;
525
+ case "GrandMedia_Albums" :
526
+ if ( isset( $_GET['edit_term'] ) ) {
527
+ if ( $gmCore->caps['gmedia_album_manage'] ) {
528
+ wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
529
+ wp_enqueue_script( 'jquery-ui-full', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js', array(), '1.10.2' );
530
+ }
531
+
532
+ wp_enqueue_script( 'moment', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/moment.min.js', array( 'jquery' ), '2.5.1' );
533
+ wp_enqueue_style( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css', array( 'gmedia-bootstrap' ), '2.1.32' );
534
+ wp_enqueue_script( 'datetimepicker', $gmCore->gmedia_url . '/assets/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js', array(
535
+ 'jquery',
536
+ 'moment',
537
+ 'gmedia-bootstrap',
538
+ ), '2.1.32' );
539
+ }
540
+ break;
541
+ case "GrandMedia_Categories" :
542
+ break;
543
+ case "GrandMedia_AddMedia" :
544
+ if ( $gmCore->caps['gmedia_upload'] ) {
545
+ $tab = $gmCore->_get( 'tab', 'upload' );
546
+ if ( $tab == 'upload' ) {
547
+ wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
548
+ wp_enqueue_script( 'jquery-ui-full', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js', array(), '1.10.2' );
549
+
550
+ wp_enqueue_script( 'gmedia-plupload', $gmCore->gmedia_url . '/assets/plupload/plupload.full.min.js', array( 'jquery', 'jquery-ui-full' ), '2.1.2' );
551
+
552
+ wp_enqueue_style( 'jquery.ui.plupload', $gmCore->gmedia_url . '/assets/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css', array( 'jquery-ui-smoothness' ), '2.1.2', 'screen' );
553
+ wp_enqueue_script( 'jquery.ui.plupload', $gmCore->gmedia_url . '/assets/plupload/jquery.ui.plupload/jquery.ui.plupload.min.js', array(
554
+ 'gmedia-plupload',
555
+ 'jquery-ui-full',
556
+ ), '2.1.2' );
557
+
558
+ }
559
+ }
560
+ break;
561
+ case "GrandMedia_Settings" :
562
+ case "GrandMedia_App" :
563
+ // under construction
564
+ break;
565
+ case "GrandMedia_Galleries" :
566
+ if ( $gmCore->caps['gmedia_gallery_manage'] && ( isset( $_GET['gallery_module'] ) || isset( $_GET['edit_term'] ) ) ) {
567
+
568
+ wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
569
+ wp_enqueue_script( 'jquery-ui-resizable' );
570
+
571
+ wp_enqueue_script( 'jquery-ui-sortable' );
572
+
573
+ wp_enqueue_style( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.css', array( 'gmedia-bootstrap' ), '0.9.13' );
574
+ wp_enqueue_script( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.js', array( 'jquery' ), '0.9.13' );
575
+
576
+ wp_enqueue_style( 'spectrum' );
577
+ wp_enqueue_script( 'spectrum' );
578
+ }
579
+ break;
580
+ case "GrandMedia_Modules" :
581
+ if ( isset( $_GET['preset_module'] ) || isset( $_GET['preset'] ) ) {
582
+
583
+ wp_enqueue_style( 'jquery-ui-smoothness', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css', array(), '1.10.2', 'screen' );
584
+ wp_enqueue_script( 'jquery-ui-resizable' );
585
+
586
+ wp_enqueue_script( 'jquery-ui-sortable' );
587
+
588
+ wp_enqueue_style( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.css', array( 'gmedia-bootstrap' ), '0.9.13' );
589
+ wp_enqueue_script( 'jquery.minicolors', $gmCore->gmedia_url . '/assets/minicolors/jquery.minicolors.js', array( 'jquery' ), '0.9.13' );
590
+
591
+ wp_enqueue_style( 'spectrum' );
592
+ wp_enqueue_script( 'spectrum' );
593
+ }
594
+ break;
595
+ }
596
+ }
597
+ wp_enqueue_style( 'selectize' );
598
+ wp_enqueue_script( 'selectize' );
599
+
600
+ wp_enqueue_style( 'grand-media' );
601
+ wp_enqueue_script( 'grand-media' );
602
+
603
+ }
604
+
605
+ function gmedia_widget_scripts() {
606
+
607
+ }
608
+
609
+ /**
610
+ * Enqueue the block's assets for the gutenberg editor.
611
+ */
612
+ function gutenberg_assets() {
613
+ global $gmGallery, $gmDB, $gmCore;
614
+
615
+ wp_enqueue_style( 'gmedia-block-editor', $gmCore->gmedia_url . '/admin/assets/css/gmedia-block.css', array(), $gmGallery->version );
616
+ wp_register_script(
617
+ 'gmedia-block-editor',
618
+ $gmCore->gmedia_url . '/admin/assets/js/gmedia-block.js',
619
+ array( 'wp-blocks', 'wp-element' ),
620
+ $gmGallery->version
621
+ );
622
+
623
+ $default_module = $gmGallery->options['default_gmedia_module'];
624
+ $default_preset = $gmCore->getModulePreset( $default_module );
625
+ $default_module = $default_preset['module'];
626
+
627
+ $modules_data = get_gmedia_modules( false );
628
+ $modules = array();
629
+ $modules_options = array();
630
+ if ( ! empty( $modules_data['in'] ) ) {
631
+ foreach ( $modules_data['in'] as $module_name => $module_data ) {
632
+
633
+ $presets = $gmDB->get_terms( 'gmedia_module', array( 'status' => $module_name ) );
634
+ $option = array();
635
+ $option[ $module_name ] = $module_data['title'] . ' - ' . __( 'Default Settings' );
636
+ foreach ( $presets as $preset ) {
637
+ if ( ! (int) $preset->global && '[' . $module_name . ']' === $preset->name ) {
638
+ continue;
639
+ }
640
+ $by_author = '';
641
+ if ( (int) $preset->global ) {
642
+ $display_name = get_the_author_meta( 'display_name', $preset->global );
643
+ $by_author = $display_name ? ' [' . $display_name . ']' : '';
644
+ }
645
+ if ( '[' . $module_name . ']' === $preset->name ) {
646
+ $option[ $preset->term_id ] = $module_data['title'] . $by_author . ' - ' . __( 'Default Settings' );
647
+ } else {
648
+ $preset_name = str_replace( '[' . $module_name . '] ', '', $preset->name );
649
+ $option[ $preset->term_id ] = $module_data['title'] . $by_author . ' - ' . $preset_name;
650
+ }
651
+ }
652
+ $modules_options[ $module_name ] = array( 'title' => $module_data['title'], 'options' => $option );
653
+
654
+ $modules[ $module_name ] = array(
655
+ 'name' => $module_data['title'],
656
+ 'screenshot' => $module_data['module_url'] . '/screenshot.png',
657
+ );
658
+ }
659
+ }
660
+
661
+ $gm_galleries = array();
662
+ $gm_albums = array();
663
+ $gm_categories = array();
664
+ $gm_tags = array();
665
+
666
+ $gm_terms = $gmDB->get_terms( 'gmedia_gallery' );
667
+ if ( count( $gm_terms ) ) {
668
+ foreach ( $gm_terms as $_term ) {
669
+ unset( $_term->description );
670
+ unset( $_term->taxonomy );
671
+ $_term->module_name = $gmDB->get_metadata( 'gmedia_term', $_term->term_id, '_module', true );
672
+ if ( $_term->global ) {
673
+ $display_name = sprintf( __( 'by %s', 'grand-media' ), get_the_author_meta( 'display_name', $_term->global ) );
674
+ $_term->name .= 'by ' === $display_name ? '' : ' ' . $display_name;
675
+ }
676
+ if ( $_term->status && 'publish' !== $_term->status ) {
677
+ $_term->name .= " [{$_term->status}]";
678
+ }
679
+ $gm_galleries[ $_term->term_id ] = $_term;
680
+ }
681
+ }
682
+ $gm_galleries = array(
683
+ 0 => array(
684
+ 'term_id' => 0,
685
+ 'name' => __( ' - select gallery - ', 'grand-media' ),
686
+ ),
687
+ ) + $gm_galleries;
688
+
689
+ $gm_terms = $gmDB->get_terms( 'gmedia_album' );
690
+ if ( count( $gm_terms ) ) {
691
+ foreach ( $gm_terms as $_term ) {
692
+ unset( $_term->description );
693
+ unset( $_term->taxonomy );
694
+ $module_preset = $gmDB->get_metadata( 'gmedia_term', $_term->term_id, '_module_preset', true );
695
+ if ( $module_preset ) {
696
+ $preset = $gmCore->getModulePreset( $module_preset );
697
+ $_term->module_name = $preset['module'];
698
+ } else {
699
+ $_term->module_name = '';
700
+ }
701
+ if ( $_term->global ) {
702
+ $display_name = sprintf( __( 'by %s', 'grand-media' ), get_the_author_meta( 'display_name', $_term->global ) );
703
+ $_term->name .= 'by ' === $display_name ? '' : ' ' . $display_name;
704
+ }
705
+ if ( $_term->status && 'publish' !== $_term->status ) {
706
+ $_term->name .= " [{$_term->status}]";
707
+ }
708
+ $_term->name .= " ({$_term->count})";
709
+ $gm_albums[ $_term->term_id ] = $_term;
710
+ }
711
+ }
712
+ $gm_albums = array(
713
+ 0 => array(
714
+ 'term_id' => 0,
715
+ 'name' => __( ' - select album - ', 'grand-media' ),
716
+ ),
717
+ ) + $gm_albums;
718
+
719
+ $gm_terms = $gmDB->get_terms( 'gmedia_category' );
720
+ if ( count( $gm_terms ) ) {
721
+ foreach ( $gm_terms as $_term ) {
722
+ unset( $_term->description );
723
+ unset( $_term->taxonomy );
724
+ unset( $_term->global );
725
+ unset( $_term->status );
726
+ $_term->name .= " ({$_term->count})";
727
+ $gm_categories[ $_term->term_id ] = $_term;
728
+ }
729
+ }
730
+ $gm_categories = array(
731
+ 0 => array(
732
+ 'term_id' => 0,
733
+ 'name' => __( ' - select category - ', 'grand-media' ),
734
+ ),
735
+ ) + $gm_categories;
736
+
737
+ $gm_terms = $gmDB->get_terms( 'gmedia_tag' );
738
+ if ( count( $gm_terms ) ) {
739
+ foreach ( $gm_terms as $_term ) {
740
+ unset( $_term->description );
741
+ unset( $_term->taxonomy );
742
+ unset( $_term->global );
743
+ unset( $_term->status );
744
+ $_term->name .= " ({$_term->count})";
745
+ $gm_tags[ $_term->term_id ] = $_term;
746
+ }
747
+ }
748
+ $gm_tags = array(
749
+ 0 => array(
750
+ 'term_id' => 0,
751
+ 'name' => __( ' - select tag - ', 'grand-media' ),
752
+ ),
753
+ ) + $gm_tags;
754
+
755
+ $data = array(
756
+ 'modules' => $modules,
757
+ 'default_module' => $default_module,
758
+ 'modules_options' => $modules_options,
759
+ 'gmedia_image' => $gmCore->gmedia_url . '/admin/assets/img/gmedia-icon-320x240.png',
760
+ 'galleries' => $gm_galleries,
761
+ 'albums' => $gm_albums,
762
+ 'categories' => $gm_categories,
763
+ 'tags' => $gm_tags,
764
+ );
765
+
766
+ wp_localize_script( 'gmedia-block-editor', 'gmedia_data', $data );
767
+ wp_enqueue_script( 'gmedia-block-editor' );
768
+ }
769
+
770
+ function screen_help() {
771
+ $screen = get_current_screen();
772
+ $screen_id = explode( 'page_', $screen->id, 2 );
773
+ $screen_id = $screen_id[1];
774
+
775
+ $screen->add_help_tab( array(
776
+ 'id' => 'help_' . $screen_id . '_support',
777
+ 'title' => __( 'Support' ),
778
+ 'content' => __( '<h4>First steps</h4>
779
+ <p>If you have any problems with displaying Gmedia Gallery in admin or on website. Before posting to the Forum try next:</p>
780
+ <ul>
781
+ <li>Exclude plugin conflicts: Disable other plugins one by one and check if it resolve problem</li>
782
+ <li>Exclude theme conflict: Temporary switch to one of default themes and check if gallery works</li>
783
+ </ul>
784
+ <h4>Links</h4>', 'grand-media' )
785
+ . '<p><a href="https://codeasily.com/community/forum/gmedia-gallery-wordpress-plugin/" target="_blank">' . __( 'Support Forum', 'grand-media' ) . '</a>
786
+ | <a href="https://codeasily.com/contact/" target="_blank">' . __( 'Contact', 'grand-media' ) . '</a>
787
+ | <a href="https://codeasily.com/portfolio/gmedia-gallery-modules/" target="_blank">' . __( 'Demo', 'grand-media' ) . '</a>
788
+ | <a href="https://codeasily.com/product/one-site-license/" target="_blank">' . __( 'Premium', 'grand-media' ) . '</a>
789
+ </p>',
790
+ ) );
791
+
792
+ switch ( $screen_id ) {
793
+ case 'GrandMedia' :
794
+ break;
795
+ case 'GrandMedia_Settings' :
796
+ if ( current_user_can( 'manage_options' ) ) {
797
+ $screen->add_help_tab( array(
798
+ 'id' => 'help_' . $screen_id . '_license',
799
+ 'title' => __( 'License Key' ),
800
+ 'content' => sprintf( __( '<h4>Should I buy it, to use plugin?</h4>
801
+ <p>No, plugin is absolutely free and all modules for it are free to install.</p>
802
+ <p>Even premium modules are fully functional and free to test, but have backlink labels. To remove baclink labels from premium modules you need license key.</p>
803
+ <p>Note: License Key will remove backlinks from all current and future premium modules, so you can use all available modules on one website.</p>
804
+ <p>Do not purchase license key before testing module you like. Only if everything works fine and you satisfied with functionality you are good to purchase license. Otherwise use <a href="%1$s" target="_blank">Gmedia Support Forum</a>.</p>
805
+ <h4>I have license key but I can\'t activate it</h4>
806
+ <p>Contact developer <a href="mailto:%2$s">%2$s</a> with your problem and wait for additional instructions and code for manual activation</p>', 'grand-media' ), 'https://codeasily.com/community/forum/gmedia-gallery-wordpress-plugin/', 'gmediafolder@gmail.com' )
807
+ . '<div><a class="btn btn-default" href="' . admin_url( 'admin.php?page=' . $screen_id . '&license_activate=manual' ) . '">' . __( 'Manual Activation', 'grand-media' ) . '</a></div>',
808
+ ) );
809
+ }
810
+ break;
811
+ case 'GrandMedia_App' :
812
+ $gm_options = get_option( 'gmediaOptions' );
813
+ $nonce = wp_create_nonce( 'GmediaService' );
814
+ if ( current_user_can( 'manage_options' ) && (int) $gm_options['mobile_app'] ) {
815
+ $screen->add_help_tab( array(
816
+ 'id' => 'help_' . $screen_id . '_optout',
817
+ 'title' => __( 'Opt Out' ),
818
+ 'content' => __( '<h4>We appreciate your help in making the plugin better by letting us track some usage data.</h4>
819
+ <p>Usage tracking is done in the name of making <strong>Gmedia Gallery</strong> better. Making a better user experience, prioritizing new features, and more good things.</p>
820
+ <p>By clicking "Opt Out", we will no longer be sending any data from <strong>Gmedia Gallery</strong> to <a href="https://codeasily.com" target="_blank">codeasily.com</a>.</p>
821
+ <p>You\'ll also not be able to use Gmedia iOS application.</p>', 'grand-media' )
822
+ . '<p><button class="button button-default gm_service_action" data-action="app_deactivate" data-nonce="' . $nonce . '">' . __( 'Opt Out', 'grand-media' ) . '</button><span class="spinner" style="float: none;"></span></p>'
823
+ . '<div style="display:none;">Test:
824
+ <button type="button" data-action="app_updateinfo" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Update</button>
825
+ <button type="button" data-action="app_updatecron" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">CronJob</button> &nbsp;&nbsp;
826
+ <button type="button" data-action="app_deactivateplugin" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Deactivate Plugin</button>
827
+ <button type="button" data-action="app_uninstallplugin" data-nonce="' . $nonce . '" class="btn btn-sm btn-primary gm_service_action">Uninstall Plugin</button>
828
+ </div>
829
+ ',
830
+ ) );
831
+ }
832
+ break;
833
+ }
834
+ }
835
+
836
+ /**
837
+ * @param $current
838
+ * @param $screen
839
+ *
840
+ * @return string
841
+ */
842
+ function screen_settings( $current, $screen ) {
843
+ global $gmProcessor, $gmCore;
844
+ if ( in_array( $screen->id, $this->pages ) ) {
845
+
846
+ $gm_screen_options = $gmProcessor->user_options;
847
+
848
+ $title = '<h5><strong>' . __( 'Settings', 'grand-media' ) . '</strong></h5>';
849
+ $wp_screen_options = '<input type="hidden" name="wp_screen_options[option]" value="gm_screen_options" /><input type="hidden" name="wp_screen_options[value]" value="' . $screen->id . '" />';
850
+ $button = get_submit_button( __( 'Apply', 'grand-media' ), 'button', 'screen-options-apply', false );
851
+
852
+ $settings = false;
853
+
854
+ $screen_id = explode( 'page_', $screen->id, 2 );
855
+
856
+ switch ( $screen_id[1] ) {
857
+ case 'GrandMedia' :
858
+ $settings = '
859
+ <div class="form-inline pull-left">
860
+ <div class="form-group">
861
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
862
+ </div>
863
+ <div class="form-group">
864
+ <select name="gm_screen_options[orderby_gmedia]" class="form-control input-sm">
865
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'ID', false ) . ' value="ID">' . __( 'ID', 'grand-media' ) . '</option>
866
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'title', false ) . ' value="title">' . __( 'Title', 'grand-media' ) . '</option>
867
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'gmuid', false ) . ' value="gmuid">' . __( 'Filename', 'grand-media' ) . '</option>
868
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'mime_type', false ) . ' value="mime_type">' . __( 'MIME Type', 'grand-media' ) . '</option>
869
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'author', false ) . ' value="author">' . __( 'Author', 'grand-media' ) . '</option>
870
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'date', false ) . ' value="date">' . __( 'Date', 'grand-media' ) . '</option>
871
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'modified', false ) . ' value="modified">' . __( 'Last Modified', 'grand-media' ) . '</option>
872
+ <option' . selected( $gm_screen_options['orderby_gmedia'], '_created_timestamp', false ) . ' value="_created_timestamp">' . __( 'Created Timestamp', 'grand-media' ) . '</option>
873
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'comment_count', false ) . ' value="comment_count">' . __( 'Comment Count', 'grand-media' ) . '</option>
874
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'views', false ) . ' value="views">' . __( 'Views Count', 'grand-media' ) . '</option>
875
+ <option' . selected( $gm_screen_options['orderby_gmedia'], 'likes', false ) . ' value="likes">' . __( 'Likes Count', 'grand-media' ) . '</option>
876
+ <option' . selected( $gm_screen_options['orderby_gmedia'], '_size', false ) . ' value="_size">' . __( 'File Size', 'grand-media' ) . '</option>
877
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
878
+ </div>
879
+ <div class="form-group">
880
+ <select name="gm_screen_options[sortorder_gmedia]" class="form-control input-sm">
881
+ <option' . selected( $gm_screen_options['sortorder_gmedia'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
882
+ <option' . selected( $gm_screen_options['sortorder_gmedia'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
883
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
884
+ </div>
885
+ ';
886
+ if ( 'edit' == $gmCore->_get( 'mode' ) ) {
887
+ $settings .= '
888
+ <div class="form-group">
889
+ <select name="gm_screen_options[library_edit_quicktags]" class="form-control input-sm">
890
+ <option' . selected( $gm_screen_options['library_edit_quicktags'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
891
+ <option' . selected( $gm_screen_options['library_edit_quicktags'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
892
+ </select> <span>' . __( 'Quick Tags panel for Description field', 'grand-media' ) . '</span>
893
+ </div>
894
+ ';
895
+ }
896
+ $settings .= '
897
+ </div>
898
+ ';
899
+ break;
900
+ case 'GrandMedia_AddMedia' :
901
+ $tab = $gmCore->_get( 'tab', 'upload' );
902
+ if ( 'upload' == $tab ) {
903
+ $html4_hide = ( 'html4' == $gm_screen_options['uploader_runtime'] ) ? ' hide' : '';
904
+ $settings = '
905
+ <div class="form-inline pull-left">
906
+ <div id="uploader_runtime" class="form-group"><span>' . __( 'Uploader runtime:', 'grand-media' ) . ' </span>
907
+ <select name="gm_screen_options[uploader_runtime]" class="form-control input-sm">
908
+ <option' . selected( $gm_screen_options['uploader_runtime'], 'auto', false ) . ' value="auto">' . __( 'Auto', 'grand-media' ) . '</option>
909
+ <option' . selected( $gm_screen_options['uploader_runtime'], 'html5', false ) . ' value="html5">' . __( 'HTML5 Uploader', 'grand-media' ) . '</option>
910
+ <option' . selected( $gm_screen_options['uploader_runtime'], 'flash', false ) . ' value="flash">' . __( 'Flash Uploader', 'grand-media' ) . '</option>
911
+ <option' . selected( $gm_screen_options['uploader_runtime'], 'html4', false ) . ' value="html4">' . __( 'HTML4 Uploader', 'grand-media' ) . '</option>
912
+ </select>
913
+ </div>
914
+ <div id="uploader_chunking" class="form-group' . $html4_hide . '"><span>' . __( 'Chunking:', 'grand-media' ) . ' </span>
915
+ <select name="gm_screen_options[uploader_chunking]" class="form-control input-sm">
916
+ <option' . selected( $gm_screen_options['uploader_chunking'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
917
+ <option' . selected( $gm_screen_options['uploader_chunking'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
918
+ </select>
919
+ </div>
920
+ <div id="uploader_urlstream_upload" class="form-group' . $html4_hide . '"><span>' . __( 'URL streem upload:', 'grand-media' ) . ' </span>
921
+ <select name="gm_screen_options[uploader_urlstream_upload]" class="form-control input-sm">
922
+ <option' . selected( $gm_screen_options['uploader_urlstream_upload'], 'true', false ) . ' value="true">' . __( 'TRUE', 'grand-media' ) . '</option>
923
+ <option' . selected( $gm_screen_options['uploader_urlstream_upload'], 'false', false ) . ' value="false">' . __( 'FALSE', 'grand-media' ) . '</option>
924
+ </select>
925
+ </div>
926
+ </div>
927
+ ';
928
+ }
929
+ break;
930
+ case 'GrandMedia_Albums' :
931
+ if ( isset( $_GET['edit_term'] ) ) {
932
+ $settings = '
933
+ <div class="form-inline pull-left">
934
+ <div class="form-group">
935
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_album_edit]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_album_edit'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
936
+ </div>
937
+ </div>
938
+ ';
939
+ } else {
940
+ $settings = '
941
+ <div class="form-inline pull-left">
942
+ <div class="form-group">
943
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_album]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_album'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
944
+ </div>
945
+ <div class="form-group">
946
+ <select name="gm_screen_options[orderby_gmedia_album]" class="form-control input-sm">
947
+ <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
948
+ <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
949
+ <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
950
+ <option' . selected( $gm_screen_options['orderby_gmedia_album'], 'global', false ) . ' value="global">' . __( 'Author ID', 'grand-media' ) . '</option>
951
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
952
+ </div>
953
+ <div class="form-group">
954
+ <select name="gm_screen_options[sortorder_gmedia_album]" class="form-control input-sm">
955
+ <option' . selected( $gm_screen_options['sortorder_gmedia_album'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
956
+ <option' . selected( $gm_screen_options['sortorder_gmedia_album'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
957
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
958
+ </div>
959
+ </div>
960
+ ';
961
+ }
962
+ break;
963
+ case 'GrandMedia_Categories' :
964
+ if ( isset( $_GET['edit_term'] ) ) {
965
+ $settings = '
966
+ <div class="form-inline pull-left">
967
+ <div class="form-group">
968
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_category_edit]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_category_edit'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
969
+ </div>
970
+ </div>
971
+ ';
972
+ } else {
973
+ $settings = '
974
+ <div class="form-inline pull-left">
975
+ <div class="form-group">
976
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_category]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_category'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
977
+ </div>
978
+ <div class="form-group">
979
+ <select name="gm_screen_options[orderby_gmedia_category]" class="form-control input-sm">
980
+ <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
981
+ <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
982
+ <option' . selected( $gm_screen_options['orderby_gmedia_category'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
983
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
984
+ </div>
985
+ <div class="form-group">
986
+ <select name="gm_screen_options[sortorder_gmedia_category]" class="form-control input-sm">
987
+ <option' . selected( $gm_screen_options['sortorder_gmedia_category'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
988
+ <option' . selected( $gm_screen_options['sortorder_gmedia_category'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
989
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
990
+ </div>
991
+ </div>
992
+ ';
993
+ }
994
+ break;
995
+ case 'GrandMedia_Tags' :
996
+ $settings = '
997
+ <div class="form-inline pull-left">
998
+ <div class="form-group">
999
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_tag]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_tag'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1000
+ </div>
1001
+ <div class="form-group">
1002
+ <select name="gm_screen_options[orderby_gmedia_tag]" class="form-control input-sm">
1003
+ <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
1004
+ <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
1005
+ <option' . selected( $gm_screen_options['orderby_gmedia_tag'], 'count', false ) . ' value="count">' . __( 'Gmedia Count', 'grand-media' ) . '</option>
1006
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1007
+ </div>
1008
+ <div class="form-group">
1009
+ <select name="gm_screen_options[sortorder_gmedia_tag]" class="form-control input-sm">
1010
+ <option' . selected( $gm_screen_options['sortorder_gmedia_tag'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1011
+ <option' . selected( $gm_screen_options['sortorder_gmedia_tag'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1012
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1013
+ </div>
1014
+ </div>
1015
+ ';
1016
+ break;
1017
+ case 'GrandMedia_Galleries' :
1018
+ if ( ! $gmCore->_get( 'edit_term' ) && ! $gmCore->_get( 'gallery_module' ) ) {
1019
+ $settings = '
1020
+ <div class="form-inline pull-left">
1021
+ <div class="form-group">
1022
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_gallery]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_gallery'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1023
+ </div>
1024
+ <div class="form-group">
1025
+ <select name="gm_screen_options[orderby_gmedia_gallery]" class="form-control input-sm">
1026
+ <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'id', false ) . ' value="id">' . __( 'ID', 'grand-media' ) . '</option>
1027
+ <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'name', false ) . ' value="name">' . __( 'Name', 'grand-media' ) . '</option>
1028
+ <option' . selected( $gm_screen_options['orderby_gmedia_gallery'], 'global', false ) . ' value="global">' . __( 'Author ID', 'grand-media' ) . '</option>
1029
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1030
+ </div>
1031
+ <div class="form-group">
1032
+ <select name="gm_screen_options[sortorder_gmedia_gallery]" class="form-control input-sm">
1033
+ <option' . selected( $gm_screen_options['sortorder_gmedia_gallery'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1034
+ <option' . selected( $gm_screen_options['sortorder_gmedia_gallery'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1035
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1036
+ </div>
1037
+ </div>
1038
+ ';
1039
+ }
1040
+ break;
1041
+ case 'GrandMedia_WordpressLibrary' :
1042
+ $settings = '<p>' . __( 'Set query options for this page to be loaded by default.', 'grand-media' ) . '</p>
1043
+ <div class="form-inline pull-left">
1044
+ <div class="form-group">
1045
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_wpmedia]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_wpmedia'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1046
+ </div>
1047
+ <div class="form-group">
1048
+ <select name="gm_screen_options[orderby_wpmedia]" class="form-control input-sm">
1049
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'ID', false ) . ' value="ID">' . __( 'ID', 'grand-media' ) . '</option>
1050
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'title', false ) . ' value="title">' . __( 'Title', 'grand-media' ) . '</option>
1051
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'filename', false ) . ' value="filename">' . __( 'Filename', 'grand-media' ) . '</option>
1052
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'date', false ) . ' value="date">' . __( 'Date', 'grand-media' ) . '</option>
1053
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'modified', false ) . ' value="modified">' . __( 'Last Modified', 'grand-media' ) . '</option>
1054
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'mime_type', false ) . ' value="mime_type">' . __( 'MIME Type', 'grand-media' ) . '</option>
1055
+ <option' . selected( $gm_screen_options['orderby_wpmedia'], 'author', false ) . ' value="author">' . __( 'Author', 'grand-media' ) . '</option>
1056
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1057
+ </div>
1058
+ <div class="form-group">
1059
+ <select name="gm_screen_options[sortorder_wpmedia]" class="form-control input-sm">
1060
+ <option' . selected( $gm_screen_options['sortorder_wpmedia'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1061
+ <option' . selected( $gm_screen_options['sortorder_wpmedia'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1062
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1063
+ </div>
1064
+ </div>
1065
+ ';
1066
+ break;
1067
+ case 'GrandMedia_Logs' :
1068
+ $settings = '
1069
+ <div class="form-inline pull-left">
1070
+ <div class="form-group">
1071
+ <input type="number" max="999" min="0" step="5" size="3" name="gm_screen_options[per_page_gmedia_log]" class="form-control input-sm" style="width: 5em;" value="' . $gm_screen_options['per_page_gmedia_log'] . '" /> <span>' . __( 'items per page', 'grand-media' ) . '</span>
1072
+ </div>
1073
+ <div class="form-group">
1074
+ <select name="gm_screen_options[orderby_gmedia_log]" class="form-control input-sm">
1075
+ <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'log_date', false ) . ' value="log_date">' . __( 'Date', 'grand-media' ) . '</option>
1076
+ <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'ID', false ) . ' value="ID">' . __( 'Gmedia ID', 'grand-media' ) . '</option>
1077
+ <option' . selected( $gm_screen_options['orderby_gmedia_log'], 'author', false ) . ' value="author">' . __( 'Author ID', 'grand-media' ) . '</option>
1078
+ </select> <span>' . __( 'order items', 'grand-media' ) . '</span>
1079
+ </div>
1080
+ <div class="form-group">
1081
+ <select name="gm_screen_options[sortorder_gmedia_log]" class="form-control input-sm">
1082
+ <option' . selected( $gm_screen_options['sortorder_gmedia_log'], 'DESC', false ) . ' value="DESC">' . __( 'DESC', 'grand-media' ) . '</option>
1083
+ <option' . selected( $gm_screen_options['sortorder_gmedia_log'], 'ASC', false ) . ' value="ASC">' . __( 'ASC', 'grand-media' ) . '</option>
1084
+ </select> <span>' . __( 'sort order', 'grand-media' ) . '</span>
1085
+ </div>
1086
+ </div>
1087
+ ';
1088
+ break;
1089
+ }
1090
+
1091
+ if ( $settings ) {
1092
+ $current = $title . $settings . $wp_screen_options . $button;
1093
+ }
1094
+
1095
+ }
1096
+
1097
+ return $current;
1098
+ }
1099
+
1100
+ /**
1101
+ * @param $status
1102
+ * @param $option
1103
+ * @param $value
1104
+ *
1105
+ * @return array
1106
+ */
1107
+ function screen_settings_save( $status, $option, $value ) {
1108
+ global $user_ID;
1109
+ if ( 'gm_screen_options' == $option ) {
1110
+ /*
1111
+ global $gmGallery;
1112
+ foreach ( $_POST['gm_screen_options'] as $key => $val ) {
1113
+ $gmGallery->options['gm_screen_options'][$key] = $val;
1114
+ }
1115
+ update_option( 'gmediaOptions', $gmGallery->options );
1116
+ */
1117
+ $gm_screen_options = get_user_meta( $user_ID, 'gm_screen_options', true );
1118
+ if ( ! is_array( $gm_screen_options ) ) {
1119
+ $gm_screen_options = array();
1120
+ }
1121
+ $value = array_merge( $gm_screen_options, $_POST['gm_screen_options'] );
1122
+
1123
+ return $value;
1124
+ }
1125
+
1126
+ return $status;
1127
+ }
1128
+
1129
+ }
1130
+
1131
+ global $gmAdmin;
1132
+ // Start GmediaAdmin
1133
+ $gmAdmin = new GmediaAdmin();
admin/assets/js/gmedia.admin.js CHANGED
@@ -1,1777 +1,1778 @@
1
- /**
2
- * Gmedia Library
3
- */
4
- var gmedia_DOM;
5
- var GmediaLibrary = {
6
- init: function() {
7
- window.gm_wavesurfer = {};
8
- if(jQuery('.gmedia-audio-item').length) {
9
-
10
- jQuery('.gm-waveform-player').each(function() {
11
- var data = jQuery(this).data();
12
- data.gmid = data.id;
13
- data.id = 'ws' + data.gmid;
14
-
15
- if(data.peaks){
16
- jQuery('.gm-play', this).show();
17
- jQuery('.gm-pause', this).hide();
18
-
19
- GmediaLibrary.waveplayer(data, true);
20
- }
21
- });
22
- gmedia_DOM.on('click', '.gm-waveform', function() {
23
- var parent = jQuery(this).parent(),
24
- data = parent.data();
25
-
26
- jQuery(this).remove();
27
-
28
- GmediaLibrary.waveplayer(data);
29
-
30
- if(data.peaks) {
31
- //window.gm_wavesurfer[data.id].play();
32
- } else {
33
- window.gm_wavesurfer[data.id].on('waveform-ready', function() {
34
- jQuery('.gm-play', parent).hide();
35
- jQuery('.gm-pause', parent).show();
36
- jQuery('.spinner', parent).removeClass('is-active');
37
- var peaks = window.gm_wavesurfer[data.id].exportPCM(1800, 10000, true);
38
- var post_data = {
39
- action: 'gmedia_save_waveform',
40
- id: data.gmid,
41
- peaks: peaks,
42
- _wpnonce: jQuery('#_wpnonce').val()
43
- };
44
- jQuery.post(ajaxurl, post_data, function(return_data, textStatus, jqXHR) {
45
- var data_peaks = window.gm_wavesurfer[data.id].exportPCM(450, 10000, true);
46
- parent.attr('data-peaks', data_peaks);
47
- });
48
- });
49
- }
50
- });
51
- gmedia_DOM.on('click', '.gm-play, .gm-pause', function() {
52
- var parent = jQuery(this).parent();
53
- var data = parent.data();
54
- if(!parent.hasClass('ws-loaded')) {
55
- parent.addClass('ws-loaded');
56
- window.gm_wavesurfer[data.id].load(data.file, data.peaks);
57
- window.gm_wavesurfer[data.id].toggleInteraction();
58
- window.gm_wavesurfer[data.id].play();
59
- } else {
60
- window.gm_wavesurfer[data.id].playPause();
61
- }
62
- });
63
-
64
- var resize;
65
- jQuery(window).on('resize.gmedia', function(){
66
- clearTimeout(resize);
67
- resize = setTimeout(function(){
68
- jQuery('.gm-waveform-player').each(function() {
69
- var data = jQuery(this).data();
70
- if(data.peaks && window.gm_wavesurfer[data.id]){
71
- window.gm_wavesurfer[data.id].load(data.file, data.peaks);
72
- }
73
- });
74
- }, 500);
75
- });
76
-
77
- }
78
-
79
- if(jQuery('body').hasClass('GrandMedia_edit')) {
80
- GmediaLibrary.editmode();
81
- }
82
-
83
- if(jQuery('body').hasClass('gmedia_library')) {
84
- var previewFrame = jQuery('#previewFrame', window.parent.document);
85
- jQuery(window).on('load.gmedia', function(){
86
- setTimeout(function(){
87
- previewFrame.animate({'height': getDocHeight('gmedia_iframe_content') + 3}, 200);
88
- }, 10);
89
- });
90
- var refresh = !jQuery('body').is('.GrandMedia_select_single, .GrandMedia_select_multiple');
91
- var observer = new MutationObserver(function(mutations) {
92
- previewFrame.height(getDocHeight('gmedia_iframe_content') + 3);
93
- if(refresh) {
94
- jQuery('#previewModal', window.parent.document).attr('data-refresh', 'true');
95
- }
96
- });
97
- var gmedia_iframe_content = window.document.getElementById('gmedia_iframe_content');
98
- observer.observe(gmedia_iframe_content, {
99
- childList: true,
100
- subtree: true,
101
- attributes: true,
102
- attributeFilter: ['value']
103
- });
104
- }
105
-
106
- },
107
- waveplayer: function(data, draw) {
108
- window.gm_wavesurfer[data.id] = Object.create(WaveSurfer);
109
- window.gm_wavesurfer[data.id].init({
110
- container: '#' + data.id,
111
- waveColor: '#428bca',
112
- progressColor: '#31708f',
113
- backend: 'MediaElement',
114
- renderer: 'Canvas',
115
- height: 60,
116
- interact: false,
117
- barWidth: 0
118
- });
119
- // Play on audio load
120
- var parent = jQuery(window.gm_wavesurfer[data.id].container).parent();
121
-
122
- if(!parent.hasClass('ws-loaded')) {
123
- if(draw) {
124
- window.gm_wavesurfer[data.id].backend.setPeaks(data.peaks);
125
- window.gm_wavesurfer[data.id].drawBuffer();
126
- } else {
127
- parent.addClass('ws-loaded');
128
- window.gm_wavesurfer[data.id].load(data.file, data.peaks);
129
- window.gm_wavesurfer[data.id].toggleInteraction();
130
- window.gm_wavesurfer[data.id].play();
131
- }
132
- } else {
133
- window.gm_wavesurfer[data.id].play();
134
- }
135
-
136
- jQuery(window.gm_wavesurfer[data.id].container).on('click', function(e) {
137
- if(!parent.hasClass('ws-loaded')) {
138
- parent.addClass('ws-loaded');
139
- window.gm_wavesurfer[data.id].load(data.file, data.peaks);
140
- window.gm_wavesurfer[data.id].toggleInteraction();
141
- window.gm_wavesurfer[data.id].play();
142
- }
143
- if(window.gm_wavesurfer[data.id].isPlaying()) {
144
- window.gm_wavesurfer[data.id].backend.media.currentTime = 0;
145
- } else{
146
- window.gm_wavesurfer[data.id].play();
147
- }
148
- });
149
-
150
- window.gm_wavesurfer[data.id].on('play', function() {
151
- parent.find('.gm-play').hide();
152
- parent.find('.gm-pause').show();
153
- parent.find('.spinner').removeClass('is-active');
154
-
155
- jQuery.each(window.gm_wavesurfer, function(id) {
156
- if(id !== data.id && window.gm_wavesurfer[id].isPlaying()) {
157
- window.gm_wavesurfer[id].pause();
158
- }
159
- });
160
- })
161
- window.gm_wavesurfer[data.id].on('pause', function() {
162
- parent.find('.gm-play').show();
163
- parent.find('.gm-pause').hide();
164
- });
165
- window.gm_wavesurfer[data.id].on('loading', function(p) {
166
- if(p == 100) {
167
- //parent.find('.spinner').removeClass('is-active');
168
- } else {
169
- parent.find('.spinner').addClass('is-active');
170
- }
171
- });
172
- },
173
- /**
174
- * Edit Mode
175
- */
176
- editmode: function() {
177
- var focus_input_val;
178
- // SelectBox for albums
179
- var combobox_albums = jQuery('.combobox_gmedia_album');
180
- var selectize_albums = combobox_albums.selectize({
181
- create: (combobox_albums.data('create')? true : false),
182
- onOptionAdd: function(value, data){
183
- jQuery.each(selectize_albums, function(i, e){
184
- e.selectize.options[value] = data;
185
- });
186
- },
187
- onFocus: function(){
188
- this.$input.addClass('edit-gmedia-ignore');
189
- focus_input_val = this.$input.val();
190
- },
191
- onBlur: function(){
192
- this.$input.removeClass('edit-gmedia-ignore');
193
- if(focus_input_val != this.$input.val()) {
194
- var inporder = this.$input.prev('.gm-order-input');
195
- inporder.val('0');
196
- if('' == this.$input.val()){
197
- inporder.prop('disabled', true);
198
- } else {
199
- inporder.prop('disabled', false);
200
- }
201
- this.$input.trigger('change');
202
- }
203
- },
204
- persist: true
205
- });
206
-
207
- if(window.gmedia_categories) {
208
- var categories = jQuery('.combobox_gmedia_category');
209
- if(categories.length) {
210
- var categories_data = window.gmedia_categories.map(function(x) {
211
- return {item: x};
212
- });
213
-
214
- var selectize_categories = categories.selectize({
215
- create: function(input) {
216
- if(categories.data('create')) {
217
- return {
218
- item: input
219
- }
220
- } else {
221
- return false;
222
- }
223
- },
224
- onOptionAdd: function(value, data){
225
- jQuery.each(selectize_categories, function(i, e){
226
- e.selectize.options[value] = data;
227
- });
228
- },
229
- onFocus: function(){
230
- this.$input.addClass('edit-gmedia-ignore');
231
- focus_input_val = this.$input.val();
232
- },
233
- onBlur: function(){
234
- this.$input.removeClass('edit-gmedia-ignore');
235
- if(focus_input_val != this.$input.val()) {
236
- this.$input.trigger('change');
237
- }
238
- },
239
- createOnBlur: true,
240
- delimiter: ',',
241
- maxItems: null,
242
- openOnFocus: true,
243
- persist: true,
244
- options: categories_data,
245
- labelField: 'item',
246
- valueField: 'item',
247
- searchField: ['item'],
248
- hideSelected: true
249
- });
250
- }
251
- }
252
- if(window.gmedia_tags) {
253
- var tags = jQuery('.combobox_gmedia_tag');
254
- if(tags.length) {
255
- var tags_data = window.gmedia_tags.map(function(x) {
256
- return {item: x};
257
- });
258
-
259
- var selectize_tags = tags.selectize({
260
- create: function(input) {
261
- if(this.$input.data('create')) {
262
- var option = { item: input }
263
- tags_data.push(option);
264
- return option;
265
- } else {
266
- return false;
267
- }
268
- },
269
- onOptionAdd: function(value, data){
270
- jQuery.each(selectize_tags, function(i, e){
271
- e.selectize.options[value] = data;
272
- });
273
- },
274
- onFocus: function(){
275
- this.$input.addClass('edit-gmedia-ignore');
276
- focus_input_val = this.$input.val();
277
- },
278
- onBlur: function(){
279
- this.$input.removeClass('edit-gmedia-ignore');
280
- if(focus_input_val != this.$input.val()) {
281
- this.$input.trigger('change');
282
- }
283
- },
284
- createOnBlur: true,
285
- delimiter: ',',
286
- maxItems: null,
287
- openOnFocus: true,
288
- persist: true,
289
- options: tags_data,
290
- labelField: 'item',
291
- valueField: 'item',
292
- searchField: ['item'],
293
- hideSelected: true
294
- });
295
-
296
- }
297
- }
298
-
299
- // Date/Time picker
300
- var gmedia_date_temp;
301
- jQuery('.input-group.gmedia_date').datetimepicker({format: 'YYYY-MM-DD HH:mm:ss', focusOnShow: true, ignoreReadonly: true, allowInputToggle: true}).on('dp.show', function() {
302
- gmedia_date_temp = jQuery('input', this).val();
303
- }).on('dp.hide', function() {
304
- if(jQuery('input', this).val() !== gmedia_date_temp) {
305
- jQuery('input', this).trigger('modified');
306
- }
307
- });
308
-
309
- // Mask for filename input
310
- var inp_filename = jQuery('input.gmedia-filename').not('[readonly]');
311
- if(inp_filename.length) {
312
- inp_filename.alphanum({
313
- allow: '-_',
314
- disallow: '',
315
- allowSpace: false,
316
- allowNumeric: true,
317
- allowUpper: true,
318
- allowLower: true,
319
- allowCaseless: true,
320
- allowLatin: true,
321
- allowOtherCharSets: false,
322
- forceUpper: false,
323
- forceLower: false,
324
- maxLength: NaN
325
- });
326
- }
327
-
328
- if(jQuery('#wp-link-wrap').parent().hasClass('hidden')){
329
- jQuery('#wp-link-backdrop, #wp-link-wrap').appendTo('body');
330
- }
331
- jQuery(document).on('click.gmedia', '.gmedia-custom-link', function(e) {
332
- var editorId = jQuery(this).attr('data-target');
333
- wpActiveEditor = true;
334
- wpLink.open(editorId);
335
- wpLink.gmediaCustomLinkTarget = editorId;
336
- jQuery('#wp-link-wrap').removeClass('has-text-field').addClass('gmLinkModal').find('.link-target').css('visibility','hidden');
337
-
338
- return false;
339
- });
340
- function closeLinkModal(){
341
- jQuery('#wp-link-wrap').removeClass('gmLinkModal').find('.link-target').removeAttr('style');
342
- wpLink.close();
343
- }
344
- jQuery(document).on('click.gmedia', '.gmLinkModal #wp-link-submit', function(e) {
345
- e.preventDefault ? e.preventDefault() : e.returnValue = false;
346
- e.stopPropagation();
347
-
348
- var link = wpLink.getAttrs();
349
- wpLink.textarea = jQuery('#' + wpLink.gmediaCustomLinkTarget);
350
-
351
- if (!link.href) {
352
- closeLinkModal();
353
- return;
354
- }
355
- wpLink.textarea.val(link.href).trigger('change');
356
- closeLinkModal();
357
- });
358
- jQuery(document).on('click.gmedia', '#wp-link-cancel, #wp-link-close, #wp-link-backdrop', function(e) {
359
- closeLinkModal()
360
- });
361
-
362
- var related_sortable = jQuery('.related-media-previews');
363
- if(related_sortable.length){
364
- related_sortable.sortable({
365
- items: '.gmedia-related-image',
366
- handle: '.image-wrapper',
367
- placeholder: 'gmedia-related-image',
368
- tolerance: 'pointer',
369
- //helper: 'clone',
370
- revert: true,
371
- forcePlaceholderSize: true,
372
- stop: function(event, ui){
373
- console.log(ui);
374
- ui.item.find('input').trigger('change');
375
- }
376
- });
377
- }
378
-
379
-
380
- }
381
- };
382
-
383
- /**
384
- * Gmedia AddMedia
385
- */
386
- var GmediaAddMedia = {
387
- init: function() {
388
-
389
- if(jQuery('body').hasClass('GrandMedia_AddMedia')) {
390
- gmedia_DOM.on('change', '#uploader_runtime select', function() {
391
- if('html4' == jQuery(this).val()) {
392
- jQuery('#uploader_chunking').addClass('hide');
393
- jQuery('#uploader_urlstream_upload').addClass('hide');
394
- } else {
395
- jQuery('#uploader_chunking').removeClass('hide');
396
- jQuery('#uploader_urlstream_upload').removeClass('hide');
397
- }
398
- });
399
- }
400
-
401
- var albums = jQuery('select#combobox_gmedia_album');
402
- if(albums.length) {
403
- var albums_data = jQuery('option', albums);
404
- albums.selectize({
405
- create: function(input) {
406
- if(albums.data('create')) {
407
- return {
408
- value: input,
409
- text: input
410
- }
411
- } else {
412
- return false;
413
- }
414
- },
415
- createOnBlur: true,
416
- persist: false,
417
- render: {
418
- item: function(item, escape) {
419
- if(0 === (parseInt(item.value, 10) || 0)) {
420
- return '<div>' + escape(item.text) + '</div>';
421
- }
422
- if(item.$order) {
423
- var data = jQuery(albums_data[item.$order]).data();
424
- return '<div>' + escape(data.name) + ' <small>' + escape(data.meta) + '</small></div>';
425
- }
426
- },
427
- option: function(item, escape) {
428
- if(0 === (parseInt(item.value) || 0)) {
429
- return '<div>' + escape(item.text) + '</div>';
430
- }
431
- if(item.$order) {
432
- var data = jQuery(albums_data[item.$order]).data();
433
- return '<div>' + escape(data.name) + ' <small>' + escape(data.meta) + '</small></div>';
434
- }
435
- }
436
- }
437
- });
438
- }
439
-
440
- if(window.gmedia_tags) {
441
- var tags = jQuery('#combobox_gmedia_tag');
442
- if(tags.length) {
443
- var tags_data = window.gmedia_tags.map(function(x) {
444
- return {item: x};
445
- });
446
-
447
- tags.selectize({
448
- create: function(input) {
449
- if(tags.data('create')) {
450
- return {
451
- item: input
452
- }
453
- } else {
454
- return false;
455
- }
456
- },
457
- createOnBlur: true,
458
- delimiter: ',',
459
- maxItems: null,
460
- openOnFocus: true,
461
- persist: false,
462
- options: tags_data,
463
- labelField: 'item',
464
- valueField: 'item',
465
- searchField: ['item'],
466
- hideSelected: true
467
- });
468
- }
469
- }
470
- if(window.gmedia_categories) {
471
- var categories = jQuery('#combobox_gmedia_category');
472
- if(categories.length) {
473
- var categories_data = window.gmedia_categories.map(function(x) {
474
- return {item: x};
475
- });
476
-
477
- categories.selectize({
478
- create: function(input) {
479
- if(categories.data('create')) {
480
- return {
481
- item: input
482
- }
483
- } else {
484
- return false;
485
- }
486
- },
487
- createOnBlur: true,
488
- delimiter: ',',
489
- maxItems: null,
490
- openOnFocus: true,
491
- persist: false,
492
- options: categories_data,
493
- labelField: 'item',
494
- valueField: 'item',
495
- searchField: ['item'],
496
- hideSelected: true
497
- });
498
- }
499
- }
500
-
501
-
502
- },
503
- /**
504
- * Gmedia Import
505
- */
506
- importmode: function() {
507
- }
508
- };
509
-
510
- /**
511
- * Gmedia Terms
512
- */
513
- var GmediaTerms = {
514
- init: function(){
515
-
516
- if(jQuery('body').hasClass('GrandMedia_Tags')){
517
- jQuery('#gm-list-table').data('edit', false);
518
- gmedia_DOM.on('keypress', 'input.edit_tag_input', function(e){
519
- var tagdiv = jQuery('#tag_' + jQuery(this).data('tag_id'));
520
- var charCode = e.charCode || e.keyCode || e.which;
521
- if(charCode == 13){
522
- e.preventDefault();
523
- edit_tag(tagdiv);
524
- }
525
- }).on('blur', 'input.edit_tag_input', function(){
526
- var tagdiv = jQuery('#tag_' + jQuery(this).data('tag_id'));
527
- edit_tag(tagdiv);
528
- });
529
-
530
- gmedia_DOM.on('click', '.edit_tag_link', function(e){
531
- e.preventDefault();
532
- var id = jQuery(this).attr('href');
533
- jQuery(this).hide();
534
- jQuery(id).find('.edit_tag_form').show().find('input').focus();
535
- jQuery('#gm-list-table').data('edit', true);
536
- });
537
- gmedia_DOM.on('click', '.edit_tag_save', function(e){
538
- e.preventDefault();
539
- });
540
-
541
- function edit_tag(tagdiv){
542
- var inp = tagdiv.find('.edit_tag_form input');
543
- var new_tag_name = jQuery.trim(inp.val());
544
- var old_tag_name = inp.attr('placeholder');
545
- if((old_tag_name == new_tag_name) || ('' === new_tag_name) || jQuery.isNumeric()){
546
- inp.val(old_tag_name);
547
- tagdiv.find('.edit_tag_form').hide();
548
- tagdiv.find('.edit_tag_link').show();
549
- return;
550
- }
551
- var post_data = {
552
- action: 'gmedia_tag_edit',
553
- tag_id: inp.data('tag_id'),
554
- tag_name: new_tag_name,
555
- _wpnonce_terms: jQuery('#_wpnonce_terms').val()
556
- };
557
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR){
558
- console.log(data);
559
- if(data.error){
560
- //inp.val(inp.attr('placeholder'));
561
- jQuery('#gmedia-panel').before(data.error);
562
- } else{
563
- //new_tag_name = new_tag_name.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
564
- inp.attr('placeholder', new_tag_name);
565
- tagdiv.find('.edit_tag_link').text(new_tag_name).show();
566
- //noinspection JSUnresolvedVariable
567
- jQuery('#gmedia-panel').before(data.msg);
568
- tagdiv.find('.edit_tag_form').hide();
569
- }
570
- });
571
- }
572
- }
573
-
574
- gmedia_DOM.on('click', '.term-shortcode input', function(){
575
- this.setSelectionRange(0, 0);
576
- this.setSelectionRange(0, this.value.length);
577
- });
578
- gmedia_DOM.on('change', '.term-shortcode input', function(){
579
- shortcode_inp_autowidth(this);
580
- });
581
- jQuery('.term-shortcode input', gmedia_DOM).each(function(i, e){
582
- shortcode_inp_autowidth(this)
583
- });
584
-
585
- function shortcode_inp_autowidth(e){
586
- var inp = jQuery(e),
587
- buffer = inp.next('.input-buffer');
588
- buffer.text(inp.val());
589
- inp.width(buffer.width());
590
- }
591
-
592
- var sortable = jQuery('#gm-sortable');
593
- if(sortable.length && !jQuery('#gmedia-panel', sortable).hasClass('gmedia-filtered')){
594
- var sortdiv = jQuery('#gm-list-table', sortable);
595
- var post_data = sortable.data();
596
- post_data['idx0'] = parseInt(sortdiv.attr('data-idx0'));
597
-
598
- var _ids = [];
599
- jQuery('.gm-item-cell', sortdiv).each(function(index){
600
- _ids.push(jQuery(this).attr('data-id'));
601
- });
602
- sortdiv.sortable({
603
- items: '.gm-item-cell',
604
- handle: '.cb_media-object',
605
- placeholder: 'cb_list-item gm-item-cell col-xs-6 col-sm-4 col-md-3 col-lg-2 gmedia-image-item ui-highlight-placeholder',
606
- tolerance: 'pointer',
607
- helper: 'clone',
608
- revert: true,
609
- forcePlaceholderSize: true,
610
- stop: function(event, ui){
611
- var ids = [];
612
- jQuery('.gm-item-cell', sortdiv).each(function(index){
613
- ids.push(jQuery(this).attr('data-id'));
614
- });
615
-
616
- if(_ids.toString() != ids.toString()){
617
- _ids = ids;
618
- jQuery('.panel-heading .spinner', sortable).addClass('is-active');
619
- post_data['ids'] = ids
620
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR){
621
- jQuery('.panel-heading .spinner', sortable).removeClass('is-active');
622
- console.log(data);
623
- });
624
- }
625
- }
626
- });
627
- }
628
-
629
- gmedia_DOM.on('change', '#gmedia_term_orderby', function(){
630
- if('custom' == jQuery(this).val()){
631
- jQuery('#gmedia_term_order').val('ASC').addClass('disabled');
632
- } else{
633
- jQuery('#gmedia_term_order').removeClass('disabled');
634
- }
635
- });
636
-
637
- // Date/Time picker
638
- if(jQuery.fn.datetimepicker){
639
- jQuery('.input-group.gmedia_date').datetimepicker({format: 'YYYY-MM-DD HH:mm:ss', focusOnShow: true, ignoreReadonly: true, allowInputToggle: true});
640
- }
641
- }
642
- };
643
-
644
- var GmediaSelect = {
645
- msg_stack: function(global) {
646
- var gm_cb = jQuery('.gm-stack input');
647
- var sel = jQuery('#gm-stack');
648
- if(!sel.length) {
649
- return;
650
- }
651
-
652
- var arr = sel.val().split(',');
653
- arr = jQuery.grep(arr, function(e) {
654
- return (e);
655
- });
656
-
657
- if(global) {
658
- var cur = false;
659
- gm_cb.each(function() {
660
- cur = jQuery(this);
661
- if(cur.is(':checked') && (jQuery.inArray(cur.val(), arr) === -1)) {
662
- cur.prop('checked', false);
663
- } else if(!(cur.is(':checked')) && (jQuery.inArray(cur.val(), arr) !== -1)) {
664
- cur.prop('checked', true);
665
- }
666
- });
667
- }
668
-
669
- if(sel.data('userid')) {
670
- var storedData = getStorage();
671
- storedData.set(sel.data('key'), arr.join('.'));
672
- }
673
- jQuery('#gm-stack-qty').text(arr.length);
674
- if(arr.length) {
675
- jQuery('#gm-stack-btn').removeClass('hidden');
676
- jQuery('.rel-stack-show').show();
677
- jQuery('.rel-stack-hide').hide();
678
- }
679
- else {
680
- jQuery('#gm-stack-btn').addClass('hidden');
681
- jQuery('.rel-stack-show').hide();
682
- jQuery('.rel-stack-hide').show();
683
- }
684
- sel.trigger('change');
685
- },
686
- msg_selected: function(obj, global) {
687
- var gm_cb = jQuery('.' + obj + ' input'),
688
- qty_v = gm_cb.length,
689
- sel_v = gm_cb.filter(':checked').length,
690
- c = jQuery('#cb_global');
691
- if((sel_v != qty_v) && (0 !== sel_v)) {
692
- c.css('opacity', '0.5').prop('checked', true);
693
- } else if((sel_v == qty_v) && (0 !== qty_v)) {
694
- c.css('opacity', '1').prop('checked', true);
695
- } else if(0 === sel_v) {
696
- c.css('opacity', '1').prop('checked', false);
697
- }
698
-
699
- var sel = jQuery('#gm-selected');
700
- if(!sel.length) {
701
- return;
702
- }
703
-
704
- var arr = sel.val().split(',');
705
-
706
- arr = jQuery.grep(arr, function(e) {
707
- return (e);
708
- });
709
- if(global) {
710
- var cur = false;
711
- gm_cb.each(function() {
712
- cur = jQuery(this);
713
- if(cur.is(':checked') && (jQuery.inArray(cur.val(), arr) === -1)) {
714
- arr.push(cur.val());
715
- } else if(!(cur.is(':checked')) && (jQuery.inArray(cur.val(), arr) !== -1)) {
716
- arr = jQuery.grep(arr, function(e) {
717
- return e != cur.val();
718
- });
719
- }
720
- });
721
- sel.val(arr.join(','));
722
- }
723
-
724
- if(sel.data('userid')) {
725
- var storedData = getStorage();
726
- storedData.set(sel.data('key'), arr.join('.'));
727
- }
728
- jQuery('#gm-selected-qty').text(arr.length);
729
-
730
- var selbtn = jQuery('#gm-selected-btn');
731
- if(arr.length) {
732
- selbtn.removeClass('hidden');
733
- jQuery('.rel-selected-show').show();
734
- jQuery('.rel-selected-hide').hide();
735
- }
736
- else {
737
- if(!selbtn.hasClass('gm-active')) {
738
- jQuery('#gm-selected-btn').addClass('hidden');
739
- }
740
- jQuery('.rel-selected-show').hide();
741
- jQuery('.rel-selected-hide').show();
742
- }
743
- sel.trigger('change');
744
- },
745
- chk_all: function(type, obj) {
746
- jQuery('.' + obj + ' input').filter(function() {
747
- return type? jQuery(this).data('type') == type : true;
748
- }).prop('checked', true).closest('.cb_list-item').addClass('gm-selected');
749
- },
750
- chk_none: function(type, obj) {
751
- jQuery('.' + obj + ' input').filter(function() {
752
- return type? jQuery(this).data('type') == type : true;
753
- }).prop('checked', false).closest('.cb_list-item').removeClass('gm-selected');
754
- },
755
- chk_toggle: function(type, obj) {
756
- if(type) {
757
- if(jQuery('.' + obj + ' input:checked').filter(function() {
758
- return jQuery(this).data('type') == type;
759
- }).length) {
760
- GmediaSelect.chk_none(type, obj);
761
- } else {
762
- GmediaSelect.chk_all(type, obj);
763
- }
764
- } else {
765
- jQuery('.' + obj + ' input').each(function() {
766
- jQuery(this).prop("checked", !jQuery(this).prop("checked")).closest('.cb_list-item').toggleClass('gm-selected');
767
- });
768
- }
769
- },
770
- init: function() {
771
- var cb_obj = jQuery('#cb_global').data('group');
772
-
773
- if(jQuery('#gm-selected').length) {
774
- GmediaSelect.msg_selected(cb_obj);
775
- gmedia_DOM.on('click', '#gm-selected-clear', function(e) {
776
- jQuery('#gm-selected').val('');
777
- GmediaSelect.chk_none(false, cb_obj);
778
- GmediaSelect.msg_selected(cb_obj);
779
- e.preventDefault();
780
- });
781
- gmedia_DOM.on('click', '#gm-selected-show', function(e) {
782
- jQuery('#gm-selected-btn').submit();
783
- e.preventDefault();
784
- });
785
- gmedia_DOM.on('click', '#gm-stack-in', function(e) {
786
- e.preventDefault();
787
- var stack_obj = jQuery('#gm-stack'),
788
- sel_obj = jQuery('#gm-selected'),
789
- stack = stack_obj.val().split(','),
790
- selected = sel_obj.val().split(','),
791
- arr = stack.concat(selected);
792
- arr = jQuery.grep(arr, function(e) {
793
- return (e);
794
- });
795
- arr = jQuery.unique(arr);
796
- stack_obj.val(arr.join(','));
797
- GmediaSelect.msg_stack(true);
798
- //sel_obj.val('');
799
- //GmediaSelect.chk_none(false, cb_obj);
800
- //GmediaSelect.msg_selected(cb_obj);
801
- });
802
- gmedia_DOM.on('click', '#gm-stack-out', function(e) {
803
- e.preventDefault();
804
- var stack_obj = jQuery('#gm-stack'),
805
- sel_obj = jQuery('#gm-selected'),
806
- stack = stack_obj.val().split(','),
807
- selected = sel_obj.val().split(','),
808
- arr = jQuery(stack).not(selected).get();
809
- arr = jQuery.grep(arr, function(e) {
810
- return (e);
811
- });
812
- arr = jQuery.unique(arr);
813
- stack_obj.val(arr.join(','));
814
- GmediaSelect.msg_stack(true);
815
- //sel_obj.val('');
816
- //GmediaSelect.chk_none(false, cb_obj);
817
- //GmediaSelect.msg_selected(cb_obj);
818
- });
819
- }
820
- gmedia_DOM.on('click', '#cb_global', function() {
821
- if(jQuery(this).is(':checked')) {
822
- GmediaSelect.chk_all(false, cb_obj);
823
- } else {
824
- GmediaSelect.chk_none(false, cb_obj);
825
- }
826
- GmediaSelect.msg_selected(cb_obj, true);
827
- });
828
- gmedia_DOM.on('click', '#cb_global-btn li a', function(e) {
829
- var sel = jQuery(this).data('select');
830
- switch(sel) {
831
- case 'total':
832
- GmediaSelect.chk_all(false, cb_obj);
833
- break;
834
- case 'none':
835
- GmediaSelect.chk_none(false, cb_obj);
836
- break;
837
- case 'reverse':
838
- GmediaSelect.chk_toggle(false, cb_obj);
839
- break;
840
- case 'image':
841
- case 'audio':
842
- case 'video':
843
- GmediaSelect.chk_toggle(sel, cb_obj);
844
- break;
845
- }
846
- GmediaSelect.msg_selected(cb_obj, true);
847
- e.preventDefault();
848
- });
849
- gmedia_DOM.on('change', '.gm-item-check input:checkbox, .cb_object input:checkbox', function() {
850
- var selected = jQuery('#gm-selected'),
851
- arr = selected.val();
852
- var cur = jQuery(this).val();
853
- if(jQuery(this).is(':checked')) {
854
- if(arr) {
855
- arr = arr + ',' + cur;
856
- } else {
857
- arr = cur;
858
- }
859
- } else {
860
- arr = jQuery.grep(arr.split(','), function(a) {
861
- return a != cur;
862
- }).join(',');
863
- }
864
- jQuery('#list-item-' + cur).toggleClass('gm-selected');
865
- selected.val(arr);
866
- GmediaSelect.msg_selected(cb_obj);
867
- });
868
-
869
- gmedia_DOM.on('click', '.gm-item-check input:radio', function() {
870
- var id = jQuery(this).val(), img, checked_thumb, data;
871
- jQuery('#list-item-' + id).addClass('gm-selected').siblings().removeClass('gm-selected');
872
- img = jQuery(this).closest('.thumbnail').find('.gmedia-thumb').clone();
873
- checked_thumb = jQuery('#gmedia-panel .panel-heading .checked_thumb');
874
- if(!checked_thumb.length){
875
- checked_thumb = jQuery('<div class="checked_thumb"></div>').appendTo(jQuery('#gmedia-panel .panel-heading'));
876
- }
877
- checked_thumb.html(img);
878
- data = {'id':id, 'src':img.attr('src')};
879
- window.parent.gmediaTempData = data;
880
- });
881
-
882
- if(jQuery('#gm-stack').length) {
883
- GmediaSelect.msg_stack();
884
- gmedia_DOM.on('click', '#gm-stack-clear', function(e) {
885
- jQuery('#gm-stack').val('');
886
- jQuery('.gm-stack input').prop('checked', false);
887
- GmediaSelect.msg_stack();
888
- e.preventDefault();
889
- });
890
- gmedia_DOM.on('click', '#gm-stack-show', function(e) {
891
- jQuery('#gm-stack-btn').submit();
892
- e.preventDefault();
893
- });
894
-
895
- }
896
- gmedia_DOM.on('change', '.gm-stack input:checkbox', function() {
897
- var selected = jQuery('#gm-stack'),
898
- arr = selected.val();
899
- var cur = jQuery(this).val();
900
- if(jQuery(this).is(':checked')) {
901
- if(arr) {
902
- arr = arr + ',' + cur;
903
- } else {
904
- arr = cur;
905
- }
906
- } else {
907
- arr = jQuery.grep(arr.split(','), function(a) {
908
- return a != cur;
909
- }).join(',');
910
- }
911
- selected.val(arr);
912
- GmediaSelect.msg_stack();
913
- });
914
-
915
- gmedia_DOM.on('click', '.term-label', function(e) {
916
- if('DIV' == e.target.nodeName) {
917
- if(!jQuery('#gm-list-table').data('edit')) {
918
- var cb = jQuery('input:checkbox', this);
919
- cb.prop("checked", !cb.prop("checked")).change();
920
- jQuery(this).closest('.term-list-item').toggleClass('gm-selected');
921
- } else {
922
- jQuery('#gm-list-table').data('edit', false);
923
- }
924
- }
925
- });
926
- }
927
- }
928
-
929
- var GmediaFunction = {
930
- confirm: function(txt) {
931
- if(!txt) {
932
- return true;
933
- }
934
- var r = false;
935
- //noinspection UnusedCatchParameterJS
936
- try{
937
- r = confirm(txt);
938
- }
939
- catch(err){
940
- alert('Disable Popup Blocker');
941
- }
942
- return r;
943
- },
944
- init: function() {
945
- jQuery('#toplevel_page_GrandMedia').addClass('current').removeClass('wp-not-current-submenu');
946
- if(!("ontouchstart" in document.documentElement)) {
947
- jQuery('html').addClass('no-touch');
948
- }
949
-
950
- //jQuery(document).ajaxStart(function(a,b,c){
951
- // //jQuery('body').addClass('gmedia-busy');
952
- // jQuery('.panel-heading .spinner').addClass('is-active');
953
- //}).ajaxStop(function(){
954
- // //jQuery('body').removeClass('gmedia-busy');
955
- // jQuery('.panel-heading .spinner').removeClass('is-active');
956
- //});
957
-
958
- gmedia_DOM.on('click', '[data-confirm]', function() {
959
- return GmediaFunction.confirm(jQuery(this).data('confirm'));
960
- });
961
-
962
- jQuery(document).on('click.gmedia', '.gm_service_action', function() {
963
- var el = jQuery(this),
964
- service = jQuery(this).attr('data-action'),
965
- nonce = jQuery(this).attr('data-nonce');
966
- var post_data = {
967
- action: 'gmedia_application',
968
- service: service,
969
- _wpnonce: nonce
970
- };
971
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
972
- console.log(data);
973
- el.siblings('.spinner').removeClass('is-active');
974
- if(data.error) {
975
- jQuery('#gmedia-service-msg-panel').prepend(data.error);
976
- } else if(data.message) {
977
- jQuery('#gmedia-service-msg-panel').html(data.message);
978
- }
979
- });
980
-
981
- el.siblings('.spinner').addClass('is-active');
982
- jQuery('.gmedia-service__message').remove();
983
- });
984
-
985
- gmedia_DOM.on('click', '.show-settings-link', function(e) {
986
- e.preventDefault();
987
- jQuery('#show-settings-link').trigger('click');
988
- });
989
-
990
- gmedia_DOM.on('click', '.fit-thumbs', function(e) {
991
- e.preventDefault();
992
- jQuery(this).toggleClass('btn-success btn-default');
993
- jQuery('.display-as-grid').toggleClass('invert-ratio');
994
- jQuery.get(jQuery(this).attr('href'), {ajaxload: 1});
995
- });
996
-
997
- gmedia_DOM.on('click', '.gm-cell-more-btn, .gm-cell-title', function() {
998
- jQuery(this).parent().toggleClass('gm-cell-more-active');
999
- });
1000
-
1001
- jQuery('div.gmedia-modal', gmedia_DOM).each(function(){
1002
- var id = jQuery(this).attr('id');
1003
- jQuery('body').children('#' + id).remove();
1004
- jQuery(this).appendTo('body');
1005
- });
1006
- gmedia_DOM.on('click', 'a.gmedia-modal', function(e) {
1007
- jQuery('body').addClass('gmedia-busy');
1008
- var modal_div = jQuery(jQuery(this).attr('href'));
1009
- var post_data = jQuery(this).data();
1010
- post_data['_wpnonce'] = jQuery('#_wpnonce').val();
1011
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1012
- if(!data || ('-1' == data)) {
1013
- jQuery('body').removeClass('gmedia-busy');
1014
- alert(data);
1015
- return false;
1016
- }
1017
- jQuery('.modal-dialog', modal_div).html(data);
1018
- modal_div.modal({
1019
- backdrop: 'static',
1020
- show: true,
1021
- keyboard: false
1022
- }).one('hidden.bs.modal', function() {
1023
- jQuery('.modal-dialog', this).empty();
1024
- });
1025
- jQuery('body').removeClass('gmedia-busy');
1026
- });
1027
- e.preventDefault();
1028
- });
1029
-
1030
- gmedia_DOM.on('click', 'a.gmedit-modal', function(e) {
1031
- e.preventDefault();
1032
- var modal_div = jQuery(jQuery(this).data('target'));
1033
- jQuery('.modal-content', modal_div).html(
1034
- jQuery('<iframe />', {
1035
- name: 'gmeditFrame',
1036
- id: 'gmeditFrame',
1037
- width: '100%',
1038
- height: '500',
1039
- src: jQuery(this).attr('href')
1040
- }).css({display: 'block', margin: '4px 0'})
1041
- );
1042
- modal_div.modal({
1043
- backdrop: true,
1044
- show: true,
1045
- keyboard: false
1046
- }).one('hidden.bs.modal', function() {
1047
- jQuery('.modal-content', this).empty();
1048
- });
1049
- });
1050
-
1051
- jQuery(document).on('click.gmedia', 'a.preview-modal', function(e) {
1052
- e.preventDefault();
1053
- var initiator = jQuery(this),
1054
- data = initiator.data(),
1055
- modal_div = jQuery(data['target']),
1056
- modal_dialog = jQuery('.modal-dialog', modal_div),
1057
- modal_body = jQuery('.modal-body', modal_div),
1058
- modal_title = jQuery('.modal-title', modal_div);
1059
- modal_title.text(jQuery(this).attr('data-title')? jQuery(this).attr('data-title') : jQuery(this).attr('title'));
1060
-
1061
- if(data['metainfo']) {
1062
- modal_dialog.addClass('modal-md');
1063
- modal_body.html(jQuery('#metainfo_' + data['metainfo']).html());
1064
- } else {
1065
- var r = data['width'] / data['height'],
1066
- w = Math.min(jQuery(window).width() * 0.98 - 32, data['width']),
1067
- h = w / r;
1068
- modal_dialog.css({'width': (data['width'] + 32), 'max-width': '98%'});
1069
- if(data['cls']){
1070
- modal_dialog.addClass(data['cls']);
1071
- }
1072
- modal_body.html(
1073
- jQuery('<iframe />', {
1074
- name: 'previewFrame',
1075
- id: 'previewFrame',
1076
- width: '100%',
1077
- height: h,
1078
- src: jQuery(this).attr('href')
1079
- }).on('load', function(){
1080
- jQuery(this.contentWindow.document.body).css('margin', 0);
1081
- jQuery('.modal-backdrop', modal_div).css({'width': (data['width'] + 32), 'min-width': '100%'});
1082
- }).css({display: 'block', margin: '4px 0'})
1083
- );
1084
- }
1085
-
1086
- initiator.addClass('previewModal_initiator');
1087
- modal_div.modal({
1088
- backdrop: true,
1089
- show: true
1090
- }).one('hidden.bs.modal', function() {
1091
- if (jQuery('div.gmedia-modal:visible').length) {
1092
- jQuery('body').addClass('modal-open');
1093
- }
1094
- modal_title.empty();
1095
- modal_body.empty();
1096
- modal_dialog.removeAttr('style').attr('class', 'modal-dialog');
1097
- if(modal_div.attr('data-refresh')){
1098
- modal_div.removeAttr('data-refresh');
1099
- jQuery('.panel-heading .spinner').addClass('is-active');
1100
- var url = window.location.href;
1101
- jQuery.get(url, function(data) {
1102
- jQuery('#gmedia-panel').html(jQuery('#gmedia-panel', data).html());
1103
- GmediaInit();
1104
- jQuery('.panel-heading .spinner').removeClass('is-active');
1105
- });
1106
- }
1107
- initiator.removeClass('previewModal_initiator');
1108
- });
1109
- });
1110
-
1111
- jQuery(document).on('click.gmedia', '#previewModal .select_gmedia_image .btn-primary', function() {
1112
- var img, form = jQuery('.previewModal_initiator').closest('form');
1113
- form.find('.gmedia-cover-id').val(window.gmediaTempData.id).trigger('change');
1114
- img = form.find('.gmedia-cover-image img:first-child');
1115
- if(img.length){
1116
- img.attr('src', window.gmediaTempData.src);
1117
- } else {
1118
- jQuery('<img src="" alt="" />').attr('src', window.gmediaTempData.src).appendTo(form.find('.gmedia-cover-image'));
1119
- }
1120
- jQuery('#previewModal').modal('hide');
1121
- });
1122
-
1123
- jQuery(document).on('click.gmedia', '#previewModal .select_gmedia_related .btn-primary', function() {
1124
- var relatedDiv = jQuery('.previewModal_initiator').closest('.form-group').find('.related-media-previews');
1125
- var fields = relatedDiv.find('input');
1126
- var valData = [],
1127
- getData = [];
1128
- if(fields){
1129
- fields.each(function(){
1130
- valData.push(jQuery(this).val());
1131
- });
1132
- }
1133
- var storage = getStorage();
1134
- storedData = storage.get('gmedia_library:frame').split('.');
1135
- jQuery.each(storedData, function(i, id) {
1136
- if(!id) {
1137
- return true;
1138
- }
1139
- if(jQuery.inArray(id, valData) === -1) {
1140
- getData.push(id);
1141
- }
1142
- });
1143
- if(getData.length){
1144
- jQuery.get(ajaxurl, {action: 'gmedia_get_data', gmedia__in: getData}, function(data, textStatus, jqXHR) {
1145
- if(jQuery.isArray(data) && data.length){
1146
- var thumbHTML
1147
- jQuery.each(data, function(i, item){
1148
- thumbHTML = '<p class="thumbnail gmedia-related-image">' +
1149
- '<span class="image-wrapper"><img class="gmedia-thumb" src="" alt=""></span>' +
1150
- '<span class="gm-remove">&times;</span>' +
1151
- '<input type="hidden" name="meta[_related][]" value="">' +
1152
- '</p>';
1153
- jQuery(thumbHTML).find('img').attr('src', item.url_thumb).end().find('input').val(item.ID).end().appendTo(relatedDiv);
1154
- });
1155
- relatedDiv.sortable( "refresh" );
1156
- relatedDiv.closest('form').find('input[name="title"]').trigger('change');
1157
- }
1158
- });
1159
- }
1160
- storage.set('gmedia_library:frame', '');
1161
- jQuery('#previewModal').modal('hide');
1162
- });
1163
-
1164
- jQuery(document).on('click.gmedia', '.related-media-previews .gm-remove', function() {
1165
- var inpTitle = jQuery(this).closest('form').find('input[name="title"]');
1166
- jQuery(this).closest('.gmedia-related-image').remove();
1167
- inpTitle.trigger('change');
1168
- });
1169
-
1170
- jQuery(document).on('click.gmedia', '#previewModal .select_gmedia:not(.assign_gmedia_term) .btn-primary', function() {
1171
- var field = jQuery('.previewModal_initiator').closest('.form-group').find('.form-control');
1172
- var valData = field.val().split(',');
1173
- var storedData = getStorage();
1174
- storedData = storedData.get('gmedia_library:frame').split('.');
1175
- valData = jQuery.grep(valData, function(e) {
1176
- return e.trim();
1177
- });
1178
- jQuery.each(storedData, function(i, id) {
1179
- if(!id) {
1180
- return true;
1181
- }
1182
- if(jQuery.inArray(id, valData) === -1) {
1183
- valData.push(id);
1184
- }
1185
- });
1186
- field.val(valData.join(','));
1187
- jQuery('#previewModal').modal('hide');
1188
- });
1189
-
1190
- jQuery(document).on('click.gmedia', '#previewModal .assign_gmedia_term .btn-primary', function() {
1191
- jQuery('.panel-heading .spinner').addClass('is-active');
1192
- var url = window.location.href,
1193
- post_data = jQuery('#gmedia-assign-term').serialize();
1194
- jQuery.post(url, post_data, function(data) {
1195
- jQuery('.gmedia_term__in').html(jQuery('.gmedia_term__in', data).html());
1196
- GmediaInit();
1197
- jQuery('.panel-heading .spinner').removeClass('is-active');
1198
- });
1199
- jQuery('#previewModal').modal('hide');
1200
- //console.log(window.gmediaTempData);
1201
- });
1202
-
1203
- jQuery(document).on('click.gmedia focus.gmedia', 'input.sharelink', function() {
1204
- this.setSelectionRange(0, this.value.length);
1205
- });
1206
- jQuery(document).on('keyup.gmedia', 'input.sharetoemail', function() {
1207
- jQuery('.sharebutton').prop('disabled', !validateEmail(this.value));
1208
- });
1209
- jQuery(document).on('click.gmedia', '.sharebutton', function() {
1210
- var sharetoemail = jQuery('input.sharetoemail');
1211
- if(!validateEmail(sharetoemail.val())) {
1212
- sharetoemail.focus();
1213
- sharetoemail.parent().addClass('has-error');
1214
- return false;
1215
- }
1216
- var post_data = jQuery('#shareForm').serialize();
1217
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1218
- jQuery('body').removeClass('gmedia-busy');
1219
- if(data) {
1220
- jQuery('#gm-message').append(data);
1221
- }
1222
- });
1223
- jQuery('#shareModal').modal('hide');
1224
- });
1225
- gmedia_DOM.on('click', 'a.share-modal', function(e) {
1226
- e.preventDefault();
1227
- var data = jQuery(this).data(),
1228
- modal_div = jQuery(data['target']),
1229
- postlink = jQuery(this).attr('href'),
1230
- cloudlink = jQuery(this).attr('data-gmediacloud'),
1231
- sharetoemail = jQuery('input.sharetoemail'),
1232
- cloudlink_checked = false;
1233
-
1234
- if(postlink) {
1235
- jQuery('.sharelink_post', modal_div).show();
1236
- jQuery('.sharelink_post input[type="text"]', modal_div).val(postlink);
1237
- jQuery('.sharelink_post a', modal_div).attr('href', postlink);
1238
- } else {
1239
- jQuery('.sharelink_post', modal_div).hide();
1240
- jQuery('.sharelink_post input[type="radio"]', modal_div).prop('checked', false);
1241
- cloudlink_checked = true;
1242
- }
1243
- if(cloudlink) {
1244
- jQuery('.sharelink_page', modal_div).show();
1245
- jQuery('.sharelink_page input[type="text"]', modal_div).val(cloudlink);
1246
- jQuery('.sharelink_page a', modal_div).attr('href', cloudlink);
1247
- if(cloudlink_checked) {
1248
- jQuery('.sharelink_page input[type="radio"]', modal_div).prop('checked', true);
1249
- }
1250
- } else {
1251
- jQuery('.sharelink_page', modal_div).hide();
1252
- }
1253
- jQuery('.sharebutton').prop('disabled', !validateEmail(sharetoemail.val()));
1254
-
1255
- modal_div.modal({
1256
- backdrop: true,
1257
- show: true,
1258
- keyboard: false
1259
- }).one('shown.bs.modal', function() {
1260
- jQuery('input.sharelink', this).focus();
1261
- }).one('hidden.bs.modal', function() {
1262
- jQuery('input.sharelink', this).val('');
1263
- });
1264
- });
1265
-
1266
- gmedia_DOM.on('click', '.buildquery-modal', function(e) {
1267
- e.preventDefault();
1268
- var data = jQuery(this).data(),
1269
- modal_div = jQuery(jQuery(this).attr('href')),
1270
- query_field = jQuery(jQuery(this).attr('id') + '_field');
1271
- query = query_field.val();
1272
-
1273
- modal_div.modal({
1274
- backdrop: true,
1275
- show: true,
1276
- keyboard: false
1277
- }).one('shown.bs.modal', function() {
1278
- if(query) {
1279
- query = gm_parse_query(query);
1280
- console.log(query);
1281
- }
1282
- }).one('hidden.bs.modal', function() {});
1283
- });
1284
-
1285
- jQuery(document).on('click.gmedia', '.buildquerysubmit', function() {
1286
- var qform = jQuery('#buildQuery :input').filter(function() {
1287
- return !!jQuery(this).val();
1288
- });
1289
-
1290
- qform = decodeURIComponent(qform.serialize());
1291
- console.log(qform);
1292
- jQuery('#build_query_field').val(qform);
1293
- jQuery('#buildQuery').modal('hide');
1294
- });
1295
- gmedia_DOM.on('click', 'a.newcustomfield-modal', function(e) {
1296
- e.preventDefault();
1297
- var data = jQuery(this).data(),
1298
- modal_div = jQuery(jQuery(this).attr('href'));
1299
-
1300
- modal_div.modal({
1301
- backdrop: false,
1302
- show: true,
1303
- keyboard: false
1304
- }).one('shown.bs.modal', function() {
1305
- jQuery('input.newcustomfield-for-id', this).val(data['gmid']);
1306
- }).one('hidden.bs.modal', function() {
1307
- jQuery(':input.form-control, input.newcustomfield-for-id', this).val('');
1308
- if(jQuery('.newcfield', this).length) {
1309
- jQuery('a.gmediacustomstuff').click();
1310
- }
1311
- });
1312
- });
1313
- jQuery(document).on('click.gmedia', '.customfieldsubmit', function() {
1314
- var cform = jQuery('#newCustomFieldForm');
1315
- if(!jQuery('.newcustomfield-for-id', cform).val()) {
1316
- jQuery('#newCustomFieldModal').modal('hide');
1317
- alert('No ID');
1318
- return false;
1319
- }
1320
- var post_data = cform.serialize();
1321
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1322
- jQuery('body').removeClass('gmedia-busy');
1323
- if(data.success) {
1324
- jQuery('#newCustomFieldModal').modal('hide').one('hidden.bs.modal', function() {
1325
- //noinspection JSUnresolvedVariable
1326
- if(data.newmeta_form) {
1327
- //noinspection JSUnresolvedVariable
1328
- jQuery('#newmeta').replaceWith(data.newmeta_form);
1329
- }
1330
- });
1331
- jQuery('.row:last', '#gmediacustomstuff_' + data.id).append(data.success.data);
1332
- } else {
1333
- if(data.error) {
1334
- if('100' == data.error.code) {
1335
- jQuery('#newCustomFieldModal').modal('hide');
1336
- }
1337
- alert(data.error.message);
1338
- } else {
1339
- console.log(data);
1340
- }
1341
- }
1342
- });
1343
- });
1344
- gmedia_DOM.on('click', '.delete-custom-field', function() {
1345
- var t = jQuery(this).closest('.form-group'),
1346
- post_data = convertInputsToJSON(jQuery(':input', t));
1347
- if(!post_data) {
1348
- return false;
1349
- }
1350
- var meta_type = jQuery(this).closest('fieldset').attr('data-metatype');
1351
- post_data.action = meta_type + '_delete_custom_field';
1352
- post_data.ID = jQuery(this).closest('form').attr('data-id');
1353
- post_data._wpnonce_custom_field = jQuery('#_wpnonce_custom_field').val();
1354
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1355
- jQuery('body').removeClass('gmedia-busy');
1356
- //noinspection JSUnresolvedVariable
1357
- if(data.deleted) {
1358
- //noinspection JSUnresolvedVariable
1359
- jQuery.each(data.deleted, function(i, val) {
1360
- jQuery('.gm-custom-meta-' + val).remove();
1361
- });
1362
- } else {
1363
- if(data.error) {
1364
- alert(data.error.message);
1365
- } else {
1366
- console.log(data);
1367
- }
1368
- }
1369
- });
1370
- });
1371
-
1372
-
1373
- gmedia_DOM.on('change modified', 'form.edit-gmedia :input:not([name="doaction[]"])', function() {
1374
- if(jQuery(this).hasClass('edit-gmedia-ignore')) {
1375
- return;
1376
- }
1377
- jQuery('body').addClass('gmedia-busy');
1378
- jQuery('.panel-heading .spinner').addClass('is-active');
1379
- var post_data = {
1380
- action: 'gmedia_update_data', data: jQuery(this).closest('form').serialize(), _wpnonce: jQuery('#_wpnonce').val()
1381
- };
1382
- jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1383
- console.log(data);
1384
- var item = jQuery('#list-item-' + data.ID);
1385
- item.find('.modified').text(data.modified);
1386
- //noinspection JSUnresolvedVariable
1387
- item.find('.status-album').attr('class', 'form-group status-album bg-status-' + data.album_status);
1388
- item.find('.status-item').attr('class', 'form-group status-item bg-status-' + data.status);
1389
- if(data.thumbnail) {
1390
- item.find('.gmedia-cover-image').html(data.thumbnail);
1391
- }
1392
- //if(data.tags) {
1393
- // item.find('.gmedia_tags_input').val(data.tags);
1394
- //}
1395
- //noinspection JSUnresolvedVariable
1396
- if(data.meta_error) {
1397
- jQuery.each(data.meta_error, function(i, err) {
1398
- console.log(err);
1399
- alert(err.meta_key + ': ' + err.message);
1400
- if(err.meta_value) {
1401
- jQuery('.gm-custom-field-' + err.meta_id).val(err.meta_value);
1402
- }
1403
- });
1404
- }
1405
- jQuery('body').removeClass('gmedia-busy');
1406
- jQuery('.panel-heading .spinner').removeClass('is-active');
1407
- });
1408
- });
1409
-
1410
- gmedia_DOM.on('click', '.gm-toggle-cb', function(e) {
1411
- var checkBoxes = jQuery(this).attr('href');
1412
- jQuery(checkBoxes + ' :checkbox').each(function() {
1413
- jQuery(this).prop("checked", !jQuery(this).prop("checked"));
1414
- });
1415
- e.preventDefault();
1416
- });
1417
- jQuery(document).on('click.gmedia', '.linkblock [data-href]', function() {
1418
- window.location.href = jQuery(this).data('href');
1419
- });
1420
-
1421
- gmedia_DOM.on('click', '.gmedia-import', function() {
1422
- jQuery('#import-action').val(jQuery(this).attr('name'));
1423
- jQuery('#importModal').modal({
1424
- backdrop: 'static',
1425
- show: true,
1426
- keyboard: false
1427
- }).one('shown.bs.modal', function() {
1428
- jQuery('#import_form').submit();
1429
- }).one('hidden.bs.modal', function() {
1430
- var btn = jQuery('#import-done');
1431
- btn.text(btn.data('reset-text')).prop('disabled', true);
1432
- jQuery('#import_window').attr('src', 'about:blank');
1433
- });
1434
- });
1435
-
1436
- gmedia_DOM.on('click', '.module_install', function(e) {
1437
- e.preventDefault();
1438
- jQuery('body').addClass('gmedia-busy');
1439
- var module = jQuery(this).data('module');
1440
- var btn = jQuery('.module_install').filter('[data-module="' + module + '"]');
1441
- btn.text(btn.data('loading-text'));
1442
- var post_data = {
1443
- action: 'gmedia_module_install', download: jQuery(this).attr('href'), module: module, _wpnonce: jQuery('#_wpnonce').val()
1444
- };
1445
- var pathname = window.location.href + '&time=' + jQuery.now();
1446
- jQuery.post(ajaxurl, post_data, function(data, status, xhr) {
1447
- setTimeout(function(){
1448
- jQuery('#gmedia_modules').load(pathname + ' #gmedia_modules_wrapper', function(){
1449
- setTimeout(function(){
1450
- var update_count = jQuery('#gmedia_modules').find('#gmedia_modules_wrapper').attr('data-update');
1451
- if(parseInt(update_count)){
1452
- jQuery('.gm-module-count').html(update_count);
1453
- } else {
1454
- jQuery('.gm-module-count').remove();
1455
- }
1456
- }, 1);
1457
- });
1458
- }, 1);
1459
- jQuery('#gmedia_modules').before(data);
1460
- jQuery('body').removeClass('gmedia-busy');
1461
- });
1462
- });
1463
-
1464
- gmedia_DOM.on('keydown', 'form :input:visible:not(:submit,:button,:reset,textarea,.allow-key-enter)', function(e) {
1465
- var charCode = e.charCode || e.keyCode || e.which;
1466
- if(13 == charCode && !jQuery(this).parent().hasClass('selectize-input')) {
1467
- var inputs = jQuery(this).parents("form").eq(0).find(":input:visible");
1468
- var inp = inputs[inputs.index(this) + 1];
1469
- if(inp !== null) {
1470
- jQuery(inp).focus();
1471
- var inp_type = jQuery(inp).attr('type');
1472
- if(!!inp_type && (inp_type == 'text' || inp_type == 'number')) {
1473
- console.log(inp);
1474
- inp.setSelectionRange(0, inp.value.length);
1475
- }
1476
- }
1477
- e.preventDefault();
1478
- return false;
1479
- }
1480
- });
1481
-
1482
- var preset_popover = function() {
1483
- jQuery('#module_presets').popover({
1484
- container: '#module_preset',
1485
- content: function() {
1486
- return jQuery('#_module_presets').html();
1487
- },
1488
- html: true,
1489
- placement: 'bottom'
1490
- }).on('show.bs.popover', function() {
1491
- jQuery(this).addClass('active');
1492
- }).on('hide.bs.popover', function() {
1493
- jQuery(this).removeClass('active');
1494
- });
1495
- };
1496
- preset_popover();
1497
- gmedia_DOM.on('click', '#module_preset .ajax-submit', function(e) {
1498
- e.preventDefault();
1499
- jQuery('body').addClass('gmedia-busy');
1500
- var form = jQuery('#gmedia-edit-term');
1501
- var post_data = form.serializeArray();
1502
- post_data.push({name: jQuery(this).attr('name'), value: 1});
1503
- var pathname = window.location.href;
1504
- jQuery.post(pathname, jQuery.param(post_data), function(data, status, xhr) {
1505
- jQuery('body').removeClass('gmedia-busy');
1506
- data = jQuery(data).find('#gmedia-container');
1507
- jQuery('#gm-message').append(jQuery('#gm-message', data).html());
1508
- jQuery('#save_buttons').html(jQuery('#save_buttons', data).html());
1509
- jQuery('#save_buttons_duplicate').html(jQuery('#save_buttons_duplicate', data).html());
1510
- jQuery('#module_preset').html(jQuery('#module_preset', data).html());
1511
- preset_popover();
1512
- });
1513
- });
1514
- jQuery(document).on('click.gmedia', function(e) {
1515
- if(jQuery(e.target).data('toggle') !== 'popover'
1516
- && jQuery(e.target).parents('.popover.in').length === 0) {
1517
- jQuery('[data-toggle="popover"]').popover('hide');
1518
- }
1519
- });
1520
-
1521
- gmedia_DOM.on('click', '[data-clicktarget]', function(e){
1522
- e.preventDefault();
1523
- var id = jQuery(this).attr('data-clicktarget');
1524
- jQuery('#' + id).click();
1525
- });
1526
-
1527
- gmedia_DOM.on('click', '#module_preset .delpreset span, .module_presets .delpreset span', function() {
1528
- jQuery('body').addClass('gmedia-busy');
1529
- var module_preset = this;
1530
- var preset_item_li = jQuery(this).closest('li');
1531
- var preset_id = jQuery(this).data('id');
1532
- var post_data = {
1533
- action: 'gmedia_module_preset_delete', preset_id: preset_id, _wpnonce: jQuery('#_wpnonce').val()
1534
- };
1535
- jQuery.post(ajaxurl, post_data, function(data, status, xhr) {
1536
- if(data.error) {
1537
- jQuery('#gm-message').append(data.error);
1538
- } else {
1539
- preset_item_li.remove();
1540
- if('module_presets_list' !== jQuery(this).attr('id')) {
1541
- var _module_presets = jQuery('#module_preset').find('.popover-content').html();
1542
- jQuery('#_module_presets').replaceWith('<script type="text/html" id="_module_presets">' + _module_presets + '</script>');
1543
- }
1544
- }
1545
- jQuery('body').removeClass('gmedia-busy');
1546
- });
1547
- });
1548
-
1549
- gmedia_DOM.on('click', '.filter-modules > *', function(){
1550
- jQuery('.filter-modules > .btn-primary').removeClass('btn-primary').addClass('btn-default');
1551
- jQuery('.filter-modules > .label-primary').removeClass('label-primary').addClass('label-default');
1552
- if(jQuery(this).is('button')){
1553
- jQuery(this).addClass('btn-primary').removeClass('btn-default');
1554
- } else{
1555
- jQuery(this).addClass('label-primary').removeClass('label-default');
1556
- }
1557
- var filter = jQuery(this).attr('data-filter');
1558
- jQuery('#gmedia_modules .media').removeClass('module-filtered').filter('.module-' + filter).addClass('module-filtered');
1559
- if(!jQuery('#gmedia_modules .module-filtered').length){
1560
- if('not-installed' == filter){
1561
- jQuery('#gmedia_modules .nomodules.nomodule-' + filter).addClass('module-filtered');
1562
- } else{
1563
- jQuery('#gmedia_modules .nomodules.nomodule-tag').addClass('module-filtered');
1564
- }
1565
- }
1566
- })
1567
-
1568
- if(jQuery(".panel-fixed-header").length) {
1569
- setPanelHeadersWidth();
1570
- setTimeout(function() {
1571
- setPanelHeadersWidth();
1572
- }, 800);
1573
- jQuery(window).on('resize.gmedia', function() {
1574
- setPanelHeadersWidth();
1575
- });
1576
- jQuery(document).on('click.gmedia', '#collapse-menu', function() {
1577
- setTimeout(function() {
1578
- setPanelHeadersWidth();
1579
- }, 10);
1580
- });
1581
-
1582
- jQuery(window).on('scroll.gmedia', function() {
1583
- UpdatePanelHeaders();
1584
- /*clearTimeout(jQuery.data(this, 'scrollTimer'));
1585
- jQuery.data(this, 'scrollTimer', setTimeout(function() {
1586
- UpdatePanelHeaders();
1587
- console.log("Haven't scrolled in 250ms!");
1588
- }, 250));*/
1589
- }).trigger("scroll.gmedia");
1590
- }
1591
-
1592
- }
1593
- };
1594
-
1595
-
1596
- window.closeModal = function(id) {
1597
- jQuery('#' + id).modal('hide');
1598
- };
1599
-
1600
-
1601
- /*
1602
- * jQuery functions for GRAND Media
1603
- */
1604
- function GmediaInit(){
1605
- gmedia_DOM = jQuery('#gmedia-container');
1606
- gmedia_DOM.off();
1607
- jQuery(window).off('.gmedia');
1608
- jQuery(document).off('.gmedia');
1609
-
1610
- GmediaSelect.init();
1611
- GmediaFunction.init();
1612
-
1613
- if(jQuery('body').hasClass('GrandMedia')) {
1614
- GmediaLibrary.init();
1615
- }
1616
- if(jQuery('body').hasClass('GrandMedia_AddMedia')) {
1617
- GmediaAddMedia.init();
1618
- }
1619
- if(jQuery('body').is('.GrandMedia_Tags,.GrandMedia_Categories,.GrandMedia_Albums,.GrandMedia_Galleries')) {
1620
- GmediaTerms.init();
1621
- }
1622
-
1623
- var helper, helper_width, title;
1624
- jQuery('[title]', gmedia_DOM).each(function(){
1625
- title = jQuery(this).attr('title');
1626
- if(title) {
1627
- jQuery(this).attr('title','').attr('data-title', title);
1628
- }
1629
- });
1630
- gmedia_DOM.on('mouseenter', '[title]', function(e) {
1631
- title = jQuery(this).attr('data-title');
1632
- if(title) {
1633
- helper = jQuery('<div id="gmedia-data-helper">' + title + '</div>').appendTo('body');
1634
- helper_width = 0;
1635
- if(e.pageX > (window.innerWidth / 2)) {
1636
- helper_width = helper.width() - 25;
1637
- helper.addClass('tiptoleft');
1638
- }
1639
- helper.css({left: e.clientX - helper_width - 25, top: e.clientY + 25});
1640
- } else{
1641
- jQuery(this).removeAttr('title');
1642
- }
1643
- }).on('mousemove', '[title]', function(e) {
1644
- if(helper) {
1645
- helper.css({left: e.clientX - helper_width - 25, top: e.clientY + 25});
1646
- }
1647
- }).on('mouseleave', '[title]', function(e) {
1648
- jQuery('#gmedia-data-helper').remove();
1649
- helper = null;
1650
- });
1651
- }
1652
- jQuery(document).on('ready', function() {
1653
- GmediaInit();
1654
- });
1655
-
1656
- function convertInputsToJSON(form) {
1657
- var array = jQuery(form).serializeArray();
1658
- var json = {};
1659
-
1660
- jQuery.each(array, function() {
1661
- json[this.name] = this.value || '';
1662
- });
1663
-
1664
- return json;
1665
- }
1666
-
1667
- function gm_parse_query(s) {
1668
- var j = {},
1669
- res = s.split(/&/gm).map(function(e) {
1670
- var o = e.split(/=/),
1671
- pt = j;
1672
- if(typeof o[1] == 'undefined') {
1673
- o[1] = '';
1674
- }
1675
- o[0].replace(/^(\w+)\[([^&]*)\]/, '$1][$2').split(/\]\[/).map(function(e, i, a) {
1676
- if(e === '') {
1677
- e = Object.keys(pt).length;
1678
- }
1679
- pt = (pt[e] = pt[e] || (i == a.length - 1? decodeURIComponent(o[1].replace(/\+/, ' ')) : {}));
1680
- });
1681
- });
1682
- return j;
1683
- }
1684
-
1685
- function validateEmail(email) {
1686
- var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1687
- return re.test(email);
1688
- }
1689
-
1690
- function getStorage() {
1691
- // use document.cookie:
1692
- return {
1693
- set: function(id, data) {
1694
- document.cookie = id + '=' + encodeURIComponent(data);
1695
- },
1696
- get: function(id) {
1697
- var cookies = document.cookie, parsed = {};
1698
- cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
1699
- parsed[key] = decodeURIComponent(value);
1700
- });
1701
- return parsed[id];
1702
- }
1703
- };
1704
- }
1705
-
1706
- function getDocHeight(id){
1707
- var H;
1708
- if(id){
1709
- H = Math.max(
1710
- jQuery('#' + id).height(),
1711
- document.getElementById(id).clientHeight
1712
- );
1713
- } else {
1714
- H = Math.max(
1715
- jQuery(document).height(),
1716
- jQuery(window).height(),
1717
- document.documentElement.clientHeight
1718
- );
1719
- }
1720
-
1721
- return H;
1722
- };
1723
- /*
1724
- function gmHashCode(str){
1725
- var l = str.length,
1726
- hash = 5381 * l * (str.charCodeAt(0) + l);
1727
- for(var i = 0; i < str.length; i++){
1728
- hash += Math.floor((str.charCodeAt(i) + i + 0.33) / (str.charCodeAt(l - i - 1) + l) + (str.charCodeAt(i) + l) * (str.charCodeAt(l - i - 1) + i + 0.33));
1729
- }
1730
- return hash;
1731
- }
1732
- function gmCreateKey(site, lic, uuid){
1733
- if(!lic){
1734
- lic = '0:lk';
1735
- }
1736
- if(!uuid){
1737
- uuid = 'xyxx-xxyx-xxxy';
1738
- }
1739
- var d = gmHashCode((site + ':' + lic).toLowerCase());
1740
- var p = d;
1741
- uuid = uuid.replace(/[xy]/g, function(c){
1742
- var r = d % 16 | 0, v = c == 'x'? r : (r & 0x7 | 0x8);
1743
- d = Math.floor(d * 15 / 16);
1744
- return v.toString(16);
1745
- });
1746
- var key = p + ': ' + lic + '-' + uuid;
1747
- return key.toLowerCase();
1748
- }
1749
- */
1750
-
1751
- function UpdatePanelHeaders() {
1752
- jQuery(".panel-fixed-header").each(function() {
1753
- var el = jQuery(this),
1754
- headerRow = jQuery(".panel-heading", this),
1755
- offset = el.offset(),
1756
- scrollTop = jQuery(window).scrollTop(),
1757
- floatingHeader = "panel-floatingHeader",
1758
- absoluteHeader = "panel-absoluteHeader",
1759
- pad_top = jQuery('#wpadminbar').height();
1760
-
1761
- if((scrollTop > offset.top - pad_top) && (scrollTop < offset.top - pad_top + (el.height() - headerRow.outerHeight(false)) + 4)) {
1762
- el.addClass(floatingHeader).removeClass(absoluteHeader);
1763
- } else if(scrollTop > (offset.top - pad_top + (el.height() - headerRow.outerHeight(false)))) {
1764
- el.addClass(absoluteHeader).removeClass(floatingHeader);
1765
- } else {
1766
- el.removeClass(absoluteHeader + ' ' + floatingHeader)
1767
- }
1768
- });
1769
- }
1770
-
1771
- function setPanelHeadersWidth() {
1772
- jQuery(".panel-fixed-header").each(function() {
1773
- var headerRow = jQuery(".panel-heading", this);
1774
- headerRow.css("width", jQuery(this).innerWidth());
1775
- jQuery(".panel-heading-fake", this).height(headerRow.outerHeight());
1776
- });
1777
- }
 
1
+ /**
2
+ * Gmedia Library
3
+ */
4
+ var wp = window.wp || {};
5
+ var gmedia_DOM;
6
+ var GmediaLibrary = {
7
+ init: function() {
8
+ window.gm_wavesurfer = {};
9
+ if(jQuery('.gmedia-audio-item').length) {
10
+
11
+ jQuery('.gm-waveform-player').each(function() {
12
+ var data = jQuery(this).data();
13
+ data.gmid = data.id;
14
+ data.id = 'ws' + data.gmid;
15
+
16
+ if(data.peaks){
17
+ jQuery('.gm-play', this).show();
18
+ jQuery('.gm-pause', this).hide();
19
+
20
+ GmediaLibrary.waveplayer(data, true);
21
+ }
22
+ });
23
+ gmedia_DOM.on('click', '.gm-waveform', function() {
24
+ var parent = jQuery(this).parent(),
25
+ data = parent.data();
26
+
27
+ jQuery(this).remove();
28
+
29
+ GmediaLibrary.waveplayer(data);
30
+
31
+ if(data.peaks) {
32
+ //window.gm_wavesurfer[data.id].play();
33
+ } else {
34
+ window.gm_wavesurfer[data.id].on('waveform-ready', function() {
35
+ jQuery('.gm-play', parent).hide();
36
+ jQuery('.gm-pause', parent).show();
37
+ jQuery('.spinner', parent).removeClass('is-active');
38
+ var peaks = window.gm_wavesurfer[data.id].exportPCM(1800, 10000, true);
39
+ var post_data = {
40
+ action: 'gmedia_save_waveform',
41
+ id: data.gmid,
42
+ peaks: peaks,
43
+ _wpnonce: jQuery('#_wpnonce').val()
44
+ };
45
+ jQuery.post(ajaxurl, post_data, function(return_data, textStatus, jqXHR) {
46
+ var data_peaks = window.gm_wavesurfer[data.id].exportPCM(450, 10000, true);
47
+ parent.attr('data-peaks', data_peaks);
48
+ });
49
+ });
50
+ }
51
+ });
52
+ gmedia_DOM.on('click', '.gm-play, .gm-pause', function() {
53
+ var parent = jQuery(this).parent();
54
+ var data = parent.data();
55
+ if(!parent.hasClass('ws-loaded')) {
56
+ parent.addClass('ws-loaded');
57
+ window.gm_wavesurfer[data.id].load(data.file, data.peaks);
58
+ window.gm_wavesurfer[data.id].toggleInteraction();
59
+ window.gm_wavesurfer[data.id].play();
60
+ } else {
61
+ window.gm_wavesurfer[data.id].playPause();
62
+ }
63
+ });
64
+
65
+ var resize;
66
+ jQuery(window).on('resize.gmedia', function(){
67
+ clearTimeout(resize);
68
+ resize = setTimeout(function(){
69
+ jQuery('.gm-waveform-player').each(function() {
70
+ var data = jQuery(this).data();
71
+ if(data.peaks && window.gm_wavesurfer[data.id]){
72
+ window.gm_wavesurfer[data.id].load(data.file, data.peaks);
73
+ }
74
+ });
75
+ }, 500);
76
+ });
77
+
78
+ }
79
+
80
+ if(jQuery('body').hasClass('GrandMedia_edit')) {
81
+ GmediaLibrary.editmode();
82
+ }
83
+
84
+ if(jQuery('body').hasClass('gmedia_library')) {
85
+ var previewFrame = jQuery('#previewFrame', window.parent.document);
86
+ jQuery(window).on('load.gmedia', function(){
87
+ setTimeout(function(){
88
+ previewFrame.animate({'height': getDocHeight('gmedia_iframe_content') + 3}, 200);
89
+ }, 10);
90
+ });
91
+ var refresh = !jQuery('body').is('.GrandMedia_select_single, .GrandMedia_select_multiple');
92
+ var observer = new MutationObserver(function(mutations) {
93
+ previewFrame.height(getDocHeight('gmedia_iframe_content') + 3);
94
+ if(refresh) {
95
+ jQuery('#previewModal', window.parent.document).attr('data-refresh', 'true');
96
+ }
97
+ });
98
+ var gmedia_iframe_content = window.document.getElementById('gmedia_iframe_content');
99
+ observer.observe(gmedia_iframe_content, {
100
+ childList: true,
101
+ subtree: true,
102
+ attributes: true,
103
+ attributeFilter: ['value']
104
+ });
105
+ }
106
+
107
+ },
108
+ waveplayer: function(data, draw) {
109
+ window.gm_wavesurfer[data.id] = Object.create(WaveSurfer);
110
+ window.gm_wavesurfer[data.id].init({
111
+ container: '#' + data.id,
112
+ waveColor: '#428bca',
113
+ progressColor: '#31708f',
114
+ backend: 'MediaElement',
115
+ renderer: 'Canvas',
116
+ height: 60,
117
+ interact: false,
118
+ barWidth: 0
119
+ });
120
+ // Play on audio load
121
+ var parent = jQuery(window.gm_wavesurfer[data.id].container).parent();
122
+
123
+ if(!parent.hasClass('ws-loaded')) {
124
+ if(draw) {
125
+ window.gm_wavesurfer[data.id].backend.setPeaks(data.peaks);
126
+ window.gm_wavesurfer[data.id].drawBuffer();
127
+ } else {
128
+ parent.addClass('ws-loaded');
129
+ window.gm_wavesurfer[data.id].load(data.file, data.peaks);
130
+ window.gm_wavesurfer[data.id].toggleInteraction();
131
+ window.gm_wavesurfer[data.id].play();
132
+ }
133
+ } else {
134
+ window.gm_wavesurfer[data.id].play();
135
+ }
136
+
137
+ jQuery(window.gm_wavesurfer[data.id].container).on('click', function(e) {
138
+ if(!parent.hasClass('ws-loaded')) {
139
+ parent.addClass('ws-loaded');
140
+ window.gm_wavesurfer[data.id].load(data.file, data.peaks);
141
+ window.gm_wavesurfer[data.id].toggleInteraction();
142
+ window.gm_wavesurfer[data.id].play();
143
+ }
144
+ if(window.gm_wavesurfer[data.id].isPlaying()) {
145
+ window.gm_wavesurfer[data.id].backend.media.currentTime = 0;
146
+ } else{
147
+ window.gm_wavesurfer[data.id].play();
148
+ }
149
+ });
150
+
151
+ window.gm_wavesurfer[data.id].on('play', function() {
152
+ parent.find('.gm-play').hide();
153
+ parent.find('.gm-pause').show();
154
+ parent.find('.spinner').removeClass('is-active');
155
+
156
+ jQuery.each(window.gm_wavesurfer, function(id) {
157
+ if(id !== data.id && window.gm_wavesurfer[id].isPlaying()) {
158
+ window.gm_wavesurfer[id].pause();
159
+ }
160
+ });
161
+ })
162
+ window.gm_wavesurfer[data.id].on('pause', function() {
163
+ parent.find('.gm-play').show();
164
+ parent.find('.gm-pause').hide();
165
+ });
166
+ window.gm_wavesurfer[data.id].on('loading', function(p) {
167
+ if(p == 100) {
168
+ //parent.find('.spinner').removeClass('is-active');
169
+ } else {
170
+ parent.find('.spinner').addClass('is-active');
171
+ }
172
+ });
173
+ },
174
+ /**
175
+ * Edit Mode
176
+ */
177
+ editmode: function() {
178
+ var focus_input_val;
179
+ // SelectBox for albums
180
+ var combobox_albums = jQuery('.combobox_gmedia_album');
181
+ var selectize_albums = combobox_albums.selectize({
182
+ create: (combobox_albums.data('create')? true : false),
183
+ onOptionAdd: function(value, data){
184
+ jQuery.each(selectize_albums, function(i, e){
185
+ e.selectize.options[value] = data;
186
+ });
187
+ },
188
+ onFocus: function(){
189
+ this.$input.addClass('edit-gmedia-ignore');
190
+ focus_input_val = this.$input.val();
191
+ },
192
+ onBlur: function(){
193
+ this.$input.removeClass('edit-gmedia-ignore');
194
+ if(focus_input_val != this.$input.val()) {
195
+ var inporder = this.$input.prev('.gm-order-input');
196
+ inporder.val('0');
197
+ if('' == this.$input.val()){
198
+ inporder.prop('disabled', true);
199
+ } else {
200
+ inporder.prop('disabled', false);
201
+ }
202
+ this.$input.trigger('change');
203
+ }
204
+ },
205
+ persist: true
206
+ });
207
+
208
+ if(window.gmedia_categories) {
209
+ var categories = jQuery('.combobox_gmedia_category');
210
+ if(categories.length) {
211
+ var categories_data = window.gmedia_categories.map(function(x) {
212
+ return {item: x};
213
+ });
214
+
215
+ var selectize_categories = categories.selectize({
216
+ create: function(input) {
217
+ if(categories.data('create')) {
218
+ return {
219
+ item: input
220
+ }
221
+ } else {
222
+ return false;
223
+ }
224
+ },
225
+ onOptionAdd: function(value, data){
226
+ jQuery.each(selectize_categories, function(i, e){
227
+ e.selectize.options[value] = data;
228
+ });
229
+ },
230
+ onFocus: function(){
231
+ this.$input.addClass('edit-gmedia-ignore');
232
+ focus_input_val = this.$input.val();
233
+ },
234
+ onBlur: function(){
235
+ this.$input.removeClass('edit-gmedia-ignore');
236
+ if(focus_input_val != this.$input.val()) {
237
+ this.$input.trigger('change');
238
+ }
239
+ },
240
+ createOnBlur: true,
241
+ delimiter: ',',
242
+ maxItems: null,
243
+ openOnFocus: true,
244
+ persist: true,
245
+ options: categories_data,
246
+ labelField: 'item',
247
+ valueField: 'item',
248
+ searchField: ['item'],
249
+ hideSelected: true
250
+ });
251
+ }
252
+ }
253
+ if(window.gmedia_tags) {
254
+ var tags = jQuery('.combobox_gmedia_tag');
255
+ if(tags.length) {
256
+ var tags_data = window.gmedia_tags.map(function(x) {
257
+ return {item: x};
258
+ });
259
+
260
+ var selectize_tags = tags.selectize({
261
+ create: function(input) {
262
+ if(this.$input.data('create')) {
263
+ var option = { item: input }
264
+ tags_data.push(option);
265
+ return option;
266
+ } else {
267
+ return false;
268
+ }
269
+ },
270
+ onOptionAdd: function(value, data){
271
+ jQuery.each(selectize_tags, function(i, e){
272
+ e.selectize.options[value] = data;
273
+ });
274
+ },
275
+ onFocus: function(){
276
+ this.$input.addClass('edit-gmedia-ignore');
277
+ focus_input_val = this.$input.val();
278
+ },
279
+ onBlur: function(){
280
+ this.$input.removeClass('edit-gmedia-ignore');
281
+ if(focus_input_val != this.$input.val()) {
282
+ this.$input.trigger('change');
283
+ }
284
+ },
285
+ createOnBlur: true,
286
+ delimiter: ',',
287
+ maxItems: null,
288
+ openOnFocus: true,
289
+ persist: true,
290
+ options: tags_data,
291
+ labelField: 'item',
292
+ valueField: 'item',
293
+ searchField: ['item'],
294
+ hideSelected: true
295
+ });
296
+
297
+ }
298
+ }
299
+
300
+ // Date/Time picker
301
+ var gmedia_date_temp;
302
+ jQuery('.input-group.gmedia_date').datetimepicker({format: 'YYYY-MM-DD HH:mm:ss', focusOnShow: true, ignoreReadonly: true, allowInputToggle: true}).on('dp.show', function() {
303
+ gmedia_date_temp = jQuery('input', this).val();
304
+ }).on('dp.hide', function() {
305
+ if(jQuery('input', this).val() !== gmedia_date_temp) {
306
+ jQuery('input', this).trigger('modified');
307
+ }
308
+ });
309
+
310
+ // Mask for filename input
311
+ var inp_filename = jQuery('input.gmedia-filename').not('[readonly]');
312
+ if(inp_filename.length) {
313
+ inp_filename.alphanum({
314
+ allow: '-_',
315
+ disallow: '',
316
+ allowSpace: false,
317
+ allowNumeric: true,
318
+ allowUpper: true,
319
+ allowLower: true,
320
+ allowCaseless: true,
321
+ allowLatin: true,
322
+ allowOtherCharSets: false,
323
+ forceUpper: false,
324
+ forceLower: false,
325
+ maxLength: NaN
326
+ });
327
+ }
328
+
329
+ if(jQuery('#wp-link-wrap').parent().hasClass('hidden')){
330
+ jQuery('#wp-link-backdrop, #wp-link-wrap').appendTo('body');
331
+ }
332
+ jQuery(document).on('click.gmedia', '.gmedia-custom-link', function(e) {
333
+ var editorId = jQuery(this).attr('data-target');
334
+ wpActiveEditor = true;
335
+ wpLink.open(editorId);
336
+ wpLink.gmediaCustomLinkTarget = editorId;
337
+ jQuery('#wp-link-wrap').removeClass('has-text-field').addClass('gmLinkModal').find('.link-target').css('visibility','hidden');
338
+
339
+ return false;
340
+ });
341
+ function closeLinkModal(){
342
+ jQuery('#wp-link-wrap').removeClass('gmLinkModal').find('.link-target').removeAttr('style');
343
+ wpLink.close();
344
+ }
345
+ jQuery(document).on('click.gmedia', '.gmLinkModal #wp-link-submit', function(e) {
346
+ e.preventDefault ? e.preventDefault() : e.returnValue = false;
347
+ e.stopPropagation();
348
+
349
+ var link = wpLink.getAttrs();
350
+ wpLink.textarea = jQuery('#' + wpLink.gmediaCustomLinkTarget);
351
+
352
+ if (!link.href) {
353
+ closeLinkModal();
354
+ return;
355
+ }
356
+ wpLink.textarea.val(link.href).trigger('change');
357
+ closeLinkModal();
358
+ });
359
+ jQuery(document).on('click.gmedia', '#wp-link-cancel, #wp-link-close, #wp-link-backdrop', function(e) {
360
+ closeLinkModal()
361
+ });
362
+
363
+ var related_sortable = jQuery('.related-media-previews');
364
+ if(related_sortable.length){
365
+ related_sortable.sortable({
366
+ items: '.gmedia-related-image',
367
+ handle: '.image-wrapper',
368
+ placeholder: 'gmedia-related-image',
369
+ tolerance: 'pointer',
370
+ //helper: 'clone',
371
+ revert: true,
372
+ forcePlaceholderSize: true,
373
+ stop: function(event, ui){
374
+ console.log(ui);
375
+ ui.item.find('input').trigger('change');
376
+ }
377
+ });
378
+ }
379
+
380
+
381
+ }
382
+ };
383
+
384
+ /**
385
+ * Gmedia AddMedia
386
+ */
387
+ var GmediaAddMedia = {
388
+ init: function() {
389
+
390
+ if(jQuery('body').hasClass('GrandMedia_AddMedia')) {
391
+ gmedia_DOM.on('change', '#uploader_runtime select', function() {
392
+ if('html4' == jQuery(this).val()) {
393
+ jQuery('#uploader_chunking').addClass('hide');
394
+ jQuery('#uploader_urlstream_upload').addClass('hide');
395
+ } else {
396
+ jQuery('#uploader_chunking').removeClass('hide');
397
+ jQuery('#uploader_urlstream_upload').removeClass('hide');
398
+ }
399
+ });
400
+ }
401
+
402
+ var albums = jQuery('select#combobox_gmedia_album');
403
+ if(albums.length) {
404
+ var albums_data = jQuery('option', albums);
405
+ albums.selectize({
406
+ create: function(input) {
407
+ if(albums.data('create')) {
408
+ return {
409
+ value: input,
410
+ text: input
411
+ }
412
+ } else {
413
+ return false;
414
+ }
415
+ },
416
+ createOnBlur: true,
417
+ persist: false,
418
+ render: {
419
+ item: function(item, escape) {
420
+ if(0 === (parseInt(item.value, 10) || 0)) {
421
+ return '<div>' + escape(item.text) + '</div>';
422
+ }
423
+ if(item.$order) {
424
+ var data = jQuery(albums_data[item.$order]).data();
425
+ return '<div>' + escape(data.name) + ' <small>' + escape(data.meta) + '</small></div>';
426
+ }
427
+ },
428
+ option: function(item, escape) {
429
+ if(0 === (parseInt(item.value) || 0)) {
430
+ return '<div>' + escape(item.text) + '</div>';
431
+ }
432
+ if(item.$order) {
433
+ var data = jQuery(albums_data[item.$order]).data();
434
+ return '<div>' + escape(data.name) + ' <small>' + escape(data.meta) + '</small></div>';
435
+ }
436
+ }
437
+ }
438
+ });
439
+ }
440
+
441
+ if(window.gmedia_tags) {
442
+ var tags = jQuery('#combobox_gmedia_tag');
443
+ if(tags.length) {
444
+ var tags_data = window.gmedia_tags.map(function(x) {
445
+ return {item: x};
446
+ });
447
+
448
+ tags.selectize({
449
+ create: function(input) {
450
+ if(tags.data('create')) {
451
+ return {
452
+ item: input
453
+ }
454
+ } else {
455
+ return false;
456
+ }
457
+ },
458
+ createOnBlur: true,
459
+ delimiter: ',',
460
+ maxItems: null,
461
+ openOnFocus: true,
462
+ persist: false,
463
+ options: tags_data,
464
+ labelField: 'item',
465
+ valueField: 'item',
466
+ searchField: ['item'],
467
+ hideSelected: true
468
+ });
469
+ }
470
+ }
471
+ if(window.gmedia_categories) {
472
+ var categories = jQuery('#combobox_gmedia_category');
473
+ if(categories.length) {
474
+ var categories_data = window.gmedia_categories.map(function(x) {
475
+ return {item: x};
476
+ });
477
+
478
+ categories.selectize({
479
+ create: function(input) {
480
+ if(categories.data('create')) {
481
+ return {
482
+ item: input
483
+ }
484
+ } else {
485
+ return false;
486
+ }
487
+ },
488
+ createOnBlur: true,
489
+ delimiter: ',',
490
+ maxItems: null,
491
+ openOnFocus: true,
492
+ persist: false,
493
+ options: categories_data,
494
+ labelField: 'item',
495
+ valueField: 'item',
496
+ searchField: ['item'],
497
+ hideSelected: true
498
+ });
499
+ }
500
+ }
501
+
502
+
503
+ },
504
+ /**
505
+ * Gmedia Import
506
+ */
507
+ importmode: function() {
508
+ }
509
+ };
510
+
511
+ /**
512
+ * Gmedia Terms
513
+ */
514
+ var GmediaTerms = {
515
+ init: function(){
516
+
517
+ if(jQuery('body').hasClass('GrandMedia_Tags')){
518
+ jQuery('#gm-list-table').data('edit', false);
519
+ gmedia_DOM.on('keypress', 'input.edit_tag_input', function(e){
520
+ var tagdiv = jQuery('#tag_' + jQuery(this).data('tag_id'));
521
+ var charCode = e.charCode || e.keyCode || e.which;
522
+ if(charCode == 13){
523
+ e.preventDefault();
524
+ edit_tag(tagdiv);
525
+ }
526
+ }).on('blur', 'input.edit_tag_input', function(){
527
+ var tagdiv = jQuery('#tag_' + jQuery(this).data('tag_id'));
528
+ edit_tag(tagdiv);
529
+ });
530
+
531
+ gmedia_DOM.on('click', '.edit_tag_link', function(e){
532
+ e.preventDefault();
533
+ var id = jQuery(this).attr('href');
534
+ jQuery(this).hide();
535
+ jQuery(id).find('.edit_tag_form').show().find('input').focus();
536
+ jQuery('#gm-list-table').data('edit', true);
537
+ });
538
+ gmedia_DOM.on('click', '.edit_tag_save', function(e){
539
+ e.preventDefault();
540
+ });
541
+
542
+ function edit_tag(tagdiv){
543
+ var inp = tagdiv.find('.edit_tag_form input');
544
+ var new_tag_name = jQuery.trim(inp.val());
545
+ var old_tag_name = inp.attr('placeholder');
546
+ if((old_tag_name == new_tag_name) || ('' === new_tag_name) || jQuery.isNumeric()){
547
+ inp.val(old_tag_name);
548
+ tagdiv.find('.edit_tag_form').hide();
549
+ tagdiv.find('.edit_tag_link').show();
550
+ return;
551
+ }
552
+ var post_data = {
553
+ action: 'gmedia_tag_edit',
554
+ tag_id: inp.data('tag_id'),
555
+ tag_name: new_tag_name,
556
+ _wpnonce_terms: jQuery('#_wpnonce_terms').val()
557
+ };
558
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR){
559
+ console.log(data);
560
+ if(data.error){
561
+ //inp.val(inp.attr('placeholder'));
562
+ jQuery('#gmedia-panel').before(data.error);
563
+ } else{
564
+ //new_tag_name = new_tag_name.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
565
+ inp.attr('placeholder', new_tag_name);
566
+ tagdiv.find('.edit_tag_link').text(new_tag_name).show();
567
+ //noinspection JSUnresolvedVariable
568
+ jQuery('#gmedia-panel').before(data.msg);
569
+ tagdiv.find('.edit_tag_form').hide();
570
+ }
571
+ });
572
+ }
573
+ }
574
+
575
+ gmedia_DOM.on('click', '.term-shortcode input', function(){
576
+ this.setSelectionRange(0, 0);
577
+ this.setSelectionRange(0, this.value.length);
578
+ });
579
+ gmedia_DOM.on('change', '.term-shortcode input', function(){
580
+ shortcode_inp_autowidth(this);
581
+ });
582
+ jQuery('.term-shortcode input', gmedia_DOM).each(function(i, e){
583
+ shortcode_inp_autowidth(this)
584
+ });
585
+
586
+ function shortcode_inp_autowidth(e){
587
+ var inp = jQuery(e),
588
+ buffer = inp.next('.input-buffer');
589
+ buffer.text(inp.val());
590
+ inp.width(buffer.width());
591
+ }
592
+
593
+ var sortable = jQuery('#gm-sortable');
594
+ if(sortable.length && !jQuery('#gmedia-panel', sortable).hasClass('gmedia-filtered')){
595
+ var sortdiv = jQuery('#gm-list-table', sortable);
596
+ var post_data = sortable.data();
597
+ post_data['idx0'] = parseInt(sortdiv.attr('data-idx0'));
598
+
599
+ var _ids = [];
600
+ jQuery('.gm-item-cell', sortdiv).each(function(index){
601
+ _ids.push(jQuery(this).attr('data-id'));
602
+ });
603
+ sortdiv.sortable({
604
+ items: '.gm-item-cell',
605
+ handle: '.cb_media-object',
606
+ placeholder: 'cb_list-item gm-item-cell col-xs-6 col-sm-4 col-md-3 col-lg-2 gmedia-image-item ui-highlight-placeholder',
607
+ tolerance: 'pointer',
608
+ helper: 'clone',
609
+ revert: true,
610
+ forcePlaceholderSize: true,
611
+ stop: function(event, ui){
612
+ var ids = [];
613
+ jQuery('.gm-item-cell', sortdiv).each(function(index){
614
+ ids.push(jQuery(this).attr('data-id'));
615
+ });
616
+
617
+ if(_ids.toString() != ids.toString()){
618
+ _ids = ids;
619
+ jQuery('.panel-heading .spinner', sortable).addClass('is-active');
620
+ post_data['ids'] = ids
621
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR){
622
+ jQuery('.panel-heading .spinner', sortable).removeClass('is-active');
623
+ console.log(data);
624
+ });
625
+ }
626
+ }
627
+ });
628
+ }
629
+
630
+ gmedia_DOM.on('change', '#gmedia_term_orderby', function(){
631
+ if('custom' == jQuery(this).val()){
632
+ jQuery('#gmedia_term_order').val('ASC').addClass('disabled');
633
+ } else{
634
+ jQuery('#gmedia_term_order').removeClass('disabled');
635
+ }
636
+ });
637
+
638
+ // Date/Time picker
639
+ if(jQuery.fn.datetimepicker){
640
+ jQuery('.input-group.gmedia_date').datetimepicker({format: 'YYYY-MM-DD HH:mm:ss', focusOnShow: true, ignoreReadonly: true, allowInputToggle: true});
641
+ }
642
+ }
643
+ };
644
+
645
+ var GmediaSelect = {
646
+ msg_stack: function(global) {
647
+ var gm_cb = jQuery('.gm-stack input');
648
+ var sel = jQuery('#gm-stack');
649
+ if(!sel.length) {
650
+ return;
651
+ }
652
+
653
+ var arr = sel.val().split(',');
654
+ arr = jQuery.grep(arr, function(e) {
655
+ return (e);
656
+ });
657
+
658
+ if(global) {
659
+ var cur = false;
660
+ gm_cb.each(function() {
661
+ cur = jQuery(this);
662
+ if(cur.is(':checked') && (jQuery.inArray(cur.val(), arr) === -1)) {
663
+ cur.prop('checked', false);
664
+ } else if(!(cur.is(':checked')) && (jQuery.inArray(cur.val(), arr) !== -1)) {
665
+ cur.prop('checked', true);
666
+ }
667
+ });
668
+ }
669
+
670
+ if(sel.data('userid')) {
671
+ var storedData = getStorage();
672
+ storedData.set(sel.data('key'), arr.join('.'));
673
+ }
674
+ jQuery('#gm-stack-qty').text(arr.length);
675
+ if(arr.length) {
676
+ jQuery('#gm-stack-btn').removeClass('hidden');
677
+ jQuery('.rel-stack-show').show();
678
+ jQuery('.rel-stack-hide').hide();
679
+ }
680
+ else {
681
+ jQuery('#gm-stack-btn').addClass('hidden');
682
+ jQuery('.rel-stack-show').hide();
683
+ jQuery('.rel-stack-hide').show();
684
+ }
685
+ sel.trigger('change');
686
+ },
687
+ msg_selected: function(obj, global) {
688
+ var gm_cb = jQuery('.' + obj + ' input'),
689
+ qty_v = gm_cb.length,
690
+ sel_v = gm_cb.filter(':checked').length,
691
+ c = jQuery('#cb_global');
692
+ if((sel_v != qty_v) && (0 !== sel_v)) {
693
+ c.css('opacity', '0.5').prop('checked', true);
694
+ } else if((sel_v == qty_v) && (0 !== qty_v)) {
695
+ c.css('opacity', '1').prop('checked', true);
696
+ } else if(0 === sel_v) {
697
+ c.css('opacity', '1').prop('checked', false);
698
+ }
699
+
700
+ var sel = jQuery('#gm-selected');
701
+ if(!sel.length) {
702
+ return;
703
+ }
704
+
705
+ var arr = sel.val().split(',');
706
+
707
+ arr = jQuery.grep(arr, function(e) {
708
+ return (e);
709
+ });
710
+ if(global) {
711
+ var cur = false;
712
+ gm_cb.each(function() {
713
+ cur = jQuery(this);
714
+ if(cur.is(':checked') && (jQuery.inArray(cur.val(), arr) === -1)) {
715
+ arr.push(cur.val());
716
+ } else if(!(cur.is(':checked')) && (jQuery.inArray(cur.val(), arr) !== -1)) {
717
+ arr = jQuery.grep(arr, function(e) {
718
+ return e != cur.val();
719
+ });
720
+ }
721
+ });
722
+ sel.val(arr.join(','));
723
+ }
724
+
725
+ if(sel.data('userid')) {
726
+ var storedData = getStorage();
727
+ storedData.set(sel.data('key'), arr.join('.'));
728
+ }
729
+ jQuery('#gm-selected-qty').text(arr.length);
730
+
731
+ var selbtn = jQuery('#gm-selected-btn');
732
+ if(arr.length) {
733
+ selbtn.removeClass('hidden');
734
+ jQuery('.rel-selected-show').show();
735
+ jQuery('.rel-selected-hide').hide();
736
+ }
737
+ else {
738
+ if(!selbtn.hasClass('gm-active')) {
739
+ jQuery('#gm-selected-btn').addClass('hidden');
740
+ }
741
+ jQuery('.rel-selected-show').hide();
742
+ jQuery('.rel-selected-hide').show();
743
+ }
744
+ sel.trigger('change');
745
+ },
746
+ chk_all: function(type, obj) {
747
+ jQuery('.' + obj + ' input').filter(function() {
748
+ return type? jQuery(this).data('type') == type : true;
749
+ }).prop('checked', true).closest('.cb_list-item').addClass('gm-selected');
750
+ },
751
+ chk_none: function(type, obj) {
752
+ jQuery('.' + obj + ' input').filter(function() {
753
+ return type? jQuery(this).data('type') == type : true;
754
+ }).prop('checked', false).closest('.cb_list-item').removeClass('gm-selected');
755
+ },
756
+ chk_toggle: function(type, obj) {
757
+ if(type) {
758
+ if(jQuery('.' + obj + ' input:checked').filter(function() {
759
+ return jQuery(this).data('type') == type;
760
+ }).length) {
761
+ GmediaSelect.chk_none(type, obj);
762
+ } else {
763
+ GmediaSelect.chk_all(type, obj);
764
+ }
765
+ } else {
766
+ jQuery('.' + obj + ' input').each(function() {
767
+ jQuery(this).prop("checked", !jQuery(this).prop("checked")).closest('.cb_list-item').toggleClass('gm-selected');
768
+ });
769
+ }
770
+ },
771
+ init: function() {
772
+ var cb_obj = jQuery('#cb_global').data('group');
773
+
774
+ if(jQuery('#gm-selected').length) {
775
+ GmediaSelect.msg_selected(cb_obj);
776
+ gmedia_DOM.on('click', '#gm-selected-clear', function(e) {
777
+ jQuery('#gm-selected').val('');
778
+ GmediaSelect.chk_none(false, cb_obj);
779
+ GmediaSelect.msg_selected(cb_obj);
780
+ e.preventDefault();
781
+ });
782
+ gmedia_DOM.on('click', '#gm-selected-show', function(e) {
783
+ jQuery('#gm-selected-btn').submit();
784
+ e.preventDefault();
785
+ });
786
+ gmedia_DOM.on('click', '#gm-stack-in', function(e) {
787
+ e.preventDefault();
788
+ var stack_obj = jQuery('#gm-stack'),
789
+ sel_obj = jQuery('#gm-selected'),
790
+ stack = stack_obj.val().split(','),
791
+ selected = sel_obj.val().split(','),
792
+ arr = stack.concat(selected);
793
+ arr = jQuery.grep(arr, function(e) {
794
+ return (e);
795
+ });
796
+ arr = jQuery.unique(arr);
797
+ stack_obj.val(arr.join(','));
798
+ GmediaSelect.msg_stack(true);
799
+ //sel_obj.val('');
800
+ //GmediaSelect.chk_none(false, cb_obj);
801
+ //GmediaSelect.msg_selected(cb_obj);
802
+ });
803
+ gmedia_DOM.on('click', '#gm-stack-out', function(e) {
804
+ e.preventDefault();
805
+ var stack_obj = jQuery('#gm-stack'),
806
+ sel_obj = jQuery('#gm-selected'),
807
+ stack = stack_obj.val().split(','),
808
+ selected = sel_obj.val().split(','),
809
+ arr = jQuery(stack).not(selected).get();
810
+ arr = jQuery.grep(arr, function(e) {
811
+ return (e);
812
+ });
813
+ arr = jQuery.unique(arr);
814
+ stack_obj.val(arr.join(','));
815
+ GmediaSelect.msg_stack(true);
816
+ //sel_obj.val('');
817
+ //GmediaSelect.chk_none(false, cb_obj);
818
+ //GmediaSelect.msg_selected(cb_obj);
819
+ });
820
+ }
821
+ gmedia_DOM.on('click', '#cb_global', function() {
822
+ if(jQuery(this).is(':checked')) {
823
+ GmediaSelect.chk_all(false, cb_obj);
824
+ } else {
825
+ GmediaSelect.chk_none(false, cb_obj);
826
+ }
827
+ GmediaSelect.msg_selected(cb_obj, true);
828
+ });
829
+ gmedia_DOM.on('click', '#cb_global-btn li a', function(e) {
830
+ var sel = jQuery(this).data('select');
831
+ switch(sel) {
832
+ case 'total':
833
+ GmediaSelect.chk_all(false, cb_obj);
834
+ break;
835
+ case 'none':
836
+ GmediaSelect.chk_none(false, cb_obj);
837
+ break;
838
+ case 'reverse':
839
+ GmediaSelect.chk_toggle(false, cb_obj);
840
+ break;
841
+ case 'image':
842
+ case 'audio':
843
+ case 'video':
844
+ GmediaSelect.chk_toggle(sel, cb_obj);
845
+ break;
846
+ }
847
+ GmediaSelect.msg_selected(cb_obj, true);
848
+ e.preventDefault();
849
+ });
850
+ gmedia_DOM.on('change', '.gm-item-check input:checkbox, .cb_object input:checkbox', function() {
851
+ var selected = jQuery('#gm-selected'),
852
+ arr = selected.val();
853
+ var cur = jQuery(this).val();
854
+ if(jQuery(this).is(':checked')) {
855
+ if(arr) {
856
+ arr = arr + ',' + cur;
857
+ } else {
858
+ arr = cur;
859
+ }
860
+ } else {
861
+ arr = jQuery.grep(arr.split(','), function(a) {
862
+ return a != cur;
863
+ }).join(',');
864
+ }
865
+ jQuery('#list-item-' + cur).toggleClass('gm-selected');
866
+ selected.val(arr);
867
+ GmediaSelect.msg_selected(cb_obj);
868
+ });
869
+
870
+ gmedia_DOM.on('click', '.gm-item-check input:radio', function() {
871
+ var id = jQuery(this).val(), img, checked_thumb, data;
872
+ jQuery('#list-item-' + id).addClass('gm-selected').siblings().removeClass('gm-selected');
873
+ img = jQuery(this).closest('.thumbnail').find('.gmedia-thumb').clone();
874
+ checked_thumb = jQuery('#gmedia-panel .panel-heading .checked_thumb');
875
+ if(!checked_thumb.length){
876
+ checked_thumb = jQuery('<div class="checked_thumb"></div>').appendTo(jQuery('#gmedia-panel .panel-heading'));
877
+ }
878
+ checked_thumb.html(img);
879
+ data = {'id':id, 'src':img.attr('src')};
880
+ window.parent.gmediaTempData = data;
881
+ });
882
+
883
+ if(jQuery('#gm-stack').length) {
884
+ GmediaSelect.msg_stack();
885
+ gmedia_DOM.on('click', '#gm-stack-clear', function(e) {
886
+ jQuery('#gm-stack').val('');
887
+ jQuery('.gm-stack input').prop('checked', false);
888
+ GmediaSelect.msg_stack();
889
+ e.preventDefault();
890
+ });
891
+ gmedia_DOM.on('click', '#gm-stack-show', function(e) {
892
+ jQuery('#gm-stack-btn').submit();
893
+ e.preventDefault();
894
+ });
895
+
896
+ }
897
+ gmedia_DOM.on('change', '.gm-stack input:checkbox', function() {
898
+ var selected = jQuery('#gm-stack'),
899
+ arr = selected.val();
900
+ var cur = jQuery(this).val();
901
+ if(jQuery(this).is(':checked')) {
902
+ if(arr) {
903
+ arr = arr + ',' + cur;
904
+ } else {
905
+ arr = cur;
906
+ }
907
+ } else {
908
+ arr = jQuery.grep(arr.split(','), function(a) {
909
+ return a != cur;
910
+ }).join(',');
911
+ }
912
+ selected.val(arr);
913
+ GmediaSelect.msg_stack();
914
+ });
915
+
916
+ gmedia_DOM.on('click', '.term-label', function(e) {
917
+ if('DIV' == e.target.nodeName) {
918
+ if(!jQuery('#gm-list-table').data('edit')) {
919
+ var cb = jQuery('input:checkbox', this);
920
+ cb.prop("checked", !cb.prop("checked")).change();
921
+ jQuery(this).closest('.term-list-item').toggleClass('gm-selected');
922
+ } else {
923
+ jQuery('#gm-list-table').data('edit', false);
924
+ }
925
+ }
926
+ });
927
+ }
928
+ }
929
+
930
+ var GmediaFunction = {
931
+ confirm: function(txt) {
932
+ if(!txt) {
933
+ return true;
934
+ }
935
+ var r = false;
936
+ //noinspection UnusedCatchParameterJS
937
+ try{
938
+ r = confirm(txt);
939
+ }
940
+ catch(err){
941
+ alert('Disable Popup Blocker');
942
+ }
943
+ return r;
944
+ },
945
+ init: function() {
946
+ jQuery('#toplevel_page_GrandMedia').addClass('current').removeClass('wp-not-current-submenu');
947
+ if(!("ontouchstart" in document.documentElement)) {
948
+ jQuery('html').addClass('no-touch');
949
+ }
950
+
951
+ //jQuery(document).ajaxStart(function(a,b,c){
952
+ // //jQuery('body').addClass('gmedia-busy');
953
+ // jQuery('.panel-heading .spinner').addClass('is-active');
954
+ //}).ajaxStop(function(){
955
+ // //jQuery('body').removeClass('gmedia-busy');
956
+ // jQuery('.panel-heading .spinner').removeClass('is-active');
957
+ //});
958
+
959
+ gmedia_DOM.on('click', '[data-confirm]', function() {
960
+ return GmediaFunction.confirm(jQuery(this).data('confirm'));
961
+ });
962
+
963
+ jQuery(document).on('click.gmedia', '.gm_service_action', function() {
964
+ var el = jQuery(this),
965
+ service = jQuery(this).attr('data-action'),
966
+ nonce = jQuery(this).attr('data-nonce');
967
+ var post_data = {
968
+ action: 'gmedia_application',
969
+ service: service,
970
+ _wpnonce: nonce
971
+ };
972
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
973
+ console.log(data);
974
+ el.siblings('.spinner').removeClass('is-active');
975
+ if(data.error) {
976
+ jQuery('#gmedia-service-msg-panel').prepend(data.error);
977
+ } else if(data.message) {
978
+ jQuery('#gmedia-service-msg-panel').html(data.message);
979
+ }
980
+ });
981
+
982
+ el.siblings('.spinner').addClass('is-active');
983
+ jQuery('.gmedia-service__message').remove();
984
+ });
985
+
986
+ gmedia_DOM.on('click', '.show-settings-link', function(e) {
987
+ e.preventDefault();
988
+ jQuery('#show-settings-link').trigger('click');
989
+ });
990
+
991
+ gmedia_DOM.on('click', '.fit-thumbs', function(e) {
992
+ e.preventDefault();
993
+ jQuery(this).toggleClass('btn-success btn-default');
994
+ jQuery('.display-as-grid').toggleClass('invert-ratio');
995
+ jQuery.get(jQuery(this).attr('href'), {ajaxload: 1});
996
+ });
997
+
998
+ gmedia_DOM.on('click', '.gm-cell-more-btn, .gm-cell-title', function() {
999
+ jQuery(this).parent().toggleClass('gm-cell-more-active');
1000
+ });
1001
+
1002
+ jQuery('div.gmedia-modal', gmedia_DOM).each(function(){
1003
+ var id = jQuery(this).attr('id');
1004
+ jQuery('body').children('#' + id).remove();
1005
+ jQuery(this).appendTo('body');
1006
+ });
1007
+ gmedia_DOM.on('click', 'a.gmedia-modal', function(e) {
1008
+ jQuery('body').addClass('gmedia-busy');
1009
+ var modal_div = jQuery(jQuery(this).attr('href'));
1010
+ var post_data = jQuery(this).data();
1011
+ post_data['_wpnonce'] = jQuery('#_wpnonce').val();
1012
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1013
+ if(!data || ('-1' == data)) {
1014
+ jQuery('body').removeClass('gmedia-busy');
1015
+ alert(data);
1016
+ return false;
1017
+ }
1018
+ jQuery('.modal-dialog', modal_div).html(data);
1019
+ modal_div.modal({
1020
+ backdrop: 'static',
1021
+ show: true,
1022
+ keyboard: false
1023
+ }).one('hidden.bs.modal', function() {
1024
+ jQuery('.modal-dialog', this).empty();
1025
+ });
1026
+ jQuery('body').removeClass('gmedia-busy');
1027
+ });
1028
+ e.preventDefault();
1029
+ });
1030
+
1031
+ gmedia_DOM.on('click', 'a.gmedit-modal', function(e) {
1032
+ e.preventDefault();
1033
+ var modal_div = jQuery(jQuery(this).data('target'));
1034
+ jQuery('.modal-content', modal_div).html(
1035
+ jQuery('<iframe />', {
1036
+ name: 'gmeditFrame',
1037
+ id: 'gmeditFrame',
1038
+ width: '100%',
1039
+ height: '500',
1040
+ src: jQuery(this).attr('href')
1041
+ }).css({display: 'block', margin: '4px 0'})
1042
+ );
1043
+ modal_div.modal({
1044
+ backdrop: true,
1045
+ show: true,
1046
+ keyboard: false
1047
+ }).one('hidden.bs.modal', function() {
1048
+ jQuery('.modal-content', this).empty();
1049
+ });
1050
+ });
1051
+
1052
+ jQuery(document).on('click.gmedia', 'a.preview-modal', function(e) {
1053
+ e.preventDefault();
1054
+ var initiator = jQuery(this),
1055
+ data = initiator.data(),
1056
+ modal_div = jQuery(data['target']),
1057
+ modal_dialog = jQuery('.modal-dialog', modal_div),
1058
+ modal_body = jQuery('.modal-body', modal_div),
1059
+ modal_title = jQuery('.modal-title', modal_div);
1060
+ modal_title.text(jQuery(this).attr('data-title')? jQuery(this).attr('data-title') : jQuery(this).attr('title'));
1061
+
1062
+ if(data['metainfo']) {
1063
+ modal_dialog.addClass('modal-md');
1064
+ modal_body.html(jQuery('#metainfo_' + data['metainfo']).html());
1065
+ } else {
1066
+ var r = data['width'] / data['height'],
1067
+ w = Math.min(jQuery(window).width() * 0.98 - 32, data['width']),
1068
+ h = w / r;
1069
+ modal_dialog.css({'width': (data['width'] + 32), 'max-width': '98%'});
1070
+ if(data['cls']){
1071
+ modal_dialog.addClass(data['cls']);
1072
+ }
1073
+ modal_body.html(
1074
+ jQuery('<iframe />', {
1075
+ name: 'previewFrame',
1076
+ id: 'previewFrame',
1077
+ width: '100%',
1078
+ height: h,
1079
+ src: jQuery(this).attr('href')
1080
+ }).on('load', function(){
1081
+ jQuery(this.contentWindow.document.body).css('margin', 0);
1082
+ jQuery('.modal-backdrop', modal_div).css({'width': (data['width'] + 32), 'min-width': '100%'});
1083
+ }).css({display: 'block', margin: '4px 0'})
1084
+ );
1085
+ }
1086
+
1087
+ initiator.addClass('previewModal_initiator');
1088
+ modal_div.modal({
1089
+ backdrop: true,
1090
+ show: true
1091
+ }).one('hidden.bs.modal', function() {
1092
+ if (jQuery('div.gmedia-modal:visible').length) {
1093
+ jQuery('body').addClass('modal-open');
1094
+ }
1095
+ modal_title.empty();
1096
+ modal_body.empty();
1097
+ modal_dialog.removeAttr('style').attr('class', 'modal-dialog');
1098
+ if(modal_div.attr('data-refresh')){
1099
+ modal_div.removeAttr('data-refresh');
1100
+ jQuery('.panel-heading .spinner').addClass('is-active');
1101
+ var url = window.location.href;
1102
+ jQuery.get(url, function(data) {
1103
+ jQuery('#gmedia-panel').html(jQuery('#gmedia-panel', data).html());
1104
+ GmediaInit();
1105
+ jQuery('.panel-heading .spinner').removeClass('is-active');
1106
+ });
1107
+ }
1108
+ initiator.removeClass('previewModal_initiator');
1109
+ });
1110
+ });
1111
+
1112
+ jQuery(document).on('click.gmedia', '#previewModal .select_gmedia_image .btn-primary', function() {
1113
+ var img, form = jQuery('.previewModal_initiator').closest('form');
1114
+ form.find('.gmedia-cover-id').val(window.gmediaTempData.id).trigger('change');
1115
+ img = form.find('.gmedia-cover-image img:first-child');
1116
+ if(img.length){
1117
+ img.attr('src', window.gmediaTempData.src);
1118
+ } else {
1119
+ jQuery('<img src="" alt="" />').attr('src', window.gmediaTempData.src).appendTo(form.find('.gmedia-cover-image'));
1120
+ }
1121
+ jQuery('#previewModal').modal('hide');
1122
+ });
1123
+
1124
+ jQuery(document).on('click.gmedia', '#previewModal .select_gmedia_related .btn-primary', function() {
1125
+ var relatedDiv = jQuery('.previewModal_initiator').closest('.form-group').find('.related-media-previews');
1126
+ var fields = relatedDiv.find('input');
1127
+ var valData = [],
1128
+ getData = [];
1129
+ if(fields){
1130
+ fields.each(function(){
1131
+ valData.push(jQuery(this).val());
1132
+ });
1133
+ }
1134
+ var storage = getStorage();
1135
+ storedData = storage.get('gmedia_library:frame').split('.');
1136
+ jQuery.each(storedData, function(i, id) {
1137
+ if(!id) {
1138
+ return true;
1139
+ }
1140
+ if(jQuery.inArray(id, valData) === -1) {
1141
+ getData.push(id);
1142
+ }
1143
+ });
1144
+ if(getData.length){
1145
+ jQuery.get(ajaxurl, {action: 'gmedia_get_data', gmedia__in: getData}, function(data, textStatus, jqXHR) {
1146
+ if(jQuery.isArray(data) && data.length){
1147
+ var thumbHTML
1148
+ jQuery.each(data, function(i, item){
1149
+ thumbHTML = '<p class="thumbnail gmedia-related-image">' +
1150
+ '<span class="image-wrapper"><img class="gmedia-thumb" src="" alt=""></span>' +
1151
+ '<span class="gm-remove">&times;</span>' +
1152
+ '<input type="hidden" name="meta[_related][]" value="">' +
1153
+ '</p>';
1154
+ jQuery(thumbHTML).find('img').attr('src', item.url_thumb).end().find('input').val(item.ID).end().appendTo(relatedDiv);
1155
+ });
1156
+ relatedDiv.sortable( "refresh" );
1157
+ relatedDiv.closest('form').find('input[name="title"]').trigger('change');
1158
+ }
1159
+ });
1160
+ }
1161
+ storage.set('gmedia_library:frame', '');
1162
+ jQuery('#previewModal').modal('hide');
1163
+ });
1164
+
1165
+ jQuery(document).on('click.gmedia', '.related-media-previews .gm-remove', function() {
1166
+ var inpTitle = jQuery(this).closest('form').find('input[name="title"]');
1167
+ jQuery(this).closest('.gmedia-related-image').remove();
1168
+ inpTitle.trigger('change');
1169
+ });
1170
+
1171
+ jQuery(document).on('click.gmedia', '#previewModal .select_gmedia:not(.assign_gmedia_term) .btn-primary', function() {
1172
+ var field = jQuery('.previewModal_initiator').closest('.form-group').find('.form-control');
1173
+ var valData = field.val().split(',');
1174
+ var storedData = getStorage();
1175
+ storedData = storedData.get('gmedia_library:frame').split('.');
1176
+ valData = jQuery.grep(valData, function(e) {
1177
+ return e.trim();
1178
+ });
1179
+ jQuery.each(storedData, function(i, id) {
1180
+ if(!id) {
1181
+ return true;
1182
+ }
1183
+ if(jQuery.inArray(id, valData) === -1) {
1184
+ valData.push(id);
1185
+ }
1186
+ });
1187
+ field.val(valData.join(','));
1188
+ jQuery('#previewModal').modal('hide');
1189
+ });
1190
+
1191
+ jQuery(document).on('click.gmedia', '#previewModal .assign_gmedia_term .btn-primary', function() {
1192
+ jQuery('.panel-heading .spinner').addClass('is-active');
1193
+ var url = window.location.href,
1194
+ post_data = jQuery('#gmedia-assign-term').serialize();
1195
+ jQuery.post(url, post_data, function(data) {
1196
+ jQuery('.gmedia_term__in').html(jQuery('.gmedia_term__in', data).html());
1197
+ GmediaInit();
1198
+ jQuery('.panel-heading .spinner').removeClass('is-active');
1199
+ });
1200
+ jQuery('#previewModal').modal('hide');
1201
+ //console.log(window.gmediaTempData);
1202
+ });
1203
+
1204
+ jQuery(document).on('click.gmedia focus.gmedia', 'input.sharelink', function() {
1205
+ this.setSelectionRange(0, this.value.length);
1206
+ });
1207
+ jQuery(document).on('keyup.gmedia', 'input.sharetoemail', function() {
1208
+ jQuery('.sharebutton').prop('disabled', !validateEmail(this.value));
1209
+ });
1210
+ jQuery(document).on('click.gmedia', '.sharebutton', function() {
1211
+ var sharetoemail = jQuery('input.sharetoemail');
1212
+ if(!validateEmail(sharetoemail.val())) {
1213
+ sharetoemail.focus();
1214
+ sharetoemail.parent().addClass('has-error');
1215
+ return false;
1216
+ }
1217
+ var post_data = jQuery('#shareForm').serialize();
1218
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1219
+ jQuery('body').removeClass('gmedia-busy');
1220
+ if(data) {
1221
+ jQuery('#gm-message').append(data);
1222
+ }
1223
+ });
1224
+ jQuery('#shareModal').modal('hide');
1225
+ });
1226
+ gmedia_DOM.on('click', 'a.share-modal', function(e) {
1227
+ e.preventDefault();
1228
+ var data = jQuery(this).data(),
1229
+ modal_div = jQuery(data['target']),
1230
+ postlink = jQuery(this).attr('href'),
1231
+ cloudlink = jQuery(this).attr('data-gmediacloud'),
1232
+ sharetoemail = jQuery('input.sharetoemail'),
1233
+ cloudlink_checked = false;
1234
+
1235
+ if(postlink) {
1236
+ jQuery('.sharelink_post', modal_div).show();
1237
+ jQuery('.sharelink_post input[type="text"]', modal_div).val(postlink);
1238
+ jQuery('.sharelink_post a', modal_div).attr('href', postlink);
1239
+ } else {
1240
+ jQuery('.sharelink_post', modal_div).hide();
1241
+ jQuery('.sharelink_post input[type="radio"]', modal_div).prop('checked', false);
1242
+ cloudlink_checked = true;
1243
+ }
1244
+ if(cloudlink) {
1245
+ jQuery('.sharelink_page', modal_div).show();
1246
+ jQuery('.sharelink_page input[type="text"]', modal_div).val(cloudlink);
1247
+ jQuery('.sharelink_page a', modal_div).attr('href', cloudlink);
1248
+ if(cloudlink_checked) {
1249
+ jQuery('.sharelink_page input[type="radio"]', modal_div).prop('checked', true);
1250
+ }
1251
+ } else {
1252
+ jQuery('.sharelink_page', modal_div).hide();
1253
+ }
1254
+ jQuery('.sharebutton').prop('disabled', !validateEmail(sharetoemail.val()));
1255
+
1256
+ modal_div.modal({
1257
+ backdrop: true,
1258
+ show: true,
1259
+ keyboard: false
1260
+ }).one('shown.bs.modal', function() {
1261
+ jQuery('input.sharelink', this).focus();
1262
+ }).one('hidden.bs.modal', function() {
1263
+ jQuery('input.sharelink', this).val('');
1264
+ });
1265
+ });
1266
+
1267
+ gmedia_DOM.on('click', '.buildquery-modal', function(e) {
1268
+ e.preventDefault();
1269
+ var data = jQuery(this).data(),
1270
+ modal_div = jQuery(jQuery(this).attr('href')),
1271
+ query_field = jQuery(jQuery(this).attr('id') + '_field');
1272
+ query = query_field.val();
1273
+
1274
+ modal_div.modal({
1275
+ backdrop: true,
1276
+ show: true,
1277
+ keyboard: false
1278
+ }).one('shown.bs.modal', function() {
1279
+ if(query) {
1280
+ query = gm_parse_query(query);
1281
+ console.log(query);
1282
+ }
1283
+ }).one('hidden.bs.modal', function() {});
1284
+ });
1285
+
1286
+ jQuery(document).on('click.gmedia', '.buildquerysubmit', function() {
1287
+ var qform = jQuery('#buildQuery :input').filter(function() {
1288
+ return !!jQuery(this).val();
1289
+ });
1290
+
1291
+ qform = decodeURIComponent(qform.serialize());
1292
+ console.log(qform);
1293
+ jQuery('#build_query_field').val(qform);
1294
+ jQuery('#buildQuery').modal('hide');
1295
+ });
1296
+ gmedia_DOM.on('click', 'a.newcustomfield-modal', function(e) {
1297
+ e.preventDefault();
1298
+ var data = jQuery(this).data(),
1299
+ modal_div = jQuery(jQuery(this).attr('href'));
1300
+
1301
+ modal_div.modal({
1302
+ backdrop: false,
1303
+ show: true,
1304
+ keyboard: false
1305
+ }).one('shown.bs.modal', function() {
1306
+ jQuery('input.newcustomfield-for-id', this).val(data['gmid']);
1307
+ }).one('hidden.bs.modal', function() {
1308
+ jQuery(':input.form-control, input.newcustomfield-for-id', this).val('');
1309
+ if(jQuery('.newcfield', this).length) {
1310
+ jQuery('a.gmediacustomstuff').click();
1311
+ }
1312
+ });
1313
+ });
1314
+ jQuery(document).on('click.gmedia', '.customfieldsubmit', function() {
1315
+ var cform = jQuery('#newCustomFieldForm');
1316
+ if(!jQuery('.newcustomfield-for-id', cform).val()) {
1317
+ jQuery('#newCustomFieldModal').modal('hide');
1318
+ alert('No ID');
1319
+ return false;
1320
+ }
1321
+ var post_data = cform.serialize();
1322
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1323
+ jQuery('body').removeClass('gmedia-busy');
1324
+ if(data.success) {
1325
+ jQuery('#newCustomFieldModal').modal('hide').one('hidden.bs.modal', function() {
1326
+ //noinspection JSUnresolvedVariable
1327
+ if(data.newmeta_form) {
1328
+ //noinspection JSUnresolvedVariable
1329
+ jQuery('#newmeta').replaceWith(data.newmeta_form);
1330
+ }
1331
+ });
1332
+ jQuery('.row:last', '#gmediacustomstuff_' + data.id).append(data.success.data);
1333
+ } else {
1334
+ if(data.error) {
1335
+ if('100' == data.error.code) {
1336
+ jQuery('#newCustomFieldModal').modal('hide');
1337
+ }
1338
+ alert(data.error.message);
1339
+ } else {
1340
+ console.log(data);
1341
+ }
1342
+ }
1343
+ });
1344
+ });
1345
+ gmedia_DOM.on('click', '.delete-custom-field', function() {
1346
+ var t = jQuery(this).closest('.form-group'),
1347
+ post_data = convertInputsToJSON(jQuery(':input', t));
1348
+ if(!post_data) {
1349
+ return false;
1350
+ }
1351
+ var meta_type = jQuery(this).closest('fieldset').attr('data-metatype');
1352
+ post_data.action = meta_type + '_delete_custom_field';
1353
+ post_data.ID = jQuery(this).closest('form').attr('data-id');
1354
+ post_data._wpnonce_custom_field = jQuery('#_wpnonce_custom_field').val();
1355
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1356
+ jQuery('body').removeClass('gmedia-busy');
1357
+ //noinspection JSUnresolvedVariable
1358
+ if(data.deleted) {
1359
+ //noinspection JSUnresolvedVariable
1360
+ jQuery.each(data.deleted, function(i, val) {
1361
+ jQuery('.gm-custom-meta-' + val).remove();
1362
+ });
1363
+ } else {
1364
+ if(data.error) {
1365
+ alert(data.error.message);
1366
+ } else {
1367
+ console.log(data);
1368
+ }
1369
+ }
1370
+ });
1371
+ });
1372
+
1373
+
1374
+ gmedia_DOM.on('change modified', 'form.edit-gmedia :input:not([name="doaction[]"])', function() {
1375
+ if(jQuery(this).hasClass('edit-gmedia-ignore')) {
1376
+ return;
1377
+ }
1378
+ jQuery('body').addClass('gmedia-busy');
1379
+ jQuery('.panel-heading .spinner').addClass('is-active');
1380
+ var post_data = {
1381
+ action: 'gmedia_update_data', data: jQuery(this).closest('form').serialize(), _wpnonce: jQuery('#_wpnonce').val()
1382
+ };
1383
+ jQuery.post(ajaxurl, post_data, function(data, textStatus, jqXHR) {
1384
+ console.log(data);
1385
+ var item = jQuery('#list-item-' + data.ID);
1386
+ item.find('.modified').text(data.modified);
1387
+ //noinspection JSUnresolvedVariable
1388
+ item.find('.status-album').attr('class', 'form-group status-album bg-status-' + data.album_status);
1389
+ item.find('.status-item').attr('class', 'form-group status-item bg-status-' + data.status);
1390
+ if(data.thumbnail) {
1391
+ item.find('.gmedia-cover-image').html(data.thumbnail);
1392
+ }
1393
+ //if(data.tags) {
1394
+ // item.find('.gmedia_tags_input').val(data.tags);
1395
+ //}
1396
+ //noinspection JSUnresolvedVariable
1397
+ if(data.meta_error) {
1398
+ jQuery.each(data.meta_error, function(i, err) {
1399
+ console.log(err);
1400
+ alert(err.meta_key + ': ' + err.message);
1401
+ if(err.meta_value) {
1402
+ jQuery('.gm-custom-field-' + err.meta_id).val(err.meta_value);
1403
+ }
1404
+ });
1405
+ }
1406
+ jQuery('body').removeClass('gmedia-busy');
1407
+ jQuery('.panel-heading .spinner').removeClass('is-active');
1408
+ });
1409
+ });
1410
+
1411
+ gmedia_DOM.on('click', '.gm-toggle-cb', function(e) {
1412
+ var checkBoxes = jQuery(this).attr('href');
1413
+ jQuery(checkBoxes + ' :checkbox').each(function() {
1414
+ jQuery(this).prop("checked", !jQuery(this).prop("checked"));
1415
+ });
1416
+ e.preventDefault();
1417
+ });
1418
+ jQuery(document).on('click.gmedia', '.linkblock [data-href]', function() {
1419
+ window.location.href = jQuery(this).data('href');
1420
+ });
1421
+
1422
+ gmedia_DOM.on('click', '.gmedia-import', function() {
1423
+ jQuery('#import-action').val(jQuery(this).attr('name'));
1424
+ jQuery('#importModal').modal({
1425
+ backdrop: 'static',
1426
+ show: true,
1427
+ keyboard: false
1428
+ }).one('shown.bs.modal', function() {
1429
+ jQuery('#import_form').submit();
1430
+ }).one('hidden.bs.modal', function() {
1431
+ var btn = jQuery('#import-done');
1432
+ btn.text(btn.data('reset-text')).prop('disabled', true);
1433
+ jQuery('#import_window').attr('src', 'about:blank');
1434
+ });
1435
+ });
1436
+
1437
+ gmedia_DOM.on('click', '.module_install', function(e) {
1438
+ e.preventDefault();
1439
+ jQuery('body').addClass('gmedia-busy');
1440
+ var module = jQuery(this).data('module');
1441
+ var btn = jQuery('.module_install').filter('[data-module="' + module + '"]');
1442
+ btn.text(btn.data('loading-text'));
1443
+ var post_data = {
1444
+ action: 'gmedia_module_install', download: jQuery(this).attr('href'), module: module, _wpnonce: jQuery('#_wpnonce').val()
1445
+ };
1446
+ var pathname = window.location.href + '&time=' + jQuery.now();
1447
+ jQuery.post(ajaxurl, post_data, function(data, status, xhr) {
1448
+ setTimeout(function(){
1449
+ jQuery('#gmedia_modules').load(pathname + ' #gmedia_modules_wrapper', function(){
1450
+ setTimeout(function(){
1451
+ var update_count = jQuery('#gmedia_modules').find('#gmedia_modules_wrapper').attr('data-update');
1452
+ if(parseInt(update_count)){
1453
+ jQuery('.gm-module-count').html(update_count);
1454
+ } else {
1455
+ jQuery('.gm-module-count').remove();
1456
+ }
1457
+ }, 1);
1458
+ });
1459
+ }, 1);
1460
+ jQuery('#gmedia_modules').before(data);
1461
+ jQuery('body').removeClass('gmedia-busy');
1462
+ });
1463
+ });
1464
+
1465
+ gmedia_DOM.on('keydown', 'form :input:visible:not(:submit,:button,:reset,textarea,.allow-key-enter)', function(e) {
1466
+ var charCode = e.charCode || e.keyCode || e.which;
1467
+ if(13 == charCode && !jQuery(this).parent().hasClass('selectize-input')) {
1468
+ var inputs = jQuery(this).parents("form").eq(0).find(":input:visible");
1469
+ var inp = inputs[inputs.index(this) + 1];
1470
+ if(inp !== null) {
1471
+ jQuery(inp).focus();
1472
+ var inp_type = jQuery(inp).attr('type');
1473
+ if(!!inp_type && (inp_type == 'text' || inp_type == 'number')) {
1474
+ console.log(inp);
1475
+ inp.setSelectionRange(0, inp.value.length);
1476
+ }
1477
+ }
1478
+ e.preventDefault();
1479
+ return false;
1480
+ }
1481
+ });
1482
+
1483
+ var preset_popover = function() {
1484
+ jQuery('#module_presets').popover({
1485
+ container: '#module_preset',
1486
+ content: function() {
1487
+ return jQuery('#_module_presets').html();
1488
+ },
1489
+ html: true,
1490
+ placement: 'bottom'
1491
+ }).on('show.bs.popover', function() {
1492
+ jQuery(this).addClass('active');
1493
+ }).on('hide.bs.popover', function() {
1494
+ jQuery(this).removeClass('active');
1495
+ });
1496
+ };
1497
+ preset_popover();
1498
+ gmedia_DOM.on('click', '#module_preset .ajax-submit', function(e) {
1499
+ e.preventDefault();
1500
+ jQuery('body').addClass('gmedia-busy');
1501
+ var form = jQuery('#gmedia-edit-term');
1502
+ var post_data = form.serializeArray();
1503
+ post_data.push({name: jQuery(this).attr('name'), value: 1});
1504
+ var pathname = window.location.href;
1505
+ jQuery.post(pathname, jQuery.param(post_data), function(data, status, xhr) {
1506
+ jQuery('body').removeClass('gmedia-busy');
1507
+ data = jQuery(data).find('#gmedia-container');
1508
+ jQuery('#gm-message').append(jQuery('#gm-message', data).html());
1509
+ jQuery('#save_buttons').html(jQuery('#save_buttons', data).html());
1510
+ jQuery('#save_buttons_duplicate').html(jQuery('#save_buttons_duplicate', data).html());
1511
+ jQuery('#module_preset').html(jQuery('#module_preset', data).html());
1512
+ preset_popover();
1513
+ });
1514
+ });
1515
+ jQuery(document).on('click.gmedia', function(e) {
1516
+ if(jQuery(e.target).data('toggle') !== 'popover'
1517
+ && jQuery(e.target).parents('.popover.in').length === 0) {
1518
+ jQuery('[data-toggle="popover"]').popover('hide');
1519
+ }
1520
+ });
1521
+
1522
+ gmedia_DOM.on('click', '[data-clicktarget]', function(e){
1523
+ e.preventDefault();
1524
+ var id = jQuery(this).attr('data-clicktarget');
1525
+ jQuery('#' + id).click();
1526
+ });
1527
+
1528
+ gmedia_DOM.on('click', '#module_preset .delpreset span, .module_presets .delpreset span', function() {
1529
+ jQuery('body').addClass('gmedia-busy');
1530
+ var module_preset = this;
1531
+ var preset_item_li = jQuery(this).closest('li');
1532
+ var preset_id = jQuery(this).data('id');
1533
+ var post_data = {
1534
+ action: 'gmedia_module_preset_delete', preset_id: preset_id, _wpnonce: jQuery('#_wpnonce').val()
1535
+ };
1536
+ jQuery.post(ajaxurl, post_data, function(data, status, xhr) {
1537
+ if(data.error) {
1538
+ jQuery('#gm-message').append(data.error);
1539
+ } else {
1540
+ preset_item_li.remove();
1541
+ if('module_presets_list' !== jQuery(this).attr('id')) {
1542
+ var _module_presets = jQuery('#module_preset').find('.popover-content').html();
1543
+ jQuery('#_module_presets').replaceWith('<script type="text/html" id="_module_presets">' + _module_presets + '</script>');
1544
+ }
1545
+ }
1546
+ jQuery('body').removeClass('gmedia-busy');
1547
+ });
1548
+ });
1549
+
1550
+ gmedia_DOM.on('click', '.filter-modules > *', function(){
1551
+ jQuery('.filter-modules > .btn-primary').removeClass('btn-primary').addClass('btn-default');
1552
+ jQuery('.filter-modules > .label-primary').removeClass('label-primary').addClass('label-default');
1553
+ if(jQuery(this).is('button')){
1554
+ jQuery(this).addClass('btn-primary').removeClass('btn-default');
1555
+ } else{
1556
+ jQuery(this).addClass('label-primary').removeClass('label-default');
1557
+ }
1558
+ var filter = jQuery(this).attr('data-filter');
1559
+ jQuery('#gmedia_modules .media').removeClass('module-filtered').filter('.module-' + filter).addClass('module-filtered');
1560
+ if(!jQuery('#gmedia_modules .module-filtered').length){
1561
+ if('not-installed' == filter){
1562
+ jQuery('#gmedia_modules .nomodules.nomodule-' + filter).addClass('module-filtered');
1563
+ } else{
1564
+ jQuery('#gmedia_modules .nomodules.nomodule-tag').addClass('module-filtered');
1565
+ }
1566
+ }
1567
+ })
1568
+
1569
+ if(jQuery(".panel-fixed-header").length) {
1570
+ setPanelHeadersWidth();
1571
+ setTimeout(function() {
1572
+ setPanelHeadersWidth();
1573
+ }, 800);
1574
+ jQuery(window).on('resize.gmedia', function() {
1575
+ setPanelHeadersWidth();
1576
+ });
1577
+ jQuery(document).on('click.gmedia', '#collapse-menu', function() {
1578
+ setTimeout(function() {
1579
+ setPanelHeadersWidth();
1580
+ }, 10);
1581
+ });
1582
+
1583
+ jQuery(window).on('scroll.gmedia', function() {
1584
+ UpdatePanelHeaders();
1585
+ /*clearTimeout(jQuery.data(this, 'scrollTimer'));
1586
+ jQuery.data(this, 'scrollTimer', setTimeout(function() {
1587
+ UpdatePanelHeaders();
1588
+ console.log("Haven't scrolled in 250ms!");
1589
+ }, 250));*/
1590
+ }).trigger("scroll.gmedia");
1591
+ }
1592
+
1593
+ }
1594
+ };
1595
+
1596
+
1597
+ window.closeModal = function(id) {
1598
+ jQuery('#' + id).modal('hide');
1599
+ };
1600
+
1601
+
1602
+ /*
1603
+ * jQuery functions for GRAND Media
1604
+ */
1605
+ function GmediaInit(){
1606
+ gmedia_DOM = jQuery('#gmedia-container');
1607
+ gmedia_DOM.off();
1608
+ jQuery(window).off('.gmedia');
1609
+ jQuery(document).off('.gmedia');
1610
+
1611
+ GmediaSelect.init();
1612
+ GmediaFunction.init();
1613
+
1614
+ if(jQuery('body').hasClass('GrandMedia')) {
1615
+ GmediaLibrary.init();
1616
+ }
1617
+ if(jQuery('body').hasClass('GrandMedia_AddMedia')) {
1618
+ GmediaAddMedia.init();
1619
+ }
1620
+ if(jQuery('body').is('.GrandMedia_Tags,.GrandMedia_Categories,.GrandMedia_Albums,.GrandMedia_Galleries')) {
1621
+ GmediaTerms.init();
1622
+ }
1623
+
1624
+ var helper, helper_width, title;
1625
+ jQuery('[title]', gmedia_DOM).each(function(){
1626
+ title = jQuery(this).attr('title');
1627
+ if(title) {
1628
+ jQuery(this).attr('title','').attr('data-title', title);
1629
+ }
1630
+ });
1631
+ gmedia_DOM.on('mouseenter', '[title]', function(e) {
1632
+ title = jQuery(this).attr('data-title');
1633
+ if(title) {
1634
+ helper = jQuery('<div id="gmedia-data-helper">' + title + '</div>').appendTo('body');
1635
+ helper_width = 0;
1636
+ if(e.pageX > (window.innerWidth / 2)) {
1637
+ helper_width = helper.width() - 25;
1638
+ helper.addClass('tiptoleft');
1639
+ }
1640
+ helper.css({left: e.clientX - helper_width - 25, top: e.clientY + 25});
1641
+ } else{
1642
+ jQuery(this).removeAttr('title');
1643
+ }
1644
+ }).on('mousemove', '[title]', function(e) {
1645
+ if(helper) {
1646
+ helper.css({left: e.clientX - helper_width - 25, top: e.clientY + 25});
1647
+ }
1648
+ }).on('mouseleave', '[title]', function(e) {
1649
+ jQuery('#gmedia-data-helper').remove();
1650
+ helper = null;
1651
+ });
1652
+ }
1653
+ jQuery(document).on('ready', function() {
1654
+ GmediaInit();
1655
+ });
1656
+
1657
+ function convertInputsToJSON(form) {
1658
+ var array = jQuery(form).serializeArray();
1659
+ var json = {};
1660
+
1661
+ jQuery.each(array, function() {
1662
+ json[this.name] = this.value || '';
1663
+ });
1664
+
1665
+ return json;
1666
+ }
1667
+
1668
+ function gm_parse_query(s) {
1669
+ var j = {},
1670
+ res = s.split(/&/gm).map(function(e) {
1671
+ var o = e.split(/=/),
1672
+ pt = j;
1673
+ if(typeof o[1] == 'undefined') {
1674
+ o[1] = '';
1675
+ }
1676
+ o[0].replace(/^(\w+)\[([^&]*)\]/, '$1][$2').split(/\]\[/).map(function(e, i, a) {
1677
+ if(e === '') {
1678
+ e = Object.keys(pt).length;
1679
+ }
1680
+ pt = (pt[e] = pt[e] || (i == a.length - 1? decodeURIComponent(o[1].replace(/\+/, ' ')) : {}));
1681
+ });
1682
+ });
1683
+ return j;
1684
+ }
1685
+
1686
+ function validateEmail(email) {
1687
+ var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1688
+ return re.test(email);
1689
+ }
1690
+
1691
+ function getStorage() {
1692
+ // use document.cookie:
1693
+ return {
1694
+ set: function(id, data) {
1695
+ document.cookie = id + '=' + encodeURIComponent(data);
1696
+ },
1697
+ get: function(id) {
1698
+ var cookies = document.cookie, parsed = {};
1699
+ cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
1700
+ parsed[key] = decodeURIComponent(value);
1701
+ });
1702
+ return parsed[id];
1703
+ }
1704
+ };
1705
+ }
1706
+
1707
+ function getDocHeight(id){
1708
+ var H;
1709
+ if(id){
1710
+ H = Math.max(
1711
+ jQuery('#' + id).height(),
1712
+ document.getElementById(id).clientHeight
1713
+ );
1714
+ } else {
1715
+ H = Math.max(
1716
+ jQuery(document).height(),
1717
+ jQuery(window).height(),
1718
+ document.documentElement.clientHeight
1719
+ );
1720
+ }
1721
+
1722
+ return H;
1723
+ };
1724
+ /*
1725
+ function gmHashCode(str){
1726
+ var l = str.length,
1727
+ hash = 5381 * l * (str.charCodeAt(0) + l);
1728
+ for(var i = 0; i < str.length; i++){
1729
+ hash += Math.floor((str.charCodeAt(i) + i + 0.33) / (str.charCodeAt(l - i - 1) + l) + (str.charCodeAt(i) + l) * (str.charCodeAt(l - i - 1) + i + 0.33));
1730
+ }
1731
+ return hash;
1732
+ }
1733
+ function gmCreateKey(site, lic, uuid){
1734
+ if(!lic){
1735
+ lic = '0:lk';
1736
+ }
1737
+ if(!uuid){
1738
+ uuid = 'xyxx-xxyx-xxxy';
1739
+ }
1740
+ var d = gmHashCode((site + ':' + lic).toLowerCase());
1741
+ var p = d;
1742
+ uuid = uuid.replace(/[xy]/g, function(c){
1743
+ var r = d % 16 | 0, v = c == 'x'? r : (r & 0x7 | 0x8);
1744
+ d = Math.floor(d * 15 / 16);
1745
+ return v.toString(16);
1746
+ });
1747
+ var key = p + ': ' + lic + '-' + uuid;
1748
+ return key.toLowerCase();
1749
+ }
1750
+ */
1751
+
1752
+ function UpdatePanelHeaders() {
1753
+ jQuery(".panel-fixed-header").each(function() {
1754
+ var el = jQuery(this),
1755
+ headerRow = jQuery(".panel-heading", this),
1756
+ offset = el.offset(),
1757
+ scrollTop = jQuery(window).scrollTop(),
1758
+ floatingHeader = "panel-floatingHeader",
1759
+ absoluteHeader = "panel-absoluteHeader",
1760
+ pad_top = jQuery('#wpadminbar').height();
1761
+
1762
+ if((scrollTop > offset.top - pad_top) && (scrollTop < offset.top - pad_top + (el.height() - headerRow.outerHeight(false)) + 4)) {
1763
+ el.addClass(floatingHeader).removeClass(absoluteHeader);
1764
+ } else if(scrollTop > (offset.top - pad_top + (el.height() - headerRow.outerHeight(false)))) {
1765
+ el.addClass(absoluteHeader).removeClass(floatingHeader);
1766
+ } else {
1767
+ el.removeClass(absoluteHeader + ' ' + floatingHeader)
1768
+ }
1769
+ });
1770
+ }
1771
+
1772
+ function setPanelHeadersWidth() {
1773
+ jQuery(".panel-fixed-header").each(function() {
1774
+ var headerRow = jQuery(".panel-heading", this);
1775
+ headerRow.css("width", jQuery(this).innerWidth());
1776
+ jQuery(".panel-heading-fake", this).height(headerRow.outerHeight());
1777
+ });
1778
+ }
grand-media.php CHANGED
@@ -1,1012 +1,1012 @@
1
- <?php
2
- /*
3
- * Plugin Name: Gmedia Gallery
4
- * Plugin URI: http://wordpress.org/extend/plugins/grand-media/
5
- * Description: Gmedia Gallery - powerful media library plugin for creating beautiful galleries and managing files.
6
- * Version: 1.16.7
7
- * Author: Rattus
8
- * Author URI: https://codeasily.com/
9
- * Requires at least: 3.7
10
- * Tested up to: 5.2
11
- * Text Domain: grand-media
12
- * Domain Path: /lang
13
- *
14
- */
15
- /* -------------------
16
-
17
- Copyright (C) 2011 Rattus (email : gmediafolder@gmail.com)
18
-
19
- This program is free software; you can redistribute it and/or
20
- modify it under the terms of the GNU General Public License
21
- as published by the Free Software Foundation; either version 2
22
- of the License, or (at your option) any later version.
23
-
24
- This program is distributed in the hope that it will be useful,
25
- but WITHOUT ANY WARRANTY; without even the implied warranty of
26
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27
- GNU General Public License for more details.
28
-
29
- You should have received a copy of the GNU General Public License
30
- along with this program; if not, write to the Free Software
31
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
32
- */
33
-
34
- // Stop direct call
35
- if ( preg_match( '#' . basename( __FILE__ ) . '#', $_SERVER['PHP_SELF'] ) ) {
36
- die( 'You are not allowed to call this page directly.' );
37
- }
38
-
39
- if ( ! class_exists( 'Gmedia' ) ) {
40
- /**
41
- * Class Gmedia
42
- */
43
- class Gmedia {
44
-
45
- var $version = '1.16.7';
46
- var $dbversion = '1.8.0';
47
- var $minium_WP = '3.7';
48
- var $options = '';
49
- var $do_module = array();
50
- var $import_styles = array();
51
- var $shortcode = array();
52
-
53
- /**
54
- *
55
- */
56
- function __construct() {
57
-
58
- // Stop the plugin if we missed the requirements
59
- if ( ! $this->required_version() ) {
60
- return;
61
- }
62
-
63
- // Get some constants first
64
- include_once( dirname( __FILE__ ) . '/config.php' );
65
- $this->load_options();
66
- $this->define_constant();
67
- $this->define_tables();
68
-
69
- // Load global libraries
70
- require_once( dirname( __FILE__ ) . '/inc/core.php' );
71
- require_once( dirname( __FILE__ ) . '/inc/db.connect.php' );
72
- require_once( dirname( __FILE__ ) . '/inc/permalinks.php' );
73
-
74
- if ( $this->options['debug_mode'] ) {
75
- ini_set( 'display_errors', true );
76
- error_reporting( E_ALL );
77
- } else {
78
- @ini_set( 'display_errors', true ); //Ensure that Fatal errors are displayed.
79
- error_reporting( E_CORE_ERROR | E_COMPILE_ERROR | E_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR );
80
- }
81
-
82
- $this->plugin_name = plugin_basename( __FILE__ );
83
-
84
- add_filter( 'cron_schedules', array( &$this, 'gmedia_cron_schedules' ) );
85
-
86
- // Init options & tables during activation & deregister init option
87
- register_activation_hook( $this->plugin_name, array( &$this, 'activate' ) );
88
- register_deactivation_hook( $this->plugin_name, array( &$this, 'deactivate' ) );
89
-
90
- // Register a uninstall hook to remove all tables & option automatic
91
- //register_uninstall_hook( $this->plugin_name, array(__CLASS__, 'uninstall' ) );
92
-
93
- add_action( 'wp_enqueue_scripts', array( &$this, 'register_scripts_frontend' ), 20 );
94
-
95
- add_action( 'admin_enqueue_scripts', array( &$this, 'register_scripts_backend' ), 8 );
96
-
97
- add_action( 'wpmu_new_blog', array( &$this, 'new_blog' ), 10, 6 );
98
-
99
- // Start this plugin once all other plugins are fully loaded
100
- add_action( 'plugins_loaded', array( &$this, 'start_plugin' ) );
101
-
102
- add_action( 'deleted_user', array( &$this, 'reassign_media' ), 10, 2 );
103
-
104
- add_action( 'init', array( &$this, 'gmedia_post_type' ), 0 );
105
- add_action( 'init', array( &$this, 'compatibility' ), 11 );
106
- //add_action('init', array(&$this, 'gm_schedule_update_checks'), 0);
107
-
108
- // register widget
109
- add_action( 'widgets_init', array( &$this, 'register_gmedia_widget' ) );
110
-
111
- add_action( 'gmedia_app_cronjob', array( &$this, 'gmedia_app_cronjob' ) );
112
- add_action( 'gmedia_modules_update', array( &$this, 'gmedia_modules_update' ) );
113
-
114
- //Add some message on the plugins page
115
- //add_action( 'after_plugin_row', array(&$this, 'check_message_version') );
116
- //Add some links on the plugins page
117
- add_filter( 'plugin_row_meta', array( &$this, 'add_plugin_links' ), 10, 2 );
118
- add_action( 'admin_footer', array( &$this, 'add_plugin_feedback' ) );
119
-
120
- }
121
-
122
- function start_plugin() {
123
-
124
- $this->load_dependencies();
125
-
126
- // Load the language file
127
- $this->load_textdomain();
128
-
129
- require_once( dirname( __FILE__ ) . '/inc/functions.php' );
130
-
131
- // Check for upgrade
132
- $this->upgrade();
133
-
134
- require_once( dirname( __FILE__ ) . '/inc/hashids.php' );
135
- require_once( dirname( __FILE__ ) . '/inc/shortcodes.php' );
136
-
137
- // Load the admin panel or the frontend functions
138
- if ( is_admin() ) {
139
-
140
- // Pass the init check or show a message
141
- if ( get_option( 'gmediaActivated' ) ) {
142
- add_action( 'init', array( &$this, 'gmedia_after_activation' ) );
143
- }
144
-
145
- // Pass the init check or show a message
146
- if ( get_option( 'gmediaInitCheck' ) ) {
147
- add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
148
- }
149
-
150
- require_once( dirname( __FILE__ ) . '/admin/functions.php' );
151
-
152
- require_once( dirname( __FILE__ ) . '/admin/class.processor.php' );
153
-
154
- } else {
155
-
156
- // Add the script and style files
157
- //add_action('wp_enqueue_scripts', array(&$this, 'load_scripts'), 4);
158
-
159
- require_once( dirname( __FILE__ ) . '/inc/frontend.filters.php' );
160
-
161
- // Add a version number to the header
162
- add_action( 'wp_head', array( &$this, 'gmedia_head_meta' ) );
163
- add_action( 'wp_footer', array( &$this, 'load_module_scripts' ) );
164
-
165
- }
166
-
167
- add_action( 'gmedia_head', array( &$this, 'gmedia_head_meta' ) );
168
- add_action( 'gmedia_head', array( &$this, 'load_scripts' ), 2 );
169
- add_action( 'gmedia_head', 'wp_print_head_scripts', 9 );
170
- add_action( 'gmedia_enqueue_scripts', array( &$this, 'load_module_scripts' ) );
171
-
172
- add_action( 'gmedia_head', array( &$this, 'print_import_styles' ) );
173
- add_action( 'gmedia_footer', array( &$this, 'print_import_styles' ) );
174
-
175
- }
176
-
177
- function gmedia_head_meta() {
178
- $lk = strtolower( $this->options['license_key'] );
179
- $db_version = get_option( 'gmediaDbVersion' );
180
- echo "\n<!-- <meta name='GmediaGallery' version='{$this->version}/{$db_version}' license='{$lk}' /> -->\n";
181
- }
182
-
183
- function admin_notices() {
184
- echo '<div id="message" class="error"><p><strong>' . get_option( 'gmediaInitCheck' ) . '</strong></p></div>';
185
- delete_option( 'gmediaInitCheck' );
186
- }
187
-
188
- /**
189
- * @return bool
190
- */
191
- function required_version() {
192
- global $wp_version;
193
-
194
- // Check for WP version installation
195
- if ( version_compare( $wp_version, $this->minium_WP, '<' ) ) {
196
- $note = sprintf( __( 'Sorry, Gmedia Gallery works only under WordPress %s or higher', 'grand-media' ), $this->minium_WP );
197
- update_option( 'gmediaInitCheck', $note );
198
- add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
199
-
200
- return false;
201
- }
202
- if ( version_compare( '5.3', phpversion(), '>' ) ) {
203
- $note = sprintf( __( 'Attention! Your server php version is: %s. Gmedia Gallery requires php version 5.3+ in order to run properly. Please upgrade your server!', 'grand-media' ), phpversion() );
204
- update_option( 'gmediaInitCheck', $note );
205
- add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
206
-
207
- return false;
208
- }
209
-
210
- return true;
211
- }
212
-
213
- /**
214
- * Called via Setup and register_activate hook after gmedia_install() function
215
- */
216
- function gmedia_after_activation() {
217
- global $gmCore;
218
-
219
- delete_option( 'gmediaActivated' );
220
-
221
- flush_rewrite_rules( false );
222
-
223
- if ( (int) $this->options['mobile_app'] ) {
224
- wp_clear_scheduled_hook( 'gmedia_app_cronjob' );
225
- wp_schedule_event( time(), 'gmedia_app', 'gmedia_app_cronjob' );
226
-
227
- $gmCore->app_service( 'app_activateplugin' );
228
- }
229
-
230
- $wp_installing = (bool) ( defined( 'WP_INSTALLING' ) && WP_INSTALLING );
231
- if ( ! wp_next_scheduled( 'gmedia_modules_update' ) && ! $wp_installing ) {
232
- wp_schedule_event( time(), 'daily', 'gmedia_modules_update' );
233
- }
234
- }
235
-
236
- function upgrade() {
237
- // Queue upgrades
238
- $current_version = get_option( 'gmediaVersion', null );
239
- $current_db_version = get_option( 'gmediaDbVersion', null );
240
-
241
- if ( null === $current_db_version ) {
242
- add_option( "gmediaDbVersion", GMEDIA_DBVERSION );
243
- } elseif ( version_compare( $current_db_version, GMEDIA_DBVERSION, '<' ) ) {
244
- require_once( dirname( __FILE__ ) . '/config/update.php' );
245
-
246
- if ( get_transient( 'gmediaUpgrade' ) || ( isset( $_GET['do_update'] ) && ( 'gmedia' == $_GET['do_update'] ) ) ) {
247
- add_action( 'admin_notices', 'gmedia_upgrade_process_admin_notice' );
248
- } else {
249
- add_action( 'admin_notices', 'gmedia_upgrade_required_admin_notice' );
250
- }
251
- }
252
-
253
- if ( null === $current_version ) {
254
- require_once( dirname( __FILE__ ) . '/config/update.php' );
255
-
256
- add_option( "gmediaVersion", GMEDIA_VERSION );
257
- add_action( 'init', 'gmedia_flush_rewrite_rules', 1000 );
258
- } elseif ( version_compare( $current_version, GMEDIA_VERSION, '<' ) ) {
259
- require_once( dirname( __FILE__ ) . '/config/update.php' );
260
-
261
- gmedia_quite_update();
262
- gmedia_delete_transients( 'gm_cache' );
263
- add_action( 'init', 'gmedia_flush_rewrite_rules', 1000 );
264
-
265
- if ( (int) $this->options['mobile_app'] ) {
266
- if ( ! wp_get_schedule( 'gmedia_app_cronjob' ) ) {
267
- wp_schedule_event( time(), 'gmedia_app', 'gmedia_app_cronjob' );
268
- }
269
- global $gmCore;
270
- $gmCore->app_service( 'app_updatecron' );
271
- }
272
- }
273
-
274
- }
275
-
276
- function define_tables() {
277
- global $wpdb;
278
-
279
- // add database pointer
280
- $wpdb->gmedia = $wpdb->prefix . 'gmedia';
281
- $wpdb->gmedia_meta = $wpdb->prefix . 'gmedia_meta';
282
- $wpdb->gmedia_term = $wpdb->prefix . 'gmedia_term';
283
- $wpdb->gmedia_term_meta = $wpdb->prefix . 'gmedia_term_meta';
284
- $wpdb->gmedia_term_relationships = $wpdb->prefix . 'gmedia_term_relationships';
285
-
286
- }
287
-
288
- function define_constant() {
289
-
290
- define( 'GMEDIA_VERSION', $this->version );
291
- // Minimum required database version
292
- define( 'GMEDIA_DBVERSION', $this->dbversion );
293
-
294
- }
295
-
296
- function load_options() {
297
- include_once( dirname( __FILE__ ) . '/config/setup.php' );
298
- // Load the options
299
- $default_options = gmedia_default_options();
300
- $db_options = get_option( 'gmediaOptions' );
301
- if ( ! is_array( $db_options ) ) {
302
- $db_options = array();
303
- }
304
- $this->options = array_merge( $default_options, $db_options );
305
- }
306
-
307
- function load_dependencies() {
308
-
309
- // We didn't need all stuff during a AJAX operation
310
- if ( defined( 'DOING_AJAX' ) ) {
311
- require_once( dirname( __FILE__ ) . '/admin/ajax.php' );
312
- } else {
313
-
314
- // Load backend libraries
315
- if ( is_admin() ) {
316
- require_once( dirname( __FILE__ ) . '/inc/media-upload.php' );
317
- require_once( dirname( __FILE__ ) . '/inc/post-metabox.php' );
318
-
319
- require_once( dirname( __FILE__ ) . '/admin/admin.php' );
320
-
321
- // Load frontend libraries
322
- }
323
-
324
- $current_plugins = get_option( 'active_plugins' );
325
- if ( in_array( 'wordpress-seo/wp-seo.php', $current_plugins ) ) {
326
- require_once( dirname( __FILE__ ) . '/inc/sitemap.php' );
327
- }
328
- }
329
-
330
- }
331
-
332
- function compatibility() {
333
- require_once( dirname( __FILE__ ) . '/inc/compatibility.php' );
334
- }
335
-
336
- function load_textdomain() {
337
-
338
- load_plugin_textdomain( 'grand-media', false, GMEDIA_FOLDER . '/lang/' );
339
-
340
- }
341
-
342
- function register_scripts_backend() {
343
- global $gmCore;
344
-
345
- wp_register_script( 'gmedia-global-backend', $gmCore->gmedia_url . '/admin/assets/js/gmedia.global.js', array( 'jquery' ), '1.13.0' );
346
- wp_localize_script( 'gmedia-global-backend', 'GmediaGallery', array(
347
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
348
- '_wpnonce' => wp_create_nonce( 'GmediaGallery' ),
349
- 'upload_dirurl' => $gmCore->upload['url'],
350
- 'plugin_dirurl' => $gmCore->gmedia_url,
351
- 'google_api_key' => $this->options['google_api_key'],
352
- ) );
353
-
354
- wp_register_style( 'grand-media', $gmCore->gmedia_url . '/admin/assets/css/gmedia.admin.css', array(), '1.15.4', 'all' );
355
- wp_register_script( 'grand-media', $gmCore->gmedia_url . '/admin/assets/js/gmedia.admin.js', array( 'jquery', 'gmedia-global-backend' ), '1.15.4' );
356
- wp_localize_script( 'grand-media', 'grandMedia', array(
357
- 'error3' => __( 'Disable your Popup Blocker and try again.', 'grand-media' ),
358
- 'download' => __( 'downloading...', 'grand-media' ),
359
- 'wait' => __( 'Working. Wait please.', 'grand-media' ),
360
- '_wpnonce' => wp_create_nonce( 'GmediaGallery' ),
361
- ) );
362
-
363
- wp_register_style( 'gmedia-bootstrap', $gmCore->gmedia_url . '/assets/bootstrap/css/bootstrap.min.css', array(), '3.3.4', 'all' );
364
- wp_register_script( 'gmedia-bootstrap', $gmCore->gmedia_url . '/assets/bootstrap/js/bootstrap.min.js', array( 'jquery' ), '3.3.4' );
365
-
366
- wp_register_script( 'outside-events', $gmCore->gmedia_url . '/assets/jq-plugins/outside-events.js', array( 'jquery' ), '1.1' );
367
-
368
- }
369
-
370
- function register_scripts_frontend() {
371
- global $gmCore, $wp_scripts;
372
-
373
- wp_register_style( 'gmedia-global-frontend', $gmCore->gmedia_url . '/assets/gmedia.global.front.css', array(), '1.15.0' );
374
- wp_register_script( 'gmedia-global-frontend', $gmCore->gmedia_url . '/assets/gmedia.global.front.js', array( 'jquery' ), '1.13.0' );
375
- wp_localize_script( 'gmedia-global-frontend', 'GmediaGallery', array(
376
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
377
- 'nonce' => wp_create_nonce( 'GmediaGallery' ),
378
- 'upload_dirurl' => $gmCore->upload['url'],
379
- 'plugin_dirurl' => $gmCore->upload['url'],
380
- 'license' => strtolower( $this->options['license_key'] ),
381
- 'license2' => $this->options['license_key2'],
382
- 'google_api_key' => $this->options['google_api_key'],
383
- ) );
384
-
385
-
386
- if ( ! wp_script_is( 'velocity', 'registered' ) || version_compare( $wp_scripts->registered['velocity']->ver, '1.4.1', '<' ) ) {
387
- wp_deregister_script( 'velocity' );
388
- wp_register_script( 'velocity', $gmCore->gmedia_url . '/assets/velocity/velocity.min.js', array( 'jquery' ), '1.4.1', true );
389
- }
390
-
391
- if ( ! wp_script_is( 'mediaelement', 'registered' ) ) {
392
- wp_register_style( 'mediaelement', $gmCore->gmedia_url . '/assets/mediaelement/mediaelementplayer.min.css', array(), '4.2.8', 'screen' );
393
- wp_register_script( 'mediaelement', $gmCore->gmedia_url . '/assets/mediaelement/mediaelement-and-player.min.js', array( 'jquery' ), '4.2.8', true );
394
- }
395
-
396
- if ( ! wp_script_is( 'wavesurfer', 'registered' ) ) {
397
- wp_register_script( 'wavesurfer', $gmCore->gmedia_url . '/assets/wavesurfer/wavesurfer.min.js', array( 'jquery' ), '1.2.8', true );
398
- }
399
-
400
- if ( ! wp_script_is( 'swiper', 'registered' ) ) {
401
- wp_register_style( 'swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.min.css', array(), '3.4.0', 'screen' );
402
- wp_register_script( 'swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.jquery.min.js', array( 'jquery' ), '3.4.0', true );
403
- }
404
-
405
- wp_register_style( 'gmedia-swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.min.css', array(), '3.4.0', 'screen' );
406
- wp_register_script( 'gmedia-swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.jquery.min.js', array( 'jquery' ), '3.4.0', true );
407
-
408
- if ( ! wp_script_is( 'magnific-popup', 'registered' ) || version_compare( $wp_scripts->registered['magnific-popup']->ver, '1.1.0', '<' ) ) {
409
- wp_deregister_style( 'magnific-popup' );
410
- wp_deregister_script( 'magnific-popup' );
411
- wp_register_style( 'magnific-popup', $gmCore->gmedia_url . '/assets/mag-popup/magnific-popup.css', array(), '1.1.0', 'screen' );
412
- wp_register_script( 'magnific-popup', $gmCore->gmedia_url . '/assets/mag-popup/jquery.magnific-popup.min.js', array( 'jquery' ), '1.1.0', true );
413
- }
414
-
415
- if ( ! wp_script_is( 'photoswipe', 'registered' ) || version_compare( $wp_scripts->registered['photoswipe']->ver, '3.0.5', '<=' ) ) {
416
- wp_deregister_style( 'photoswipe' );
417
- wp_deregister_script( 'photoswipe' );
418
- wp_register_style( 'photoswipe', $gmCore->gmedia_url . '/assets/photoswipe/photoswipe.css', array(), '3.0.5', 'screen' );
419
- wp_register_script( 'photoswipe', $gmCore->gmedia_url . '/assets/photoswipe/photoswipe.jquery.min.js', array( 'jquery' ), '3.0.5', true );
420
- }
421
-
422
- if ( ! wp_script_is( 'easing', 'registered' ) || ( $wp_scripts->registered['easing']->ver !== false && version_compare( $wp_scripts->registered['easing']->ver, '1.3.0', '<' ) ) ) {
423
- wp_deregister_script( 'easing' );
424
- wp_register_script( 'easing', $gmCore->gmedia_url . '/assets/jq-plugins/jquery.easing.js', array( 'jquery' ), '1.3.0', true );
425
- }
426
- if ( ! wp_script_is( 'fancybox', 'registered' ) || ( $wp_scripts->registered['fancybox']->ver !== false && version_compare( $wp_scripts->registered['fancybox']->ver, '1.3.4', '<' ) ) ) {
427
- if ( ! defined( 'FANCYBOX_VERSION' ) ) {
428
- wp_deregister_style( 'fancybox' );
429
- wp_register_style( 'fancybox', $gmCore->gmedia_url . '/assets/fancybox/jquery.fancybox-1.3.4.css', array(), '1.3.4' );
430
- }
431
- wp_deregister_script( 'fancybox' );
432
- wp_register_script( 'fancybox', $gmCore->gmedia_url . '/assets/fancybox/jquery.fancybox-1.3.4.pack.js', array( 'jquery', 'easing' ), '1.3.4', true );
433
- }
434
-
435
-
436
- if ( ! wp_script_is( 'jplayer', 'registered' ) || version_compare( $wp_scripts->registered['jplayer']->ver, '2.6.4', '<' ) ) {
437
- wp_deregister_script( 'jplayer' );
438
- wp_register_script( 'jplayer', $gmCore->gmedia_url . '/assets/jplayer/jquery.jplayer.min.js', array( 'jquery' ), '2.6.4', true );
439
- }
440
- if ( ! wp_script_is( 'swfobject', 'registered' ) || version_compare( $wp_scripts->registered['swfobject']->ver, '2.2', '<' ) ) {
441
- wp_deregister_script( 'swfobject' );
442
- wp_register_script( 'swfobject', $gmCore->gmedia_url . '/assets/swf/swfobject.js', array(), '2.2', true );
443
- wp_register_script( 'swfaddress', $gmCore->gmedia_url . '/assets/swf/swfaddress.js', array(), '2.4', true );
444
- }
445
-
446
- wp_register_script( 'mousetrap', $gmCore->gmedia_url . '/assets/mousetrap/mousetrap.min.js', array(), '1.5.2', true );
447
-
448
- $this->load_scripts();
449
- }
450
-
451
- function load_scripts() {
452
- wp_enqueue_script( 'jquery' );
453
- wp_enqueue_style( 'gmedia-global-frontend' );
454
- wp_enqueue_script( 'gmedia-global-frontend' );
455
- }
456
-
457
- function load_module_scripts() {
458
- global $wp_styles;
459
- $deps = array();
460
- $xmlhttprequest = ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' );
461
- foreach ( $this->do_module as $m => $module ) {
462
- $deps = array_merge( $deps, explode( ',', $module['info']['dependencies'] ) );
463
- $deps = apply_filters( 'gmedia_module_js_dependencies', $deps, $m );
464
- $deps = array_filter( array_unique( $deps ) );
465
- foreach ( $deps as $handle ) {
466
- if ( wp_script_is( $handle, 'registered' ) ) {
467
- wp_enqueue_script( $handle, $_src = false, $_deps = array( 'jquery' ), $this->version, $_in_footer = true );
468
- if ( $xmlhttprequest ) {
469
- wp_print_scripts( $handle );
470
- }
471
- }
472
- if ( wp_style_is( $handle, 'registered' ) ) {
473
- //wp_print_styles($handle);
474
- $this->import_styles[ $handle ] = $wp_styles->registered[ $handle ]->src;
475
- }
476
- }
477
- // $files = glob($module['path'] . '/css/*.css', GLOB_NOSORT);
478
- // if(!empty($files)){
479
- // $files = array_map('basename', $files);
480
- // foreach($files as $file){
481
- // $this->import_styles[] = "{$module['url']}/css/{$file}";
482
- // }
483
- // }
484
- $files = glob( $module['path'] . '/js/*.js', GLOB_NOSORT );
485
- if ( ! empty( $files ) ) {
486
- $files = array_map( 'basename', $files );
487
- $files_deps = array_merge( array( 'jquery' ), $deps );
488
- foreach ( $files as $file ) {
489
- $_ver = isset( $module['info']['version'] ) ? $module['info']['version'] : false;
490
- $handle = "{$module['name']}_{$file}";
491
- wp_enqueue_script( $handle, "{$module['url']}/js/{$file}", $files_deps, $_ver, true );
492
- if ( $xmlhttprequest ) {
493
- wp_print_scripts( $handle );
494
- }
495
- }
496
- }
497
- }
498
- $this->do_module = array();
499
- if ( ! empty( $this->import_styles ) ) {
500
- add_action( 'wp_print_head_scripts', array( &$this, 'print_import_styles' ), 1 );
501
- add_action( 'wp_print_footer_scripts', array( &$this, 'print_import_styles' ), 1 );
502
- }
503
- if ( $xmlhttprequest ) {
504
- $this->print_import_styles();
505
- }
506
- }
507
-
508
- /** Return module styles like <style>@import(...)</style>
509
- *
510
- * @param $module
511
- *
512
- * @return string
513
- */
514
- function load_module_styles( $module ) {
515
- $module_styles = '';
516
- $files = glob( $module['path'] . '/css/*.css', GLOB_NOSORT );
517
- if ( ! empty( $files ) ) {
518
- $_ver = isset( $module['info']['version'] ) ? $module['info']['version'] : false;
519
- $files = array_map( 'basename', $files );
520
- foreach ( $files as $file ) {
521
- $src = "{$module['url']}/css/{$file}";
522
- if ( 'http' !== substr( $src, 0, 4 ) ) {
523
- $src = site_url( $src );
524
- }
525
- $src = add_query_arg( array( 'v' => $_ver ), $src );
526
- $module_styles .= "@import url('{$src}') all;";
527
- }
528
- }
529
-
530
- return $module_styles;
531
- }
532
-
533
- function print_import_styles() {
534
- if ( ! empty( $this->import_styles ) ) {
535
- echo "\n<style type='text/css' class='gmedia_assets_style_import'>";
536
- foreach ( $this->import_styles as $src ) {
537
- if ( 'http' !== substr( $src, 0, 4 ) ) {
538
- $src = site_url( $src );
539
- }
540
- echo "\n@import url('{$src}') all;";
541
- }
542
- echo "\n</style>\n";
543
- $this->import_styles = array();
544
- }
545
- }
546
-
547
- /**
548
- * Call user function to all blogs in network
549
- * called during register_activation hook
550
- *
551
- * @param $pfunction string UserFunction name
552
- * @param $networkwide bool Check if plugin has been activated for the entire blog network.
553
- *
554
- * @return void
555
- */
556
- static function network_propagate( $pfunction, $networkwide ) {
557
-
558
- include_once( dirname( __FILE__ ) . '/config/setup.php' );
559
-
560
- if ( function_exists( 'is_multisite' ) && is_multisite() ) {
561
- // check if it is a network activation - if so, run the activation function
562
- // for each blog id
563
- if ( $networkwide ) {
564
- global $wpdb;
565
- //$old_blog = $wpdb->blogid;
566
- // Get all blog ids
567
- $blogids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
568
- foreach ( $blogids as $blog_id ) {
569
- switch_to_blog( $blog_id );
570
- call_user_func( $pfunction );
571
- }
572
- //switch_to_blog($old_blog);
573
- restore_current_blog();
574
-
575
- return;
576
- }
577
- }
578
- call_user_func( $pfunction );
579
- }
580
-
581
- /**
582
- * @param $networkwide
583
- */
584
- function activate( $networkwide ) {
585
- $this->network_propagate( 'gmedia_install', $networkwide );
586
- }
587
-
588
- /**
589
- * @param $networkwide
590
- */
591
- function deactivate( $networkwide ) {
592
- $this->network_propagate( 'gmedia_deactivate', $networkwide );
593
- }
594
-
595
- /*
596
- static function uninstall($networkwide) {
597
- //wp_die( '<h1>This is run on <code>init</code> during uninstallation</h1>', 'Uninstallation hook example' );
598
- Gmedia::network_propagate('gmedia_uninstall', $networkwide);
599
- }
600
- */
601
-
602
- /**
603
- * @param $blog_id
604
- * @param $user_id
605
- * @param $domain
606
- * @param $path
607
- * @param $site_id
608
- * @param $meta
609
- */
610
- function new_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
611
- if ( is_plugin_active_for_network( GMEDIA_FOLDER . '/grand-media.php' ) ) {
612
- include_once( dirname( __FILE__ ) . '/config/setup.php' );
613
- switch_to_blog( $blog_id );
614
- gmedia_install();
615
- restore_current_blog();
616
- }
617
- }
618
-
619
- /**
620
- * @param $user_id
621
- * @param $reassign
622
- */
623
- function reassign_media( $user_id, $reassign ) {
624
- global $gmDB;
625
- $gmDB->reassign_media( $user_id, $reassign );
626
- }
627
-
628
- /**
629
- * Register Gmedia Post Types
630
- */
631
- function gmedia_post_type() {
632
- $args = array(
633
- 'label' => __( 'Gmedia Posts', 'grand-media' ),
634
- 'supports' => array( 'comments' ),
635
- 'hierarchical' => false,
636
- 'public' => true,
637
- 'show_ui' => false,
638
- 'show_in_menu' => false,
639
- 'show_in_admin_bar' => true,
640
- 'show_in_nav_menus' => false,
641
- 'can_export' => false,
642
- 'has_archive' => (bool) ( (int) $this->options['gmedia_has_archive'] ), //'gmedia-library',
643
- 'publicly_queryable' => true,
644
- 'exclude_from_search' => (bool) ( (int) $this->options['gmedia_exclude_from_search'] ),
645
- 'rewrite' => array( 'slug' => $this->options['gmedia_post_slug'] ),
646
- 'map_meta_cap' => true,
647
- 'capabilities' => array(
648
- 'read_private_posts' => 'read_private_gmedia_posts',
649
- // 'edit_comment' => 'edit_gmedia_comment',
650
- // 'moderate_comments' => 'moderate_gmedia_comments',
651
- // 'edit_post' => 'edit_gmedia_post',
652
- // 'edit_posts' => 'edit_gmedia_posts',
653
- 'create_posts' => false,
654
- ),
655
- );
656
- register_post_type( 'gmedia', $args );
657
-
658
- $args['label'] = __( 'Gmedia Albums', 'grand-media' );
659
- $args['show_in_nav_menus'] = true;
660
- $args['hierarchical'] = true;
661
- $args['has_archive'] = (bool) ( (int) $this->options['gmedia_album_has_archive'] );
662
- $args['exclude_from_search'] = (bool) ( (int) $this->options['gmedia_album_exclude_from_search'] );
663
- $args['rewrite'] = array( 'slug' => $this->options['gmedia_album_post_slug'] );
664
- register_post_type( 'gmedia_album', $args );
665
-
666
- $args['label'] = __( 'Gmedia Galleries', 'grand-media' );
667
- $args['has_archive'] = (bool) ( (int) $this->options['gmedia_gallery_has_archive'] );
668
- $args['exclude_from_search'] = (bool) ( (int) $this->options['gmedia_gallery_exclude_from_search'] );
669
- $args['rewrite'] = array( 'slug' => $this->options['gmedia_gallery_post_slug'] );
670
- register_post_type( 'gmedia_gallery', $args );
671
-
672
- add_filter( 'get_gmedia_metadata', array( $this, 'get_gmedia_metadata' ), 10, 4 );
673
- add_filter( 'get_gmedia_term_metadata', array( $this, 'get_gmedia_term_metadata' ), 10, 4 );
674
- add_filter( 'get_edit_post_link', array( $this, 'gmedia_post_type_edit_link' ), 10, 3 );
675
-
676
-
677
- $args = array(
678
- 'hierarchical' => false,
679
- 'public' => true,
680
- 'show_ui' => false,
681
- 'show_admin_column' => false,
682
- 'show_in_nav_menus' => false,
683
- 'show_tagcloud' => false,
684
- 'rewrite' => array( 'slug' => 'gmedia-category' ),
685
- );
686
- $args['labels'] = array(
687
- 'name' => _x( 'Gmedia Categories', 'Taxonomy General Name', 'grand-media' ),
688
- 'singular_name' => _x( 'Gmedia Category', 'Taxonomy Singular Name', 'grand-media' ),
689
- 'menu_name' => __( 'Gmedia Categories', 'grand-media' ),
690
- );
691
- register_taxonomy( 'gmedia_category', null, $args );
692
-
693
- $args['rewrite'] = array( 'slug' => 'gmedia-tag' );
694
- $args['labels'] = array(
695
- 'name' => _x( 'Gmedia Tags', 'Taxonomy General Name', 'grand-media' ),
696
- 'singular_name' => _x( 'Gmedia Tag', 'Taxonomy Singular Name', 'grand-media' ),
697
- 'menu_name' => __( 'Gmedia Tags', 'grand-media' ),
698
- );
699
- register_taxonomy( 'gmedia_tag', null, $args );
700
-
701
- add_filter( 'wp_link_query_args', array( $this, 'exclude_gmedia_from_link_query' ) );
702
-
703
- if ( ! empty( $this->options['flush_rewrite_rules'] ) ) {
704
- unset( $this->options['flush_rewrite_rules'] );
705
- update_option( 'gmediaOptions', $this->options );
706
- flush_rewrite_rules( false );
707
- }
708
- }
709
-
710
- /**
711
- * Get gmedia metadata
712
- *
713
- * @param $meta
714
- * @param $post_ID
715
- * @param $meta_key
716
- * @param $single
717
- *
718
- * @return array|string
719
- */
720
- function get_gmedia_metadata( $meta, $post_ID, $meta_key, $single ) {
721
- global $gmDB;
722
- $gmedia_id = get_post_meta( $post_ID, '_gmedia_ID', true );
723
- $meta = $gmDB->get_metadata( 'gmedia', $gmedia_id, $meta_key, $single );
724
-
725
- return $meta;
726
- }
727
-
728
- /**
729
- * Get gmedia term metadata
730
- *
731
- * @param $meta
732
- * @param $post_ID
733
- * @param $meta_key
734
- * @param $single
735
- *
736
- * @return array|string
737
- */
738
- function get_gmedia_term_metadata( $meta, $post_ID, $meta_key, $single ) {
739
- global $gmDB;
740
- $gmedia_term_id = get_post_meta( $post_ID, '_gmedia_term_ID', true );
741
- $meta = $gmDB->get_metadata( 'gmedia_term', $gmedia_term_id, $meta_key, $single );
742
-
743
- return $meta;
744
- }
745
-
746
- /**
747
- * Edit link for gmedia
748
- *
749
- * @param $link
750
- * @param $post_ID
751
- * @param $context
752
- *
753
- * @return string|void
754
- */
755
- function gmedia_post_type_edit_link( $link, $post_ID, $context ) {
756
- $post = get_post( $post_ID );
757
- if ( isset( $post->ID ) && 'gmedia' == substr( $post->post_type, 0, 6 ) ) {
758
- global $gmDB;
759
- if ( $post->post_type == 'gmedia' ) {
760
- $gmedia_id = get_post_meta( $post->ID, '_gmedia_ID', true );
761
- $gmedia = $gmDB->get_gmedia( $gmedia_id );
762
- if ( $gmedia ) {
763
- $link = admin_url( "admin.php?page=GrandMedia&mode=edit&gmedia__in={$gmedia->ID}" );
764
- } else {
765
- wp_delete_post( $post->ID, true );
766
- $link = '#';
767
- }
768
- } else {
769
- $term_id = get_post_meta( $post->ID, '_gmedia_term_ID', true );
770
- $term = $gmDB->get_term( $term_id );
771
- if ( $term ) {
772
- if ( $term->taxonomy == 'gmedia_album' ) {
773
- $link = admin_url( "admin.php?page=GrandMedia_Albums&edit_term={$term->term_id}" );
774
- } elseif ( $term->taxonomy == 'gmedia_gallery' ) {
775
- $link = admin_url( "admin.php?page=GrandMedia_Galleries&edit_term={$term->term_id}" );
776
- }
777
- } else {
778
- wp_delete_post( $post->ID, true );
779
- $link = '#';
780
- }
781
- }
782
- }
783
-
784
- return $link;
785
- }
786
-
787
- function register_gmedia_widget() {
788
- require_once( dirname( __FILE__ ) . '/inc/widget.php' );
789
- register_widget( 'GrandMedia_Gallery_Widget' );
790
- register_widget( 'GrandMedia_Album_Widget' );
791
- }
792
-
793
- /**
794
- * @param $query
795
- *
796
- * @return mixed
797
- */
798
- function exclude_gmedia_from_link_query( $query ) {
799
- if ( ( $key = array_search( 'gmedia', $query['post_type'] ) ) !== false ) {
800
- unset( $query['post_type'][ $key ] );
801
- }
802
-
803
- return $query;
804
- }
805
-
806
- /**
807
- * @param $shedules
808
- *
809
- * @return array
810
- */
811
- function gmedia_cron_schedules( $shedules ) {
812
- $gmedia_shedules = array( 'gmedia_app' => array( 'interval' => 5 * DAY_IN_SECONDS, 'display' => __( 'Gmedia App Defined' ) ) );
813
- $shedules = array_merge( $shedules, $gmedia_shedules );
814
-
815
- return $shedules;
816
- }
817
-
818
- function gmedia_app_cronjob() {
819
- global $gmCore;
820
- $gmCore->app_service( 'app_updatecron' );
821
- }
822
-
823
- function gmedia_modules_update() {
824
- global $gmCore;
825
- $gmCore->modules_update();
826
- }
827
-
828
-
829
- /*
830
- // PLUGIN MESSAGE ON PLUGINS PAGE
831
- function check_message_version($file)
832
- {
833
- static $this_plugin;
834
- global $wp_version;
835
- if (!$this_plugin) $this_plugin = GMEDIA_FOLDER;
836
-
837
- if ($file == $this_plugin ){
838
- $checkfile = "http://codeasily.com/grand-flam.chk";
839
-
840
- $message = wp_remote_fopen($checkfile);
841
-
842
- if($message)
843
- {
844
- preg_match( '|grand'.str_replace('.','',GMEDIA_VERSION).':(.*)$|mi', $message, $theMessage );
845
- $columns = 5;
846
- if ( !empty( $theMessage ) )
847
- {
848
- $theMessage = trim($theMessage[1]);
849
- echo '<td colspan="'.$columns.'" class="plugin-update" style="line-height:1.2em; font-size:11px; padding:1px;"><div id="flag-update-msg" style="padding-bottom:1px;" >'.$theMessage.'</div></td>';
850
- } else {
851
- return;
852
- }
853
- }
854
- }
855
- }
856
- */
857
-
858
- function add_plugin_links( $links, $file ) {
859
- if ( $file == plugin_basename( __FILE__ ) ) {
860
- $links[] = '<a href="admin.php?page=GrandMedia_Settings">' . __( 'Settings', 'grand-media' ) . '</a>';
861
- $links[] = '<a href="admin.php?page=GrandMedia_Modules">' . __( 'Modules', 'grand-media' ) . '</a>';
862
- $links[] = '<a href="https://codeasily.com/product/one-site-license/">' . __( 'Get Premium', 'grand-media' ) . '</a>';
863
- $links[] = '<a href="https://codeasily.com/donate/">' . __( 'Donate', 'grand-media' ) . '</a>';
864
- }
865
-
866
- return $links;
867
- }
868
-
869
- function add_plugin_feedback() {
870
- global $pagenow;
871
- if ( 'plugins.php' !== $pagenow ) {
872
- return;
873
- }
874
- ?>
875
- <script type="text/javascript">
876
- jQuery(function($) {
877
- function gm_parse_query(s) {
878
- var j = {}, res = s.split(/&/gm).map(function(e) {
879
- var o = e.split(/=/), pt = j;
880
- if(typeof o[1] == 'undefined') {
881
- o[1] = '';
882
- }
883
- o[0].replace(/^(\w+)\[([^&]*)\]/, '$1][$2').split(/\]\[/).map(function(e, i, a) {
884
- if(e === '') {
885
- e = Object.keys(pt).length;
886
- }
887
- pt = (pt[e] = pt[e] || (i == a.length - 1 ? decodeURIComponent(o[1].replace(/\+/, ' ')) : {}));
888
- });
889
- });
890
- return j;
891
- }
892
-
893
- $('tr[data-slug="grand-media"] .deactivate a').on('click', function(e) {
894
- e.preventDefault();
895
- e.stopPropagation();
896
-
897
- $('body').append($('#tmpl-gmedia-feedback').html());
898
- var deactivate_link = $(this).attr('href');
899
- $('.gm-button-submit-deactivate, .gm-button-skip-deactivate').attr('href', deactivate_link);
900
- $('#gmedia-feedback [name="reason"]').on('change', function() {
901
- var parent = $(this).closest('.reason');
902
- parent.siblings('.has-input').find('.reason-input').hide().find('input').prop('disabled', true);
903
- if(parent.hasClass('has-input')) {
904
- if($(this).is(':checked')) {
905
- $('.reason-input', parent).show().find('input').prop('disabled', false);
906
- }
907
- }
908
- });
909
- $('#gmedia-feedback .gm-button-submit-deactivate').on('click', function(e) {
910
- e.preventDefault();
911
-
912
- var feedback = $('#gmedia-feedback input').serialize();
913
- feedback = gm_parse_query(feedback);
914
-
915
- if(feedback.reason === '') {
916
- window.location = deactivate_link;
917
- return;
918
- }
919
-
920
- $('#gmedia-feedback .spinner').addClass('is-active');
921
- var post_data = {
922
- action: 'gmedia_feedback',
923
- data: feedback,
924
- _wpnonce_gmedia_feedback: '<?php echo wp_create_nonce( 'gmedia_feedback' ); ?>'
925
- };
926
- $.post(ajaxurl, post_data).always(function(data) {
927
- $('#gmedia-feedback .spinner').removeClass('is-active');
928
- window.location = deactivate_link;
929
- });
930
- return false;
931
- });
932
- $('#gmedia-feedback .gm-button-close').on('click', function() {
933
- $('#gmedia-feedback').remove();
934
- return false;
935
- });
936
-
937
- return false;
938
- });
939
- });
940
- </script>
941
- <script id="tmpl-gmedia-feedback" type="text/template">
942
- <div class="gm-modal gm-modal-deactivation-feedback" id="gmedia-feedback">
943
- <style>
944
- .gm-modal { position: fixed; overflow: auto; height: 100%; width: 100%; top: 0; z-index: 100000; background: rgba(0, 0, 0, 0.6); }
945
-
946
- .gm-modal-dialog { position: absolute; left: 50%; padding-bottom: 30px; top: 10%; z-index: 100001; max-width: 600px; min-width: 220px; transform: translateX(-50%); }
947
-
948
- .gm-modal-header { border-bottom: #eeeeee solid 1px; background: #fbfbfb; padding: 15px 20px; position: relative; margin-bottom: -10px; }
949
-
950
- .gm-modal-header h4 { margin: 0; padding: 0; text-transform: uppercase; font-size: 1.2em; font-weight: bold; color: #cacaca; text-shadow: 1px 1px 1px #fff; letter-spacing: 0.6px; -webkit-font-smoothing: antialiased; }
951
-
952
- .gm-modal-body,
953
- .gm-modal-footer { border: 0; background: #fefefe; padding: 20px; }
954
-
955
- .gm-modal-footer { border-top: #eeeeee solid 1px; text-align: right; }
956
-
957
- .gm-modal-body h3 { margin-top: 0; line-height: 1.5em; }
958
-
959
- .gm-modal-body .reason { margin: 7px 0; }
960
-
961
- .gm-modal-body .reason-input { margin: 3px 0 3px 22px; display: none; }
962
-
963
- .gm-modal-body .reason-input input { width: 100%; }
964
-
965
- .gm-modal-footer a.button { margin-right: 7px; }
966
- </style>
967
- <div class="gm-modal-dialog">
968
- <div class="gm-modal-header"><h4><?php _e( 'Quick feedback', 'grand-media' ); ?></h4></div>
969
- <div class="gm-modal-body">
970
- <h3><strong><?php _e( 'If you have a moment, please let us know why you are deactivating:', 'grand-media' ); ?></strong></h3>
971
- <div id="reasons-list">
972
- <div class="reason">
973
- <label><input type="radio" name="reason" value="" checked/> <span><?php _e( 'It\'s a temporary deactivation. I\'m just debugging an issue.', 'grand-media' ); ?></span></label>
974
- </div>
975
- <div class="reason">
976
- <label><input type="radio" name="reason" value="I no longer need the gallery plugin"/> <span><?php _e( 'I no longer need the gallery plugin', 'grand-media' ); ?></span></label>
977
- </div>
978
- <div class="reason has-input">
979
- <label><input type="radio" name="reason" value="I found a better gallery plugin"/> <span><?php _e( 'I found a better gallery plugin', 'grand-media' ); ?></span></label>
980
- <div class="reason-input"><input type="text" name="better_plugin" disabled placeholder="<?php _e( 'What\'s the plugin\'s name?', 'grand-media' ); ?>"/></div>
981
- </div>
982
- <div class="reason">
983
- <label><input type="radio" name="reason" value="The plugin is too coomplicated for me"/> <span><?php _e( 'The plugin is too coomplicated for me', 'grand-media' ); ?></span></label>
984
- </div>
985
- <div class="reason">
986
- <label><input type="radio" name="reason" value="The plugin broke my life"/> <span><?php _e( 'The plugin broke my life', 'grand-media' ); ?></span></label>
987
- </div>
988
- <div class="reason has-input">
989
- <label><input type="radio" name="reason" value="Other"/> <span><?php _e( 'Other', 'grand-media' ); ?></span></label>
990
- <div class="reason-input"><input type="text" name="other_reason" value="" disabled/></div>
991
- </div>
992
- </div>
993
- </div>
994
- <div class="gm-modal-footer">
995
- <span class="spinner" style="float: none;"></span>
996
- <a href="#" class="button button-secondary gm-button-submit-deactivate"><?php _e( 'Submit & Deactivate', 'grand-media' ); ?></a>
997
- <a href="#" class="button button-secondary gm-button-skip-deactivate"><?php _e( 'Skip', 'grand-media' ); ?></a>
998
- <a href="#" class="button button-primary gm-button-close"><?php _e( 'Cancel', 'grand-media' ); ?></a>
999
- </div>
1000
- </div>
1001
- </div>
1002
- </script>
1003
- <?php
1004
- }
1005
-
1006
- }
1007
-
1008
- // Let's start the holy plugin
1009
- global $gmGallery;
1010
- $gmGallery = new Gmedia();
1011
-
1012
- }
1
+ <?php
2
+ /*
3
+ * Plugin Name: Gmedia Gallery
4
+ * Plugin URI: http://wordpress.org/extend/plugins/grand-media/
5
+ * Description: Gmedia Gallery - powerful media library plugin for creating beautiful galleries and managing files.
6
+ * Version: 1.17.6
7
+ * Author: Rattus
8
+ * Author URI: https://codeasily.com/
9
+ * Requires at least: 3.7
10
+ * Tested up to: 5.2
11
+ * Text Domain: grand-media
12
+ * Domain Path: /lang
13
+ *
14
+ */
15
+ /* -------------------
16
+
17
+ Copyright (C) 2011 Rattus (email : gmediafolder@gmail.com)
18
+
19
+ This program is free software; you can redistribute it and/or
20
+ modify it under the terms of the GNU General Public License
21
+ as published by the Free Software Foundation; either version 2
22
+ of the License, or (at your option) any later version.
23
+
24
+ This program is distributed in the hope that it will be useful,
25
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
26
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27
+ GNU General Public License for more details.
28
+
29
+ You should have received a copy of the GNU General Public License
30
+ along with this program; if not, write to the Free Software
31
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
32
+ */
33
+
34
+ // Stop direct call
35
+ if ( preg_match( '#' . basename( __FILE__ ) . '#', $_SERVER['PHP_SELF'] ) ) {
36
+ die( 'You are not allowed to call this page directly.' );
37
+ }
38
+
39
+ if ( ! class_exists( 'Gmedia' ) ) {
40
+ /**
41
+ * Class Gmedia
42
+ */
43
+ class Gmedia {
44
+
45
+ var $version = '1.17.6';
46
+ var $dbversion = '1.8.0';
47
+ var $minium_WP = '3.7';
48
+ var $options = '';
49
+ var $do_module = array();
50
+ var $import_styles = array();
51
+ var $shortcode = array();
52
+
53
+ /**
54
+ *
55
+ */
56
+ function __construct() {
57
+
58
+ // Stop the plugin if we missed the requirements
59
+ if ( ! $this->required_version() ) {
60
+ return;
61
+ }
62
+
63
+ // Get some constants first
64
+ include_once( dirname( __FILE__ ) . '/config.php' );
65
+ $this->load_options();
66
+ $this->define_constant();
67
+ $this->define_tables();
68
+
69
+ // Load global libraries
70
+ require_once( dirname( __FILE__ ) . '/inc/core.php' );
71
+ require_once( dirname( __FILE__ ) . '/inc/db.connect.php' );
72
+ require_once( dirname( __FILE__ ) . '/inc/permalinks.php' );
73
+
74
+ if ( $this->options['debug_mode'] ) {
75
+ ini_set( 'display_errors', true );
76
+ error_reporting( E_ALL );
77
+ } else {
78
+ @ini_set( 'display_errors', true ); //Ensure that Fatal errors are displayed.
79
+ error_reporting( E_CORE_ERROR | E_COMPILE_ERROR | E_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR );
80
+ }
81
+
82
+ $this->plugin_name = plugin_basename( __FILE__ );
83
+
84
+ add_filter( 'cron_schedules', array( &$this, 'gmedia_cron_schedules' ) );
85
+
86
+ // Init options & tables during activation & deregister init option
87
+ register_activation_hook( $this->plugin_name, array( &$this, 'activate' ) );
88
+ register_deactivation_hook( $this->plugin_name, array( &$this, 'deactivate' ) );
89
+
90
+ // Register a uninstall hook to remove all tables & option automatic
91
+ //register_uninstall_hook( $this->plugin_name, array(__CLASS__, 'uninstall' ) );
92
+
93
+ add_action( 'wp_enqueue_scripts', array( &$this, 'register_scripts_frontend' ), 20 );
94
+
95
+ add_action( 'admin_enqueue_scripts', array( &$this, 'register_scripts_backend' ), 8 );
96
+
97
+ add_action( 'wpmu_new_blog', array( &$this, 'new_blog' ), 10, 6 );
98
+
99
+ // Start this plugin once all other plugins are fully loaded
100
+ add_action( 'plugins_loaded', array( &$this, 'start_plugin' ) );
101
+
102
+ add_action( 'deleted_user', array( &$this, 'reassign_media' ), 10, 2 );
103
+
104
+ add_action( 'init', array( &$this, 'gmedia_post_type' ), 0 );
105
+ add_action( 'init', array( &$this, 'compatibility' ), 11 );
106
+ //add_action('init', array(&$this, 'gm_schedule_update_checks'), 0);
107
+
108
+ // register widget
109
+ add_action( 'widgets_init', array( &$this, 'register_gmedia_widget' ) );
110
+
111
+ add_action( 'gmedia_app_cronjob', array( &$this, 'gmedia_app_cronjob' ) );
112
+ add_action( 'gmedia_modules_update', array( &$this, 'gmedia_modules_update' ) );
113
+
114
+ //Add some message on the plugins page
115
+ //add_action( 'after_plugin_row', array(&$this, 'check_message_version') );
116
+ //Add some links on the plugins page
117
+ add_filter( 'plugin_row_meta', array( &$this, 'add_plugin_links' ), 10, 2 );
118
+ add_action( 'admin_footer', array( &$this, 'add_plugin_feedback' ) );
119
+
120
+ }
121
+
122
+ function start_plugin() {
123
+
124
+ $this->load_dependencies();
125
+
126
+ // Load the language file
127
+ $this->load_textdomain();
128
+
129
+ require_once( dirname( __FILE__ ) . '/inc/functions.php' );
130
+
131
+ // Check for upgrade
132
+ $this->upgrade();
133
+
134
+ require_once( dirname( __FILE__ ) . '/inc/hashids.php' );
135
+ require_once( dirname( __FILE__ ) . '/inc/shortcodes.php' );
136
+
137
+ // Load the admin panel or the frontend functions
138
+ if ( is_admin() ) {
139
+
140
+ // Pass the init check or show a message
141
+ if ( get_option( 'gmediaActivated' ) ) {
142
+ add_action( 'init', array( &$this, 'gmedia_after_activation' ) );
143
+ }
144
+
145
+ // Pass the init check or show a message
146
+ if ( get_option( 'gmediaInitCheck' ) ) {
147
+ add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
148
+ }
149
+
150
+ require_once( dirname( __FILE__ ) . '/admin/functions.php' );
151
+
152
+ require_once( dirname( __FILE__ ) . '/admin/class.processor.php' );
153
+
154
+ } else {
155
+
156
+ // Add the script and style files
157
+ //add_action('wp_enqueue_scripts', array(&$this, 'load_scripts'), 4);
158
+
159
+ require_once( dirname( __FILE__ ) . '/inc/frontend.filters.php' );
160
+
161
+ // Add a version number to the header
162
+ add_action( 'wp_head', array( &$this, 'gmedia_head_meta' ) );
163
+ add_action( 'wp_footer', array( &$this, 'load_module_scripts' ) );
164
+
165
+ }
166
+
167
+ add_action( 'gmedia_head', array( &$this, 'gmedia_head_meta' ) );
168
+ add_action( 'gmedia_head', array( &$this, 'load_scripts' ), 2 );
169
+ add_action( 'gmedia_head', 'wp_print_head_scripts', 9 );
170
+ add_action( 'gmedia_enqueue_scripts', array( &$this, 'load_module_scripts' ) );
171
+
172
+ add_action( 'gmedia_head', array( &$this, 'print_import_styles' ) );
173
+ add_action( 'gmedia_footer', array( &$this, 'print_import_styles' ) );
174
+
175
+ }
176
+
177
+ function gmedia_head_meta() {
178
+ $lk = strtolower( $this->options['license_key'] );
179
+ $db_version = get_option( 'gmediaDbVersion' );
180
+ echo "\n<!-- <meta name='GmediaGallery' version='{$this->version}/{$db_version}' license='{$lk}' /> -->\n";
181
+ }
182
+
183
+ function admin_notices() {
184
+ echo '<div id="message" class="error"><p><strong>' . get_option( 'gmediaInitCheck' ) . '</strong></p></div>';
185
+ delete_option( 'gmediaInitCheck' );
186
+ }
187
+
188
+ /**
189
+ * @return bool
190
+ */
191
+ function required_version() {
192
+ global $wp_version;
193
+
194
+ // Check for WP version installation
195
+ if ( version_compare( $wp_version, $this->minium_WP, '<' ) ) {
196
+ $note = sprintf( __( 'Sorry, Gmedia Gallery works only under WordPress %s or higher', 'grand-media' ), $this->minium_WP );
197
+ update_option( 'gmediaInitCheck', $note );
198
+ add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
199
+
200
+ return false;
201
+ }
202
+ if ( version_compare( '5.3', phpversion(), '>' ) ) {
203
+ $note = sprintf( __( 'Attention! Your server php version is: %s. Gmedia Gallery requires php version 5.3+ in order to run properly. Please upgrade your server!', 'grand-media' ), phpversion() );
204
+ update_option( 'gmediaInitCheck', $note );
205
+ add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
206
+
207
+ return false;
208
+ }
209
+
210
+ return true;
211
+ }
212
+
213
+ /**
214
+ * Called via Setup and register_activate hook after gmedia_install() function
215
+ */
216
+ function gmedia_after_activation() {
217
+ global $gmCore;
218
+
219
+ delete_option( 'gmediaActivated' );
220
+
221
+ flush_rewrite_rules( false );
222
+
223
+ if ( (int) $this->options['mobile_app'] ) {
224
+ wp_clear_scheduled_hook( 'gmedia_app_cronjob' );
225
+ wp_schedule_event( time(), 'gmedia_app', 'gmedia_app_cronjob' );
226
+
227
+ $gmCore->app_service( 'app_activateplugin' );
228
+ }
229
+
230
+ $wp_installing = (bool) ( defined( 'WP_INSTALLING' ) && WP_INSTALLING );
231
+ if ( ! wp_next_scheduled( 'gmedia_modules_update' ) && ! $wp_installing ) {
232
+ wp_schedule_event( time(), 'daily', 'gmedia_modules_update' );
233
+ }
234
+ }
235
+
236
+ function upgrade() {
237
+ // Queue upgrades
238
+ $current_version = get_option( 'gmediaVersion', null );
239
+ $current_db_version = get_option( 'gmediaDbVersion', null );
240
+
241
+ if ( null === $current_db_version ) {
242
+ add_option( "gmediaDbVersion", GMEDIA_DBVERSION );
243
+ } elseif ( version_compare( $current_db_version, GMEDIA_DBVERSION, '<' ) ) {
244
+ require_once( dirname( __FILE__ ) . '/config/update.php' );
245
+
246
+ if ( get_transient( 'gmediaUpgrade' ) || ( isset( $_GET['do_update'] ) && ( 'gmedia' == $_GET['do_update'] ) ) ) {
247
+ add_action( 'admin_notices', 'gmedia_upgrade_process_admin_notice' );
248
+ } else {
249
+ add_action( 'admin_notices', 'gmedia_upgrade_required_admin_notice' );
250
+ }
251
+ }
252
+
253
+ if ( null === $current_version ) {
254
+ require_once( dirname( __FILE__ ) . '/config/update.php' );
255
+
256
+ add_option( "gmediaVersion", GMEDIA_VERSION );
257
+ add_action( 'init', 'gmedia_flush_rewrite_rules', 1000 );
258
+ } elseif ( version_compare( $current_version, GMEDIA_VERSION, '<' ) ) {
259
+ require_once( dirname( __FILE__ ) . '/config/update.php' );
260
+
261
+ gmedia_quite_update();
262
+ gmedia_delete_transients( 'gm_cache' );
263
+ add_action( 'init', 'gmedia_flush_rewrite_rules', 1000 );
264
+
265
+ if ( (int) $this->options['mobile_app'] ) {
266
+ if ( ! wp_get_schedule( 'gmedia_app_cronjob' ) ) {
267
+ wp_schedule_event( time(), 'gmedia_app', 'gmedia_app_cronjob' );
268
+ }
269
+ global $gmCore;
270
+ $gmCore->app_service( 'app_updatecron' );
271
+ }
272
+ }
273
+
274
+ }
275
+
276
+ function define_tables() {
277
+ global $wpdb;
278
+
279
+ // add database pointer
280
+ $wpdb->gmedia = $wpdb->prefix . 'gmedia';
281
+ $wpdb->gmedia_meta = $wpdb->prefix . 'gmedia_meta';
282
+ $wpdb->gmedia_term = $wpdb->prefix . 'gmedia_term';
283
+ $wpdb->gmedia_term_meta = $wpdb->prefix . 'gmedia_term_meta';
284
+ $wpdb->gmedia_term_relationships = $wpdb->prefix . 'gmedia_term_relationships';
285
+
286
+ }
287
+
288
+ function define_constant() {
289
+
290
+ define( 'GMEDIA_VERSION', $this->version );
291
+ // Minimum required database version
292
+ define( 'GMEDIA_DBVERSION', $this->dbversion );
293
+
294
+ }
295
+
296
+ function load_options() {
297
+ include_once( dirname( __FILE__ ) . '/config/setup.php' );
298
+ // Load the options
299
+ $default_options = gmedia_default_options();
300
+ $db_options = get_option( 'gmediaOptions' );
301
+ if ( ! is_array( $db_options ) ) {
302
+ $db_options = array();
303
+ }
304
+ $this->options = array_merge( $default_options, $db_options );
305
+ }
306
+
307
+ function load_dependencies() {
308
+
309
+ // We didn't need all stuff during a AJAX operation
310
+ if ( defined( 'DOING_AJAX' ) ) {
311
+ require_once( dirname( __FILE__ ) . '/admin/ajax.php' );
312
+ } else {
313
+
314
+ // Load backend libraries
315
+ if ( is_admin() ) {
316
+ require_once( dirname( __FILE__ ) . '/inc/media-upload.php' );
317
+ require_once( dirname( __FILE__ ) . '/inc/post-metabox.php' );
318
+
319
+ require_once( dirname( __FILE__ ) . '/admin/admin.php' );
320
+
321
+ // Load frontend libraries
322
+ }
323
+
324
+ $current_plugins = get_option( 'active_plugins' );
325
+ if ( in_array( 'wordpress-seo/wp-seo.php', $current_plugins ) ) {
326
+ require_once( dirname( __FILE__ ) . '/inc/sitemap.php' );
327
+ }
328
+ }
329
+
330
+ }
331
+
332
+ function compatibility() {
333
+ require_once( dirname( __FILE__ ) . '/inc/compatibility.php' );
334
+ }
335
+
336
+ function load_textdomain() {
337
+
338
+ load_plugin_textdomain( 'grand-media', false, GMEDIA_FOLDER . '/lang/' );
339
+
340
+ }
341
+
342
+ function register_scripts_backend() {
343
+ global $gmCore;
344
+
345
+ wp_register_script( 'gmedia-global-backend', $gmCore->gmedia_url . '/admin/assets/js/gmedia.global.js', array( 'jquery' ), '1.13.0' );
346
+ wp_localize_script( 'gmedia-global-backend', 'GmediaGallery', array(
347
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
348
+ '_wpnonce' => wp_create_nonce( 'GmediaGallery' ),
349
+ 'upload_dirurl' => $gmCore->upload['url'],
350
+ 'plugin_dirurl' => $gmCore->gmedia_url,
351
+ 'google_api_key' => $this->options['google_api_key'],
352
+ ) );
353
+
354
+ wp_register_style( 'grand-media', $gmCore->gmedia_url . '/admin/assets/css/gmedia.admin.css', array(), '1.15.4', 'all' );
355
+ wp_register_script( 'grand-media', $gmCore->gmedia_url . '/admin/assets/js/gmedia.admin.js', array( 'jquery', 'gmedia-global-backend' ), '1.15.4' );
356
+ wp_localize_script( 'grand-media', 'grandMedia', array(
357
+ 'error3' => __( 'Disable your Popup Blocker and try again.', 'grand-media' ),
358
+ 'download' => __( 'downloading...', 'grand-media' ),
359
+ 'wait' => __( 'Working. Wait please.', 'grand-media' ),
360
+ '_wpnonce' => wp_create_nonce( 'GmediaGallery' ),
361
+ ) );
362
+
363
+ wp_register_style( 'gmedia-bootstrap', $gmCore->gmedia_url . '/assets/bootstrap/css/bootstrap.min.css', array(), '3.3.4', 'all' );
364
+ wp_register_script( 'gmedia-bootstrap', $gmCore->gmedia_url . '/assets/bootstrap/js/bootstrap.min.js', array( 'jquery' ), '3.3.4' );
365
+
366
+ wp_register_script( 'outside-events', $gmCore->gmedia_url . '/assets/jq-plugins/outside-events.js', array( 'jquery' ), '1.1' );
367
+
368
+ }
369
+
370
+ function register_scripts_frontend() {
371
+ global $gmCore, $wp_scripts;
372
+
373
+ wp_register_style( 'gmedia-global-frontend', $gmCore->gmedia_url . '/assets/gmedia.global.front.css', array(), '1.15.0' );
374
+ wp_register_script( 'gmedia-global-frontend', $gmCore->gmedia_url . '/assets/gmedia.global.front.js', array( 'jquery' ), '1.13.0' );
375
+ wp_localize_script( 'gmedia-global-frontend', 'GmediaGallery', array(
376
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
377
+ 'nonce' => wp_create_nonce( 'GmediaGallery' ),
378
+ 'upload_dirurl' => $gmCore->upload['url'],
379
+ 'plugin_dirurl' => $gmCore->upload['url'],
380
+ 'license' => strtolower( $this->options['license_key'] ),
381
+ 'license2' => $this->options['license_key2'],
382
+ 'google_api_key' => $this->options['google_api_key'],
383
+ ) );
384
+
385
+
386
+ if ( ! wp_script_is( 'velocity', 'registered' ) || version_compare( $wp_scripts->registered['velocity']->ver, '1.4.1', '<' ) ) {
387
+ wp_deregister_script( 'velocity' );
388
+ wp_register_script( 'velocity', $gmCore->gmedia_url . '/assets/velocity/velocity.min.js', array( 'jquery' ), '1.4.1', true );
389
+ }
390
+
391
+ if ( ! wp_script_is( 'mediaelement', 'registered' ) ) {
392
+ wp_register_style( 'mediaelement', $gmCore->gmedia_url . '/assets/mediaelement/mediaelementplayer.min.css', array(), '4.2.8', 'screen' );
393
+ wp_register_script( 'mediaelement', $gmCore->gmedia_url . '/assets/mediaelement/mediaelement-and-player.min.js', array( 'jquery' ), '4.2.8', true );
394
+ }
395
+
396
+ if ( ! wp_script_is( 'wavesurfer', 'registered' ) ) {
397
+ wp_register_script( 'wavesurfer', $gmCore->gmedia_url . '/assets/wavesurfer/wavesurfer.min.js', array( 'jquery' ), '1.2.8', true );
398
+ }
399
+
400
+ if ( ! wp_script_is( 'swiper', 'registered' ) ) {
401
+ wp_register_style( 'swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.min.css', array(), '3.4.0', 'screen' );
402
+ wp_register_script( 'swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.jquery.min.js', array( 'jquery' ), '3.4.0', true );
403
+ }
404
+
405
+ wp_register_style( 'gmedia-swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.min.css', array(), '3.4.0', 'screen' );
406
+ wp_register_script( 'gmedia-swiper', $gmCore->gmedia_url . '/assets/swiper/swiper.jquery.min.js', array( 'jquery' ), '3.4.0', true );
407
+
408
+ if ( ! wp_script_is( 'magnific-popup', 'registered' ) || version_compare( $wp_scripts->registered['magnific-popup']->ver, '1.1.0', '<' ) ) {
409
+ wp_deregister_style( 'magnific-popup' );
410
+ wp_deregister_script( 'magnific-popup' );
411
+ wp_register_style( 'magnific-popup', $gmCore->gmedia_url . '/assets/mag-popup/magnific-popup.css', array(), '1.1.0', 'screen' );
412
+ wp_register_script( 'magnific-popup', $gmCore->gmedia_url . '/assets/mag-popup/jquery.magnific-popup.min.js', array( 'jquery' ), '1.1.0', true );
413
+ }
414
+
415
+ if ( ! wp_script_is( 'photoswipe', 'registered' ) || version_compare( $wp_scripts->registered['photoswipe']->ver, '3.0.5', '<=' ) ) {
416
+ wp_deregister_style( 'photoswipe' );
417
+ wp_deregister_script( 'photoswipe' );
418
+ wp_register_style( 'photoswipe', $gmCore->gmedia_url . '/assets/photoswipe/photoswipe.css', array(), '3.0.5', 'screen' );
419
+ wp_register_script( 'photoswipe', $gmCore->gmedia_url . '/assets/photoswipe/photoswipe.jquery.min.js', array( 'jquery' ), '3.0.5', true );
420
+ }
421
+
422
+ if ( ! wp_script_is( 'easing', 'registered' ) || ( $wp_scripts->registered['easing']->ver !== false && version_compare( $wp_scripts->registered['easing']->ver, '1.3.0', '<' ) ) ) {
423
+ wp_deregister_script( 'easing' );
424
+ wp_register_script( 'easing', $gmCore->gmedia_url . '/assets/jq-plugins/jquery.easing.js', array( 'jquery' ), '1.3.0', true );
425
+ }
426
+ if ( ! wp_script_is( 'fancybox', 'registered' ) || ( $wp_scripts->registered['fancybox']->ver !== false && version_compare( $wp_scripts->registered['fancybox']->ver, '1.3.4', '<' ) ) ) {
427
+ if ( ! defined( 'FANCYBOX_VERSION' ) ) {
428
+ wp_deregister_style( 'fancybox' );
429
+ wp_register_style( 'fancybox', $gmCore->gmedia_url . '/assets/fancybox/jquery.fancybox-1.3.4.css', array(), '1.3.4' );
430
+ }
431
+ wp_deregister_script( 'fancybox' );
432
+ wp_register_script( 'fancybox', $gmCore->gmedia_url . '/assets/fancybox/jquery.fancybox-1.3.4.pack.js', array( 'jquery', 'easing' ), '1.3.4', true );
433
+ }
434
+
435
+
436
+ if ( ! wp_script_is( 'jplayer', 'registered' ) || version_compare( $wp_scripts->registered['jplayer']->ver, '2.6.4', '<' ) ) {
437
+ wp_deregister_script( 'jplayer' );
438
+ wp_register_script( 'jplayer', $gmCore->gmedia_url . '/assets/jplayer/jquery.jplayer.min.js', array( 'jquery' ), '2.6.4', true );
439
+ }
440
+ if ( ! wp_script_is( 'swfobject', 'registered' ) || version_compare( $wp_scripts->registered['swfobject']->ver, '2.2', '<' ) ) {
441
+ wp_deregister_script( 'swfobject' );
442
+ wp_register_script( 'swfobject', $gmCore->gmedia_url . '/assets/swf/swfobject.js', array(), '2.2', true );
443
+ wp_register_script( 'swfaddress', $gmCore->gmedia_url . '/assets/swf/swfaddress.js', array(), '2.4', true );
444
+ }
445
+
446
+ wp_register_script( 'mousetrap', $gmCore->gmedia_url . '/assets/mousetrap/mousetrap.min.js', array(), '1.5.2', true );
447
+
448
+ $this->load_scripts();
449
+ }
450
+
451
+ function load_scripts() {
452
+ wp_enqueue_script( 'jquery' );
453
+ wp_enqueue_style( 'gmedia-global-frontend' );
454
+ wp_enqueue_script( 'gmedia-global-frontend' );
455
+ }
456
+
457
+ function load_module_scripts() {
458
+ global $wp_styles;
459
+ $deps = array();
460
+ $xmlhttprequest = ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' );
461
+ foreach ( $this->do_module as $m => $module ) {
462
+ $deps = array_merge( $deps, explode( ',', $module['info']['dependencies'] ) );
463
+ $deps = apply_filters( 'gmedia_module_js_dependencies', $deps, $m );
464
+ $deps = array_filter( array_unique( $deps ) );
465
+ foreach ( $deps as $handle ) {
466
+ if ( wp_script_is( $handle, 'registered' ) ) {
467
+ wp_enqueue_script( $handle, $_src = false, $_deps = array( 'jquery' ), $this->version, $_in_footer = true );
468
+ if ( $xmlhttprequest ) {
469
+ wp_print_scripts( $handle );
470
+ }
471
+ }
472
+ if ( wp_style_is( $handle, 'registered' ) ) {
473
+ //wp_print_styles($handle);
474
+ $this->import_styles[ $handle ] = $wp_styles->registered[ $handle ]->src;
475
+ }
476
+ }
477
+ // $files = glob($module['path'] . '/css/*.css', GLOB_NOSORT);
478
+ // if(!empty($files)){
479
+ // $files = array_map('basename', $files);
480
+ // foreach($files as $file){
481
+ // $this->import_styles[] = "{$module['url']}/css/{$file}";
482
+ // }
483
+ // }
484
+ $files = glob( $module['path'] . '/js/*.js', GLOB_NOSORT );
485
+ if ( ! empty( $files ) ) {
486
+ $files = array_map( 'basename', $files );
487
+ $files_deps = array_merge( array( 'jquery' ), $deps );
488
+ foreach ( $files as $file ) {
489
+ $_ver = isset( $module['info']['version'] ) ? $module['info']['version'] : false;
490
+ $handle = "{$module['name']}_{$file}";
491
+ wp_enqueue_script( $handle, "{$module['url']}/js/{$file}", $files_deps, $_ver, true );
492
+ if ( $xmlhttprequest ) {
493
+ wp_print_scripts( $handle );
494
+ }
495
+ }
496
+ }
497
+ }
498
+ $this->do_module = array();
499
+ if ( ! empty( $this->import_styles ) ) {
500
+ add_action( 'wp_print_head_scripts', array( &$this, 'print_import_styles' ), 1 );
501
+ add_action( 'wp_print_footer_scripts', array( &$this, 'print_import_styles' ), 1 );
502
+ }
503
+ if ( $xmlhttprequest ) {
504
+ $this->print_import_styles();
505
+ }
506
+ }
507
+
508
+ /** Return module styles like <style>@import(...)</style>
509
+ *
510
+ * @param $module
511
+ *
512
+ * @return string
513
+ */
514
+ function load_module_styles( $module ) {
515
+ $module_styles = '';
516
+ $files = glob( $module['path'] . '/css/*.css', GLOB_NOSORT );
517
+ if ( ! empty( $files ) ) {
518
+ $_ver = isset( $module['info']['version'] ) ? $module['info']['version'] : false;
519
+ $files = array_map( 'basename', $files );
520
+ foreach ( $files as $file ) {
521
+ $src = "{$module['url']}/css/{$file}";
522
+ if ( 'http' !== substr( $src, 0, 4 ) ) {
523
+ $src = site_url( $src );
524
+ }
525
+ $src = add_query_arg( array( 'v' => $_ver ), $src );
526
+ $module_styles .= "@import url('{$src}') all;";
527
+ }
528
+ }
529
+
530
+ return $module_styles;
531
+ }
532
+
533
+ function print_import_styles() {
534
+ if ( ! empty( $this->import_styles ) ) {
535
+ echo "\n<style type='text/css' class='gmedia_assets_style_import'>";
536
+ foreach ( $this->import_styles as $src ) {
537
+ if ( 'http' !== substr( $src, 0, 4 ) ) {
538
+ $src = site_url( $src );
539
+ }
540
+ echo "\n@import url('{$src}') all;";
541
+ }
542
+ echo "\n</style>\n";
543
+ $this->import_styles = array();
544
+ }
545
+ }
546
+
547
+ /**
548
+ * Call user function to all blogs in network
549
+ * called during register_activation hook
550
+ *
551
+ * @param $pfunction string UserFunction name
552
+ * @param $networkwide bool Check if plugin has been activated for the entire blog network.
553
+ *
554
+ * @return void
555
+ */
556
+ static function network_propagate( $pfunction, $networkwide ) {
557
+
558
+ include_once( dirname( __FILE__ ) . '/config/setup.php' );
559
+
560
+ if ( function_exists( 'is_multisite' ) && is_multisite() ) {
561
+ // check if it is a network activation - if so, run the activation function
562
+ // for each blog id
563
+ if ( $networkwide ) {
564
+ global $wpdb;
565
+ //$old_blog = $wpdb->blogid;
566
+ // Get all blog ids
567
+ $blogids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
568
+ foreach ( $blogids as $blog_id ) {
569
+ switch_to_blog( $blog_id );
570
+ call_user_func( $pfunction );
571
+ }
572
+ //switch_to_blog($old_blog);
573
+ restore_current_blog();
574
+
575
+ return;
576
+ }
577
+ }
578
+ call_user_func( $pfunction );
579
+ }
580
+
581
+ /**
582
+ * @param $networkwide
583
+ */
584
+ function activate( $networkwide ) {
585
+ $this->network_propagate( 'gmedia_install', $networkwide );
586
+ }
587
+
588
+ /**
589
+ * @param $networkwide
590
+ */
591
+ function deactivate( $networkwide ) {
592
+ $this->network_propagate( 'gmedia_deactivate', $networkwide );
593
+ }
594
+
595
+ /*
596
+ static function uninstall($networkwide) {
597
+ //wp_die( '<h1>This is run on <code>init</code> during uninstallation</h1>', 'Uninstallation hook example' );
598
+ Gmedia::network_propagate('gmedia_uninstall', $networkwide);
599
+ }
600
+ */
601
+
602
+ /**
603
+ * @param $blog_id
604
+ * @param $user_id
605
+ * @param $domain
606
+ * @param $path
607
+ * @param $site_id
608
+ * @param $meta
609
+ */
610
+ function new_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
611
+ if ( is_plugin_active_for_network( GMEDIA_FOLDER . '/grand-media.php' ) ) {
612
+ include_once( dirname( __FILE__ ) . '/config/setup.php' );
613
+ switch_to_blog( $blog_id );
614
+ gmedia_install();
615
+ restore_current_blog();
616
+ }
617
+ }
618
+
619
+ /**
620
+ * @param $user_id
621
+ * @param $reassign
622
+ */
623
+ function reassign_media( $user_id, $reassign ) {
624
+ global $gmDB;
625
+ $gmDB->reassign_media( $user_id, $reassign );
626
+ }
627
+
628
+ /**
629
+ * Register Gmedia Post Types
630
+ */
631
+ function gmedia_post_type() {
632
+ $args = array(
633
+ 'label' => __( 'Gmedia Posts', 'grand-media' ),
634
+ 'supports' => array( 'comments' ),
635
+ 'hierarchical' => false,
636
+ 'public' => true,
637
+ 'show_ui' => false,
638
+ 'show_in_menu' => false,
639
+ 'show_in_admin_bar' => false,
640
+ 'show_in_nav_menus' => false,
641
+ 'can_export' => false,
642
+ 'has_archive' => (bool) ( (int) $this->options['gmedia_has_archive'] ), //'gmedia-library',
643
+ 'publicly_queryable' => true,
644
+ 'exclude_from_search' => (bool) ( (int) $this->options['gmedia_exclude_from_search'] ),
645
+ 'rewrite' => array( 'slug' => $this->options['gmedia_post_slug'] ),
646
+ 'map_meta_cap' => true,
647
+ 'capabilities' => array(
648
+ 'read_private_posts' => 'read_private_gmedia_posts',
649
+ // 'edit_comment' => 'edit_gmedia_comment',
650
+ // 'moderate_comments' => 'moderate_gmedia_comments',
651
+ // 'edit_post' => 'edit_gmedia_post',
652
+ // 'edit_posts' => 'edit_gmedia_posts',
653
+ 'create_posts' => false,
654
+ ),
655
+ );
656
+ register_post_type( 'gmedia', $args );
657
+
658
+ $args['label'] = __( 'Gmedia Albums', 'grand-media' );
659
+ $args['show_in_nav_menus'] = true;
660
+ $args['hierarchical'] = true;
661
+ $args['has_archive'] = (bool) ( (int) $this->options['gmedia_album_has_archive'] );
662
+ $args['exclude_from_search'] = (bool) ( (int) $this->options['gmedia_album_exclude_from_search'] );
663
+ $args['rewrite'] = array( 'slug' => $this->options['gmedia_album_post_slug'] );
664
+ register_post_type( 'gmedia_album', $args );
665
+
666
+ $args['label'] = __( 'Gmedia Galleries', 'grand-media' );
667
+ $args['has_archive'] = (bool) ( (int) $this->options['gmedia_gallery_has_archive'] );
668
+ $args['exclude_from_search'] = (bool) ( (int) $this->options['gmedia_gallery_exclude_from_search'] );
669
+ $args['rewrite'] = array( 'slug' => $this->options['gmedia_gallery_post_slug'] );
670
+ register_post_type( 'gmedia_gallery', $args );
671
+
672
+ add_filter( 'get_gmedia_metadata', array( $this, 'get_gmedia_metadata' ), 10, 4 );
673
+ add_filter( 'get_gmedia_term_metadata', array( $this, 'get_gmedia_term_metadata' ), 10, 4 );
674
+ add_filter( 'get_edit_post_link', array( $this, 'gmedia_post_type_edit_link' ), 10, 3 );
675
+
676
+
677
+ $args = array(
678
+ 'hierarchical' => false,
679
+ 'public' => true,
680
+ 'show_ui' => false,
681
+ 'show_admin_column' => false,
682
+ 'show_in_nav_menus' => false,
683
+ 'show_tagcloud' => false,
684
+ 'rewrite' => array( 'slug' => 'gmedia-category' ),
685
+ );
686
+ $args['labels'] = array(
687
+ 'name' => _x( 'Gmedia Categories', 'Taxonomy General Name', 'grand-media' ),
688
+ 'singular_name' => _x( 'Gmedia Category', 'Taxonomy Singular Name', 'grand-media' ),
689
+ 'menu_name' => __( 'Gmedia Categories', 'grand-media' ),
690
+ );
691
+ register_taxonomy( 'gmedia_category', null, $args );
692
+
693
+ $args['rewrite'] = array( 'slug' => 'gmedia-tag' );
694
+ $args['labels'] = array(
695
+ 'name' => _x( 'Gmedia Tags', 'Taxonomy General Name', 'grand-media' ),
696
+ 'singular_name' => _x( 'Gmedia Tag', 'Taxonomy Singular Name', 'grand-media' ),
697
+ 'menu_name' => __( 'Gmedia Tags', 'grand-media' ),
698
+ );
699
+ register_taxonomy( 'gmedia_tag', null, $args );
700
+
701
+ add_filter( 'wp_link_query_args', array( $this, 'exclude_gmedia_from_link_query' ) );
702
+
703
+ if ( ! empty( $this->options['flush_rewrite_rules'] ) ) {
704
+ unset( $this->options['flush_rewrite_rules'] );
705
+ update_option( 'gmediaOptions', $this->options );
706
+ flush_rewrite_rules( false );
707
+ }
708
+ }
709
+
710
+ /**
711
+ * Get gmedia metadata
712
+ *
713
+ * @param $meta
714
+ * @param $post_ID
715
+ * @param $meta_key
716
+ * @param $single
717
+ *
718
+ * @return array|string
719
+ */
720
+ function get_gmedia_metadata( $meta, $post_ID, $meta_key, $single ) {
721
+ global $gmDB;
722
+ $gmedia_id = get_post_meta( $post_ID, '_gmedia_ID', true );
723
+ $meta = $gmDB->get_metadata( 'gmedia', $gmedia_id, $meta_key, $single );
724
+
725
+ return $meta;
726
+ }
727
+
728
+ /**
729
+ * Get gmedia term metadata
730
+ *
731
+ * @param $meta
732
+ * @param $post_ID
733
+ * @param $meta_key
734
+ * @param $single
735
+ *
736
+ * @return array|string
737
+ */
738
+ function get_gmedia_term_metadata( $meta, $post_ID, $meta_key, $single ) {
739
+ global $gmDB;
740
+ $gmedia_term_id = get_post_meta( $post_ID, '_gmedia_term_ID', true );
741
+ $meta = $gmDB->get_metadata( 'gmedia_term', $gmedia_term_id, $meta_key, $single );
742
+
743
+ return $meta;
744
+ }
745
+
746
+ /**
747
+ * Edit link for gmedia
748
+ *
749
+ * @param $link
750
+ * @param $post_ID
751
+ * @param $context
752
+ *
753
+ * @return string|void
754
+ */
755
+ function gmedia_post_type_edit_link( $link, $post_ID, $context ) {
756
+ $post = get_post( $post_ID );
757
+ if ( isset( $post->ID ) && 'gmedia' == substr( $post->post_type, 0, 6 ) ) {
758
+ global $gmDB;
759
+ if ( $post->post_type == 'gmedia' ) {
760
+ $gmedia_id = get_post_meta( $post->ID, '_gmedia_ID', true );
761
+ $gmedia = $gmDB->get_gmedia( $gmedia_id );
762
+ if ( $gmedia ) {
763
+ $link = admin_url( "admin.php?page=GrandMedia&mode=edit&gmedia__in={$gmedia->ID}" );
764
+ } else {
765
+ wp_delete_post( $post->ID, true );
766
+ $link = '#';
767
+ }
768
+ } else {
769
+ $term_id = get_post_meta( $post->ID, '_gmedia_term_ID', true );
770
+ $term = $gmDB->get_term( $term_id );
771
+ if ( $term ) {
772
+ if ( $term->taxonomy == 'gmedia_album' ) {
773
+ $link = admin_url( "admin.php?page=GrandMedia_Albums&edit_term={$term->term_id}" );
774
+ } elseif ( $term->taxonomy == 'gmedia_gallery' ) {
775
+ $link = admin_url( "admin.php?page=GrandMedia_Galleries&edit_term={$term->term_id}" );
776
+ }
777
+ } else {
778
+ wp_delete_post( $post->ID, true );
779
+ $link = '#';
780
+ }
781
+ }
782
+ }
783
+
784
+ return $link;
785
+ }
786
+
787
+ function register_gmedia_widget() {
788
+ require_once( dirname( __FILE__ ) . '/inc/widget.php' );
789
+ register_widget( 'GrandMedia_Gallery_Widget' );
790
+ register_widget( 'GrandMedia_Album_Widget' );
791
+ }
792
+
793
+ /**
794
+ * @param $query
795
+ *
796
+ * @return mixed
797
+ */
798
+ function exclude_gmedia_from_link_query( $query ) {
799
+ if ( ( $key = array_search( 'gmedia', $query['post_type'] ) ) !== false ) {
800
+ unset( $query['post_type'][ $key ] );
801
+ }
802
+
803
+ return $query;
804
+ }
805
+
806
+ /**
807
+ * @param $shedules
808
+ *
809
+ * @return array
810
+ */
811
+ function gmedia_cron_schedules( $shedules ) {
812
+ $gmedia_shedules = array( 'gmedia_app' => array( 'interval' => 5 * DAY_IN_SECONDS, 'display' => __( 'Gmedia App Defined' ) ) );
813
+ $shedules = array_merge( $shedules, $gmedia_shedules );
814
+
815
+ return $shedules;
816
+ }
817
+
818
+ function gmedia_app_cronjob() {
819
+ global $gmCore;
820
+ $gmCore->app_service( 'app_updatecron' );
821
+ }
822
+
823
+ function gmedia_modules_update() {
824
+ global $gmCore;
825
+ $gmCore->modules_update();
826
+ }
827
+
828
+
829
+ /*
830
+ // PLUGIN MESSAGE ON PLUGINS PAGE
831
+ function check_message_version($file)
832
+ {
833
+ static $this_plugin;
834
+ global $wp_version;
835
+ if (!$this_plugin) $this_plugin = GMEDIA_FOLDER;
836
+
837
+ if ($file == $this_plugin ){
838
+ $checkfile = "http://codeasily.com/grand-flam.chk";
839
+
840
+ $message = wp_remote_fopen($checkfile);
841
+
842
+ if($message)
843
+ {
844
+ preg_match( '|grand'.str_replace('.','',GMEDIA_VERSION).':(.*)$|mi', $message, $theMessage );
845
+ $columns = 5;
846
+ if ( !empty( $theMessage ) )
847
+ {
848
+ $theMessage = trim($theMessage[1]);
849
+ echo '<td colspan="'.$columns.'" class="plugin-update" style="line-height:1.2em; font-size:11px; padding:1px;"><div id="flag-update-msg" style="padding-bottom:1px;" >'.$theMessage.'</div></td>';
850
+ } else {
851
+ return;
852
+ }
853
+ }
854
+ }
855
+ }
856
+ */
857
+
858
+ function add_plugin_links( $links, $file ) {
859
+ if ( $file == plugin_basename( __FILE__ ) ) {
860
+ $links[] = '<a href="admin.php?page=GrandMedia_Settings">' . __( 'Settings', 'grand-media' ) . '</a>';
861
+ $links[] = '<a href="admin.php?page=GrandMedia_Modules">' . __( 'Modules', 'grand-media' ) . '</a>';
862
+ $links[] = '<a href="https://codeasily.com/product/one-site-license/">' . __( 'Get Premium', 'grand-media' ) . '</a>';
863
+ $links[] = '<a href="https://codeasily.com/donate/">' . __( 'Donate', 'grand-media' ) . '</a>';
864
+ }
865
+
866
+ return $links;
867
+ }
868
+
869
+ function add_plugin_feedback() {
870
+ global $pagenow;
871
+ if ( 'plugins.php' !== $pagenow ) {
872
+ return;
873
+ }
874
+ ?>
875
+ <script type="text/javascript">
876
+ jQuery(function($) {
877
+ function gm_parse_query(s) {
878
+ var j = {}, res = s.split(/&/gm).map(function(e) {
879
+ var o = e.split(/=/), pt = j;
880
+ if(typeof o[1] == 'undefined') {
881
+ o[1] = '';
882
+ }
883
+ o[0].replace(/^(\w+)\[([^&]*)\]/, '$1][$2').split(/\]\[/).map(function(e, i, a) {
884
+ if(e === '') {
885
+ e = Object.keys(pt).length;
886
+ }
887
+ pt = (pt[e] = pt[e] || (i == a.length - 1 ? decodeURIComponent(o[1].replace(/\+/, ' ')) : {}));
888
+ });
889
+ });
890
+ return j;
891
+ }
892
+
893
+ $('tr[data-slug="grand-media"] .deactivate a').on('click', function(e) {
894
+ e.preventDefault();
895
+ e.stopPropagation();
896
+
897
+ $('body').append($('#tmpl-gmedia-feedback').html());
898
+ var deactivate_link = $(this).attr('href');
899
+ $('.gm-button-submit-deactivate, .gm-button-skip-deactivate').attr('href', deactivate_link);
900
+ $('#gmedia-feedback [name="reason"]').on('change', function() {
901
+ var parent = $(this).closest('.reason');
902
+ parent.siblings('.has-input').find('.reason-input').hide().find('input').prop('disabled', true);
903
+ if(parent.hasClass('has-input')) {
904
+ if($(this).is(':checked')) {
905
+ $('.reason-input', parent).show().find('input').prop('disabled', false);
906
+ }
907
+ }
908
+ });
909
+ $('#gmedia-feedback .gm-button-submit-deactivate').on('click', function(e) {
910
+ e.preventDefault();
911
+
912
+ var feedback = $('#gmedia-feedback input').serialize();
913
+ feedback = gm_parse_query(feedback);
914
+
915
+ if(feedback.reason === '') {
916
+ window.location = deactivate_link;
917
+ return;
918
+ }
919
+
920
+ $('#gmedia-feedback .spinner').addClass('is-active');
921
+ var post_data = {
922
+ action: 'gmedia_feedback',
923
+ data: feedback,
924
+ _wpnonce_gmedia_feedback: '<?php echo wp_create_nonce( 'gmedia_feedback' ); ?>'
925
+ };
926
+ $.post(ajaxurl, post_data).always(function(data) {
927
+ $('#gmedia-feedback .spinner').removeClass('is-active');
928
+ window.location = deactivate_link;
929
+ });
930
+ return false;
931
+ });
932
+ $('#gmedia-feedback .gm-button-close').on('click', function() {
933
+ $('#gmedia-feedback').remove();
934
+ return false;
935
+ });
936
+
937
+ return false;
938
+ });
939
+ });
940
+ </script>
941
+ <script id="tmpl-gmedia-feedback" type="text/template">
942
+ <div class="gm-modal gm-modal-deactivation-feedback" id="gmedia-feedback">
943
+ <style>
944
+ .gm-modal { position: fixed; overflow: auto; height: 100%; width: 100%; top: 0; z-index: 100000; background: rgba(0, 0, 0, 0.6); }
945
+
946
+ .gm-modal-dialog { position: absolute; left: 50%; padding-bottom: 30px; top: 10%; z-index: 100001; max-width: 600px; min-width: 220px; transform: translateX(-50%); }
947
+
948
+ .gm-modal-header { border-bottom: #eeeeee solid 1px; background: #fbfbfb; padding: 15px 20px; position: relative; margin-bottom: -10px; }
949
+
950
+ .gm-modal-header h4 { margin: 0; padding: 0; text-transform: uppercase; font-size: 1.2em; font-weight: bold; color: #cacaca; text-shadow: 1px 1px 1px #fff; letter-spacing: 0.6px; -webkit-font-smoothing: antialiased; }
951
+
952
+ .gm-modal-body,
953
+ .gm-modal-footer { border: 0; background: #fefefe; padding: 20px; }
954
+
955
+ .gm-modal-footer { border-top: #eeeeee solid 1px; text-align: right; }
956
+
957
+ .gm-modal-body h3 { margin-top: 0; line-height: 1.5em; }
958
+
959
+ .gm-modal-body .reason { margin: 7px 0; }
960
+
961
+ .gm-modal-body .reason-input { margin: 3px 0 3px 22px; display: none; }
962
+
963
+ .gm-modal-body .reason-input input { width: 100%; }
964
+
965
+ .gm-modal-footer a.button { margin-right: 7px; }
966
+ </style>
967
+ <div class="gm-modal-dialog">
968
+ <div class="gm-modal-header"><h4><?php _e( 'Quick feedback', 'grand-media' ); ?></h4></div>
969
+ <div class="gm-modal-body">
970
+ <h3><strong><?php _e( 'If you have a moment, please let us know why you are deactivating:', 'grand-media' ); ?></strong></h3>
971
+ <div id="reasons-list">
972
+ <div class="reason">
973
+ <label><input type="radio" name="reason" value="" checked/> <span><?php _e( 'It\'s a temporary deactivation. I\'m just debugging an issue.', 'grand-media' ); ?></span></label>
974
+ </div>
975
+ <div class="reason">
976
+ <label><input type="radio" name="reason" value="I no longer need the gallery plugin"/> <span><?php _e( 'I no longer need the gallery plugin', 'grand-media' ); ?></span></label>
977
+ </div>
978
+ <div class="reason has-input">
979
+ <label><input type="radio" name="reason" value="I found a better gallery plugin"/> <span><?php _e( 'I found a better gallery plugin', 'grand-media' ); ?></span></label>
980
+ <div class="reason-input"><input type="text" name="better_plugin" disabled placeholder="<?php _e( 'What\'s the plugin\'s name?', 'grand-media' ); ?>"/></div>
981
+ </div>
982
+ <div class="reason">
983
+ <label><input type="radio" name="reason" value="The plugin is too coomplicated for me"/> <span><?php _e( 'The plugin is too coomplicated for me', 'grand-media' ); ?></span></label>
984
+ </div>
985
+ <div class="reason">
986
+ <label><input type="radio" name="reason" value="The plugin broke my life"/> <span><?php _e( 'The plugin broke my life', 'grand-media' ); ?></span></label>
987
+ </div>
988
+ <div class="reason has-input">
989
+ <label><input type="radio" name="reason" value="Other"/> <span><?php _e( 'Other', 'grand-media' ); ?></span></label>
990
+ <div class="reason-input"><input type="text" name="other_reason" value="" disabled/></div>
991
+ </div>
992
+ </div>
993
+ </div>
994
+ <div class="gm-modal-footer">
995
+ <span class="spinner" style="float: none;"></span>
996
+ <a href="#" class="button button-secondary gm-button-submit-deactivate"><?php _e( 'Submit & Deactivate', 'grand-media' ); ?></a>
997
+ <a href="#" class="button button-secondary gm-button-skip-deactivate"><?php _e( 'Skip', 'grand-media' ); ?></a>
998
+ <a href="#" class="button button-primary gm-button-close"><?php _e( 'Cancel', 'grand-media' ); ?></a>
999
+ </div>
1000
+ </div>
1001
+ </div>
1002
+ </script>
1003
+ <?php
1004
+ }
1005
+
1006
+ }
1007
+
1008
+ // Let's start the holy plugin
1009
+ global $gmGallery;
1010
+ $gmGallery = new Gmedia();
1011
+
1012
+ }
inc/core.php CHANGED
@@ -1,6 +1,6 @@
1
  <?php
2
- if(preg_match('#' . basename(dirname(__FILE__)) . '/' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])){
3
- die('You are not allowed to call this page directly.');
4
  }
5
 
6
  /**
@@ -8,23 +8,23 @@ if(preg_match('#' . basename(dirname(__FILE__)) . '/' . basename(__FILE__) . '#'
8
  */
9
  class GmediaCore {
10
 
11
- var $upload;
12
- var $gmedia_url;
13
- var $caps = array();
14
 
15
 
16
- /**
17
- *
18
- */
19
- function __construct(){
20
 
21
- $this->upload = $this->gm_upload_dir();
22
- $this->gmedia_url = plugins_url(GMEDIA_FOLDER);
23
 
24
- add_action('init', array(&$this, 'user_capabilities'), 8);
25
- add_action('init', array(&$this, 'init_actions'), 20);
26
 
27
- add_action('clean_gmedia_cache', array(&$this, 'clear_cache'));
28
  // add_action( 'deleted_gmedia_term_relationships', array( &$this, 'clear_cache' ) );
29
  // add_action( 'added_gmedia_meta', array( &$this, 'clear_cache' ) );
30
  // add_action( 'added_gmedia_term_meta', array( &$this, 'clear_cache' ) );
@@ -32,2218 +32,1952 @@ class GmediaCore {
32
  // add_action( 'updated_gmedia_term_meta', array( &$this, 'clear_cache' ) );
33
  // add_action( 'deleted_gmedia_meta', array( &$this, 'clear_cache' ) );
34
  // add_action( 'deleted_gmedia_term_meta', array( &$this, 'clear_cache' ) );
35
- // add_action('created_gmedia_term', array(&$this, 'clear_cache'));
36
- add_action('edited_gmedia_term', array(&$this, 'clear_cache'));
37
- add_action('deleted_gmedia_term', array(&$this, 'clear_cache'));
38
  // add_action( 'gmedia_clean_object_term_cache', array( &$this, 'clear_cache' ) );
39
 
40
- add_filter('get_the_gmedia_terms', array(&$this, 'get_the_gmedia_terms'), 10, 3);
41
- }
42
-
43
- function user_capabilities(){
44
- $capabilities = $this->plugin_capabilities();
45
- $capabilities = apply_filters('gmedia_capabilities', $capabilities);
46
- if(is_multisite() && is_super_admin()){
47
- foreach($capabilities as $cap){
48
- $this->caps[ $cap ] = 1;
49
- }
50
- } else{
51
- $curuser = wp_get_current_user();
52
- foreach($capabilities as $cap){
53
- if(isset($curuser->allcaps[ $cap ]) && intval($curuser->allcaps[ $cap ])){
54
- $this->caps[ $cap ] = 1;
55
- } else{
56
- $this->caps[ $cap ] = 0;
57
- }
58
- }
59
- }
60
- }
61
-
62
- function init_actions(){
63
- global $gmGallery;
64
- if( !empty($gmGallery->options['license_key']) && empty($gmGallery->options['disable_logs'])){
65
- add_action('gmedia_view', array(&$this, 'log_views_handler'));
66
- add_action('gmedia_like', array(&$this, 'log_likes_handler'));
67
- add_action('gmedia_rate', array(&$this, 'log_rates_handler'), 10, 2);
68
- }
69
- }
70
-
71
- /**
72
- * Check GET data
73
- *
74
- * @param string $var
75
- * @param mixed $def
76
- * @param bool $empty2false
77
- *
78
- * @return mixed
79
- */
80
- function _get($var, $def = false, $empty2false = false){
81
- return isset($_GET[ $var ])? (($empty2false && $this->is_empty($_GET[ $var ]))? false : $_GET[ $var ]) : $def;
82
- }
83
-
84
- /**
85
- * Check empty strings
86
- *
87
- * @param string $var
88
- *
89
- * @return bool
90
- */
91
- function is_empty($var){
92
- return !( !empty($var) && !in_array(strtolower($var), array('null', 'false')));
93
- }
94
-
95
- /**
96
- * Check POST data
97
- *
98
- * @param string $var
99
- * @param bool|mixed $def
100
- *
101
- * @return mixed
102
- */
103
-
104
- function _post($var, $def = false){
105
- return isset($_POST[ $var ])? $_POST[ $var ] : $def;
106
- }
107
-
108
- /**
109
- * Check REQUEST data
110
- *
111
- * @param string $var
112
- * @param mixed $def
113
- *
114
- * @return mixed
115
- */
116
- function _req($var, $def = false){
117
- return isset($_REQUEST[ $var ])? $_REQUEST[ $var ] : $def;
118
- }
119
-
120
- /**
121
- * tooltip()
122
- *
123
- * @param string $style 'tooltip', 'popover'
124
- * @param array $params
125
- * @param bool $print
126
- *
127
- * @return string
128
- */
129
- function tooltip($style, $params, $print = true){
130
- $show_tip = 0; // TODO show tooltips checkbox in settings
131
- if($show_tip){
132
- $tooltip = " data-toggle='$style'";
133
- if(is_array($params) && !empty($params)){
134
- foreach($params as $key => $val){
135
- $tooltip .= " data-$key='$val'";
136
- }
137
- }
138
- if($print){
139
- echo $tooltip;
140
- } else{
141
- return $tooltip;
142
- }
143
- }
144
-
145
- return false;
146
- }
147
-
148
- /**
149
- * @param array $add_args
150
- * @param array $remove_args
151
- * @param bool $uri
152
- * @param array $preserve_args
153
- *
154
- * @return string
155
- */
156
- function get_admin_url($add_args = array(), $remove_args = array(), $uri = false, $preserve_args = array()){
157
- if(true === $uri){
158
- $uri = admin_url('admin.php');
159
- }
160
- $remove_args = empty($remove_args)? array() : (array) $remove_args;
161
- $_wpnonce = array();
162
- foreach($_GET as $key => $value){
163
- if(strpos($key, '_wpnonce') !== false){
164
- $_wpnonce[ $key ] = $value;
165
- }
166
- }
167
- $remove_args = array_unique(array_merge(array('doing_wp_cron', '_wpnonce', 'do_gmedia', 'did_gmedia', 'do_gmedia_terms', 'did_gmedia_terms', 'ids'), $_wpnonce, $remove_args, array_keys($add_args)));
168
- $new_uri = remove_query_arg($remove_args, $uri);
169
- if( !empty($preserve_args)){
170
- $_add_args = array();
171
- foreach($preserve_args as $key){
172
- if(($value = $this->_get($key)) !== false){
173
- $_add_args[ $key ] = $value;
174
- }
175
- }
176
- $new_uri = add_query_arg($_add_args, $new_uri);
177
- }
178
- if( !empty($add_args)){
179
- $new_uri = add_query_arg($add_args, $new_uri);
180
- }
181
-
182
- return esc_url_raw($new_uri);
183
- }
184
-
185
- /**
186
- * @param $userAgent
187
- *
188
- * @return bool
189
- */
190
- function is_crawler($userAgent){
191
- $crawlers = 'Google|msnbot|Rambler|Yahoo|AbachoBOT|accoona|FeedBurner|' . 'AcioRobot|ASPSeek|CocoCrawler|Dumbot|FAST-WebCrawler|' . 'GeonaBot|Gigabot|Lycos|MSRBOT|Scooter|AltaVista|IDBot|eStyle|Scrubby|yandex|facebook';
192
- $isCrawler = (preg_match("/$crawlers/i", $userAgent) > 0);
193
-
194
- return $isCrawler;
195
- }
196
-
197
- /**
198
- * @param $userAgent
199
- *
200
- * @return bool
201
- */
202
- function is_browser($userAgent){
203
- $browsers = 'opera|aol|msie|firefox|chrome|konqueror|safari|netscape|navigator|mosaic|lynx|amaya|omniweb|avant|camino|flock|seamonkey|mozilla|gecko';
204
- $isBrowser = (preg_match("/$browsers/i", $userAgent) > 0);
205
-
206
- return $isBrowser;
207
- }
208
-
209
- /**
210
- * Get an array containing the gmedia upload directory's path and url.
211
- * If the path couldn't be created, then an error will be returned with the key
212
- * 'error' containing the error message. The error suggests that the parent
213
- * directory is not writable by the server.
214
- * On success, the returned array will have many indices:
215
- * 'path' - base directory and sub directory or full path to upload directory.
216
- * 'url' - base url and sub directory or absolute URL to upload directory.
217
- * 'error' - set to false.
218
- * @see wp_upload_dir()
219
- * @uses apply_filters() Calls 'gm_upload_dir' on returned array.
220
- *
221
- * @param bool $create
222
- *
223
- * @return array See above for description.
224
- */
225
- function gm_upload_dir($create = true){
226
- $slash = '/';
227
- // If multisite (and if not the main site)
228
- if(is_multisite() && !is_main_site()){
229
- $slash = '/blogs.dir/' . get_current_blog_id() . '/';
230
- }
231
-
232
- $dir = WP_CONTENT_DIR . $slash . GMEDIA_UPLOAD_FOLDER;
233
- $url = WP_CONTENT_URL . $slash . GMEDIA_UPLOAD_FOLDER;
234
-
235
- $url = set_url_scheme($url);
236
-
237
- $uploads = apply_filters('gm_upload_dir', array('path' => $dir, 'url' => $url, 'error' => false));
238
-
239
- if($create){
240
- // Make sure we have an uploads dir
241
- if( !wp_mkdir_p($uploads['path'])){
242
- $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $uploads['path']);
243
- $uploads['error'] = $message;
244
- }
245
- } elseif( !is_dir($uploads['path'])){
246
- $uploads['error'] = true;
247
- }
248
-
249
- return $uploads;
250
- }
251
-
252
- /**
253
- * @param $path
254
- *
255
- * @return bool|null
256
- */
257
- function delete_folder($path){
258
- $path = rtrim($path, '/');
259
- if(is_file($path)){
260
- return @unlink($path);
261
- } elseif(is_dir($path)){
262
- $files = glob($path . '/*', GLOB_NOSORT);
263
- if( !empty($files) && is_array($files)){
264
- array_map(array($this, 'delete_folder'), $files);
265
- }
266
-
267
- return @rmdir($path);
268
- }
269
-
270
- return null;
271
- }
272
-
273
- /**
274
- * Get an HTML img element representing an image attachment
275
- * @see add_image_size()
276
- * @see wp_get_attachment_image()
277
- * @uses apply_filters() Calls 'gm_get_attachment_image_attributes' hook on attributes array
278
- *
279
- * @param int|object $item Image object.
280
- * @param string $size Optional, default is empty string, could be 'thumb', 'web', 'original'
281
- * @param bool $cover Optional, try to get cover url
282
- * @param bool|string $default Optional, return if no cover and if $size != 'all'
283
- *
284
- * @return string|array img url for chosen size
285
- */
286
- function gm_get_media_image($item, $size = '', $cover = true, $default = false){
287
- global $gmDB, $gmGallery;
288
-
289
- if( !is_object($item)){
290
- $item = $gmDB->get_gmedia($item);
291
- }
292
- if( !$size){
293
- $size = 'web';
294
- }
295
- if(empty($item)){
296
- $image = $default? $default : $this->gmedia_url . '/admin/assets/img/default.png';
297
- $images = apply_filters('gm_get_media_image', array(
298
- 'thumb' => $image,
299
- 'web' => $image,
300
- 'original' => $image
301
- ));
302
- if('all' == $size){
303
- return $images;
304
- } else{
305
- return $images[ $size ];
306
- }
307
- }
308
- $type = explode('/', $item->mime_type);
309
- $img_cover = false;
310
- if('image' == $type[0]){
311
- $images = array(
312
- 'thumb' => "{$this->upload['url']}/{$gmGallery->options['folder']['image_thumb']}/{$item->gmuid}",
313
- 'web' => "{$this->upload['url']}/{$gmGallery->options['folder']['image']}/{$item->gmuid}",
314
- 'original' => "{$this->upload['url']}/{$gmGallery->options['folder']['image_original']}/{$item->gmuid}"
315
- );
316
- if('original' !== $size){
317
- $thumb_path = "{$this->upload['path']}/{$gmGallery->options['folder']['image_thumb']}/{$item->gmuid}";
318
- if( !is_file($thumb_path)){
319
- $img_cover = true;
320
- }
321
- }
322
- if('all' == $size || 'original' == $size){
323
- $original_path = "{$this->upload['path']}/{$gmGallery->options['folder']['image_original']}/{$item->gmuid}";
324
- if( !is_file($original_path)){
325
- $images['original'] = $images['web'];
326
- }
327
- }
328
- }
329
- if('image' != $type[0] || $img_cover){
330
- $ext = ltrim(strrchr($item->gmuid, '.'), '.');
331
- if( !$type = wp_ext2type($ext)){
332
- $type = 'application';
333
- }
334
- $image = "{$this->gmedia_url}/admin/assets/img/{$type}.png";
335
- $images = array(
336
- 'thumb' => $image,
337
- 'web' => $image,
338
- 'original' => $image,
339
- 'icon' => false
340
- );
341
-
342
- if($cover){
343
- $cover = $gmDB->get_metadata('gmedia', $item->ID, '_cover', true);
344
- if( !empty($cover)){
345
- if($this->is_digit($cover)){
346
- $images = $this->gm_get_media_image((int) $cover, 'all', false);
347
- $images['icon'] = $image;
348
- }
349
- } elseif($default !== false){
350
- return $default;
351
- } else{
352
- $alb = $gmDB->get_gmedia_terms(array($item->ID), array('gmedia_album'), array('fields' => 'ids'));
353
- if( !empty($alb)){
354
- $cover = $gmDB->get_metadata('gmedia_term', $alb[0], '_cover', true);
355
- if( !empty($cover)){
356
- if($this->is_digit($cover)){
357
- $images = $this->gm_get_media_image((int) $cover, 'all', false);
358
- $images['icon'] = $image;
359
- }
360
- }
361
- }
362
- }
363
- }
364
- }
365
-
366
- if('all' == $size){
367
- return $images;
368
- } else{
369
- return $images[ $size ];
370
- }
371
- }
372
-
373
- /**
374
- * Get path and url to module folder
375
- *
376
- * @param string $module_name
377
- *
378
- * @return array|bool Return array( 'path', 'url' ) OR false if no module
379
- */
380
- function get_module_path($module_name){
381
- global $gmGallery;
382
- if(empty($module_name)){
383
- return false;
384
- }
385
- $module_dirs = array(
386
- 'upload' => array(
387
- 'name' => $module_name,
388
- 'path' => $this->upload['path'] . '/' . $gmGallery->options['folder']['module'] . '/' . $module_name,
389
- 'url' => $this->upload['url'] . '/' . $gmGallery->options['folder']['module'] . '/' . $module_name
390
- ),
391
- 'plugin' => array(
392
- 'name' => $module_name,
393
- 'path' => GMEDIA_ABSPATH . 'module/' . $module_name,
394
- 'url' => plugins_url(GMEDIA_FOLDER) . '/module/' . $module_name
395
- ),
396
- 'theme' => array(
397
- 'name' => $module_name,
398
- 'path' => get_template_directory() . '/gmedia-module/' . $module_name,
399
- 'url' => get_template_directory_uri() . '/gmedia-module/' . $module_name
400
- )
401
- );
402
- foreach($module_dirs as $dir){
403
- if(is_dir($dir['path'])){
404
- return $dir;
405
- }
406
- }
407
-
408
- $getModulePreset = $this->getModulePreset();
409
-
410
- if($module_name != $getModulePreset['module']){
411
- return $this->get_module_path($getModulePreset['module']);
412
- }
413
-
414
- return false;
415
- }
416
-
417
- /** Automatic choose upload directory based on media type
418
- *
419
- * @param string $file
420
- * @param int $exists
421
- *
422
- * @return array|bool
423
- */
424
- function fileinfo($file, $exists = 0){
425
- global $gmGallery, $user_ID;
426
-
427
- $file = basename($file);
428
- $file_lower = strtolower($file);
429
- $filetype = wp_check_filetype($file_lower, $mimes = null);
430
- $title = pathinfo($file, PATHINFO_FILENAME);
431
- $pathinfo = pathinfo(preg_replace('/[^a-z0-9_\.-]+/i', '_', $file));
432
- $pathinfo['extension'] = strtolower($pathinfo['extension']);
433
- $suffix = ((false !== $exists) && absint($exists))? "_$exists" : '';
434
-
435
- $fileinfo['extension'] = (empty($filetype['ext']))? $pathinfo['extension'] : $filetype['ext'];
436
-
437
- $allowed_ext = get_allowed_mime_types($user_ID);
438
- $allowed_ext = array_keys($allowed_ext);
439
- $allowed_ext = implode('|', $allowed_ext);
440
- $allowed_ext = explode('|', $allowed_ext);
441
- if( !in_array($fileinfo['extension'], $allowed_ext)){
442
- return false;
443
- }
444
-
445
- $fileinfo['basename_original'] = $pathinfo['filename'] . '.' . $fileinfo['extension'];
446
- $fileinfo['filename'] = $pathinfo['filename'] . $suffix;
447
- $fileinfo['basename'] = $fileinfo['filename'] . '.' . $fileinfo['extension'];
448
- $fileinfo['title'] = str_replace('_', ' ', esc_sql($title));
449
- if((int) $gmGallery->options['name2title_capitalize']){
450
- $fileinfo['title'] = $this->mb_ucwords_utf8($fileinfo['title']);
451
- }
452
- $fileinfo['mime_type'] = (empty($filetype['type']))? 'application/' . $fileinfo['extension'] : $filetype['type'];
453
- list($dirname) = explode('/', $fileinfo['mime_type']);
454
- $fileinfo['dirname'] = $dirname;
455
- $fileinfo['dirpath'] = $this->upload['path'] . '/' . $gmGallery->options['folder'][ $dirname ];
456
- $fileinfo['dirpath_original'] = $this->upload['path'] . '/' . $gmGallery->options['folder'][ $dirname ];
457
- $fileinfo['dirurl'] = $this->upload['url'] . '/' . $gmGallery->options['folder'][ $dirname ];
458
- $fileinfo['dirurl_original'] = $this->upload['url'] . '/' . $gmGallery->options['folder'][ $dirname ];
459
- $fileinfo['filepath'] = $fileinfo['dirpath'] . '/' . $fileinfo['basename'];
460
- $fileinfo['filepath_original'] = $fileinfo['dirpath'] . '/' . $fileinfo['basename'];
461
- $fileinfo['fileurl'] = $fileinfo['dirurl'] . '/' . $fileinfo['basename'];
462
- $fileinfo['fileurl_original'] = $fileinfo['dirurl'] . '/' . $fileinfo['basename'];
463
- if('image' == $dirname){
464
- $fileinfo['dirpath_original'] = $this->upload['path'] . '/' . $gmGallery->options['folder']['image_original'];
465
- $fileinfo['dirurl_original'] = $this->upload['url'] . '/' . $gmGallery->options['folder']['image_original'];
466
- $fileinfo['filepath_original'] = $fileinfo['dirpath_original'] . '/' . $fileinfo['basename'];
467
- $fileinfo['fileurl_original'] = $fileinfo['dirurl_original'] . '/' . $fileinfo['basename'];
468
- $fileinfo['dirpath_thumb'] = $this->upload['path'] . '/' . $gmGallery->options['folder']['image_thumb'];
469
- $fileinfo['dirurl_thumb'] = $this->upload['url'] . '/' . $gmGallery->options['folder']['image_thumb'];
470
- $fileinfo['filepath_thumb'] = $fileinfo['dirpath_thumb'] . '/' . $fileinfo['basename'];
471
- $fileinfo['fileurl_thumb'] = $fileinfo['dirurl_thumb'] . '/' . $fileinfo['basename'];
472
- }
473
-
474
- if((false !== $exists) && is_file($fileinfo['filepath'])){
475
- $exists = absint($exists) + 1;
476
- $fileinfo = $this->fileinfo($file, $exists);
477
- }
478
-
479
- return $fileinfo;
480
- }
481
-
482
- /** Get file metadata
483
- *
484
- * @param $file
485
- * @param $fileinfo
486
- *
487
- * @return mixed|void
488
- */
489
- function get_file_metadata($file, $fileinfo = array()){
490
-
491
- if(empty($fileinfo)){
492
- $fileinfo = $this->fileinfo($file, false);
493
- }
494
- $metadata = array();
495
- require_once(ABSPATH . 'wp-admin/includes/image.php');
496
- if(preg_match('!^image/!', $fileinfo['mime_type']) && file_is_displayable_image($fileinfo['filepath'])){
497
- $is_file_original = is_file($fileinfo['filepath_original']);
498
- $filepath_original = $is_file_original? $fileinfo['filepath_original'] : $fileinfo['filepath'];
499
- $imagesize = getimagesize($fileinfo['filepath_thumb']);
500
- $metadata['thumb'] = array('width' => $imagesize[0], 'height' => $imagesize[1]);
501
- $imagesize = getimagesize($fileinfo['filepath']);
502
- $metadata['web'] = array('width' => $imagesize[0], 'height' => $imagesize[1]);
503
- if($is_file_original){
504
- $imagesize = getimagesize($filepath_original);
505
- $metadata['original'] = array('width' => $imagesize[0], 'height' => $imagesize[1]);
506
- } else{
507
- $metadata['original'] = $metadata['web'];
508
- }
509
-
510
- $metadata['file'] = $this->_gm_relative_upload_path($fileinfo['filepath']);
511
-
512
- // fetch additional metadata from exif/iptc
513
- $image_meta = $this->wp_read_image_metadata($filepath_original);
514
- if($image_meta){
515
- $metadata['image_meta'] = $image_meta;
516
- }
517
-
518
- } elseif(preg_match('#^video/#', $fileinfo['mime_type'])){
519
- $metadata = $this->wp_read_video_metadata($fileinfo['filepath']);
520
- } elseif(preg_match('#^audio/#', $fileinfo['mime_type'])){
521
- $metadata = $this->wp_read_audio_metadata($fileinfo['filepath']);
522
- //unset($metadata['image']);
523
- }
524
-
525
- return apply_filters('generate_file_metadata', $metadata);
526
- }
527
-
528
- /**
529
- * Return relative path to an uploaded file.
530
- * The path is relative to the current upload dir.
531
- * @see _wp_relative_upload_path()
532
- * @uses apply_filters() Calls '_gm_relative_upload_path' on file path.
533
- *
534
- * @param string $path Full path to the file
535
- *
536
- * @return string relative path on success, unchanged path on failure.
537
- */
538
- function _gm_relative_upload_path($path){
539
- $new_path = $path;
540
-
541
- if((false === $this->upload['error']) && (0 === strpos($new_path, $this->upload['path']))){
542
- $new_path = str_replace($this->upload['path'], '', $new_path);
543
- $new_path = ltrim($new_path, '/');
544
- }
545
-
546
- return apply_filters('_gm_relative_upload_path', $new_path, $path);
547
- }
548
-
549
- /** Set correct file permissions (chmod)
550
- *
551
- * @param string $new_file
552
- */
553
- function file_chmod($new_file){
554
- $stat = stat(dirname($new_file));
555
- $perms = $stat['mode'] & 0000666;
556
- @chmod($new_file, $perms);
557
- }
558
-
559
- /**
560
- * The most complete and efficient way to sanitize a string before using it with your database
561
- *
562
- * @param $input string
563
- *
564
- * @return mixed
565
- */
566
- function clean_input($input){
567
- $search = array(/*'@<[\/\!]*?[^<>]*?>@si'*/ /* Strip out HTML tags */
568
- '@<script' . '[^>]*?>.*?</script>@si' /* Strip out javascript */,
569
- '@<style' . '[^>]*?>.*?</style>@siU' /* Strip style tags properly */,
570
- '@<![\s\S]*?--[ \t\n\r]*>@' /* Strip multi-line comments */
571
- //,'/\s{3,}/'
572
- );
573
-
574
- $output = preg_replace($search, '', $input);
575
-
576
- return $output;
577
- }
578
-
579
- /**
580
- * Sanitize a string|array before using it with your database
581
- *
582
- * @param $input string|array
583
- *
584
- * @return mixed
585
- */
586
- function sanitize($input){
587
- $output = $input;
588
- if(is_array($input)){
589
- foreach($input as $var => $val){
590
- $output[ $var ] = $this->sanitize($val);
591
- }
592
- } else{
593
- /** @noinspection PhpDeprecationInspection */
594
- if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()){
595
- $input = stripslashes($input);
596
- }
597
- $input = $this->clean_input($input);
598
- $output = esc_sql($input);
599
- }
600
-
601
- return $output;
602
- }
603
-
604
- /**
605
- * Check input for existing only of digits (numbers)
606
- *
607
- * @param $digit
608
- *
609
- * @return bool
610
- */
611
- function is_digit($digit){
612
- if(is_int($digit)){
613
- return true;
614
- } elseif(is_string($digit) && !empty($digit)){
615
- return ctype_digit($digit);
616
- } else{
617
- // booleans, floats and others
618
- return false;
619
- }
620
- }
621
-
622
- /**
623
- * Check if user can select a author
624
- * @return array
625
- */
626
- function get_editable_user_ids(){
627
- if(current_user_can('gmedia_show_others_media') || current_user_can('gmedia_edit_others_media')){
628
- return get_users(array('fields' => 'ID'));
629
- }
630
-
631
- return get_current_user_id();
632
- }
633
-
634
- /**
635
- * Generate GmediaCloud page url
636
- *
637
- * @param $id
638
- * @param $type
639
- * @param bool $default
640
- *
641
- * @return string
642
- */
643
- function gmcloudlink($id, $type, $default = false){
644
- $options = get_option('gmediaOptions');
645
- $endpoint = $options['endpoint'];
646
- $hashid = gmedia_hash_id_encode($id, $type);
647
- $t = array(
648
- 'gallery' => 'g',
649
- 'album' => 'a',
650
- 'tag' => 't',
651
- 'single' => 's',
652
- 'category' => 'k',
653
- 'author' => 'u'
654
- );
655
- if( !$default && get_option('permalink_structure')){
656
- $cloud_link = home_url(urlencode($endpoint) . "/{$t[$type]}/{$hashid}");
657
- } else{
658
- $cloud_link = add_query_arg(array("$endpoint" => $hashid, 't' => $t[ $type ]), home_url('index.php'));
659
- }
660
-
661
- return $cloud_link;
662
- }
663
-
664
- /**
665
- * Extremely simple function to get human filesize
666
- *
667
- * @param $file
668
- * @param int $decimals
669
- *
670
- * @return string
671
- */
672
- function filesize($file, $decimals = 2){
673
- $bytes = filesize($file);
674
- $sz = array('b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb');
675
- $factor = (int) floor((strlen($bytes) - 1) / 3);
676
-
677
- return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sz[ $factor ];
678
- }
679
-
680
- /**
681
- * @author Gajus Kuizinas <g.kuizinas@anuary.com>
682
- * @version 1.0.0 (2013 03 19)
683
- *
684
- * @param array $arr1
685
- * @param array $arr2
686
- *
687
- * @return array
688
- */
689
- function array_diff_key_recursive(array $arr1, array $arr2){
690
- $diff = array_diff_key($arr1, $arr2);
691
- $intersect = array_intersect_key($arr1, $arr2);
692
-
693
- foreach($intersect as $k => $v){
694
- if(is_array($arr1[ $k ]) && is_array($arr2[ $k ])){
695
- $d = $this->array_diff_key_recursive($arr1[ $k ], $arr2[ $k ]);
696
-
697
- if( !empty($d)){
698
- $diff[ $k ] = $d;
699
- }
700
- }
701
- }
702
-
703
- return $diff;
704
- }
705
-
706
- /**
707
- * @param array $arr1
708
- * @param array $arr2
709
- * @param bool $update
710
- *
711
- * @return array
712
- */
713
- function array_diff_keyval_recursive(array $arr1, array $arr2, $update = false){
714
- $diff = array_diff_key($arr1, $arr2);
715
- $intersect = array_intersect_key($arr1, $arr2);
716
-
717
- foreach($intersect as $k => $v){
718
- if(is_array($arr1[ $k ]) && is_array($arr2[ $k ])){
719
- $d = $this->array_diff_keyval_recursive($arr1[ $k ], $arr2[ $k ], $update);
720
-
721
- if( !empty($d)){
722
- $diff[ $k ] = $d;
723
- }
724
- } elseif($arr1[ $k ] !== $arr2[ $k ]){
725
- if($update){
726
- $diff[ $k ] = $arr2[ $k ];
727
- } else{
728
- $diff[ $k ] = $arr1[ $k ];
729
- }
730
- }
731
- }
732
-
733
- return $diff;
734
- }
735
-
736
- /**
737
- * @param $base
738
- * @param $replacements
739
- *
740
- * @return mixed
741
- */
742
- function array_replace_recursive($base, $replacements){
743
- if(function_exists('array_replace_recursive')){
744
- return array_replace_recursive($base, $replacements);
745
- }
746
-
747
- foreach(array_slice(func_get_args(), 1) as $replacements){
748
- $bref_stack = array(&$base);
749
- $head_stack = array($replacements);
750
-
751
- do {
752
- end($bref_stack);
753
-
754
- $bref = &$bref_stack[ key($bref_stack) ];
755
- $head = array_pop($head_stack);
756
-
757
- unset($bref_stack[ key($bref_stack) ]);
758
-
759
- foreach(array_keys($head) as $key){
760
- if(isset($bref[ $key ]) && is_array($bref[ $key ]) && is_array($head[ $key ])){
761
- $bref_stack[] = &$bref[ $key ];
762
- $head_stack[] = $head[ $key ];
763
- } else{
764
- $bref[ $key ] = $head[ $key ];
765
- }
766
- }
767
- } while(count($head_stack));
768
- }
769
-
770
- return $base;
771
- }
772
-
773
- /**
774
- * @param $callback
775
- * @param $array
776
- *
777
- * @return mixed
778
- */
779
- function array_map_recursive($callback, $array){
780
- foreach($array as $key => $value){
781
- if(is_array($array[ $key ])){
782
- $array[ $key ] = $this->array_map_recursive($callback, $array[ $key ]);
783
- } else{
784
- $array[ $key ] = call_user_func($callback, $array[ $key ]);
785
- }
786
- }
787
-
788
- return $array;
789
- }
790
-
791
- /**
792
- * @param string $type
793
- * @param string $content
794
- *
795
- * @return string
796
- */
797
- public function alert($type = 'info', $content = ''){
798
- if(empty($content)){
799
- return '';
800
- } elseif(is_array($content)){
801
- $content = array_filter($content);
802
- $content = implode('<br />', $content);
803
- }
804
- $alert = '<div class="alert alert-' . $type . ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' . $content . '</div>';
805
-
806
- return $alert;
807
- }
808
-
809
- /**
810
- * @param $photo
811
- *
812
- * @return array|bool
813
- */
814
- function process_gmedit_image($photo){
815
- $type = null;
816
- if(preg_match('/^data:image\/(jpg|jpeg|png|gif)/i', $photo, $matches)){
817
- $type = $matches[1];
818
- } else{
819
- return false;
820
- }
821
- // Remove the mime-type header
822
- $data = explode('base64,', $photo);
823
- $data = array_reverse($data);
824
- $data = reset($data);
825
-
826
- // Use strict mode to prevent characters from outside the base64 range
827
- $image = base64_decode($data, true);
828
-
829
- if( !$image){
830
- return false;
831
- }
832
-
833
- return array(
834
- 'data' => $image,
835
- 'type' => $type
836
- );
837
- }
838
-
839
- /**
840
- * @return bool
841
- */
842
- function is_bot(){
843
- if(empty($_SERVER['HTTP_USER_AGENT'])){
844
- return false;
845
- }
846
-
847
- $spiders = array(
848
- "abot",
849
- "dbot",
850
- "ebot",
851
- "hbot",
852
- "kbot",
853
- "lbot",
854
- "mbot",
855
- "nbot",
856
- "obot",
857
- "pbot",
858
- "rbot",
859
- "sbot",
860
- "tbot",
861
- "vbot",
862
- "ybot",
863
- "zbot",
864
- "bot.",
865
- "bot/",
866
- "_bot",
867
- ".bot",
868
- "/bot",
869
- "-bot",
870
- ":bot",
871
- "(bot",
872
- "crawl",
873
- "slurp",
874
- "spider",
875
- "seek",
876
- "accoona",
877
- "acoon",
878
- "adressendeutschland",
879
- "ah-ha.com",
880
- "ahoy",
881
- "altavista",
882
- "ananzi",
883
- "anthill",
884
- "appie",
885
- "arachnophilia",
886
- "arale",
887
- "araneo",
888
- "aranha",
889
- "architext",
890
- "aretha",
891
- "arks",
892
- "asterias",
893
- "atlocal",
894
- "atn",
895
- "atomz",
896
- "augurfind",
897
- "backrub",
898
- "bannana_bot",
899
- "baypup",
900
- "bdfetch",
901
- "big brother",
902
- "biglotron",
903
- "bjaaland",
904
- "blackwidow",
905
- "blaiz",
906
- "blog",
907
- "blo.",
908
- "bloodhound",
909
- "boitho",
910
- "booch",
911
- "bradley",
912
- "butterfly",
913
- "calif",
914
- "cassandra",
915
- "ccubee",
916
- "cfetch",
917
- "charlotte",
918
- "churl",
919
- "cienciaficcion",
920
- "cmc",
921
- "collective",
922
- "comagent",
923
- "combine",
924
- "computingsite",
925
- "csci",
926
- "curl",
927
- "cusco",
928
- "daumoa",
929
- "deepindex",
930
- "delorie",
931
- "depspid",
932
- "deweb",
933
- "die blinde kuh",
934
- "digger",
935
- "ditto",
936
- "dmoz",
937
- "docomo",
938
- "download express",
939
- "dtaagent",
940
- "dwcp",
941
- "ebiness",
942
- "ebingbong",
943
- "e-collector",
944
- "ejupiter",
945
- "emacs-w3 search engine",
946
- "esther",
947
- "evliya celebi",
948
- "ezresult",
949
- "falcon",
950
- "felix ide",
951
- "ferret",
952
- "fetchrover",
953
- "fido",
954
- "findlinks",
955
- "fireball",
956
- "fish search",
957
- "fouineur",
958
- "funnelweb",
959
- "gazz",
960
- "gcreep",
961
- "genieknows",
962
- "getterroboplus",
963
- "geturl",
964
- "glx",
965
- "goforit",
966
- "golem",
967
- "grabber",
968
- "grapnel",
969
- "gralon",
970
- "griffon",
971
- "gromit",
972
- "grub",
973
- "gulliver",
974
- "hamahakki",
975
- "harvest",
976
- "havindex",
977
- "helix",
978
- "heritrix",
979
- "hku www octopus",
980
- "homerweb",
981
- "htdig",
982
- "html index",
983
- "html_analyzer",
984
- "htmlgobble",
985
- "hubater",
986
- "hyper-decontextualizer",
987
- "ia_archiver",
988
- "ibm_planetwide",
989
- "ichiro",
990
- "iconsurf",
991
- "iltrovatore",
992
- "image.kapsi.net",
993
- "imagelock",
994
- "incywincy",
995
- "indexer",
996
- "infobee",
997
- "informant",
998
- "ingrid",
999
- "inktomisearch.com",
1000
- "inspector web",
1001
- "intelliagent",
1002
- "internet shinchakubin",
1003
- "ip3000",
1004
- "iron33",
1005
- "israeli-search",
1006
- "ivia",
1007
- "jack",
1008
- "jakarta",
1009
- "javabee",
1010
- "jetbot",
1011
- "jumpstation",
1012
- "katipo",
1013
- "kdd-explorer",
1014
- "kilroy",
1015
- "knowledge",
1016
- "kototoi",
1017
- "kretrieve",
1018
- "labelgrabber",
1019
- "lachesis",
1020
- "larbin",
1021
- "legs",
1022
- "libwww",
1023
- "linkalarm",
1024
- "link validator",
1025
- "linkscan",
1026
- "lockon",
1027
- "lwp",
1028
- "lycos",
1029
- "magpie",
1030
- "mantraagent",
1031
- "mapoftheinternet",
1032
- "marvin/",
1033
- "mattie",
1034
- "mediafox",
1035
- "mediapartners",
1036
- "mercator",
1037
- "merzscope",
1038
- "microsoft url control",
1039
- "minirank",
1040
- "miva",
1041
- "mj12",
1042
- "mnogosearch",
1043
- "moget",
1044
- "monster",
1045
- "moose",
1046
- "motor",
1047
- "multitext",
1048
- "muncher",
1049
- "muscatferret",
1050
- "mwd.search",
1051
- "myweb",
1052
- "najdi",
1053
- "nameprotect",
1054
- "nationaldirectory",
1055
- "nazilla",
1056
- "ncsa beta",
1057
- "nec-meshexplorer",
1058
- "nederland.zoek",
1059
- "netcarta webmap engine",
1060
- "netmechanic",
1061
- "netresearchserver",
1062
- "netscoop",
1063
- "newscan-online",
1064
- "nhse",
1065
- "nokia6682/",
1066
- "nomad",
1067
- "noyona",
1068
- "nutch",
1069
- "nzexplorer",
1070
- "objectssearch",
1071
- "occam",
1072
- "omni",
1073
- "open text",
1074
- "openfind",
1075
- "openintelligencedata",
1076
- "orb search",
1077
- "osis-project",
1078
- "pack rat",
1079
- "pageboy",
1080
- "pagebull",
1081
- "page_verifier",
1082
- "panscient",
1083
- "parasite",
1084
- "partnersite",
1085
- "patric",
1086
- "pear.",
1087
- "pegasus",
1088
- "peregrinator",
1089
- "pgp key agent",
1090
- "phantom",
1091
- "phpdig",
1092
- "picosearch",
1093
- "piltdownman",
1094
- "pimptrain",
1095
- "pinpoint",
1096
- "pioneer",
1097
- "piranha",
1098
- "plumtreewebaccessor",
1099
- "pogodak",
1100
- "poirot",
1101
- "pompos",
1102
- "poppelsdorf",
1103
- "poppi",
1104
- "popular iconoclast",
1105
- "psycheclone",
1106
- "publisher",
1107
- "python",
1108
- "rambler",
1109
- "raven search",
1110
- "roach",
1111
- "road runner",
1112
- "roadhouse",
1113
- "robbie",
1114
- "robofox",
1115
- "robozilla",
1116
- "rules",
1117
- "salty",
1118
- "sbider",
1119
- "scooter",
1120
- "scoutjet",
1121
- "scrubby",
1122
- "search.",
1123
- "searchprocess",
1124
- "semanticdiscovery",
1125
- "senrigan",
1126
- "sg-scout",
1127
- "shai'hulud",
1128
- "shark",
1129
- "shopwiki",
1130
- "sidewinder",
1131
- "sift",
1132
- "silk",
1133
- "simmany",
1134
- "site searcher",
1135
- "site valet",
1136
- "sitetech-rover",
1137
- "skymob.com",
1138
- "sleek",
1139
- "smartwit",
1140
- "sna-",
1141
- "snappy",
1142
- "snooper",
1143
- "sohu",
1144
- "speedfind",
1145
- "sphere",
1146
- "sphider",
1147
- "spinner",
1148
- "spyder",
1149
- "steeler/",
1150
- "suke",
1151
- "suntek",
1152
- "supersnooper",
1153
- "surfnomore",
1154
- "sven",
1155
- "sygol",
1156
- "szukacz",
1157
- "tach black widow",
1158
- "tarantula",
1159
- "templeton",
1160
- "/teoma",
1161
- "t-h-u-n-d-e-r-s-t-o-n-e",
1162
- "theophrastus",
1163
- "titan",
1164
- "titin",
1165
- "tkwww",
1166
- "toutatis",
1167
- "t-rex",
1168
- "tutorgig",
1169
- "twiceler",
1170
- "twisted",
1171
- "ucsd",
1172
- "udmsearch",
1173
- "url check",
1174
- "updated",
1175
- "vagabondo",
1176
- "valkyrie",
1177
- "verticrawl",
1178
- "victoria",
1179
- "vision-search",
1180
- "volcano",
1181
- "voyager/",
1182
- "voyager-hc",
1183
- "w3c_validator",
1184
- "w3m2",
1185
- "w3mir",
1186
- "walker",
1187
- "wallpaper",
1188
- "wanderer",
1189
- "wauuu",
1190
- "wavefire",
1191
- "web core",
1192
- "web hopper",
1193
- "web wombat",
1194
- "webbandit",
1195
- "webcatcher",
1196
- "webcopy",
1197
- "webfoot",
1198
- "weblayers",
1199
- "weblinker",
1200
- "weblog monitor",
1201
- "webmirror",
1202
- "webmonkey",
1203
- "webquest",
1204
- "webreaper",
1205
- "websitepulse",
1206
- "websnarf",
1207
- "webstolperer",
1208
- "webvac",
1209
- "webwalk",
1210
- "webwatch",
1211
- "webwombat",
1212
- "webzinger",
1213
- "wget",
1214
- "whizbang",
1215
- "whowhere",
1216
- "wild ferret",
1217
- "worldlight",
1218
- "wwwc",
1219
- "wwwster",
1220
- "xenu",
1221
- "xget",
1222
- "xift",
1223
- "xirq",
1224
- "yandex",
1225
- "yanga",
1226
- "yeti",
1227
- "yodao",
1228
- "zao/",
1229
- "zippp",
1230
- "zyborg",
1231
- "...."
1232
- );
1233
-
1234
- foreach($spiders as $spider){
1235
- //If the spider text is found in the current user agent, then return true
1236
- if(stripos($_SERVER['HTTP_USER_AGENT'], $spider) !== false){
1237
- return true;
1238
- break;
1239
- }
1240
- }
1241
-
1242
- return false;
1243
- }
1244
-
1245
-
1246
- /**
1247
- * Parse ID3v2, ID3v1, and getID3 comments to extract usable data
1248
- * @since 3.6.0
1249
- *
1250
- * @param array $metadata An existing array with data
1251
- * @param array $data Data supplied by ID3 tags
1252
- */
1253
- function wp_add_id3_tag_data(&$metadata, $data){
1254
- foreach(array('id3v2', 'id3v1') as $version){
1255
- if( !empty($data[ $version ]['comments'])){
1256
- foreach($data[ $version ]['comments'] as $key => $list){
1257
- if( !empty($list)){
1258
- $metadata[ $key ] = reset($list);
1259
- // fix bug in byte stream analysis
1260
- if('terms_of_use' === $key && 0 === strpos($metadata[ $key ], 'yright notice.')){
1261
- $metadata[ $key ] = 'Cop' . $metadata[ $key ];
1262
- }
1263
- }
1264
- }
1265
- break;
1266
- }
1267
- }
1268
-
1269
- if( !empty($data['id3v2']['APIC'])){
1270
- $image = reset($data['id3v2']['APIC']);
1271
- if( !empty($image['data'])){
1272
- $metadata['image'] = array(
1273
- 'data' => $image['data'],
1274
- 'mime' => $image['image_mime'],
1275
- 'width' => $image['image_width'],
1276
- 'height' => $image['image_height']
1277
- );
1278
- }
1279
- } elseif( !empty($data['comments']['picture'])){
1280
- $image = reset($data['comments']['picture']);
1281
- if( !empty($image['data'])){
1282
- $metadata['image'] = array(
1283
- 'data' => $image['data'],
1284
- 'mime' => $image['image_mime']
1285
- );
1286
- }
1287
- }
1288
- }
1289
-
1290
- /**
1291
- * Get extended image metadata, exif or iptc as available.
1292
- * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
1293
- * created_timestamp, focal_length, shutter_speed, and title.
1294
- * The IPTC metadata that is retrieved is APP13, credit, byline, created date
1295
- * and time, caption, copyright, and title. Also includes FNumber, Model,
1296
- * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
1297
- * @todo Try other exif libraries if available.
1298
- * @since 2.5.0
1299
- *
1300
- * @param string $file
1301
- *
1302
- * @return bool|array False on failure. Image metadata array on success.
1303
- */
1304
- function wp_read_image_metadata($file){
1305
- if( !is_file($file)){
1306
- return false;
1307
- }
1308
-
1309
- list(, , $sourceImageType) = getimagesize($file);
1310
-
1311
- $meta = array();
1312
-
1313
- /*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1314
  * Read IPTC first, since it might contain data not available in exif such
1315
  * as caption, description etc.
1316
  */
1317
- if(is_callable('iptcparse')){
1318
- getimagesize($file, $info);
1319
 
1320
- if( !empty($info['APP13'])){
1321
- $iptc = iptcparse($info['APP13']);
1322
 
1323
- // Headline, "A brief synopsis of the caption."
1324
- if( !empty($iptc['2#105'][0])){
1325
- $meta['title'] = trim($iptc['2#105'][0]);
1326
- /*
1327
  * Title, "Many use the Title field to store the filename of the image,
1328
  * though the field may be used in many ways."
1329
  */
1330
- } elseif( !empty($iptc['2#005'][0])){
1331
- $meta['title'] = trim($iptc['2#005'][0]);
1332
- }
1333
-
1334
- if( !empty($iptc['2#120'][0])){ // description / legacy caption
1335
- $caption = trim($iptc['2#120'][0]);
1336
- if(empty($meta['title'])){
1337
- mbstring_binary_safe_encoding();
1338
- $caption_length = strlen($caption);
1339
- reset_mbstring_encoding();
1340
-
1341
- // Assume the title is stored in 2:120 if it's short.
1342
- if($caption_length < 80){
1343
- $meta['title'] = $caption;
1344
- } else{
1345
- $meta['caption'] = $caption;
1346
- }
1347
- } elseif($caption != $meta['title']){
1348
- $meta['caption'] = $caption;
1349
- }
1350
- }
1351
-
1352
- if( !empty($iptc['2#110'][0])) // credit
1353
- {
1354
- $meta['credit'] = trim($iptc['2#110'][0]);
1355
- } elseif( !empty($iptc['2#080'][0])) // creator / legacy byline
1356
- {
1357
- $meta['credit'] = trim($iptc['2#080'][0]);
1358
- }
1359
-
1360
- if( !empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0])) // created date and time
1361
- {
1362
- $meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]);
1363
- }
1364
-
1365
- if( !empty($iptc['2#116'][0])) // copyright
1366
- {
1367
- $meta['copyright'] = trim($iptc['2#116'][0]);
1368
- }
1369
-
1370
- if( !empty($iptc['2#025'])) // keywords
1371
- {
1372
- $meta['keywords'] = $iptc['2#025'];
1373
- }
1374
- }
1375
- }
1376
-
1377
- /**
1378
- * Filter the image types to check for exif data.
1379
- * @since 2.5.0
1380
- *
1381
- * @param array $image_types Image types to check for exif data.
1382
- */
1383
- if(is_callable('exif_read_data') && in_array($sourceImageType, apply_filters('wp_read_image_metadata_types', array(
1384
- IMAGETYPE_JPEG,
1385
- IMAGETYPE_TIFF_II,
1386
- IMAGETYPE_TIFF_MM
1387
- )))
1388
- ){
1389
- $exif = @exif_read_data($file);
1390
- unset($exif['MakerNote']);
1391
-
1392
- // Title
1393
- if(empty($meta['title']) && !empty($exif['Title'])){
1394
- $meta['title'] = trim($exif['Title']);
1395
- }
1396
- // Descrioption
1397
- if( !empty($exif['ImageDescription'])){
1398
- mbstring_binary_safe_encoding();
1399
- $description_length = strlen($exif['ImageDescription']);
1400
- reset_mbstring_encoding();
1401
-
1402
- if(empty($meta['title']) && $description_length < 80){
1403
- // Assume the title is stored in ImageDescription
1404
- $meta['title'] = trim($exif['ImageDescription']);
1405
- if(empty($meta['caption']) && !empty($exif['COMPUTED']['UserComment']) && trim($exif['COMPUTED']['UserComment']) != $meta['title']){
1406
- $meta['caption'] = trim($exif['COMPUTED']['UserComment']);
1407
- }
1408
- } elseif(empty($meta['caption']) && trim($exif['ImageDescription']) != $meta['title']){
1409
- $meta['caption'] = trim($exif['ImageDescription']);
1410
- }
1411
- } elseif(empty($meta['caption']) && !empty($exif['Comments']) && trim($exif['Comments']) != $meta['title']){
1412
- $meta['caption'] = trim($exif['Comments']);
1413
- }
1414
- // Credit
1415
- if(empty($meta['credit'])){
1416
- if( !empty($exif['Artist'])){
1417
- $meta['credit'] = trim($exif['Artist']);
1418
- } elseif( !empty($exif['Author'])){
1419
- $meta['credit'] = trim($exif['Author']);
1420
- }
1421
- }
1422
- // Copyright
1423
- if(empty($meta['copyright']) && !empty($exif['Copyright'])){
1424
- $meta['copyright'] = trim($exif['Copyright']);
1425
- }
1426
- // Camera Make
1427
- if( !empty($exif['Make'])){
1428
- $meta['make'] = $exif['Make'];
1429
- }
1430
- // Camera Model
1431
- if( !empty($exif['Model'])){
1432
- $meta['model'] = trim($exif['Model']);
1433
- }
1434
- // Exposure Time (shutter speed)
1435
- if( !empty($exif['ExposureTime'])){
1436
- $meta['exposure'] = $exif['ExposureTime'] . 's';
1437
- $meta['shutter_speed'] = (string) wp_exif_frac2dec($exif['ExposureTime']) . 's';
1438
- }
1439
- // Aperture
1440
- if( !empty($exif['COMPUTED']['ApertureFNumber'])){
1441
- $meta['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
1442
- } elseif( !empty($exif['FNumber'])){
1443
- $meta['aperture'] = 'f/' . (string) round(wp_exif_frac2dec($exif['FNumber']), 2);
1444
- }
1445
- // ISO
1446
- if( !empty($exif['ISOSpeedRatings'])){
1447
- $meta['iso'] = is_array($exif['ISOSpeedRatings'])? reset($exif['ISOSpeedRatings']) : $exif['ISOSpeedRatings'];
1448
- $meta['iso'] = trim($meta['iso']);
1449
- }
1450
- // Date
1451
- if( !empty($exif['DateTime'])){
1452
- $meta['date'] = $exif['DateTime'];
1453
- }
1454
- // Created TimeStamp
1455
- if(empty($meta['created_timestamp']) && !empty($exif['DateTimeDigitized'])){
1456
- $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
1457
- }
1458
- // Lens
1459
- if( !empty($exif['UndefinedTag:0xA434'])){
1460
- $meta['lens'] = $exif['UndefinedTag:0xA434'];
1461
- }
1462
- // Focus Distance
1463
- if( !empty($exif['COMPUTED']['FocusDistance'])){
1464
- $meta['distance'] = $exif['COMPUTED']['FocusDistance'];
1465
- }
1466
- // Focal Length
1467
- if( !empty($exif['FocalLength'])){
1468
- $meta['focallength'] = (string) round(wp_exif_frac2dec($exif['FocalLength'])) . 'mm';
1469
- }
1470
- // Focal Length 35mm
1471
- if( !empty($exif['FocalLengthIn35mmFilm'])){
1472
- $meta['focallength35'] = $exif['FocalLengthIn35mmFilm'] . 'mm';
1473
- }
1474
- // Flash data
1475
- if( !empty($exif['Flash'])){
1476
- // we need to interpret the result - it's given as a number and we want a human-readable description.
1477
- $fdata = $exif['Flash'];
1478
-
1479
- switch($fdata){
1480
- case 0 :
1481
- $fdata = 'No Flash';
1482
- break;
1483
- case 1 :
1484
- $fdata = 'Flash';
1485
- break;
1486
- case 5 :
1487
- $fdata = 'Flash, strobe return light not detected';
1488
- break;
1489
- case 7 :
1490
- $fdata = 'Flash, strob return light detected';
1491
- break;
1492
- case 9 :
1493
- $fdata = 'Compulsory Flash';
1494
- break;
1495
- case 13:
1496
- $fdata = 'Compulsory Flash, Return light not detected';
1497
- break;
1498
- case 15:
1499
- $fdata = 'Compulsory Flash, Return light detected';
1500
- break;
1501
- case 16:
1502
- $fdata = 'No Flash';
1503
- break;
1504
- case 24:
1505
- $fdata = 'No Flash';
1506
- break;
1507
- case 25:
1508
- $fdata = 'Flash, Auto-Mode';
1509
- break;
1510
- case 29:
1511
- $fdata = 'Flash, Auto-Mode, Return light not detected';
1512
- break;
1513
- case 31:
1514
- $fdata = 'Flash, Auto-Mode, Return light detected';
1515
- break;
1516
- case 32:
1517
- $fdata = 'No Flash';
1518
- break;
1519
- case 65:
1520
- $fdata = 'Red Eye';
1521
- break;
1522
- case 69:
1523
- $fdata = 'Red Eye, Return light not detected';
1524
- break;
1525
- case 71:
1526
- $fdata = 'Red Eye, Return light detected';
1527
- break;
1528
- case 73:
1529
- $fdata = 'Red Eye, Compulsory Flash';
1530
- break;
1531
- case 77:
1532
- $fdata = 'Red Eye, Compulsory Flash, Return light not detected';
1533
- break;
1534
- case 79:
1535
- $fdata = 'Red Eye, Compulsory Flash, Return light detected';
1536
- break;
1537
- case 89:
1538
- $fdata = 'Red Eye, Auto-Mode';
1539
- break;
1540
- case 93:
1541
- $fdata = 'Red Eye, Auto-Mode, Return light not detected';
1542
- break;
1543
- case 95:
1544
- $fdata = 'Red Eye, Auto-Mode, Return light detected';
1545
- break;
1546
- default:
1547
- $fdata = 'Unknown: ' . $fdata;
1548
- break;
1549
- }
1550
- $meta['flashdata'] = $fdata;
1551
- }
1552
- // Lens Make
1553
- if( !empty($exif['UndefinedTag:0xA433'])){
1554
- $meta['lensmake'] = $exif['UndefinedTag:0xA433'];
1555
- }
1556
- // Software
1557
- if( !empty($exif['Software'])){
1558
- $meta['software'] = $exif['Software'];
1559
- }
1560
- // Orientation
1561
- if( !empty($exif['Orientation'])){
1562
- $meta['orientation'] = $exif['Orientation'];
1563
- }
1564
-
1565
- $exif_sections = @exif_read_data($file, null, true);
1566
- if(isset($exif_sections['GPS'])){
1567
- $meta['GPS'] = $this->getGPSfromExif($exif_sections['GPS']);
1568
- }
1569
- unset($exif_sections);
1570
- //$meta['exif'] = $exif;
1571
- }
1572
-
1573
- foreach(array('title', 'caption', 'credit', 'copyright', 'model', 'iso', 'software') as $key){
1574
- if( !empty($meta[ $key ]) && !seems_utf8($meta[ $key ])){
1575
- $meta[ $key ] = utf8_encode($meta[ $key ]);
1576
- }
1577
- }
1578
- if( !empty($meta['keywords'])){
1579
- foreach($meta['keywords'] as $i => $key){
1580
- if( !seems_utf8($key)){
1581
- $meta['keywords'][ $i ] = utf8_encode($key);
1582
- }
1583
- }
1584
- }
1585
-
1586
- foreach($meta as &$value){
1587
- if(is_string($value)){
1588
- $value = wp_kses_post($value);
1589
- }
1590
- }
1591
-
1592
- /**
1593
- * Filter the array of meta data read from an image's exif data.
1594
- * @since 2.5.0
1595
- *
1596
- * @param array $meta Image meta data.
1597
- * @param string $file Path to image file.
1598
- * @param int $sourceImageType Type of image.
1599
- */
1600
- return apply_filters('wp_read_image_metadata', $meta, $file, $sourceImageType);
1601
-
1602
- }
1603
-
1604
- /**
1605
- * Retrieve metadata from a video file's ID3 tags
1606
- * @since 3.6.0
1607
- *
1608
- * @param string $file Path to file.
1609
- *
1610
- * @return array|boolean Returns array of metadata, if found.
1611
- */
1612
- function wp_read_video_metadata($file){
1613
- if( !is_file($file)){
1614
- return false;
1615
- }
1616
-
1617
- $metadata = array();
1618
-
1619
- if( !class_exists('getID3')){
1620
- require(ABSPATH . WPINC . '/ID3/getid3.php');
1621
- }
1622
- $id3 = new getID3();
1623
- $data = $id3->analyze($file);
1624
-
1625
- if(isset($data['video']['lossless'])){
1626
- $metadata['lossless'] = $data['video']['lossless'];
1627
- }
1628
- if( !empty($data['video']['bitrate'])){
1629
- $metadata['bitrate'] = (int) $data['video']['bitrate'];
1630
- }
1631
- if( !empty($data['video']['bitrate_mode'])){
1632
- $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
1633
- }
1634
- if( !empty($data['filesize'])){
1635
- $metadata['filesize'] = (int) $data['filesize'];
1636
- }
1637
- if( !empty($data['mime_type'])){
1638
- $metadata['mime_type'] = $data['mime_type'];
1639
- }
1640
- if( !empty($data['playtime_seconds'])){
1641
- $metadata['length'] = (int) ceil($data['playtime_seconds']);
1642
- }
1643
- if( !empty($data['playtime_string'])){
1644
- $metadata['length_formatted'] = $data['playtime_string'];
1645
- }
1646
- if( !empty($data['video']['resolution_x'])){
1647
- $metadata['width'] = (int) $data['video']['resolution_x'];
1648
- }
1649
- if( !empty($data['video']['resolution_y'])){
1650
- $metadata['height'] = (int) $data['video']['resolution_y'];
1651
- }
1652
- if( !empty($data['fileformat'])){
1653
- $metadata['fileformat'] = $data['fileformat'];
1654
- }
1655
- if( !empty($data['video']['dataformat'])){
1656
- $metadata['dataformat'] = $data['video']['dataformat'];
1657
- }
1658
- if( !empty($data['video']['encoder'])){
1659
- $metadata['encoder'] = $data['video']['encoder'];
1660
- }
1661
- if( !empty($data['video']['codec'])){
1662
- $metadata['codec'] = $data['video']['codec'];
1663
- }
1664
-
1665
- if( !empty($data['audio'])){
1666
- unset($data['audio']['streams']);
1667
- $metadata['audio'] = $data['audio'];
1668
- }
1669
-
1670
- $this->wp_add_id3_tag_data($metadata, $data);
1671
-
1672
- return $metadata;
1673
- }
1674
-
1675
- /**
1676
- * Retrieve metadata from a audio file's ID3 tags
1677
- * @since 3.6.0
1678
- *
1679
- * @param string $file Path to file.
1680
- *
1681
- * @return array|boolean Returns array of metadata, if found.
1682
- */
1683
- function wp_read_audio_metadata($file){
1684
- if( !is_file($file)){
1685
- return false;
1686
- }
1687
- $metadata = array();
1688
-
1689
- if( !class_exists('getID3')){
1690
- require(ABSPATH . WPINC . '/ID3/getid3.php');
1691
- }
1692
- $id3 = new getID3();
1693
- $data = $id3->analyze($file);
1694
-
1695
- if( !empty($data['audio'])){
1696
- unset($data['audio']['streams']);
1697
- $metadata = $data['audio'];
1698
- }
1699
-
1700
- if( !empty($data['fileformat'])){
1701
- $metadata['fileformat'] = $data['fileformat'];
1702
- }
1703
- if( !empty($data['filesize'])){
1704
- $metadata['filesize'] = (int) $data['filesize'];
1705
- }
1706
- if( !empty($data['mime_type'])){
1707
- $metadata['mime_type'] = $data['mime_type'];
1708
- }
1709
- if( !empty($data['playtime_seconds'])){
1710
- $metadata['length'] = (int) ceil($data['playtime_seconds']);
1711
- }
1712
- if( !empty($data['playtime_string'])){
1713
- $metadata['length_formatted'] = $data['playtime_string'];
1714
- }
1715
-
1716
- $this->wp_add_id3_tag_data($metadata, $data);
1717
-
1718
- if(isset($metadata['image']['data']) && !empty($metadata['image']['data'])){
1719
- $image = 'data:' . $metadata['image']['mime'] . ';charset=utf-8;base64,' . base64_encode($metadata['image']['data']);
1720
- $metadata['image']['data'] = $image;
1721
- }
1722
-
1723
- return $metadata;
1724
- }
1725
-
1726
-
1727
- /** Write the file
1728
- *
1729
- * @param string $file_tmp
1730
- * @param array $fileinfo
1731
- * @param string $content_type
1732
- * @param array $post_data
1733
- *
1734
- * @return array
1735
- */
1736
- function gmedia_upload_handler($file_tmp, $fileinfo, $content_type, $post_data){
1737
- global $gmGallery, $gmDB;
1738
-
1739
- $cleanup_dir = true; // Remove old files
1740
- $file_age = 5 * 3600; // Temp file age in seconds
1741
- $chunk = (int) $this->_req('chunk', 0);
1742
- $chunks = (int) $this->_req('chunks', 0);
1743
-
1744
- // try to make grand-media dir if not exists
1745
- if( !wp_mkdir_p($fileinfo['dirpath'])){
1746
- $return = array(
1747
- "error" => array(
1748
- "code" => 100,
1749
- "message" => sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath'])
1750
- ),
1751
- "id" => $fileinfo['basename_original']
1752
- );
1753
-
1754
- return $return;
1755
- }
1756
- // Check if grand-media dir is writable
1757
- if( !is_writable($fileinfo['dirpath'])){
1758
- @chmod($fileinfo['dirpath'], 0755);
1759
- if( !is_writable($fileinfo['dirpath'])){
1760
- $return = array(
1761
- "error" => array(
1762
- "code" => 100,
1763
- "message" => sprintf(__('Directory %s or its subfolders are not writable by the server.', 'grand-media'), dirname($fileinfo['dirpath']))
1764
- ),
1765
- "id" => $fileinfo['basename_original']
1766
- );
1767
-
1768
- return $return;
1769
- }
1770
- }
1771
- // Remove old temp files
1772
- if($cleanup_dir && is_dir($fileinfo['dirpath']) && ($_dir = opendir($fileinfo['dirpath']))){
1773
- while(($_file = readdir($_dir)) !== false){
1774
- $tmpfilePath = $fileinfo['dirpath'] . DIRECTORY_SEPARATOR . $_file;
1775
-
1776
- // Remove temp file if it is older than the max age and is not the current file
1777
- if(preg_match('/\.part$/', $_file) && (filemtime($tmpfilePath) < time() - $file_age) && ($tmpfilePath != $fileinfo['filepath'] . '.part')){
1778
- @unlink($tmpfilePath);
1779
- }
1780
- }
1781
-
1782
- closedir($_dir);
1783
- } else{
1784
- $return = array(
1785
- "error" => array("code" => 100, "message" => sprintf(__('Failed to open directory: %s', 'grand-media'), $fileinfo['dirpath'])),
1786
- "id" => $fileinfo['basename_original']
1787
- );
1788
-
1789
- return $return;
1790
- }
1791
-
1792
- // Open temp file
1793
- $out = fopen($fileinfo['filepath'] . '.part', $chunk == 0? "wb" : "ab");
1794
- if($out){
1795
- // Read binary input stream and append it to temp file
1796
- $in = fopen($file_tmp, "rb");
1797
-
1798
- if($in){
1799
- while(($buff = fread($in, 4096))){
1800
- fwrite($out, $buff);
1801
- }
1802
- } else{
1803
- $return = array("error" => array("code" => 101, "message" => __("Failed to open input stream.", 'grand-media')), "id" => $fileinfo['basename']);
1804
-
1805
- return $return;
1806
- }
1807
- fclose($in);
1808
- fclose($out);
1809
- if(strpos($content_type, "multipart") !== false){
1810
- @unlink($file_tmp);
1811
- }
1812
- if( !$chunks || $chunk == ($chunks - 1)){
1813
- sleep(1);
1814
- // Strip the temp .part suffix off
1815
- rename($fileinfo['filepath'] . '.part', $fileinfo['filepath']);
1816
-
1817
- $this->file_chmod($fileinfo['filepath']);
1818
-
1819
- $size = false;
1820
- $is_webimage = false;
1821
- if('image' == $fileinfo['dirname']){
1822
- /** WordPress Image Administration API */
1823
- require_once(ABSPATH . 'wp-admin/includes/image.php');
1824
-
1825
- $size = @getimagesize($fileinfo['filepath']);
1826
- if($size && file_is_displayable_image($fileinfo['filepath'])){
1827
- $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP');
1828
- if(function_exists('memory_get_usage')){
1829
- switch($extensions[ $size[2] ]){
1830
- case 'GIF':
1831
- $CHANNEL = 1;
1832
- break;
1833
- case 'JPG':
1834
- $CHANNEL = $size['channels'];
1835
- break;
1836
- case 'PNG':
1837
- $CHANNEL = 3;
1838
- break;
1839
- case 'BMP':
1840
- default:
1841
- $CHANNEL = 6;
1842
- break;
1843
- }
1844
- $MB = 1048576; // number of bytes in 1M
1845
- $K64 = 65536; // number of bytes in 64K
1846
- $TWEAKFACTOR = 1.8; // Or whatever works for you
1847
- $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR);
1848
- $memoryNeeded = memory_get_usage() + $memoryNeeded;
1849
- $current_limit = @ini_get('memory_limit');
1850
- $current_limit_int = intval($current_limit);
1851
- if(false !== strpos($current_limit, 'M')){
1852
- $current_limit_int *= $MB;
1853
- }
1854
- if(false !== strpos($current_limit, 'G')){
1855
- $current_limit_int *= 1024;
1856
- }
1857
-
1858
- if(- 1 != $current_limit && $memoryNeeded > $current_limit_int){
1859
- $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB);
1860
- if($newLimit < 256){
1861
- $newLimit = 256;
1862
- }
1863
- @ini_set('memory_limit', $newLimit . 'M');
1864
- }
1865
- }
1866
-
1867
- if( !wp_mkdir_p($fileinfo['dirpath_thumb'])){
1868
- $return = array(
1869
- "error" => array(
1870
- "code" => 100,
1871
- "message" => sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_thumb'])
1872
- ),
1873
- "id" => $fileinfo['basename']
1874
- );
1875
-
1876
- return $return;
1877
- }
1878
- if( !is_writable($fileinfo['dirpath_thumb'])){
1879
- @chmod($fileinfo['dirpath_thumb'], 0755);
1880
- if( !is_writable($fileinfo['dirpath_thumb'])){
1881
- @unlink($fileinfo['filepath']);
1882
- $return = array(
1883
- "error" => array(
1884
- "code" => 100,
1885
- "message" => sprintf(__('Directory %s is not writable by the server.', 'grand-media'), $fileinfo['dirpath_thumb'])
1886
- ),
1887
- "id" => $fileinfo['basename']
1888
- );
1889
-
1890
- return $return;
1891
- }
1892
- }
1893
- if( !wp_mkdir_p($fileinfo['dirpath_original'])){
1894
- $return = array(
1895
- "error" => array(
1896
- "code" => 100,
1897
- "message" => sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_original'])
1898
- ),
1899
- "id" => $fileinfo['basename']
1900
- );
1901
-
1902
- return $return;
1903
- }
1904
- if( !is_writable($fileinfo['dirpath_original'])){
1905
- @chmod($fileinfo['dirpath_original'], 0755);
1906
- if( !is_writable($fileinfo['dirpath_original'])){
1907
- @unlink($fileinfo['filepath']);
1908
- $return = array(
1909
- "error" => array(
1910
- "code" => 100,
1911
- "message" => sprintf(__('Directory %s is not writable by the server.', 'grand-media'), $fileinfo['dirpath_original'])
1912
- ),
1913
- "id" => $fileinfo['basename']
1914
- );
1915
-
1916
- return $return;
1917
- }
1918
- }
1919
-
1920
- // Optimized image
1921
- $webimg = $gmGallery->options['image'];
1922
- $thumbimg = $gmGallery->options['thumb'];
1923
-
1924
- $webimg['resize'] = (($webimg['width'] < $size[0]) || ($webimg['height'] < $size[1]))? true : false;
1925
-
1926
- if($webimg['resize']){
1927
- rename($fileinfo['filepath'], $fileinfo['filepath_original']);
1928
- } else{
1929
- copy($fileinfo['filepath'], $fileinfo['filepath_original']);
1930
- }
1931
-
1932
- $size_ratio = $size[0] / $size[1];
1933
-
1934
- $angle = 0;
1935
- $image_meta = @$this->wp_read_image_metadata($fileinfo['filepath_original']);
1936
- if( !empty($image_meta['orientation'])){
1937
- switch($image_meta['orientation']){
1938
- case 3:
1939
- $angle = 180;
1940
- break;
1941
- case 6:
1942
- $angle = 270;
1943
- $size_ratio = $size[1] / $size[0];
1944
- break;
1945
- case 8:
1946
- $angle = 90;
1947
- $size_ratio = $size[1] / $size[0];
1948
- break;
1949
- }
1950
- }
1951
-
1952
- $thumbimg['resize'] = (((1 >= $size_ratio) && ($thumbimg['width'] > $size[0])) || ((1 <= $size_ratio) && ($thumbimg['height'] > $size[1])))? false : true;
1953
-
1954
- if($webimg['resize'] || $thumbimg['resize'] || $angle){
1955
- $editor = wp_get_image_editor($fileinfo['filepath_original']);
1956
- if(is_wp_error($editor)){
1957
- @unlink($fileinfo['filepath']);
1958
- @unlink($fileinfo['filepath_original']);
1959
- $return = array(
1960
- "error" => array("code" => $editor->get_error_code(), "message" => $editor->get_error_message()),
1961
- "id" => $fileinfo['basename'],
1962
- "tip" => 'wp_get_image_editor'
1963
- );
1964
-
1965
- return $return;
1966
- }
1967
-
1968
- if($angle){
1969
- $editor->rotate($angle);
1970
- }
1971
-
1972
- if($webimg['resize'] || $angle){
1973
- $editor->set_quality($webimg['quality']);
1974
-
1975
- if($webimg['resize']){
1976
- $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']);
1977
- if(is_wp_error($resized)){
1978
- @unlink($fileinfo['filepath']);
1979
- @unlink($fileinfo['filepath_original']);
1980
- $return = array(
1981
- "error" => array("code" => $resized->get_error_code(), "message" => $resized->get_error_message()),
1982
- "id" => $fileinfo['basename'],
1983
- "tip" => "editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})"
1984
- );
1985
-
1986
- return $return;
1987
- }
1988
- }
1989
-
1990
- $saved = $editor->save($fileinfo['filepath']);
1991
- if(is_wp_error($saved)){
1992
- @unlink($fileinfo['filepath']);
1993
- @unlink($fileinfo['filepath_original']);
1994
- $return = array(
1995
- "error" => array("code" => $saved->get_error_code(), "message" => $saved->get_error_message()),
1996
- "id" => $fileinfo['basename'],
1997
- "tip" => 'editor->save->webimage'
1998
- );
1999
-
2000
- return $return;
2001
- }
2002
-
2003
- if(('JPG' == $extensions[ $size[2] ]) && !(extension_loaded('imagick') || class_exists("Imagick"))){
2004
- $this->copy_exif($fileinfo['filepath_original'], $fileinfo['filepath']);
2005
- }
2006
- }
2007
-
2008
- // Thumbnail
2009
- $editor->set_quality($thumbimg['quality']);
2010
- if($thumbimg['resize']){
2011
- $ed_size = $editor->get_size();
2012
- $ed_ratio = $ed_size['width'] / $ed_size['height'];
2013
- if(1 > $ed_ratio){
2014
- $resized = $editor->resize($thumbimg['width'], 0, $thumbimg['crop']);
2015
- } else{
2016
- $resized = $editor->resize(0, $thumbimg['height'], $thumbimg['crop']);
2017
- }
2018
- if(is_wp_error($resized)){
2019
- @unlink($fileinfo['filepath']);
2020
- @unlink($fileinfo['filepath_original']);
2021
- $return = array(
2022
- "error" => array("code" => $resized->get_error_code(), "message" => $resized->get_error_message()),
2023
- "id" => $fileinfo['basename'],
2024
- "tip" => "editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})"
2025
- );
2026
-
2027
- return $return;
2028
- }
2029
- }
2030
-
2031
- $saved = $editor->save($fileinfo['filepath_thumb']);
2032
- if(is_wp_error($saved)){
2033
- @unlink($fileinfo['filepath']);
2034
- @unlink($fileinfo['filepath_original']);
2035
- $return = array(
2036
- "error" => array("code" => $saved->get_error_code(), "message" => $saved->get_error_message()),
2037
- "id" => $fileinfo['basename'],
2038
- "tip" => 'editor->save->thumb'
2039
- );
2040
-
2041
- return $return;
2042
- }
2043
-
2044
- } else{
2045
- copy($fileinfo['filepath'], $fileinfo['filepath_thumb']);
2046
- }
2047
- $is_webimage = true;
2048
- } else{
2049
- /*@unlink($fileinfo['filepath']);
2050
- $return = array("error" => array("code" => 104, "message" => __("Could not read image size. Invalid image was deleted.", 'grand-media')),
2051
- "id" => $fileinfo['basename_original']
2052
- );
2053
-
2054
- return $return;
2055
- */
2056
- }
2057
- }
2058
-
2059
- // Write media data to DB
2060
- $title = '';
2061
- $description = '';
2062
- $link = '';
2063
- $date = null;
2064
- if( !isset($post_data['set_title'])){
2065
- $post_data['set_title'] = 'filename';
2066
- }
2067
- if( !isset($post_data['set_status'])){
2068
- $post_data['set_status'] = isset($post_data['status'])? $post_data['status'] : 'inherit';
2069
- }
2070
-
2071
- $keywords = array();
2072
- // use image exif/iptc data for title and caption defaults if possible
2073
- if($size){
2074
- if( !empty($image_meta)){
2075
- if('exif' == $post_data['set_title']){
2076
- if( !empty($image_meta['title']) && trim($image_meta['title'])){
2077
- $title = $image_meta['title'];
2078
- }
2079
- }
2080
- if( !empty($image_meta['caption']) && trim($image_meta['caption'])){
2081
- $description = $image_meta['caption'];
2082
- }
2083
- if( !empty($image_meta['keywords'])){
2084
- $keywords = $image_meta['keywords'];
2085
- }
2086
- }
2087
- } else{
2088
- $file_meta = $this->get_file_metadata($fileinfo['filepath_original'], $fileinfo);
2089
- if( !empty($file_meta)){
2090
- if('exif' == $post_data['set_title']){
2091
- if( !empty($file_meta['title']) && trim($file_meta['title'])){
2092
- $title = $file_meta['title'];
2093
- }
2094
- }
2095
- if( !empty($file_meta['comment']) && trim($file_meta['comment'])){
2096
- $description = $file_meta['comment'];
2097
- }
2098
- if( !empty($file_meta['album']) && ( !isset($post_data['terms']['gmedia_album']) || empty($post_data['terms']['gmedia_album']))){
2099
- $post_data['terms']['gmedia_album'] = array($file_meta['album']);
2100
- }
2101
- }
2102
- }
2103
- if(('empty' != $post_data['set_title']) && empty($title)){
2104
- $title = $fileinfo['title'];
2105
- }
2106
-
2107
- if('public' == $post_data['set_status']){
2108
- $post_data['set_status'] = 'publish';
2109
- }
2110
-
2111
- $status = $post_data['set_status'];
2112
- if('inherit' == $post_data['set_status']){
2113
- $gmedia_album = isset($post_data['terms']['gmedia_album'])? $post_data['terms']['gmedia_album'] : false;
2114
- if($gmedia_album && $this->is_digit($gmedia_album)){
2115
- $album = $gmDB->get_term($gmedia_album);
2116
- if(empty($album) || is_wp_error($album)){
2117
- $status = 'publish';
2118
- } else{
2119
- $status = $album->status;
2120
- }
2121
- } else{
2122
- $status = 'publish';
2123
- }
2124
- }
2125
-
2126
- unset($post_data['gmuid'], $post_data['mime_type'], $post_data['set_title'], $post_data['set_status']);
2127
-
2128
- if(isset($post_data['terms']['gmedia_category']) && !empty($post_data['terms']['gmedia_category'])){
2129
- if( !is_array($post_data['terms']['gmedia_category'])){
2130
- $post_data['terms']['gmedia_category'] = explode(',', $post_data['terms']['gmedia_category']);
2131
- }
2132
- } else{
2133
- $post_data['terms']['gmedia_category'] = array();
2134
- }
2135
-
2136
- if(isset($post_data['terms']['gmedia_tag']) && !empty($post_data['terms']['gmedia_tag'])){
2137
- if( !is_array($post_data['terms']['gmedia_tag'])){
2138
- $post_data['terms']['gmedia_tag'] = explode(',', $post_data['terms']['gmedia_tag']);
2139
- }
2140
- } else{
2141
- $post_data['terms']['gmedia_tag'] = array();
2142
- }
2143
- if( !empty($keywords)){
2144
- $post_data['terms']['gmedia_tag'] = array_unique(array_merge($post_data['terms']['gmedia_tag'], $keywords));
2145
- }
2146
-
2147
- // Construct the media array
2148
- $media_data = array(
2149
- 'mime_type' => $fileinfo['mime_type'],
2150
- 'gmuid' => $fileinfo['basename'],
2151
- 'title' => $title,
2152
- 'link' => $link,
2153
- 'description' => $description,
2154
- 'status' => $status,
2155
- 'date' => $date
2156
- );
2157
-
2158
- $media_data = $this->array_replace_recursive($media_data, $post_data);
2159
-
2160
- if( !current_user_can('gmedia_delete_others_media')){
2161
- $media_data['author'] = get_current_user_id();
2162
- }
2163
-
2164
- // Save the data
2165
- $id = $gmDB->insert_gmedia($media_data);
2166
-
2167
- $media_metadata = $gmDB->generate_gmedia_metadata($id, $fileinfo);
2168
- if($size && !empty($image_meta)){
2169
- if(empty($media_metadata['image_meta'])){
2170
- $media_metadata['image_meta'] = $image_meta;
2171
- }
2172
- if( !empty($image_meta['created_timestamp'])){
2173
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_created_timestamp', $image_meta['created_timestamp']);
2174
- }
2175
- if( !empty($image_meta['GPS'])){
2176
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_gps', $image_meta['GPS']);
2177
- }
2178
- }
2179
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $media_metadata);
2180
- $hash_file = hash_file('md5', $fileinfo['filepath_original']);
2181
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_hash', $hash_file);
2182
- $file_size = filesize($fileinfo['filepath_original']);
2183
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_size', $file_size);
2184
- $return = array(
2185
- "success" => array("code" => 200, "message" => sprintf(__('File uploaded successful. Assigned ID: %s', 'grand-media'), $id)),
2186
- "id" => $fileinfo['basename']
2187
- );
2188
-
2189
- if((int) $gmGallery->options['delete_originals']){
2190
- @unlink($fileinfo['filepath_original']);
2191
- }
2192
-
2193
- return $return;
2194
- } else{
2195
- $return = array("success" => array("code" => 199, "message" => $chunk . '/' . $chunks), "id" => $fileinfo['basename']);
2196
-
2197
- return $return;
2198
- }
2199
- } else{
2200
- $return = array("error" => array("code" => 102, "message" => __("Failed to open output stream.", 'grand-media')), "id" => $fileinfo['basename']);
2201
-
2202
- return $return;
2203
- }
2204
- }
2205
-
2206
- /**
2207
- * @param $from_file
2208
- * @param $to_file
2209
- */
2210
- function copy_exif($from_file, $to_file){
2211
-
2212
- $size = @getimagesize($to_file);
2213
-
2214
- if($size){
2215
- require_once(dirname(__FILE__) . '/pel/autoload.php');
2216
- try {
2217
- Pel::setJPEGQuality(100);
2218
- /*
2219
  * We want the raw JPEG data from $scaled. Luckily, one can create a
2220
  * PelJpeg object from an image resource directly:
2221
  */
2222
- $input_jpeg = new PelJpeg($from_file);
2223
- /* Retrieve the original Exif data in $jpeg (if any). */
2224
- $input_exif = $input_jpeg->getExif();
2225
- /* If no Exif data was present, then $input_exif is null. */
2226
- if($input_exif != null){
2227
-
2228
- $input_tiff = $input_exif->getTiff();
2229
- if($input_tiff == null){
2230
- return;
2231
- }
2232
- $input_ifd0 = $input_tiff->getIfd();
2233
- if($input_ifd0 == null){
2234
- return;
2235
- }
2236
-
2237
- $input_exif_ifd = $input_ifd0->getSubIfd(PelIfd::EXIF);
2238
- $input_inter_ifd = $input_ifd0->getSubIfd(PelIfd::INTEROPERABILITY);
2239
-
2240
- $orientation = $input_ifd0->getEntry(PelTag::ORIENTATION);
2241
- if($orientation != null){
2242
- $orientation->setValue(1);
2243
- }
2244
-
2245
- if( !empty($input_ifd0)){
2246
- /*$x_resolution = $input_ifd0->getEntry( PelTag::X_RESOLUTION );
2247
  $y_resolution = $input_ifd0->getEntry( PelTag::Y_RESOLUTION );
2248
  if ( $x_resolution != null && $y_resolution != null ) {
2249
  //$x_res = $x_resolution->getValue();
@@ -2252,1777 +1986,2051 @@ class GmediaCore {
2252
  $y_resolution->setValue( $x_res );
2253
  }*/
2254
 
2255
- $image_width = $input_ifd0->getEntry(PelTag::IMAGE_WIDTH);
2256
- $image_length = $input_ifd0->getEntry(PelTag::IMAGE_LENGTH);
2257
- if($image_width != null && $image_length != null){
2258
- $image_width->setValue($size[0]);
2259
- $image_length->setValue($size[1]);
2260
- }
2261
- }
2262
- if( !empty($input_exif_ifd)){
2263
- $x_dimention = $input_exif_ifd->getEntry(PelTag::PIXEL_X_DIMENSION);
2264
- $y_dimention = $input_exif_ifd->getEntry(PelTag::PIXEL_Y_DIMENSION);
2265
- if($x_dimention != null && $y_dimention != null){
2266
- $x_dimention->setValue($size[0]);
2267
- $y_dimention->setValue($size[1]);
2268
- }
2269
- }
2270
- if( !empty($input_inter_ifd)){
2271
- $rel_image_width = $input_inter_ifd->getEntry(PelTag::RELATED_IMAGE_WIDTH);
2272
- $rel_image_length = $input_inter_ifd->getEntry(PelTag::RELATED_IMAGE_LENGTH);
2273
- if($rel_image_width != null && $rel_image_length != null){
2274
- $rel_image_width->setValue($size[0]);
2275
- $rel_image_length->setValue($size[1]);
2276
- }
2277
- }
2278
-
2279
- $output_jpeg = new PelJpeg($to_file);
2280
- $output_jpeg->setExif($input_exif);
2281
-
2282
- /* We can now save the image with input_exif. */
2283
- $output_jpeg->saveFile($to_file);
2284
- }
2285
- } catch(PelException $e){
2286
- }
2287
- }
2288
- }
2289
-
2290
-
2291
- /**
2292
- * @param $files
2293
- * @param $_terms
2294
- * @param $move
2295
- * @param int|string $exists
2296
- */
2297
- function gmedia_import_files($files, $_terms, $move, $exists = 0){
2298
- global $wpdb, $gmGallery, $gmDB;
2299
-
2300
- if(ob_get_level() == 0){
2301
- ob_start();
2302
- }
2303
- $eol = '</pre>' . PHP_EOL;
2304
-
2305
- $gmedia_album = isset($_terms['gmedia_album'])? $_terms['gmedia_album'] : false;
2306
- if($gmedia_album && $this->is_digit($gmedia_album)){
2307
- $album = $gmDB->get_term($gmedia_album);
2308
- if(empty($album) || is_wp_error($album)){
2309
- $_status = 'publish';
2310
- } else{
2311
- $_status = $album->status;
2312
- $album_name = $album->name;
2313
- }
2314
- } else{
2315
- $_status = 'publish';
2316
- }
2317
-
2318
- if(isset($_terms['gmedia_album']) && !empty($_terms['gmedia_album'])){
2319
- if(is_array($_terms['gmedia_album'])){
2320
- $_terms['gmedia_album'] = trim(reset($_terms['gmedia_album']));
2321
- }
2322
- } else{
2323
- $_terms['gmedia_album'] = '';
2324
- }
2325
- if(isset($_terms['gmedia_category']) && !empty($_terms['gmedia_category'])){
2326
- if( !is_array($_terms['gmedia_category'])){
2327
- $_terms['gmedia_category'] = array_filter(array_map('trim', explode(',', $_terms['gmedia_category'])));
2328
- }
2329
- } else{
2330
- $_terms['gmedia_category'] = array();
2331
- }
2332
- if(isset($_terms['gmedia_tag']) && !empty($_terms['gmedia_tag'])){
2333
- if( !is_array($_terms['gmedia_tag'])){
2334
- $_terms['gmedia_tag'] = array_filter(array_map('trim', explode(',', $_terms['gmedia_tag'])));
2335
- }
2336
- } else{
2337
- $_terms['gmedia_tag'] = array();
2338
- }
2339
-
2340
- $c = count($files);
2341
- $i = 0;
2342
- foreach($files as $file){
2343
-
2344
- $title = '';
2345
- $description = '';
2346
- $link = '';
2347
- $status = $_status;
2348
- $terms = $_terms;
2349
-
2350
- if(is_array($file)){
2351
- if(isset($file['file'])){
2352
- extract($file);
2353
- } else{
2354
- _e('Something went wrong...', 'grand-media');
2355
- die();
2356
- }
2357
- }
2358
-
2359
- wp_ob_end_flush_all();
2360
- flush();
2361
-
2362
- $i ++;
2363
- $prefix = "\n<pre>$i/$c - ";
2364
- $prefix_ko = "\n<pre class='ko'>$i/$c - ";
2365
-
2366
- if( !is_file($file)){
2367
- echo $prefix_ko . sprintf(__('File not exists: %s', 'grand-media'), $file) . $eol;
2368
- continue;
2369
- }
2370
-
2371
- if('skip' === $exists){
2372
- $file_suffix = false;
2373
- } else{
2374
- $file_suffix = $exists;
2375
- }
2376
- $fileinfo = $this->fileinfo($file, $file_suffix);
2377
-
2378
- if(('skip' === $exists) && is_file($fileinfo['filepath'])){
2379
- echo $prefix . $fileinfo['basename_original'] . ': ' . __('file with the same name already exists', 'grand-media') . $eol;
2380
- continue;
2381
- }
2382
-
2383
-
2384
- // try to make grand-media dir if not exists
2385
- if( !wp_mkdir_p($fileinfo['dirpath'])){
2386
- echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath']) . $eol;
2387
- continue;
2388
- }
2389
- // Check if grand-media dir is writable
2390
- if( !is_writable($fileinfo['dirpath'])){
2391
- @chmod($fileinfo['dirpath'], 0755);
2392
- if( !is_writable($fileinfo['dirpath'])){
2393
- echo $prefix_ko . sprintf(__('Directory `%s` or its subfolders are not writable by the server.', 'grand-media'), dirname($fileinfo['dirpath'])) . $eol;
2394
- continue;
2395
- }
2396
- }
2397
-
2398
- if(($file != $fileinfo['filepath']) && !copy($file, $fileinfo['filepath'])){
2399
- echo $prefix_ko . sprintf(__("Can't copy file from `%s` to `%s`", 'grand-media'), $file, $fileinfo['filepath']) . $eol;
2400
- continue;
2401
- }
2402
-
2403
- $this->file_chmod($fileinfo['filepath']);
2404
-
2405
- $hash_file = hash_file('md5', $fileinfo['filepath']);
2406
- $duplicate_id = $wpdb->get_var($wpdb->prepare("SELECT gmedia_id FROM {$wpdb->prefix}gmedia_meta WHERE meta_key = '_hash' AND meta_value = %s LIMIT 1;", $hash_file));
2407
- if($duplicate_id){
2408
- @unlink($fileinfo['filepath']);
2409
- echo $prefix_ko . $fileinfo['basename_original'] . ": " . sprintf(__("Seems like it is duplicate of file with ID #%d", 'grand-media'), $duplicate_id) . $eol;
2410
- continue;
2411
- }
2412
-
2413
- $size = false;
2414
- $is_webimage = false;
2415
- if('image' == $fileinfo['dirname']){
2416
- /** WordPress Image Administration API */
2417
- require_once(ABSPATH . 'wp-admin/includes/image.php');
2418
-
2419
- $size = @getimagesize($fileinfo['filepath']);
2420
- if($size && file_is_displayable_image($fileinfo['filepath'])){
2421
- $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP');
2422
- if(function_exists('memory_get_usage')){
2423
- switch($extensions[ $size[2] ]){
2424
- case 'GIF':
2425
- $CHANNEL = 1;
2426
- break;
2427
- case 'JPG':
2428
- $CHANNEL = $size['channels'];
2429
- break;
2430
- case 'PNG':
2431
- $CHANNEL = 3;
2432
- break;
2433
- case 'BMP':
2434
- default:
2435
- $CHANNEL = 6;
2436
- break;
2437
- }
2438
- $MB = 1048576; // number of bytes in 1M
2439
- $K64 = 65536; // number of bytes in 64K
2440
- $TWEAKFACTOR = 1.8; // Or whatever works for you
2441
- $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR);
2442
- $memoryNeeded = memory_get_usage() + $memoryNeeded;
2443
- $current_limit = @ini_get('memory_limit');
2444
- $current_limit_int = intval($current_limit);
2445
- if(false !== strpos($current_limit, 'M')){
2446
- $current_limit_int *= $MB;
2447
- }
2448
- if(false !== strpos($current_limit, 'G')){
2449
- $current_limit_int *= 1024;
2450
- }
2451
-
2452
- if(- 1 != $current_limit && $memoryNeeded > $current_limit_int){
2453
- $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB);
2454
- if($newLimit < 256){
2455
- $newLimit = 256;
2456
- }
2457
- @ini_set('memory_limit', $newLimit . 'M');
2458
- }
2459
- }
2460
-
2461
- if( !wp_mkdir_p($fileinfo['dirpath_thumb'])){
2462
- echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_thumb']) . $eol;
2463
- continue;
2464
- }
2465
- if( !is_writable($fileinfo['dirpath_thumb'])){
2466
- @chmod($fileinfo['dirpath_thumb'], 0755);
2467
- if( !is_writable($fileinfo['dirpath_thumb'])){
2468
- @unlink($fileinfo['filepath']);
2469
- echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'grand-media'), $fileinfo['dirpath_thumb']) . $eol;
2470
- continue;
2471
- }
2472
- }
2473
- if( !wp_mkdir_p($fileinfo['dirpath_original'])){
2474
- echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_original']) . $eol;
2475
- continue;
2476
- }
2477
- if( !is_writable($fileinfo['dirpath_original'])){
2478
- @chmod($fileinfo['dirpath_original'], 0755);
2479
- if( !is_writable($fileinfo['dirpath_original'])){
2480
- @unlink($fileinfo['filepath']);
2481
- echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'grand-media'), $fileinfo['dirpath_original']) . $eol;
2482
- continue;
2483
- }
2484
- }
2485
-
2486
- // Optimized image
2487
- $webimg = $gmGallery->options['image'];
2488
- $thumbimg = $gmGallery->options['thumb'];
2489
-
2490
- $webimg['resize'] = (($webimg['width'] < $size[0]) || ($webimg['height'] < $size[1]))? true : false;
2491
-
2492
- if($webimg['resize']){
2493
- rename($fileinfo['filepath'], $fileinfo['filepath_original']);
2494
- } else{
2495
- copy($fileinfo['filepath'], $fileinfo['filepath_original']);
2496
- }
2497
-
2498
- $size_ratio = $size[0] / $size[1];
2499
-
2500
- $angle = 0;
2501
- $image_meta = @$this->wp_read_image_metadata($fileinfo['filepath_original']);
2502
- if( !empty($image_meta['orientation'])){
2503
- switch($image_meta['orientation']){
2504
- case 3:
2505
- $angle = 180;
2506
- break;
2507
- case 6:
2508
- $angle = 270;
2509
- $size_ratio = $size[1] / $size[0];
2510
- break;
2511
- case 8:
2512
- $angle = 90;
2513
- $size_ratio = $size[1] / $size[0];
2514
- break;
2515
- }
2516
- }
2517
-
2518
- $thumbimg['resize'] = (((1 >= $size_ratio) && ($thumbimg['width'] > $size[0])) || ((1 <= $size_ratio) && ($thumbimg['height'] > $size[1])))? false : true;
2519
-
2520
- if($webimg['resize'] || $thumbimg['resize'] || $angle){
2521
- $editor = wp_get_image_editor($fileinfo['filepath_original']);
2522
- if(is_wp_error($editor)){
2523
- @unlink($fileinfo['filepath']);
2524
- @unlink($fileinfo['filepath_original']);
2525
- echo $prefix_ko . $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message() . $eol;
2526
- continue;
2527
- }
2528
-
2529
- if($angle){
2530
- $editor->rotate($angle);
2531
- }
2532
-
2533
- if($webimg['resize'] || $angle){
2534
- $editor->set_quality($webimg['quality']);
2535
-
2536
- if($webimg['resize']){
2537
- $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']);
2538
- if(is_wp_error($resized)){
2539
- @unlink($fileinfo['filepath']);
2540
- @unlink($fileinfo['filepath_original']);
2541
- echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message() . $eol;
2542
- continue;
2543
- }
2544
- }
2545
-
2546
- $saved = $editor->save($fileinfo['filepath']);
2547
- if(is_wp_error($saved)){
2548
- @unlink($fileinfo['filepath']);
2549
- @unlink($fileinfo['filepath_original']);
2550
- echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message() . $eol;
2551
- continue;
2552
- }
2553
-
2554
- if(('JPG' == $extensions[ $size[2] ]) && !(extension_loaded('imagick') || class_exists("Imagick"))){
2555
- $this->copy_exif($fileinfo['filepath_original'], $fileinfo['filepath']);
2556
- }
2557
-
2558
- }
2559
-
2560
- // Thumbnail
2561
- $editor->set_quality($thumbimg['quality']);
2562
- if($thumbimg['resize']){
2563
- $ed_size = $editor->get_size();
2564
- $ed_ratio = $ed_size['width'] / $ed_size['height'];
2565
- if(1 > $ed_ratio){
2566
- $resized = $editor->resize($thumbimg['width'], 0, $thumbimg['crop']);
2567
- } else{
2568
- $resized = $editor->resize(0, $thumbimg['height'], $thumbimg['crop']);
2569
- }
2570
- if(is_wp_error($resized)){
2571
- @unlink($fileinfo['filepath']);
2572
- @unlink($fileinfo['filepath_original']);
2573
- echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message() . $eol;
2574
- continue;
2575
- }
2576
- }
2577
-
2578
- $saved = $editor->save($fileinfo['filepath_thumb']);
2579
- if(is_wp_error($saved)){
2580
- @unlink($fileinfo['filepath']);
2581
- @unlink($fileinfo['filepath_original']);
2582
- echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message() . $eol;
2583
- continue;
2584
- }
2585
- } else{
2586
- copy($fileinfo['filepath'], $fileinfo['filepath_thumb']);
2587
- }
2588
- $is_webimage = true;
2589
- } else{
2590
- @unlink($fileinfo['filepath']);
2591
- echo $prefix_ko . $fileinfo['basename'] . ": " . __("Could not read image size. Invalid image was deleted.", 'grand-media') . $eol;
2592
- continue;
2593
- }
2594
- }
2595
-
2596
- // Write media data to DB
2597
- if($size){
2598
- if( !empty($image_meta)){
2599
- if(empty($title) && !empty($image_meta['title']) && trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))){
2600
- $title = $image_meta['title'];
2601
- }
2602
- if(empty($description) && !empty($image_meta['caption']) && trim($image_meta['caption'])){
2603
- $description = $image_meta['caption'];
2604
- }
2605
- if( !empty($image_meta['keywords'])){
2606
- $terms['gmedia_tag'] = array_unique(array_merge((array) $_terms['gmedia_tag'], $image_meta['keywords']));
2607
- }
2608
- }
2609
- } else{
2610
- $file_meta = $this->get_file_metadata($fileinfo['filepath_original'], $fileinfo);
2611
- if( !empty($file_meta)){
2612
- if(empty($title) && !empty($file_meta['title']) && trim($file_meta['title']) && !is_numeric(sanitize_title($file_meta['title']))){
2613
- $title = $file_meta['title'];
2614
- }
2615
- if(empty($description) && !empty($file_meta['comment']) && trim($file_meta['comment'])){
2616
- $description = $file_meta['comment'];
2617
- }
2618
- if(empty($terms['gmedia_album']) && !empty($file_meta['album'])){
2619
- $terms['gmedia_album'] = array($file_meta['album']);
2620
- }
2621
- }
2622
- }
2623
-
2624
- if(empty($title)){
2625
- $title = $fileinfo['title'];
2626
- }
2627
-
2628
- // Construct the media_data array
2629
- $media_data = array(
2630
- 'mime_type' => $fileinfo['mime_type'],
2631
- 'gmuid' => $fileinfo['basename'],
2632
- 'title' => $title,
2633
- 'link' => $link,
2634
- 'description' => $description,
2635
- 'status' => $status,
2636
- 'terms' => $terms
2637
- );
2638
-
2639
- if(!empty($file['auhtor'])){
2640
- $media_data['author'] = (int) $file['auhtor'];
2641
- } else if( !current_user_can('gmedia_delete_others_media')){
2642
- $media_data['author'] = get_current_user_id();
2643
- }
2644
-
2645
- // Save the data
2646
- $id = $gmDB->insert_gmedia($media_data);
2647
-
2648
- $media_metadata = $gmDB->generate_gmedia_metadata($id, $fileinfo);
2649
- if($size && !empty($image_meta)){
2650
- if(empty($media_metadata['image_meta'])){
2651
- $media_metadata['image_meta'] = $image_meta;
2652
- }
2653
- if( !empty($image_meta['created_timestamp'])){
2654
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_created_timestamp', $image_meta['created_timestamp']);
2655
- }
2656
- if( !empty($image_meta['GPS'])){
2657
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_gps', $image_meta['GPS']);
2658
- }
2659
- }
2660
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $media_metadata);
2661
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_hash', $hash_file);
2662
- $file_size = filesize($fileinfo['filepath_original']);
2663
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_size', $file_size);
2664
-
2665
- echo $prefix . $fileinfo['basename'] . ': <span class="ok">' . sprintf(__('success (ID #%s)', 'grand-media'), $id) . '</span>' . $eol;
2666
-
2667
- if((int) $gmGallery->options['delete_originals']){
2668
- @unlink($fileinfo['filepath_original']);
2669
- }
2670
- if($move){
2671
- @unlink($file);
2672
- }
2673
-
2674
- }
2675
-
2676
- echo '<p><b>' . __('Category') . ':</b> ' . (!empty($_terms['gmedia_category'])? esc_html(implode(', ', $_terms['gmedia_category'])) : '-') . PHP_EOL;
2677
- echo '<br /><b>' . __('Album') . ':</b> ' . (!empty($_terms['gmedia_album'])? (isset($album_name)? $album_name : esc_html($_terms['gmedia_album'])) : '-') . PHP_EOL;
2678
- echo '<br /><b>' . __('Tags') . ':</b> ' . (!empty($_terms['gmedia_tag'])? esc_html(implode(', ', $_terms['gmedia_tag'])) : '-') . '</p>' . PHP_EOL;
2679
-
2680
- wp_ob_end_flush_all();
2681
- flush();
2682
- }
2683
-
2684
- /**
2685
- * @param $gmid
2686
- */
2687
- function duplicate_gmedia($gmid){
2688
- global $gmDB;
2689
-
2690
- $gmedia = $gmDB->get_gmedia($gmid);
2691
- if( !$gmedia || is_wp_error($gmedia)){
2692
- return;
2693
- }
2694
-
2695
- $fileinfo = $this->fileinfo($gmedia->gmuid);
2696
-
2697
- if(is_file($fileinfo['dirpath_original'] . '/' . $gmedia->gmuid)){
2698
- $file = $fileinfo['dirpath_original'] . '/' . $gmedia->gmuid;
2699
- copy($file, $fileinfo['filepath_original']);
2700
- }
2701
-
2702
- if('image' == $fileinfo['dirname']){
2703
- copy($fileinfo['dirpath'] . '/' . $gmedia->gmuid, $fileinfo['filepath']);
2704
- copy($fileinfo['dirpath_thumb'] . '/' . $gmedia->gmuid, $fileinfo['filepath_thumb']);
2705
- }
2706
-
2707
- // Construct the media_data array
2708
- $media_data = array(
2709
- 'mime_type' => $fileinfo['mime_type'],
2710
- 'gmuid' => $fileinfo['basename'],
2711
- 'title' => $gmedia->title,
2712
- 'link' => $gmedia->link,
2713
- 'description' => $gmedia->description,
2714
- 'status' => $gmedia->status,
2715
- 'terms' => array(
2716
- 'gmedia_album' => $gmDB->get_gmedia_terms($gmedia->ID, array('gmedia_album'), array('fields' => 'ids')),
2717
- 'gmedia_category' => $gmDB->get_gmedia_terms($gmedia->ID, array('gmedia_category'), array('fields' => 'ids')),
2718
- 'gmedia_tag' => $gmDB->get_gmedia_terms($gmedia->ID, array('gmedia_tag'), array('fields' => 'ids', 'order' => 'term_order'))
2719
- )
2720
- );
2721
-
2722
- $media_data['author'] = get_current_user_id();
2723
-
2724
- // Save the data
2725
- $id = $gmDB->insert_gmedia($media_data);
2726
-
2727
- $media_metadata = $gmDB->get_metadata('gmedia', $gmedia->ID);
2728
- foreach($media_metadata as $key => $values){
2729
- //if($this->is_protected_meta($key, 'gmedia')){
2730
- foreach($values as $val){
2731
- $gmDB->add_metadata($meta_type = 'gmedia', $id, $key, $val);
2732
- }
2733
- //}
2734
- }
2735
-
2736
- }
2737
-
2738
- /**
2739
- * @param $gmid
2740
- *
2741
- * @return array
2742
- */
2743
- function recreate_images_from_original($gmid){
2744
- global $gmDB, $gmGallery;
2745
-
2746
- $item = $gmDB->get_gmedia($gmid);
2747
- if( !empty($item)){
2748
-
2749
- $type = explode('/', $item->mime_type);
2750
- $type = $type[0];
2751
- if('image' !== $type){
2752
- $out = array('error' => $this->alert('danger', sprintf(__('#%d: Not image type', 'grand-media'), $item->ID)));
2753
-
2754
- return $out;
2755
- }
2756
-
2757
- $gmedia = array();
2758
- $fail = '';
2759
- $success = '';
2760
-
2761
- if((int) $item->author != get_current_user_id()){
2762
- if( !current_user_can('gmedia_edit_others_media')){
2763
- $out = array('error' => $this->alert('danger', __('You are not allowed to edit others media', 'grand-media')));
2764
-
2765
- return $out;
2766
- }
2767
- }
2768
- $meta = $gmDB->get_metadata('gmedia', $item->ID);
2769
- $metadata = $meta['_metadata'][0];
2770
- $gmedia['ID'] = $gmid;
2771
- $gmedia['date'] = $item->date;
2772
- $gmedia['modified'] = current_time('mysql');
2773
- $gmedia['author'] = $item->author;
2774
-
2775
- $webimg = $gmGallery->options['image'];
2776
- $thumbimg = $gmGallery->options['thumb'];
2777
-
2778
- $fileinfo = $this->fileinfo($item->gmuid, false);
2779
- $is_file_original = is_file($fileinfo['filepath_original']);
2780
- $filepath_original = $is_file_original? $fileinfo['filepath_original'] : (is_file($fileinfo['filepath'])? $fileinfo['filepath'] : null);
2781
- if( !$filepath_original){
2782
- $out = array('error' => $this->alert('danger', __('Original file does not exists', 'grand-media')));
2783
-
2784
- return $out;
2785
- }
2786
- $size = @getimagesize($filepath_original);
2787
-
2788
- do {
2789
- $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP');
2790
- if(function_exists('memory_get_usage')){
2791
- switch($extensions[ $size[2] ]){
2792
- case 'GIF':
2793
- $CHANNEL = 1;
2794
- break;
2795
- case 'JPG':
2796
- $CHANNEL = $size['channels'];
2797
- break;
2798
- case 'PNG':
2799
- $CHANNEL = 3;
2800
- break;
2801
- case 'BMP':
2802
- default:
2803
- $CHANNEL = 6;
2804
- break;
2805
- }
2806
- $MB = 1048576; // number of bytes in 1M
2807
- $K64 = 65536; // number of bytes in 64K
2808
- $TWEAKFACTOR = 1.8; // Or whatever works for you
2809
- $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR);
2810
- $memoryNeeded = memory_get_usage() + $memoryNeeded;
2811
- $current_limit = @ini_get('memory_limit');
2812
- $current_limit_int = intval($current_limit);
2813
- if(false !== strpos($current_limit, 'M')){
2814
- $current_limit_int *= $MB;
2815
- }
2816
- if(false !== strpos($current_limit, 'G')){
2817
- $current_limit_int *= 1024;
2818
- }
2819
-
2820
- if(- 1 != $current_limit && $memoryNeeded > $current_limit_int){
2821
- $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB);
2822
- if($newLimit < 256){
2823
- $newLimit = 256;
2824
- }
2825
- @ini_set('memory_limit', $newLimit . 'M');
2826
- }
2827
- }
2828
-
2829
- $size_ratio = $size[0] / $size[1];
2830
-
2831
- $angle = 0;
2832
- if($is_file_original){
2833
- $image_meta = @$this->wp_read_image_metadata($filepath_original);
2834
- if( !empty($image_meta['orientation'])){
2835
- switch($image_meta['orientation']){
2836
- case 3:
2837
- $angle = 180;
2838
- break;
2839
- case 6:
2840
- $angle = 270;
2841
- $size_ratio = $size[1] / $size[0];
2842
- break;
2843
- case 8:
2844
- $angle = 90;
2845
- $size_ratio = $size[1] / $size[0];
2846
- break;
2847
- }
2848
- }
2849
- $webimg['resize'] = (($webimg['width'] < $size[0]) || ($webimg['height'] < $size[1]))? true : false;
2850
- } else{
2851
- $webimg['resize'] = false;
2852
- }
2853
-
2854
- $thumbimg['resize'] = (((1 >= $size_ratio) && ($thumbimg['width'] > $size[0])) || ((1 <= $size_ratio) && ($thumbimg['height'] > $size[1])))? false : true;
2855
-
2856
- if($webimg['resize'] || $thumbimg['resize'] || $angle){
2857
-
2858
- $editor = wp_get_image_editor($filepath_original);
2859
- if(is_wp_error($editor)){
2860
- $fail = $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message();
2861
- break;
2862
- }
2863
-
2864
- if($is_file_original){
2865
- if($angle){
2866
- $editor->rotate($angle);
2867
- }
2868
-
2869
- if($webimg['resize'] || $angle){
2870
- // Web-image
2871
- $editor->set_quality($webimg['quality']);
2872
-
2873
- if($webimg['resize']){
2874
- $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']);
2875
- if(is_wp_error($resized)){
2876
- $fail = $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message();
2877
- break;
2878
- }
2879
- }
2880
-
2881
- $saved = $editor->save($fileinfo['filepath']);
2882
- if(is_wp_error($saved)){
2883
- $fail = $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message();
2884
- break;
2885
- }
2886
- if(('JPG' == $extensions[ $size[2] ]) && !(extension_loaded('imagick') || class_exists("Imagick"))){
2887
- $this->copy_exif($filepath_original, $fileinfo['filepath']);
2888
- }
2889
- } else{
2890
- @copy($filepath_original, $fileinfo['filepath']);
2891
- }
2892
- }
2893
-
2894
- // Thumbnail
2895
- $editor->set_quality($thumbimg['quality']);
2896
- if($thumbimg['resize']){
2897
- $ed_size = $editor->get_size();
2898
- $ed_ratio = $ed_size['width'] / $ed_size['height'];
2899
- if(1 > $ed_ratio){
2900
- $resized = $editor->resize($thumbimg['width'], 0, $thumbimg['crop']);
2901
- } else{
2902
- $resized = $editor->resize(0, $thumbimg['height'], $thumbimg['crop']);
2903
- }
2904
- if(is_wp_error($resized)){
2905
- $fail = $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message();
2906
- break;
2907
- }
2908
- }
2909
-
2910
- $saved = $editor->save($fileinfo['filepath_thumb']);
2911
- if(is_wp_error($saved)){
2912
- $fail = $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message();
2913
- break;
2914
- }
2915
-
2916
- } else{
2917
- if($is_file_original){
2918
- @copy($filepath_original, $fileinfo['filepath']);
2919
- }
2920
- @copy($filepath_original, $fileinfo['filepath_thumb']);
2921
- }
2922
-
2923
- $id = $gmDB->insert_gmedia($gmedia);
2924
-
2925
- $new_metadata = $gmDB->generate_gmedia_metadata($id, $fileinfo);
2926
- $metadata['thumb'] = $new_metadata['thumb'];
2927
- $metadata['web'] = $new_metadata['web'];
2928
- $metadata['original'] = $new_metadata['original'];
2929
-
2930
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $metadata);
2931
- $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_modified', 0);
2932
-
2933
- $success = sprintf(__('Image "%d" restored from backup and saved', 'grand-media'), $id);
2934
- } while(0);
2935
-
2936
- if(empty($fail)){
2937
- $out = array('msg' => $this->alert('info', $success), 'modified' => $gmedia['modified']);
2938
- } else{
2939
- $out = array('error' => $this->alert('danger', $fail));
2940
- }
2941
-
2942
- } else{
2943
- $out = array('error' => $this->alert('danger', sprintf(__('#%d: No image in database', 'grand-media'), $gmid)));
2944
- }
2945
-
2946
- return $out;
2947
- }
2948
-
2949
- /**
2950
- * @param string $service
2951
- *
2952
- * @return array|bool json
2953
- */
2954
- function app_service($service){
2955
- global $gmGallery, $gmDB, $wp_version;
2956
-
2957
- if(empty($_SERVER['HTTP_X_REAL_IP']) && ('127.0.0.1' == $_SERVER['REMOTE_ADDR'] || '::1' == $_SERVER['REMOTE_ADDR'])){
2958
- return false;
2959
- }
2960
- if( !current_user_can('manage_options')){
2961
- die('-1');
2962
- }
2963
- if( !$service){
2964
- die('0');
2965
- }
2966
-
2967
- $result = array();
2968
- $data = array();
2969
- $options = $gmGallery->options;
2970
-
2971
- if($service == 'app_deactivate'){
2972
- $options['mobile_app'] = 0;
2973
- }
2974
-
2975
- $data['site_email'] = get_option('admin_email');
2976
- if(in_array($service, array('app_updateinfo')) && !is_email($data['site_email'])){
2977
- $result['error'][] = __('Invalid email', 'grand-media');
2978
- } else{
2979
-
2980
- $url = home_url();
2981
- $post_data = array('url' => $url);
2982
-
2983
- if(in_array($service, array('app_deactivateplugin', 'app_uninstallplugin'))){
2984
- if( !empty($options['site_ID'])){
2985
- $post_data['site_id'] = $options['site_ID'];
2986
- wp_remote_post('https://gmediaservice.codeasily.com/?gmService=' . $service, array(
2987
- 'method' => 'POST',
2988
- 'timeout' => 5,
2989
- 'blocking' => false,
2990
- 'sslverify' => false,
2991
- 'body' => $post_data,
2992
-
2993
- ));
2994
- }
2995
-
2996
- return false;
2997
- }
2998
-
2999
- $hash = 'gmedia_' . wp_generate_password('6', false);
3000
-
3001
- if(in_array($service, array('app_activate', 'app_updateinfo'))){
3002
- $status = 1;
3003
- } else{
3004
- $status = $options['mobile_app'];
3005
- }
3006
- $install_date = get_option('gmediaInstallDate');
3007
-
3008
- $data['service'] = $service;
3009
- $data['site_hash'] = $hash;
3010
- $data['site_ID'] = $options['site_ID'];
3011
- $data['title'] = get_bloginfo('name');
3012
- $data['description'] = get_bloginfo('description');
3013
- $data['url'] = $url;
3014
- $data['license'] = $options['license_key'];
3015
- $data['status'] = $status;
3016
- $data['install_date'] = (int)$install_date;
3017
- $data['counters'] = $gmDB->count_gmedia();
3018
- $data['php_version'] = phpversion();
3019
- $data['wp_version'] = $wp_version;
3020
- $data['gmedia_version'] = GMEDIA_VERSION;
3021
- $data['locale'] = get_locale();
3022
-
3023
- $theme = wp_get_theme();
3024
- $data['theme'] = array(
3025
- 'name' => $theme->get('Name'),
3026
- 'version' => $theme->get('Version'),
3027
- 'theme_uri' => $theme->get('ThemeURI')
3028
- );
3029
-
3030
- if ( ! function_exists( 'get_plugins' ) ) {
3031
- require_once ABSPATH . 'wp-admin/includes/plugin.php';
3032
- }
3033
- $active_plugins = get_option('active_plugins');
3034
- $plugins = get_plugins();
3035
- $data['plugins'] = array();
3036
- foreach($active_plugins as $p){
3037
- if(isset($plugins[ $p ])){
3038
- $data['plugins'][ $p ] = array(
3039
- 'name' => $plugins[ $p ]['Name'],
3040
- 'version' => $plugins[ $p ]['Version'],
3041
- 'plugin_uri' => $plugins[ $p ]['PluginURI']
3042
- );
3043
- }
3044
- }
3045
-
3046
- $tagslist = $gmDB->get_terms('gmedia_tag', array(
3047
- 'hide_empty' => true,
3048
- 'fields' => 'names_count',
3049
- 'orderby' => 'count',
3050
- 'order' => 'DESC',
3051
- 'no_found_rows' => true
3052
- ));
3053
- $data['tags'] = array();
3054
- if( !is_wp_error($tagslist)){
3055
- foreach($tagslist as $tag){
3056
- if($tag['count'] < 10){
3057
- break;
3058
- }
3059
- $data['tags'][] = $tag['name'];
3060
- }
3061
- }
3062
-
3063
- set_transient($hash, $data, 45);
3064
-
3065
- $post_data['hash'] = $hash;
3066
- $gms_post = wp_remote_post('https://gmediaservice.codeasily.com/?gmService=' . $service, array(
3067
- 'method' => 'POST',
3068
- 'timeout' => 45,
3069
- //'blocking' => false,
3070
- 'sslverify' => false,
3071
- 'body' => $post_data
3072
- ));
3073
- if(is_wp_error($gms_post)){
3074
- $result['error'][] = $gms_post->get_error_message();
3075
- }
3076
- $gms_post_body = wp_remote_retrieve_body($gms_post);
3077
- $_result = (array) json_decode($gms_post_body);
3078
- if(isset($_result['error'])){
3079
- if( !isset($result['error'])){
3080
- $result['error'] = array();
3081
- }
3082
- $_result['error'] = (array) $_result['error'];
3083
- $_result['error'] = array_filter($_result['error'], 'is_string');
3084
- $result['error'] = array_merge($result['error'], $_result['error']);
3085
- } else{
3086
- $result = array_merge($_result, $result);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3087
  // $result['gms_the_data'] = $data;
3088
  // $result['gms_post'] = $gms_post;
3089
  // $result['gms_post_body'] = $gms_post_body;
3090
- if(isset($result['message'])){
3091
- $result['message'] = $this->alert('info', $result['message']);
3092
- }
3093
-
3094
- if(isset($result['site_ID'])){
3095
- $options['site_ID'] = $result['site_ID'];
3096
- }
3097
- if(isset($result['mobile_app'])){
3098
- $options['mobile_app'] = $result['mobile_app'];
3099
- }
3100
- }
3101
- if(isset($result['error'])){
3102
- $result['error'] = $this->alert('danger', $result['error']);
3103
- }
3104
- }
3105
- update_option('gmediaOptions', $options);
3106
-
3107
- if(in_array($service, array('app_activate', 'app_updateinfo'))){
3108
- wp_clear_scheduled_hook('gmedia_app_cronjob');
3109
- wp_schedule_event(time(), 'gmedia_app', 'gmedia_app_cronjob');
3110
- }
3111
-
3112
- return $result;
3113
- }
3114
-
3115
- /**
3116
- * @param null $modules
3117
- */
3118
- function modules_update($modules = null){
3119
- $wp_installing = (bool) (defined('WP_INSTALLING') && WP_INSTALLING);
3120
- if($wp_installing){
3121
- return;
3122
- }
3123
-
3124
- if( !is_array($modules)){
3125
- $modules = get_gmedia_modules();
3126
- }
3127
- if(isset($modules['error'])){
3128
- return;
3129
- }
3130
-
3131
- global $gmGallery;
3132
- $modules_update_count = 0;
3133
-
3134
- foreach($modules['in'] as $module){
3135
- if( !empty($module['update']) && 'remote' != $module['place']){
3136
- $modules_update_count ++;
3137
- }
3138
- }
3139
-
3140
- $gmGallery->options = get_option('gmediaOptions');
3141
- $gmGallery->options['modules_update'] = $modules_update_count;
3142
- $gmGallery->options['modules_new'] = isset($modules['out'])? count($modules['out']) : 0;
3143
-
3144
- update_option('gmediaOptions', $gmGallery->options);
3145
- }
3146
-
3147
- /**
3148
- * @param $key
3149
- *
3150
- * @return mixed
3151
- */
3152
- function i18n_exif_name($key){
3153
- $_key = strtolower($key);
3154
- $tagnames = array(
3155
- 'aperture' => __('Aperture', 'grand-media'),
3156
- 'credit' => __('Credit', 'grand-media'),
3157
- 'camera' => __('Camera', 'grand-media'),
3158
- 'model' => __('Camera', 'grand-media'),
3159
- 'lens' => __('Lens', 'grand-media'),
3160
- 'lensmake' => __('Lens Make', 'grand-media'),
3161
- 'caption' => __('Caption', 'grand-media'),
3162
- 'date' => __('Date/Time', 'grand-media'),
3163
- 'created_timestamp' => __('Timestamp', 'grand-media'),
3164
- 'created_date' => __('Date Created', 'grand-media'),
3165
- 'created_time' => __('Time Created', 'grand-media'),
3166
- 'copyright' => __('Copyright', 'grand-media'),
3167
- 'focallength' => __('Focal length', 'grand-media'),
3168
- 'focallength35' => __('Focal length in 35mm Film', 'grand-media'),
3169
- 'iso' => __('ISO', 'grand-media'),
3170
- 'exposure' => __('Exposure Time', 'grand-media'),
3171
- 'shutter_speed' => __('Shutter speed', 'grand-media'),
3172
- 'title' => __('Title', 'grand-media'),
3173
- 'author' => __('Author', 'grand-media'),
3174
- 'tags' => __('Tags', 'grand-media'),
3175
- 'subject' => __('Subject', 'grand-media'),
3176
- 'make' => __('Make', 'grand-media'),
3177
- 'status' => __('Edit Status', 'grand-media'),
3178
- 'category' => __('Category', 'grand-media'),
3179
- 'keywords' => __('Keywords', 'grand-media'),
3180
- 'position' => __('Author Position', 'grand-media'),
3181
- 'GPS' => __('GPS', 'grand-media'),
3182
- 'lat' => __('Latitude', 'grand-media'),
3183
- 'lng' => __('Longtitude', 'grand-media'),
3184
- 'city' => __('City', 'grand-media'),
3185
- 'location' => __('Location', 'grand-media'),
3186
- 'state' => __('Province/State', 'grand-media'),
3187
- 'country_code' => __('Country code', 'grand-media'),
3188
- 'country' => __('Country', 'grand-media'),
3189
- 'headline' => __('Headline', 'grand-media'),
3190
- 'source' => __('Source', 'grand-media'),
3191
- 'contact' => __('Contact', 'grand-media'),
3192
- 'last_modfied' => __('Last modified', 'grand-media'),
3193
- 'tool' => __('Program tool', 'grand-media'),
3194
- 'software' => __('Software', 'grand-media'),
3195
- 'format' => __('Format', 'grand-media'),
3196
- 'width' => __('Width', 'grand-media'),
3197
- 'height' => __('Height', 'grand-media'),
3198
- 'flash' => __('Flash', 'grand-media'),
3199
- 'flashdata' => __('Flash', 'grand-media'),
3200
- 'orientation' => __('Orientation', 'grand-media')
3201
- );
3202
-
3203
- if(isset($tagnames[ $_key ])){
3204
- $key = $tagnames[ $_key ];
3205
- }
3206
-
3207
- return ($key);
3208
- }
3209
-
3210
- /**
3211
- * Determine whether a meta key is protected.
3212
- *
3213
- * @param string $meta_key Meta key
3214
- * @param string|null $meta_type
3215
- *
3216
- * @return bool True if the key is protected, false otherwise.
3217
- */
3218
- function is_protected_meta($meta_key, $meta_type = null){
3219
- $protected = ('_' == $meta_key[0]);
3220
-
3221
- return apply_filters('is_protected_gmedia_meta', $protected, $meta_key, $meta_type);
3222
- }
3223
-
3224
- /**
3225
- * Display custom fields form fields.
3226
- * @since 1.6.3
3227
- *
3228
- * @param int $gmedia_id
3229
- * @param string $meta_type
3230
- */
3231
- function gmedia_custom_meta_box($gmedia_id, $meta_type = 'gmedia'){
3232
- global $gmDB;
3233
-
3234
- if(empty($gmedia_id)){
3235
- return;
3236
- }
3237
-
3238
- if( !in_array($meta_type, array('gmedia', 'gmedia_term'))){
3239
- $meta_type = 'gmedia';
3240
- }
3241
- ?>
3242
- <fieldset id="gmediacustomstuff_<?php echo $gmedia_id; ?>" class="gmediacustomstuff" data-metatype="<?php echo $meta_type; ?>">
3243
- <legend class="label label-default" style="font-size:85%;"><?php _e('Custom Fields', 'grand-media'); ?></legend>
3244
- <?php
3245
- $metadata = $gmDB->has_meta($gmedia_id, $meta_type);
3246
- foreach($metadata as $key => $value){
3247
- if($this->is_protected_meta($metadata[ $key ]['meta_key'], $meta_type)){
3248
- unset($metadata[ $key ]);
3249
- }
3250
- } ?>
3251
- <div class="row">
3252
- <?php if( !empty($metadata)){
3253
- //$count = 0;
3254
- foreach($metadata as $entry){
3255
- echo $this->_list_meta_item($entry, $meta_type);
3256
- }
3257
- } ?>
3258
- </div>
3259
- <a href="#newCustomFieldModal" data-gmid="<?php echo $gmedia_id; ?>" class="newcustomfield-modal label label-primary"><?php _e('Add New Custom Field', 'grand-media') ?></a>
3260
- </fieldset>
3261
- <p><?php _e('Custom fields can be used to add extra metadata to a gmedia item that developer can use in their templates.'); ?></p>
3262
- <?php
3263
- }
3264
-
3265
- /**
3266
- * @since 1.6.3
3267
- *
3268
- * @param $entry
3269
- * @param string $meta_type
3270
- *
3271
- * @return string|void
3272
- */
3273
- function _list_meta_item($entry, $meta_type = 'gmedia'){
3274
- if(is_serialized($entry['meta_value'])){
3275
- if(is_serialized_string($entry['meta_value'])){
3276
- // This is a serialized string, so we should display it.
3277
- $entry['meta_value'] = maybe_unserialize($entry['meta_value']);
3278
- } else{
3279
- // This is a serialized array/object so we should NOT display it.
3280
- return;
3281
- }
3282
- }
3283
-
3284
- $entry['meta_key'] = esc_attr($entry['meta_key']);
3285
- $entry['meta_value'] = esc_textarea($entry['meta_value']); // using a <textarea />
3286
- $entry['meta_id'] = (int) $entry['meta_id'];
3287
-
3288
- $colsm = ('gmedia' == $meta_type)? 6 : 4;
3289
- //$delete_nonce = wp_create_nonce( 'gmedia_custom_field', '_wpnonce_custom_field' );
3290
- $item = '
3291
  <div class="form-group col-sm-' . $colsm . ' gm-custom-meta-' . $entry['meta_id'] . '">
3292
  <span class="delete-custom-field glyphicon glyphicon-remove pull-right text-danger"></span>
3293
  <label>' . $entry['meta_key'] . '</label>
3294
- <textarea name="meta[' . $entry['meta_id'] . ']" class="gmedia-custom-field gm-custom-field-' . $entry['meta_id'] . ' vert form-control input-sm" style="height:30px;" placeholder="' . __('Value', 'grand-media') . '" rows="1" cols="30">' . $entry['meta_value'] . '</textarea>
3295
  </div>
3296
  ';
3297
 
3298
- return $item;
3299
- }
3300
-
3301
- /**
3302
- * Prints the form in the Custom Fields meta box.
3303
- * @since 1.6.3
3304
- *
3305
- * @param string $meta_type
3306
- *
3307
- * @return string
3308
- */
3309
- function meta_form($meta_type = 'gmedia'){
3310
- global $wpdb;
3311
-
3312
- if( !in_array($meta_type, array('gmedia', 'gmedia_term'))){
3313
- $meta_type = 'gmedia';
3314
- }
3315
-
3316
- /**
3317
- * Filter the number of custom fields to retrieve for the drop-down
3318
- * in the Custom Fields meta box.
3319
- *
3320
- * @param int $limit Number of custom fields to retrieve. Default 30.
3321
- */
3322
- $limit = apply_filters('gmediameta_form_limit', 30);
3323
- $sql = "SELECT meta_key
 
3324
  FROM {$wpdb->prefix}{$meta_type}_meta
3325
  GROUP BY meta_key
3326
  HAVING meta_key NOT LIKE %s
3327
  ORDER BY meta_key
3328
  LIMIT %d";
3329
- $keys = $wpdb->get_col($wpdb->prepare($sql, addcslashes('_', '_%\\') . '%', $limit));
3330
 
3331
- $meta_form = '
3332
  <div id="newmeta" class="newmeta">
3333
  <div class="row">
3334
  <div class="form-group col-sm-6">
3335
- <label>' . _x('Name', 'meta name') . '</label>';
3336
- if($keys){
3337
- natcasesort($keys);
3338
- $meta_form .= '
3339
  <select class="metakeyselect form-control input-sm" name="metakeyselect">
3340
- <option value="">' . __('&mdash; Select &mdash;') . '</option>';
3341
- foreach($keys as $key){
3342
- if($this->is_protected_meta($key, $meta_type)){
3343
- continue;
3344
- }
3345
- $meta_form .= '
3346
- <option value="' . esc_attr($key) . '">' . esc_html($key) . '</option>';
3347
- }
3348
- $meta_form .= '
3349
  </select>
3350
  <input type="text" class="metakeyinput hide-if-js form-control input-sm" name="metakeyinput" value="" />
3351
  <a href="#gmediacustomstuff" class="hide-if-no-js gmediacustomstuff" onclick="jQuery(\'.metakeyinput, .metakeyselect, .enternew, .cancelnew\', \'#newmeta\').toggle();jQuery(this).parent().toggleClass(\'newcfield\');return false;">
3352
- <span class="enternew">' . __('Enter new', 'grand-media') . '</span>
3353
- <span class="cancelnew" style="display:none;">' . __('Cancel', 'grand-media') . '</span></a>';
3354
- } else{
3355
- $meta_form .= '
3356
  <input type="text" class="metakeyinput form-control input-sm" name="metakeyinput" value="" />';
3357
- }
3358
- $meta_form .= '
3359
  </div>
3360
  <div class="form-group col-sm-6">
3361
- <label>' . __('Value', 'grand-media') . '</label>
3362
  <textarea class="metavalue vert form-control input-sm" name="metavalue" rows="2" cols="25"></textarea>
3363
  </div>
3364
  </div>
3365
  </div>';
3366
 
3367
 
3368
- return $meta_form;
3369
- }
3370
 
3371
- /**
3372
- * @since 1.6.3
3373
- *
3374
- * @param int $gmedia_ID
3375
- * @param string $meta_type
3376
- *
3377
- * @return bool|int
3378
- */
3379
- function add_meta($gmedia_ID, $meta_type = 'gmedia'){
3380
- global $gmDB;
3381
-
3382
- if( !in_array($meta_type, array('gmedia', 'gmedia_term'))){
3383
- $meta_type = 'gmedia';
3384
- }
3385
-
3386
- $gmedia_ID = (int) $gmedia_ID;
3387
-
3388
- $metakeyselect = isset($_POST['metakeyselect'])? wp_unslash(trim($_POST['metakeyselect'])) : '';
3389
- $metakeyinput = isset($_POST['metakeyinput'])? wp_unslash(trim($_POST['metakeyinput'])) : '';
3390
- $metavalue = isset($_POST['metavalue'])? $_POST['metavalue'] : '';
3391
- if(is_string($metavalue)){
3392
- $metavalue = trim($metavalue);
3393
- }
3394
-
3395
- if(('0' === $metavalue || !empty ($metavalue)) && (( !empty($metakeyselect) && !empty($metakeyselect)) || !empty ($metakeyinput))){
3396
- /*
3397
  * We have a key/value pair. If both the select and the input
3398
  * for the key have data, the input takes precedence.
3399
  */
3400
- $metakey = $metakeyselect;
3401
-
3402
- if($metakeyinput){
3403
- $metakey = $metakeyinput;
3404
- } // default
3405
-
3406
- if($this->is_protected_meta($metakey, $meta_type)){
3407
- return false;
3408
- }
3409
-
3410
- $metakey = wp_slash($metakey);
3411
-
3412
- return $gmDB->add_metadata($meta_type, $gmedia_ID, $metakey, $metavalue);
3413
- }
3414
-
3415
- return false;
3416
- } // add_meta
3417
-
3418
- /** Get item Meta
3419
- *
3420
- * @param int|object $item
3421
- *
3422
- * @return array metadata[key] = array(name, value);
3423
- */
3424
- function metadata_info($item){
3425
- global $gmDB;
3426
-
3427
- if(is_object($item)){
3428
- $item_id = $item->ID;
3429
- } elseif($this->is_digit($item)){
3430
- $item_id = (int) $item;
3431
- } else{
3432
- return null;
3433
- }
3434
-
3435
- $metadata = array();
3436
-
3437
- $meta = $gmDB->get_metadata('gmedia', $item_id, '_metadata', true);
3438
- if($meta){
3439
- if(isset($meta['image_meta'])){
3440
- $metainfo = $meta['image_meta'];
3441
- } else{
3442
- $metainfo = $meta;
3443
- if(is_array($metainfo)){
3444
- unset($metainfo['web'], $metainfo['original'], $metainfo['thumb'], $metainfo['file']);
3445
- }
3446
- }
3447
-
3448
- if( !empty($metainfo)){
3449
- foreach($metainfo as $key => $value){
3450
- if(empty($value)){
3451
- continue;
3452
- }
3453
- $key_name = $this->i18n_exif_name($key);
3454
- $key_name = $this->mb_ucwords_utf8(str_replace('_', ' ', $key_name));
3455
- $value = $this->sanitize_meta_value($value);
3456
- $metadata[ $key ] = array('name' => $key_name, 'value' => $value);
3457
- }
3458
- }
3459
- }
3460
-
3461
- return $metadata;
3462
- }
3463
-
3464
- /**
3465
- * @param $value
3466
- *
3467
- * @return array
3468
- */
3469
- function sanitize_meta_value($value){
3470
- if(is_array($value) && (bool) count(array_filter(array_keys($value), 'is_string'))){
3471
- $value_return = array();
3472
- foreach($value as $key => $val){
3473
- if(empty($value)){
3474
- continue;
3475
- }
3476
- $key_name = $this->i18n_exif_name($key);
3477
- $key_name = $this->mb_ucwords_utf8(str_replace('_', ' ', $key_name));
3478
- if(is_array($val)){
3479
- $val = $this->sanitize_meta_value($val);
3480
- }
3481
- $value_return[ $key ] = array('name' => $key_name, 'value' => $val);
3482
- }
3483
- } else{
3484
- $value_return = $value;
3485
- }
3486
-
3487
- return $value_return;
3488
- }
3489
-
3490
- /** Get item Meta Text
3491
- *
3492
- * @param int $id
3493
- *
3494
- * @return string Meta text;
3495
- */
3496
- function metadata_text($id){
3497
- $metatext = '';
3498
- if(($metadata = $this->metadata_info($id))){
3499
- foreach($metadata as $meta){
3500
- if($meta['name'] == 'Image'){
3501
- continue;
3502
- }
3503
- $metatext .= "<b>{$meta['name']}:</b>";
3504
- if( !is_array($meta['value'])){
3505
- $metatext .= " {$meta['value']}\n";
3506
- } else{
3507
- $value = $meta['value'];
3508
- $this->meta_value_array_show($metatext, $value);
3509
- }
3510
- }
3511
- }
3512
-
3513
- return $metatext;
3514
- }
3515
-
3516
- /**
3517
- * @param $metatext
3518
- * @param $value
3519
- * @param int $pad
3520
- */
3521
- function meta_value_array_show(&$metatext, $value, $pad = 0){
3522
- if((bool) count(array_filter(array_keys($value), 'is_string'))){
3523
- $pad ++;
3524
- foreach($value as $val){
3525
- $metatext .= "\n" . str_pad('&nbsp;', $pad) . "- <b>{$val['name']}:</b> ";
3526
- if(is_array($val['value'])){
3527
- $this->meta_value_array_show($metatext, $val['value'], $pad);
3528
- } else{
3529
- $metatext .= $val['value'];
3530
- }
3531
- }
3532
- } else{
3533
- $metatext .= ' ' . implode(', ', $value);
3534
- }
3535
- $metatext .= "\n";
3536
- }
3537
-
3538
- /** Get [latitude, longtitude] coordinates from EXIF
3539
- *
3540
- * @param array $gps Exif[GPS] array
3541
- *
3542
- * @return array
3543
- */
3544
- function getGPSfromExif($gps){
3545
- $lat = $this->getGPS($gps['GPSLatitude'], $gps['GPSLatitudeRef']);
3546
- $lng = $this->getGPS($gps['GPSLongitude'], $gps['GPSLongitudeRef']);
3547
-
3548
- return array('lat' => round($lat, 4), 'lng' => round($lng, 4));
3549
- }
3550
-
3551
- /**
3552
- * @param $coordinate
3553
- * @param $hemisphere
3554
- *
3555
- * @return int
3556
- */
3557
- function getGPS($coordinate, $hemisphere){
3558
- for($i = 0; $i < 3; $i ++){
3559
- $part = explode('/', $coordinate[ $i ]);
3560
- if(count($part) == 1){
3561
- $coordinate[ $i ] = $part[0];
3562
- } else if(count($part) == 2){
3563
- $coordinate[ $i ] = floatval($part[0]) / floatval($part[1]);
3564
- } else{
3565
- $coordinate[ $i ] = 0;
3566
- }
3567
- }
3568
- list($degrees, $minutes, $seconds) = $coordinate;
3569
- $sign = ($hemisphere == 'W' || $hemisphere == 'S')? - 1 : 1;
3570
-
3571
- return $sign * ($degrees + $minutes / 60 + $seconds / 3600);
3572
- }
3573
-
3574
- /**
3575
- * Update media meta in the database
3576
- *
3577
- * @param $gmID
3578
- * @param $meta
3579
- *
3580
- * @return mixed
3581
- */
3582
- function gm_hitcounter($gmID, $meta){
3583
- /** @var wpdb $wpdb */
3584
- global $gmDB;
3585
-
3586
- $like = $this->_post('vote');
3587
- $like = $this->_post('like', $like);
3588
- if((int) $like == 1){
3589
- $meta['likes'] += 1;
3590
- $gmDB->update_metadata('gmedia', $gmID, 'likes', $meta['likes']);
3591
- do_action('gmedia_like', $gmID);
3592
- } else{
3593
- $meta['views'] += 1;
3594
- $gmDB->update_metadata('gmedia', $gmID, 'views', $meta['views']);
3595
- do_action('gmedia_view', $gmID);
3596
- }
3597
-
3598
- return $meta;
3599
- }
3600
-
3601
- /**
3602
- * Replace keys of an array based on a key map array
3603
- *
3604
- * @param $array
3605
- * @param $keymap
3606
- *
3607
- * @return array
3608
- * @throws Exception
3609
- */
3610
- function replace_array_keys(&$array, $keymap){
3611
- $replaced_keys = array();
3612
- $skipped = $keymap;
3613
- do {
3614
- $keymap = $skipped;
3615
- foreach($keymap as $new_key => $original_key){
3616
- if(isset($array[ $original_key ])){
3617
- if( !isset($array[ $new_key ]) || (isset($replaced_keys[ $new_key ]) && !isset($replaced_keys[ $original_key ]))){
3618
- $array[ $new_key ] = $array[ $original_key ];
3619
- unset($array[ $original_key ]);
3620
- $replaced_keys[ $original_key ] = $new_key;
3621
- unset($skipped[ $new_key ]);
3622
- } elseif(isset($array[ $new_key ]) && array_search($new_key, $keymap) === false){
3623
- throw new Exception('Trying to replace an array key with an already existing array key, without providing a new position for the existing array key in replace_array_keys().');
3624
- } elseif(isset($array[ $new_key ]) && $keymap[ $original_key ] == $new_key && !isset($replaced_keys[ $original_key ])){
3625
- //switch places.
3626
- $temp = $array[ $new_key ];
3627
- $array[ $new_key ] = $array[ $original_key ];
3628
- $array[ $original_key ] = $temp;
3629
- $replaced_keys[ $new_key ] = $original_key;
3630
- $replaced_keys[ $original_key ] = $new_key;
3631
- unset($skipped[ $new_key ]);
3632
- unset($skipped[ $original_key ]);
3633
- }
3634
- } else{
3635
- unset($skipped[ $new_key ]);
3636
- }
3637
- }
3638
- } while( !empty($skipped));
3639
-
3640
- return $replaced_keys;
3641
- }
3642
-
3643
- /**
3644
- * @return array Gmedia Capabilities
3645
- */
3646
- function plugin_capabilities(){
3647
- return array(
3648
- 'gmedia_library',
3649
- 'gmedia_show_others_media',
3650
- 'gmedia_edit_media',
3651
- 'gmedia_edit_others_media',
3652
- 'gmedia_delete_media',
3653
- 'gmedia_delete_others_media',
3654
- 'gmedia_upload',
3655
- 'gmedia_import',
3656
- 'gmedia_terms',
3657
- 'gmedia_album_manage',
3658
- 'gmedia_category_manage',
3659
- 'gmedia_tag_manage',
3660
- 'gmedia_terms_delete',
3661
- 'gmedia_gallery_manage',
3662
- 'gmedia_module_manage',
3663
- 'gmedia_settings'
3664
- );
3665
- }
3666
-
3667
- /**
3668
- * @return array Gmedia Capabilities
3669
- */
3670
- function modules_order(){
3671
- return array(
3672
- 'photoblog' => '',
3673
- 'cicerone' => '',
3674
- 'albumsListMasonry' => '',
3675
- 'albumsList' => '',
3676
- 'woowslider' => '',
3677
- 'albums-switcher' => '',
3678
- 'photocluster' => '',
3679
- 'albumsview' => '',
3680
- 'albumsgrid' => '',
3681
- 'phantom-pro' => '',
3682
- 'albums-stripes' => '',
3683
- 'cubik' => '',
3684
- 'desire' => '',
3685
- 'phototravlr' => '',
3686
- 'realslider' => '',
3687
- 'mosaic' => '',
3688
- 'photobox' => '',
3689
- 'amron' => '',
3690
- 'wavesurfer' => '',
3691
- 'flipgrid' => '',
3692
- 'phantom' => '',
3693
- 'cubik-lite' => '',
3694
- 'photomania' => '',
3695
- 'jq-mplayer' => '',
3696
- 'wp-videoplayer' => '',
3697
-
3698
- 'photo-pro' => '',
3699
- 'optima' => '',
3700
- 'afflux' => '',
3701
- 'slider' => '',
3702
- 'green-style' => '',
3703
- 'photo-blog' => '',
3704
- 'minima' => '',
3705
- 'sphere' => '',
3706
- 'cube' => '',
3707
- 'flatwall' => ''
3708
- );
3709
- }
3710
-
3711
- /**
3712
- * @param int|string $module
3713
- * @param string $set_module_callback
3714
- *
3715
- * @return array [module, settings]
3716
- */
3717
- function getModulePreset($module = '', $set_module_callback = ''){
3718
- global $gmDB, $gmGallery;
3719
-
3720
- if( !$set_module_callback){
3721
- $set_module_callback = 'amron';
3722
- }
3723
- if( !$module){
3724
- return $this->getModulePreset($gmGallery->options['default_gmedia_module'], $set_module_callback);
3725
- }
3726
-
3727
- if($this->is_digit($module)){
3728
- $preset = $gmDB->get_term($module);
3729
- if($preset && !is_wp_error($preset)){
3730
- $module = $preset->status;
3731
- $module_settings = array($module => (array) maybe_unserialize($preset->description));
3732
- $name = trim(str_replace('[' . $module . ']', '', $preset->name));
3733
- } else{
3734
- return $this->getModulePreset($set_module_callback);
3735
- }
3736
- } else{
3737
- $preset = $gmDB->get_term('[' . $module . ']', array('taxonomy' => 'gmedia_module', 'global' => '0'));
3738
- if($preset && !is_wp_error($preset)){
3739
- $module = $preset->status;
3740
- $module_settings = array($module => (array) maybe_unserialize($preset->description));
3741
- $name = __('Default Settings', 'grand-media');
3742
- } else{
3743
- $module_settings = array($module => array());
3744
- $name = $module;
3745
- }
3746
- }
3747
-
3748
- return array('module' => $module, 'settings' => $module_settings, 'name' => $name);
3749
- }
3750
-
3751
- /**
3752
- * Clear the caches!
3753
- */
3754
- function clear_cache(){
3755
- // Delete cache transients.
3756
- gmedia_delete_transients('gm_cache');
3757
-
3758
- // if W3 Total Cache is being used, clear the cache
3759
- if(function_exists('w3tc_pgcache_flush')){
3760
- w3tc_pgcache_flush();
3761
- } // if WP Super Cache is being used, clear the cache
3762
- else if(function_exists('wp_cache_clean_cache')){
3763
- global $file_prefix, $supercachedir;
3764
- if(empty($supercachedir) && function_exists('get_supercache_dir')){
3765
- $supercachedir = get_supercache_dir();
3766
- }
3767
- wp_cache_clean_cache($file_prefix);
3768
- } else if(class_exists('WpeCommon')){
3769
- //be extra careful, just in case 3rd party changes things on us
3770
- if(method_exists('WpeCommon', 'purge_memcached')){
3771
- WpeCommon::purge_memcached();
3772
- }
3773
- if(method_exists('WpeCommon', 'purge_memcached')){
3774
- WpeCommon::clear_maxcdn_cache();
3775
- }
3776
- if(method_exists('WpeCommon', 'purge_memcached')){
3777
- WpeCommon::purge_varnish_cache();
3778
- }
3779
- } else if(class_exists('WpFastestCache')){
3780
- global $wp_fastest_cache;
3781
- if(method_exists('WpFastestCache', 'deleteCache') && !empty($wp_fastest_cache)){
3782
- $wp_fastest_cache->deleteCache();
3783
- }
3784
- }
3785
- }
3786
-
3787
- /**
3788
- * Filter the gmedia terms (private and draft) for frontend and admin panel
3789
- *
3790
- * @param $terms
3791
- * @param $gmedia_id
3792
- * @param $taxonomy
3793
- *
3794
- * @return mixed
3795
- */
3796
- function get_the_gmedia_terms($terms, $gmedia_id, $taxonomy){
3797
- if('gmedia_album' === $taxonomy){
3798
- if( !is_user_logged_in()){
3799
- foreach($terms as $key => $term){
3800
- if('publish' !== $term->status){
3801
- unset($terms[ $key ]);
3802
- }
3803
- }
3804
- } else{
3805
- global $user_ID;
3806
- foreach($terms as $key => $term){
3807
- if('draft' === $term->status){
3808
- if( !is_admin() || ($user_ID != $term->global && !gm_user_can('edit_others_media'))){
3809
- unset($terms[ $key ]);
3810
- }
3811
- } elseif('private' === $term->status){
3812
- if($user_ID != $term->global && !gm_user_can('show_others_media')){
3813
- unset($terms[ $key ]);
3814
- }
3815
- }
3816
- }
3817
- }
3818
- }
3819
-
3820
- return $terms;
3821
- }
3822
-
3823
- /**
3824
- * mb_convert_encoding alternative function
3825
- *
3826
- * @param $string
3827
- *
3828
- * @return string
3829
- */
3830
- function mb_convert_encoding_utf8($string){
3831
- if(function_exists('mb_convert_encoding')){
3832
- $string = mb_convert_encoding($string, 'UTF-8', 'UTF-8');
3833
- } else{
3834
- $string = htmlspecialchars_decode(utf8_decode(htmlentities($string, ENT_COMPAT, 'utf-8', false)));
3835
- }
3836
-
3837
- return $string;
3838
- }
3839
-
3840
- /**
3841
- * mb_convert_case alternative function
3842
- *
3843
- * @param $string
3844
- *
3845
- * @return string
3846
- */
3847
- function mb_ucwords_utf8($string){
3848
- $string = $this->mb_convert_encoding_utf8($string);
3849
- $string = ucwords($string);
3850
-
3851
- return $string;
3852
- }
3853
-
3854
- /**
3855
- * Converts IDN in given url address to its ASCII form, also known as punycode, if possible.
3856
- * This function silently returns unmodified address if:
3857
- * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
3858
- * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
3859
- * or fails for any reason (e.g. domain has characters not allowed in an IDN)
3860
- * @see PHPMailer::$CharSet
3861
- *
3862
- * @param string $url The url to convert
3863
- *
3864
- * @return string The encoded url in ASCII form
3865
- */
3866
- public function punyencode($url){
3867
- $url_host = parse_url($url, PHP_URL_HOST);
3868
-
3869
- if((boolean) preg_match('/[\x80-\xFF]/', $url_host)){
3870
- $host = $this->mb_convert_encoding_utf8($url_host);
3871
- if(function_exists('idn_to_ascii')){
3872
- $options = 0;
3873
- if(($punycode = defined('INTL_IDNA_VARIANT_UTS46')? idn_to_ascii($host, $options, INTL_IDNA_VARIANT_UTS46) : idn_to_ascii($host)) !== false){
3874
- $new_url = str_replace($url_host, $punycode, $url);
3875
-
3876
- return $new_url;
3877
- }
3878
- }
3879
-
3880
- require_once(dirname(__FILE__) . '/punycode.php');
3881
- $gmPunycode = new gmPunycode();
3882
- $punycode = $gmPunycode->encode($host);
3883
- $new_url = str_replace($url_host, $punycode, $url);
3884
-
3885
- return $new_url;
3886
- }
3887
-
3888
- return $url;
3889
- }
3890
-
3891
- /**
3892
- * Sanitizes a hex color
3893
- *
3894
- * @param $color
3895
- * @param $def
3896
- *
3897
- * @return string
3898
- */
3899
- function sanitize_hex_color($color, $def = ''){
3900
- $hash = $color[0] === '#'? '#' : '';
3901
- $color = ltrim($color, '#');
3902
- if('' === $color){
3903
- return $def;
3904
- }
3905
-
3906
- // 3 or 6 hex digits, or the empty string.
3907
- if(preg_match('|^([A-Fa-f0-9]{3}){1,2}$|', $color)){
3908
- return $hash . $color;
3909
- }
3910
-
3911
- return $def;
3912
- }
3913
-
3914
- /**
3915
- * Convert a hex color to rgb
3916
- *
3917
- * @param $hex
3918
- *
3919
- * @return array [r ,g, b]
3920
- */
3921
- function hex2rgb($hex){
3922
- require_once(dirname(__FILE__) . '/color.php');
3923
-
3924
- $color = new gmColor($hex);
3925
- $rgb = $color->getRgb();
3926
-
3927
- return array($rgb['R'], $rgb['G'], $rgb['B']);
3928
- }
3929
-
3930
- /**
3931
- * Return gmColor class
3932
- *
3933
- * @param $hex
3934
- *
3935
- * @return object class
3936
- */
3937
- function color($hex = null){
3938
- require_once(dirname(__FILE__) . '/color.php');
3939
-
3940
- return new gmColor($hex);
3941
- }
3942
-
3943
- /**
3944
- * Log Views
3945
- *
3946
- * @param $id
3947
- */
3948
- function log_views_handler($id){
3949
- global $wpdb, $user_ID, $gmDB;
3950
-
3951
- $gmedia = $gmDB->get_gmedia($id);
3952
- if( !empty($gmedia->ID)){
3953
- $data = array(
3954
- 'log' => 'view',
3955
- 'ID' => $gmedia->ID,
3956
- 'log_author' => (int) $user_ID,
3957
- 'log_date' => current_time('mysql'),
3958
- 'log_data' => '1',
3959
- 'ip_address' => preg_replace('/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip())
3960
- );
3961
- $id = $wpdb->insert($wpdb->prefix . 'gmedia_log', $data);
3962
- }
3963
- }
3964
-
3965
- /**
3966
- * Log Likes
3967
- *
3968
- * @param $id
3969
- */
3970
- function log_likes_handler($id){
3971
- global $wpdb, $user_ID, $gmDB;
3972
-
3973
- $gmedia = $gmDB->get_gmedia($id);
3974
- if( !empty($gmedia->ID)){
3975
- $data = array(
3976
- 'log' => 'like',
3977
- 'ID' => $gmedia->ID,
3978
- 'log_author' => (int) $user_ID,
3979
- 'log_date' => current_time('mysql'),
3980
- 'log_data' => '1',
3981
- 'ip_address' => preg_replace('/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip())
3982
- );
3983
- $wpdb->insert($wpdb->prefix . 'gmedia_log', $data);
3984
- }
3985
- }
3986
-
3987
- /**
3988
- * Log Rating
3989
- *
3990
- * @param $id
3991
- * @param $val
3992
- */
3993
- function log_rates_handler($id, $val){
3994
- global $wpdb, $user_ID, $gmDB;
3995
-
3996
- $gmedia = $gmDB->get_gmedia($id);
3997
- if( !empty($gmedia->ID)){
3998
- $data = array(
3999
- 'log' => 'rate',
4000
- 'ID' => $gmedia->ID,
4001
- 'log_author' => (int) $user_ID,
4002
- 'log_date' => current_time('mysql'),
4003
- 'log_data' => $val,
4004
- 'ip_address' => preg_replace('/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip())
4005
- );
4006
- $wpdb->insert($wpdb->prefix . 'gmedia_log', $data);
4007
- }
4008
- }
4009
-
4010
- /**
4011
- * Get IP address
4012
- */
4013
- function ip(){
4014
- //Test if it is a shared client
4015
- if( !empty($_SERVER['HTTP_CLIENT_IP'])){
4016
- $ip = $_SERVER['HTTP_CLIENT_IP'];
4017
- //Is it a proxy address
4018
- } elseif( !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
4019
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
4020
- } else{
4021
- $ip = $_SERVER['REMOTE_ADDR'];
4022
- }
4023
-
4024
- return $ip;
4025
- }
4026
  }
4027
 
4028
  global $gmCore;
1
  <?php
2
+ if ( preg_match( '#' . basename( dirname( __FILE__ ) ) . '/' . basename( __FILE__ ) . '#', $_SERVER['PHP_SELF'] ) ) {
3
+ die( 'You are not allowed to call this page directly.' );
4
  }
5
 
6
  /**
8
  */
9
  class GmediaCore {
10
 
11
+ var $upload;
12
+ var $gmedia_url;
13
+ var $caps = array();
14
 
15
 
16
+ /**
17
+ *
18
+ */
19
+ function __construct() {
20
 
21
+ $this->upload = $this->gm_upload_dir();
22
+ $this->gmedia_url = plugins_url( GMEDIA_FOLDER );
23
 
24
+ add_action( 'init', array( &$this, 'user_capabilities' ), 8 );
25
+ add_action( 'init', array( &$this, 'init_actions' ), 20 );
26
 
27
+ add_action( 'clean_gmedia_cache', array( &$this, 'clear_cache' ) );
28
  // add_action( 'deleted_gmedia_term_relationships', array( &$this, 'clear_cache' ) );
29
  // add_action( 'added_gmedia_meta', array( &$this, 'clear_cache' ) );
30
  // add_action( 'added_gmedia_term_meta', array( &$this, 'clear_cache' ) );
32
  // add_action( 'updated_gmedia_term_meta', array( &$this, 'clear_cache' ) );
33
  // add_action( 'deleted_gmedia_meta', array( &$this, 'clear_cache' ) );
34
  // add_action( 'deleted_gmedia_term_meta', array( &$this, 'clear_cache' ) );
35
+ add_action( 'created_gmedia_term', array( &$this, 'clear_cache' ) );
36
+ add_action( 'edited_gmedia_term', array( &$this, 'clear_cache' ) );
37
+ add_action( 'deleted_gmedia_term', array( &$this, 'clear_cache' ) );
38
  // add_action( 'gmedia_clean_object_term_cache', array( &$this, 'clear_cache' ) );
39
 
40
+ add_filter( 'get_the_gmedia_terms', array( &$this, 'get_the_gmedia_terms' ), 10, 3 );
41
+ }
42
+
43
+ /**
44
+ * Get an array containing the gmedia upload directory's path and url.
45
+ * If the path couldn't be created, then an error will be returned with the key
46
+ * 'error' containing the error message. The error suggests that the parent
47
+ * directory is not writable by the server.
48
+ * On success, the returned array will have many indices:
49
+ * 'path' - base directory and sub directory or full path to upload directory.
50
+ * 'url' - base url and sub directory or absolute URL to upload directory.
51
+ * 'error' - set to false.
52
+ *
53
+ * @param bool $create
54
+ *
55
+ * @return array See above for description.
56
+ * @see wp_upload_dir()
57
+ * @uses apply_filters() Calls 'gm_upload_dir' on returned array.
58
+ *
59
+ */
60
+ function gm_upload_dir( $create = true ) {
61
+ $slash = '/';
62
+ // If multisite (and if not the main site)
63
+ if ( is_multisite() && ! is_main_site() ) {
64
+ $slash = '/blogs.dir/' . get_current_blog_id() . '/';
65
+ }
66
+
67
+ $dir = WP_CONTENT_DIR . $slash . GMEDIA_UPLOAD_FOLDER;
68
+ $url = WP_CONTENT_URL . $slash . GMEDIA_UPLOAD_FOLDER;
69
+
70
+ $url = set_url_scheme( $url );
71
+
72
+ $uploads = apply_filters( 'gm_upload_dir', array( 'path' => $dir, 'url' => $url, 'error' => false ) );
73
+
74
+ if ( $create ) {
75
+ // Make sure we have an uploads dir
76
+ if ( ! wp_mkdir_p( $uploads['path'] ) ) {
77
+ $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
78
+ $uploads['error'] = $message;
79
+ }
80
+ } elseif ( ! is_dir( $uploads['path'] ) ) {
81
+ $uploads['error'] = true;
82
+ }
83
+
84
+ return $uploads;
85
+ }
86
+
87
+ function user_capabilities() {
88
+ $capabilities = $this->plugin_capabilities();
89
+ $capabilities = apply_filters( 'gmedia_capabilities', $capabilities );
90
+ if ( is_multisite() && is_super_admin() ) {
91
+ foreach ( $capabilities as $cap ) {
92
+ $this->caps[ $cap ] = 1;
93
+ }
94
+ } else {
95
+ $curuser = wp_get_current_user();
96
+ foreach ( $capabilities as $cap ) {
97
+ if ( isset( $curuser->allcaps[ $cap ] ) && intval( $curuser->allcaps[ $cap ] ) ) {
98
+ $this->caps[ $cap ] = 1;
99
+ } else {
100
+ $this->caps[ $cap ] = 0;
101
+ }
102
+ }
103
+ }
104
+ }
105
+
106
+ /**
107
+ * @return array Gmedia Capabilities
108
+ */
109
+ function plugin_capabilities() {
110
+ return array(
111
+ 'gmedia_library',
112
+ 'gmedia_show_others_media',
113
+ 'gmedia_edit_media',
114
+ 'gmedia_edit_others_media',
115
+ 'gmedia_delete_media',
116
+ 'gmedia_delete_others_media',
117
+ 'gmedia_upload',
118
+ 'gmedia_import',
119
+ 'gmedia_terms',
120
+ 'gmedia_album_manage',
121
+ 'gmedia_category_manage',
122
+ 'gmedia_tag_manage',
123
+ 'gmedia_terms_delete',
124
+ 'gmedia_gallery_manage',
125
+ 'gmedia_module_manage',
126
+ 'gmedia_settings',
127
+ );
128
+ }
129
+
130
+ function init_actions() {
131
+ global $gmGallery;
132
+ if ( ! empty( $gmGallery->options['license_key'] ) && empty( $gmGallery->options['disable_logs'] ) ) {
133
+ add_action( 'gmedia_view', array( &$this, 'log_views_handler' ) );
134
+ add_action( 'gmedia_like', array( &$this, 'log_likes_handler' ) );
135
+ add_action( 'gmedia_rate', array( &$this, 'log_rates_handler' ), 10, 2 );
136
+ }
137
+ }
138
+
139
+ /**
140
+ * tooltip()
141
+ *
142
+ * @param string $style 'tooltip', 'popover'
143
+ * @param array $params
144
+ * @param bool $print
145
+ *
146
+ * @return string
147
+ */
148
+ function tooltip( $style, $params, $print = true ) {
149
+ $show_tip = 0; // TODO show tooltips checkbox in settings
150
+ if ( $show_tip ) {
151
+ $tooltip = " data-toggle='$style'";
152
+ if ( is_array( $params ) && ! empty( $params ) ) {
153
+ foreach ( $params as $key => $val ) {
154
+ $tooltip .= " data-$key='$val'";
155
+ }
156
+ }
157
+ if ( $print ) {
158
+ echo $tooltip;
159
+ } else {
160
+ return $tooltip;
161
+ }
162
+ }
163
+
164
+ return false;
165
+ }
166
+
167
+ /**
168
+ * @param array $add_args
169
+ * @param array $remove_args
170
+ * @param bool $uri
171
+ * @param array $preserve_args
172
+ *
173
+ * @return string
174
+ */
175
+ function get_admin_url( $add_args = array(), $remove_args = array(), $uri = false, $preserve_args = array() ) {
176
+ if ( true === $uri ) {
177
+ $uri = admin_url( 'admin.php' );
178
+ }
179
+ $remove_args = empty( $remove_args ) ? array() : (array) $remove_args;
180
+ $_wpnonce = array();
181
+ foreach ( $_GET as $key => $value ) {
182
+ if ( strpos( $key, '_wpnonce' ) !== false ) {
183
+ $_wpnonce[ $key ] = $value;
184
+ }
185
+ }
186
+ $remove_args = array_unique( array_merge( array( 'doing_wp_cron', '_wpnonce', 'do_gmedia', 'did_gmedia', 'do_gmedia_terms', 'did_gmedia_terms', 'ids' ), $_wpnonce, $remove_args, array_keys( $add_args ) ) );
187
+ $new_uri = remove_query_arg( $remove_args, $uri );
188
+ if ( ! empty( $preserve_args ) ) {
189
+ $_add_args = array();
190
+ foreach ( $preserve_args as $key ) {
191
+ if ( ( $value = $this->_get( $key ) ) !== false ) {
192
+ $_add_args[ $key ] = $value;
193
+ }
194
+ }
195
+ $new_uri = add_query_arg( $_add_args, $new_uri );
196
+ }
197
+ if ( ! empty( $add_args ) ) {
198
+ $new_uri = add_query_arg( $add_args, $new_uri );
199
+ }
200
+
201
+ return esc_url_raw( $new_uri );
202
+ }
203
+
204
+ /**
205
+ * Check GET data
206
+ *
207
+ * @param string $var
208
+ * @param mixed $def
209
+ * @param bool $empty2false
210
+ *
211
+ * @return mixed
212
+ */
213
+ function _get( $var, $def = false, $empty2false = false ) {
214
+ return isset( $_GET[ $var ] ) ? ( ( $empty2false && $this->is_empty( $_GET[ $var ] ) ) ? false : $_GET[ $var ] ) : $def;
215
+ }
216
+
217
+ /**
218
+ * Check empty strings
219
+ *
220
+ * @param string $var
221
+ *
222
+ * @return bool
223
+ */
224
+ function is_empty( $var ) {
225
+ return ! ( ! empty( $var ) && ! in_array( strtolower( $var ), array( 'null', 'false' ) ) );
226
+ }
227
+
228
+ /**
229
+ * @param $userAgent
230
+ *
231
+ * @return bool
232
+ */
233
+ function is_crawler( $userAgent ) {
234
+ $crawlers = 'Google|msnbot|Rambler|Yahoo|AbachoBOT|accoona|FeedBurner|' . 'AcioRobot|ASPSeek|CocoCrawler|Dumbot|FAST-WebCrawler|' . 'GeonaBot|Gigabot|Lycos|MSRBOT|Scooter|AltaVista|IDBot|eStyle|Scrubby|yandex|facebook';
235
+ $isCrawler = ( preg_match( "/$crawlers/i", $userAgent ) > 0 );
236
+
237
+ return $isCrawler;
238
+ }
239
+
240
+ /**
241
+ * @param $userAgent
242
+ *
243
+ * @return bool
244
+ */
245
+ function is_browser( $userAgent ) {
246
+ $browsers = 'opera|aol|msie|firefox|chrome|konqueror|safari|netscape|navigator|mosaic|lynx|amaya|omniweb|avant|camino|flock|seamonkey|mozilla|gecko';
247
+ $isBrowser = ( preg_match( "/$browsers/i", $userAgent ) > 0 );
248
+
249
+ return $isBrowser;
250
+ }
251
+
252
+ /**
253
+ * @param $path
254
+ *
255
+ * @return bool|null
256
+ */
257
+ function delete_folder( $path ) {
258
+ $path = rtrim( $path, '/' );
259
+ if ( is_file( $path ) ) {
260
+ return @unlink( $path );
261
+ } elseif ( is_dir( $path ) ) {
262
+ $files = glob( $path . '/*', GLOB_NOSORT );
263
+ if ( ! empty( $files ) && is_array( $files ) ) {
264
+ array_map( array( $this, 'delete_folder' ), $files );
265
+ }
266
+
267
+ return @rmdir( $path );
268
+ }
269
+
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * Get an HTML img element representing an image attachment
275
+ *
276
+ * @param int|object $item Image object.
277
+ * @param string $size Optional, default is empty string, could be 'thumb', 'web', 'original'
278
+ * @param bool $cover Optional, try to get cover url
279
+ * @param bool|string $default Optional, return if no cover and if $size != 'all'
280
+ *
281
+ * @return string|array img url for chosen size
282
+ * @uses apply_filters() Calls 'gm_get_attachment_image_attributes' hook on attributes array
283
+ *
284
+ * @see add_image_size()
285
+ * @see wp_get_attachment_image()
286
+ */
287
+ function gm_get_media_image( $item, $size = '', $cover = true, $default = false ) {
288
+ global $gmDB, $gmGallery;
289
+
290
+ if ( ! is_object( $item ) ) {
291
+ $item = $gmDB->get_gmedia( $item );
292
+ }
293
+ if ( ! $size ) {
294
+ $size = 'web';
295
+ }
296
+ if ( empty( $item ) ) {
297
+ $image = $default ? $default : $this->gmedia_url . '/admin/assets/img/default.png';
298
+ $images = apply_filters( 'gm_get_media_image', array(
299
+ 'thumb' => $image,
300
+ 'web' => $image,
301
+ 'original' => $image,
302
+ ) );
303
+ if ( 'all' == $size ) {
304
+ return $images;
305
+ } else {
306
+ return $images[ $size ];
307
+ }
308
+ }
309
+ $type = explode( '/', $item->mime_type );
310
+ $img_cover = false;
311
+ if ( 'image' == $type[0] ) {
312
+ $images = array(
313
+ 'thumb' => "{$this->upload['url']}/{$gmGallery->options['folder']['image_thumb']}/{$item->gmuid}",
314
+ 'web' => "{$this->upload['url']}/{$gmGallery->options['folder']['image']}/{$item->gmuid}",
315
+ 'original' => "{$this->upload['url']}/{$gmGallery->options['folder']['image_original']}/{$item->gmuid}",
316
+ );
317
+ if ( 'original' !== $size ) {
318
+ $thumb_path = "{$this->upload['path']}/{$gmGallery->options['folder']['image_thumb']}/{$item->gmuid}";
319
+ if ( ! is_file( $thumb_path ) ) {
320
+ $img_cover = true;
321
+ }
322
+ }
323
+ if ( 'all' == $size || 'original' == $size ) {
324
+ $original_path = "{$this->upload['path']}/{$gmGallery->options['folder']['image_original']}/{$item->gmuid}";
325
+ if ( ! is_file( $original_path ) ) {
326
+ $images['original'] = $images['web'];
327
+ }
328
+ }
329
+ }
330
+ if ( 'image' != $type[0] || $img_cover ) {
331
+ $ext = ltrim( strrchr( $item->gmuid, '.' ), '.' );
332
+ if ( ! $type = wp_ext2type( $ext ) ) {
333
+ $type = 'application';
334
+ }
335
+ $image = "{$this->gmedia_url}/admin/assets/img/{$type}.png";
336
+ $images = array(
337
+ 'thumb' => $image,
338
+ 'web' => $image,
339
+ 'original' => $image,
340
+ 'icon' => false,
341
+ );
342
+
343
+ if ( $cover ) {
344
+ $cover = $gmDB->get_metadata( 'gmedia', $item->ID, '_cover', true );
345
+ if ( ! empty( $cover ) ) {
346
+ if ( $this->is_digit( $cover ) ) {
347
+ $images = $this->gm_get_media_image( (int) $cover, 'all', false );
348
+ $images['icon'] = $image;
349
+ }
350
+ } elseif ( $default !== false ) {
351
+ return $default;
352
+ } else {
353
+ $alb = $gmDB->get_gmedia_terms( array( $item->ID ), array( 'gmedia_album' ), array( 'fields' => 'ids' ) );
354
+ if ( ! empty( $alb ) ) {
355
+ $cover = $gmDB->get_metadata( 'gmedia_term', $alb[0], '_cover', true );
356
+ if ( ! empty( $cover ) ) {
357
+ if ( $this->is_digit( $cover ) ) {
358
+ $images = $this->gm_get_media_image( (int) $cover, 'all', false );
359
+ $images['icon'] = $image;
360
+ }
361
+ }
362
+ }
363
+ }
364
+ }
365
+ }
366
+
367
+ if ( 'all' == $size ) {
368
+ return $images;
369
+ } else {
370
+ return $images[ $size ];
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Check input for existing only of digits (numbers)
376
+ *
377
+ * @param $digit
378
+ *
379
+ * @return bool
380
+ */
381
+ function is_digit( $digit ) {
382
+ if ( is_int( $digit ) ) {
383
+ return true;
384
+ } elseif ( is_string( $digit ) && ! empty( $digit ) ) {
385
+ return ctype_digit( $digit );
386
+ } else {
387
+ // booleans, floats and others
388
+ return false;
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Get path and url to module folder
394
+ *
395
+ * @param string $module_name
396
+ *
397
+ * @return array|bool Return array( 'path', 'url' ) OR false if no module
398
+ */
399
+ function get_module_path( $module_name ) {
400
+ global $gmGallery;
401
+ if ( empty( $module_name ) ) {
402
+ return false;
403
+ }
404
+ $module_dirs = array(
405
+ 'upload' => array(
406
+ 'name' => $module_name,
407
+ 'path' => $this->upload['path'] . '/' . $gmGallery->options['folder']['module'] . '/' . $module_name,
408
+ 'url' => $this->upload['url'] . '/' . $gmGallery->options['folder']['module'] . '/' . $module_name,
409
+ ),
410
+ 'plugin' => array(
411
+ 'name' => $module_name,
412
+ 'path' => GMEDIA_ABSPATH . 'module/' . $module_name,
413
+ 'url' => plugins_url( GMEDIA_FOLDER ) . '/module/' . $module_name,
414
+ ),
415
+ 'theme' => array(
416
+ 'name' => $module_name,
417
+ 'path' => get_template_directory() . '/gmedia-module/' . $module_name,
418
+ 'url' => get_template_directory_uri() . '/gmedia-module/' . $module_name,
419
+ ),
420
+ );
421
+ foreach ( $module_dirs as $dir ) {
422
+ if ( is_dir( $dir['path'] ) ) {
423
+ return $dir;
424
+ }
425
+ }
426
+
427
+ $getModulePreset = $this->getModulePreset();
428
+
429
+ if ( $module_name != $getModulePreset['module'] ) {
430
+ return $this->get_module_path( $getModulePreset['module'] );
431
+ }
432
+
433
+ return false;
434
+ }
435
+
436
+ /**
437
+ * @param int|string $module
438
+ * @param string $set_module_callback
439
+ *
440
+ * @return array [module, settings]
441
+ */
442
+ function getModulePreset( $module = '', $set_module_callback = '' ) {
443
+ global $gmDB, $gmGallery;
444
+
445
+ if ( ! $set_module_callback ) {
446
+ $set_module_callback = 'amron';
447
+ }
448
+ if ( ! $module ) {
449
+ return $this->getModulePreset( $gmGallery->options['default_gmedia_module'], $set_module_callback );
450
+ }
451
+
452
+ if ( $this->is_digit( $module ) ) {
453
+ $preset = $gmDB->get_term( $module );
454
+ if ( $preset && ! is_wp_error( $preset ) ) {
455
+ $module = $preset->status;
456
+ $module_settings = array( $module => (array) maybe_unserialize( $preset->description ) );
457
+ $name = trim( str_replace( '[' . $module . ']', '', $preset->name ) );
458
+ } else {
459
+ return $this->getModulePreset( $set_module_callback );
460
+ }
461
+ } else {
462
+ $preset = $gmDB->get_term( '[' . $module . ']', array( 'taxonomy' => 'gmedia_module', 'global' => '0' ) );
463
+ if ( $preset && ! is_wp_error( $preset ) ) {
464
+ $module = $preset->status;
465
+ $module_settings = array( $module => (array) maybe_unserialize( $preset->description ) );
466
+ $name = __( 'Default Settings', 'grand-media' );
467
+ } else {
468
+ $module_settings = array( $module => array() );
469
+ $name = $module;
470
+ }
471
+ }
472
+
473
+ return array( 'module' => $module, 'settings' => $module_settings, 'name' => $name );
474
+ }
475
+
476
+ /**
477
+ * Sanitize a string|array before using it with your database
478
+ *
479
+ * @param $input string|array
480
+ *
481
+ * @return mixed
482
+ */
483
+ function sanitize( $input ) {
484
+ $output = $input;
485
+ if ( is_array( $input ) ) {
486
+ foreach ( $input as $var => $val ) {
487
+ $output[ $var ] = $this->sanitize( $val );
488
+ }
489
+ } else {
490
+ /** @noinspection PhpDeprecationInspection */
491
+ if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
492
+ $input = stripslashes( $input );
493
+ }
494
+ $input = $this->clean_input( $input );
495
+ $output = esc_sql( $input );
496
+ }
497
+
498
+ return $output;
499
+ }
500
+
501
+ /**
502
+ * The most complete and efficient way to sanitize a string before using it with your database
503
+ *
504
+ * @param $input string
505
+ *
506
+ * @return mixed
507
+ */
508
+ function clean_input( $input ) {
509
+ $search = array(/*'@<[\/\!]*?[^<>]*?>@si'*/ /* Strip out HTML tags */
510
+ '@<script' . '[^>]*?>.*?</script>@si' /* Strip out javascript */,
511
+ '@<style' . '[^>]*?>.*?</style>@siU' /* Strip style tags properly */,
512
+ '@<![\s\S]*?--[ \t\n\r]*>@' /* Strip multi-line comments */
513
+ //,'/\s{3,}/'
514
+ );
515
+
516
+ $output = preg_replace( $search, '', $input );
517
+
518
+ return $output;
519
+ }
520
+
521
+ /**
522
+ * Check if user can select a author
523
+ *
524
+ * @return array
525
+ */
526
+ function get_editable_user_ids() {
527
+ if ( current_user_can( 'gmedia_show_others_media' ) || current_user_can( 'gmedia_edit_others_media' ) ) {
528
+ return get_users( array( 'fields' => 'ID' ) );
529
+ }
530
+
531
+ return get_current_user_id();
532
+ }
533
+
534
+ /**
535
+ * Generate GmediaCloud page url
536
+ *
537
+ * @param $id
538
+ * @param $type
539
+ * @param bool $default
540
+ *
541
+ * @return string
542
+ */
543
+ function gmcloudlink( $id, $type, $default = false ) {
544
+ $options = get_option( 'gmediaOptions' );
545
+ $endpoint = $options['endpoint'];
546
+ $hashid = gmedia_hash_id_encode( $id, $type );
547
+ $t = array(
548
+ 'gallery' => 'g',
549
+ 'album' => 'a',
550
+ 'tag' => 't',
551
+ 'single' => 's',
552
+ 'category' => 'k',
553
+ 'author' => 'u',
554
+ );
555
+ if ( ! $default && get_option( 'permalink_structure' ) ) {
556
+ $cloud_link = home_url( urlencode( $endpoint ) . "/{$t[$type]}/{$hashid}" );
557
+ } else {
558
+ $cloud_link = add_query_arg( array( "$endpoint" => $hashid, 't' => $t[ $type ] ), home_url( 'index.php' ) );
559
+ }
560
+
561
+ return $cloud_link;
562
+ }
563
+
564
+ /**
565
+ * Extremely simple function to get human filesize
566
+ *
567
+ * @param $file
568
+ * @param int $decimals
569
+ *
570
+ * @return string
571
+ */
572
+ function filesize( $file, $decimals = 2 ) {
573
+ $bytes = filesize( $file );
574
+ $sz = array( 'b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb' );
575
+ $factor = (int) floor( ( strlen( $bytes ) - 1 ) / 3 );
576
+
577
+ return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . $sz[ $factor ];
578
+ }
579
+
580
+ /**
581
+ * @param array $arr1
582
+ * @param array $arr2
583
+ *
584
+ * @return array
585
+ * @version 1.0.0 (2013 03 19)
586
+ *
587
+ * @author Gajus Kuizinas <g.kuizinas@anuary.com>
588
+ */
589
+ function array_diff_key_recursive( array $arr1, array $arr2 ) {
590
+ $diff = array_diff_key( $arr1, $arr2 );
591
+ $intersect = array_intersect_key( $arr1, $arr2 );
592
+
593
+ foreach ( $intersect as $k => $v ) {
594
+ if ( is_array( $arr1[ $k ] ) && is_array( $arr2[ $k ] ) ) {
595
+ $d = $this->array_diff_key_recursive( $arr1[ $k ], $arr2[ $k ] );
596
+
597
+ if ( ! empty( $d ) ) {
598
+ $diff[ $k ] = $d;
599
+ }
600
+ }
601
+ }
602
+
603
+ return $diff;
604
+ }
605
+
606
+ /**
607
+ * @param array $arr1
608
+ * @param array $arr2
609
+ * @param bool $update
610
+ *
611
+ * @return array
612
+ */
613
+ function array_diff_keyval_recursive( array $arr1, array $arr2, $update = false ) {
614
+ $diff = array_diff_key( $arr1, $arr2 );
615
+ $intersect = array_intersect_key( $arr1, $arr2 );
616
+
617
+ foreach ( $intersect as $k => $v ) {
618
+ if ( is_array( $arr1[ $k ] ) && is_array( $arr2[ $k ] ) ) {
619
+ $d = $this->array_diff_keyval_recursive( $arr1[ $k ], $arr2[ $k ], $update );
620
+
621
+ if ( ! empty( $d ) ) {
622
+ $diff[ $k ] = $d;
623
+ }
624
+ } elseif ( $arr1[ $k ] !== $arr2[ $k ] ) {
625
+ if ( $update ) {
626
+ $diff[ $k ] = $arr2[ $k ];
627
+ } else {
628
+ $diff[ $k ] = $arr1[ $k ];
629
+ }
630
+ }
631
+ }
632
+
633
+ return $diff;
634
+ }
635
+
636
+ /**
637
+ * @param $callback
638
+ * @param $array
639
+ *
640
+ * @return mixed
641
+ */
642
+ function array_map_recursive( $callback, $array ) {
643
+ foreach ( $array as $key => $value ) {
644
+ if ( is_array( $array[ $key ] ) ) {
645
+ $array[ $key ] = $this->array_map_recursive( $callback, $array[ $key ] );
646
+ } else {
647
+ $array[ $key ] = call_user_func( $callback, $array[ $key ] );
648
+ }
649
+ }
650
+
651
+ return $array;
652
+ }
653
+
654
+ /**
655
+ * @param $photo
656
+ *
657
+ * @return array|bool
658
+ */
659
+ function process_gmedit_image( $photo ) {
660
+ $type = null;
661
+ if ( preg_match( '/^data:image\/(jpg|jpeg|png|gif)/i', $photo, $matches ) ) {
662
+ $type = $matches[1];
663
+ } else {
664
+ return false;
665
+ }
666
+ // Remove the mime-type header
667
+ $data = explode( 'base64,', $photo );
668
+ $data = array_reverse( $data );
669
+ $data = reset( $data );
670
+
671
+ // Use strict mode to prevent characters from outside the base64 range
672
+ $image = base64_decode( $data, true );
673
+
674
+ if ( ! $image ) {
675
+ return false;
676
+ }
677
+
678
+ return array(
679
+ 'data' => $image,
680
+ 'type' => $type,
681
+ );
682
+ }
683
+
684
+ /**
685
+ * @return bool
686
+ */
687
+ function is_bot() {
688
+ if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
689
+ return false;
690
+ }
691
+
692
+ $spiders = array(
693
+ "abot",
694
+ "dbot",
695
+ "ebot",
696
+ "hbot",
697
+ "kbot",
698
+ "lbot",
699
+ "mbot",
700
+ "nbot",
701
+ "obot",
702
+ "pbot",
703
+ "rbot",
704
+ "sbot",
705
+ "tbot",
706
+ "vbot",
707
+ "ybot",
708
+ "zbot",
709
+ "bot.",
710
+ "bot/",
711
+ "_bot",
712
+ ".bot",
713
+ "/bot",
714
+ "-bot",
715
+ ":bot",
716
+ "(bot",
717
+ "crawl",
718
+ "slurp",
719
+ "spider",
720
+ "seek",
721
+ "accoona",
722
+ "acoon",
723
+ "adressendeutschland",
724
+ "ah-ha.com",
725
+ "ahoy",
726
+ "altavista",
727
+ "ananzi",
728
+ "anthill",
729
+ "appie",
730
+ "arachnophilia",
731
+ "arale",
732
+ "araneo",
733
+ "aranha",
734
+ "architext",
735
+ "aretha",
736
+ "arks",
737
+ "asterias",
738
+ "atlocal",
739
+ "atn",
740
+ "atomz",
741
+ "augurfind",
742
+ "backrub",
743
+ "bannana_bot",
744
+ "baypup",
745
+ "bdfetch",
746
+ "big brother",
747
+ "biglotron",
748
+ "bjaaland",
749
+ "blackwidow",
750
+ "blaiz",
751
+ "blog",
752
+ "blo.",
753
+ "bloodhound",
754
+ "boitho",
755
+ "booch",
756
+ "bradley",
757
+ "butterfly",
758
+ "calif",
759
+ "cassandra",
760
+ "ccubee",
761
+ "cfetch",
762
+ "charlotte",
763
+ "churl",
764
+ "cienciaficcion",
765
+ "cmc",
766
+ "collective",
767
+ "comagent",
768
+ "combine",
769
+ "computingsite",
770
+ "csci",
771
+ "curl",
772
+ "cusco",
773
+ "daumoa",
774
+ "deepindex",
775
+ "delorie",
776
+ "depspid",
777
+ "deweb",
778
+ "die blinde kuh",
779
+ "digger",
780
+ "ditto",
781
+ "dmoz",
782
+ "docomo",
783
+ "download express",
784
+ "dtaagent",
785
+ "dwcp",
786
+ "ebiness",
787
+ "ebingbong",
788
+ "e-collector",
789
+ "ejupiter",
790
+ "emacs-w3 search engine",
791
+ "esther",
792
+ "evliya celebi",
793
+ "ezresult",
794
+ "falcon",
795
+ "felix ide",
796
+ "ferret",
797
+ "fetchrover",
798
+ "fido",
799
+ "findlinks",
800
+ "fireball",
801
+ "fish search",
802
+ "fouineur",
803
+ "funnelweb",
804
+ "gazz",
805
+ "gcreep",
806
+ "genieknows",
807
+ "getterroboplus",
808
+ "geturl",
809
+ "glx",
810
+ "goforit",
811
+ "golem",
812
+ "grabber",
813
+ "grapnel",
814
+ "gralon",
815
+ "griffon",
816
+ "gromit",
817
+ "grub",
818
+ "gulliver",
819
+ "hamahakki",
820
+ "harvest",
821
+ "havindex",
822
+ "helix",
823
+ "heritrix",
824
+ "hku www octopus",
825
+ "homerweb",
826
+ "htdig",
827
+ "html index",
828
+ "html_analyzer",
829
+ "htmlgobble",
830
+ "hubater",
831
+ "hyper-decontextualizer",
832
+ "ia_archiver",
833
+ "ibm_planetwide",
834
+ "ichiro",
835
+ "iconsurf",
836
+ "iltrovatore",
837
+ "image.kapsi.net",
838
+ "imagelock",
839
+ "incywincy",
840
+ "indexer",
841
+ "infobee",
842
+ "informant",
843
+ "ingrid",
844
+ "inktomisearch.com",
845
+ "inspector web",
846
+ "intelliagent",
847
+ "internet shinchakubin",
848
+ "ip3000",
849
+ "iron33",
850
+ "israeli-search",
851
+ "ivia",
852
+ "jack",
853
+ "jakarta",
854
+ "javabee",
855
+ "jetbot",
856
+ "jumpstation",
857
+ "katipo",
858
+ "kdd-explorer",
859
+ "kilroy",
860
+ "knowledge",
861
+ "kototoi",
862
+ "kretrieve",
863
+ "labelgrabber",
864
+ "lachesis",
865
+ "larbin",
866
+ "legs",
867
+ "libwww",
868
+ "linkalarm",
869
+ "link validator",
870
+ "linkscan",
871
+ "lockon",
872
+ "lwp",
873
+ "lycos",
874
+ "magpie",
875
+ "mantraagent",
876
+ "mapoftheinternet",
877
+ "marvin/",
878
+ "mattie",
879
+ "mediafox",
880
+ "mediapartners",
881
+ "mercator",
882
+ "merzscope",
883
+ "microsoft url control",
884
+ "minirank",
885
+ "miva",
886
+ "mj12",
887
+ "mnogosearch",
888
+ "moget",
889
+ "monster",
890
+ "moose",
891
+ "motor",
892
+ "multitext",
893
+ "muncher",
894
+ "muscatferret",
895
+ "mwd.search",
896
+ "myweb",
897
+ "najdi",
898
+ "nameprotect",
899
+ "nationaldirectory",
900
+ "nazilla",
901
+ "ncsa beta",
902
+ "nec-meshexplorer",
903
+ "nederland.zoek",
904
+ "netcarta webmap engine",
905
+ "netmechanic",
906
+ "netresearchserver",
907
+ "netscoop",
908
+ "newscan-online",
909
+ "nhse",
910
+ "nokia6682/",
911
+ "nomad",
912
+ "noyona",
913
+ "nutch",
914
+ "nzexplorer",
915
+ "objectssearch",
916
+ "occam",
917
+ "omni",
918
+ "open text",
919
+ "openfind",
920
+ "openintelligencedata",
921
+ "orb search",
922
+ "osis-project",
923
+ "pack rat",
924
+ "pageboy",
925
+ "pagebull",
926
+ "page_verifier",
927
+ "panscient",
928
+ "parasite",
929
+ "partnersite",
930
+ "patric",
931
+ "pear.",
932
+ "pegasus",
933
+ "peregrinator",
934
+ "pgp key agent",
935
+ "phantom",
936
+ "phpdig",
937
+ "picosearch",
938
+ "piltdownman",
939
+ "pimptrain",
940
+ "pinpoint",
941
+ "pioneer",
942
+ "piranha",
943
+ "plumtreewebaccessor",
944
+ "pogodak",
945
+ "poirot",
946
+ "pompos",
947
+ "poppelsdorf",
948
+ "poppi",
949
+ "popular iconoclast",
950
+ "psycheclone",
951
+ "publisher",
952
+ "python",
953
+ "rambler",
954
+ "raven search",
955
+ "roach",
956
+ "road runner",
957
+ "roadhouse",
958
+ "robbie",
959
+ "robofox",
960
+ "robozilla",
961
+ "rules",
962
+ "salty",
963
+ "sbider",
964
+ "scooter",
965
+ "scoutjet",
966
+ "scrubby",
967
+ "search.",
968
+ "searchprocess",
969
+ "semanticdiscovery",
970
+ "senrigan",
971
+ "sg-scout",
972
+ "shai'hulud",
973
+ "shark",
974
+ "shopwiki",
975
+ "sidewinder",
976
+ "sift",
977
+ "silk",
978
+ "simmany",
979
+ "site searcher",
980
+ "site valet",
981
+ "sitetech-rover",
982
+ "skymob.com",
983
+ "sleek",
984
+ "smartwit",
985
+ "sna-",
986
+ "snappy",
987
+ "snooper",
988
+ "sohu",
989
+ "speedfind",
990
+ "sphere",
991
+ "sphider",
992
+ "spinner",
993
+ "spyder",
994
+ "steeler/",
995
+ "suke",
996
+ "suntek",
997
+ "supersnooper",
998
+ "surfnomore",
999
+ "sven",
1000
+ "sygol",
1001
+ "szukacz",
1002
+ "tach black widow",
1003
+ "tarantula",
1004
+ "templeton",
1005
+ "/teoma",
1006
+ "t-h-u-n-d-e-r-s-t-o-n-e",
1007
+ "theophrastus",
1008
+ "titan",
1009
+ "titin",
1010
+ "tkwww",
1011
+ "toutatis",
1012
+ "t-rex",
1013
+ "tutorgig",
1014
+ "twiceler",
1015
+ "twisted",
1016
+ "ucsd",
1017
+ "udmsearch",
1018
+ "url check",
1019
+ "updated",
1020
+ "vagabondo",
1021
+ "valkyrie",
1022
+ "verticrawl",
1023
+ "victoria",
1024
+ "vision-search",
1025
+ "volcano",
1026
+ "voyager/",
1027
+ "voyager-hc",
1028
+ "w3c_validator",
1029
+ "w3m2",
1030
+ "w3mir",
1031
+ "walker",
1032
+ "wallpaper",
1033
+ "wanderer",
1034
+ "wauuu",
1035
+ "wavefire",
1036
+ "web core",
1037
+ "web hopper",
1038
+ "web wombat",
1039
+ "webbandit",
1040
+ "webcatcher",
1041
+ "webcopy",
1042
+ "webfoot",
1043
+ "weblayers",
1044
+ "weblinker",
1045
+ "weblog monitor",
1046
+ "webmirror",
1047
+ "webmonkey",
1048
+ "webquest",
1049
+ "webreaper",
1050
+ "websitepulse",
1051
+ "websnarf",
1052
+ "webstolperer",
1053
+ "webvac",
1054
+ "webwalk",
1055
+ "webwatch",
1056
+ "webwombat",
1057
+ "webzinger",
1058
+ "wget",
1059
+ "whizbang",
1060
+ "whowhere",
1061
+ "wild ferret",
1062
+ "worldlight",
1063
+ "wwwc",
1064
+ "wwwster",
1065
+ "xenu",
1066
+ "xget",
1067
+ "xift",
1068
+ "xirq",
1069
+ "yandex",
1070
+ "yanga",
1071
+ "yeti",
1072
+ "yodao",
1073
+ "zao/",
1074
+ "zippp",
1075
+ "zyborg",
1076
+ "....",
1077
+ );
1078
+
1079
+ foreach ( $spiders as $spider ) {
1080
+ //If the spider text is found in the current user agent, then return true
1081
+ if ( stripos( $_SERVER['HTTP_USER_AGENT'], $spider ) !== false ) {
1082
+ return true;
1083
+ break;
1084
+ }
1085
+ }
1086
+
1087
+ return false;
1088
+ }
1089
+
1090
+ /** Write the file
1091
+ *
1092
+ * @param string $file_tmp
1093
+ * @param array $fileinfo
1094
+ * @param string $content_type
1095
+ * @param array $post_data
1096
+ *
1097
+ * @return array
1098
+ */
1099
+ function gmedia_upload_handler( $file_tmp, $fileinfo, $content_type, $post_data ) {
1100
+ global $gmGallery, $gmDB;
1101
+
1102
+ $cleanup_dir = true; // Remove old files
1103
+ $file_age = 5 * 3600; // Temp file age in seconds
1104
+ $chunk = (int) $this->_req( 'chunk', 0 );
1105
+ $chunks = (int) $this->_req( 'chunks', 0 );
1106
+
1107
+ // try to make grand-media dir if not exists
1108
+ if ( ! wp_mkdir_p( $fileinfo['dirpath'] ) ) {
1109
+ $return = array(
1110
+ "error" => array(
1111
+ "code" => 100,
1112
+ "message" => sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath'] ),
1113
+ ),
1114
+ "id" => $fileinfo['basename_original'],
1115
+ );
1116
+
1117
+ return $return;
1118
+ }
1119
+ // Check if grand-media dir is writable
1120
+ if ( ! is_writable( $fileinfo['dirpath'] ) ) {
1121
+ @chmod( $fileinfo['dirpath'], 0755 );
1122
+ if ( ! is_writable( $fileinfo['dirpath'] ) ) {
1123
+ $return = array(
1124
+ "error" => array(
1125
+ "code" => 100,
1126
+ "message" => sprintf( __( 'Directory %s or its subfolders are not writable by the server.', 'grand-media' ), dirname( $fileinfo['dirpath'] ) ),
1127
+ ),
1128
+ "id" => $fileinfo['basename_original'],
1129
+ );
1130
+
1131
+ return $return;
1132
+ }
1133
+ }
1134
+ // Remove old temp files
1135
+ if ( $cleanup_dir && is_dir( $fileinfo['dirpath'] ) && ( $_dir = opendir( $fileinfo['dirpath'] ) ) ) {
1136
+ while ( ( $_file = readdir( $_dir ) ) !== false ) {
1137
+ $tmpfilePath = $fileinfo['dirpath'] . DIRECTORY_SEPARATOR . $_file;
1138
+
1139
+ // Remove temp file if it is older than the max age and is not the current file
1140
+ if ( preg_match( '/\.part$/', $_file ) && ( filemtime( $tmpfilePath ) < time() - $file_age ) && ( $tmpfilePath != $fileinfo['filepath'] . '.part' ) ) {
1141
+ @unlink( $tmpfilePath );
1142
+ }
1143
+ }
1144
+
1145
+ closedir( $_dir );
1146
+ } else {
1147
+ $return = array(
1148
+ "error" => array( "code" => 100, "message" => sprintf( __( 'Failed to open directory: %s', 'grand-media' ), $fileinfo['dirpath'] ) ),
1149
+ "id" => $fileinfo['basename_original'],
1150
+ );
1151
+
1152
+ return $return;
1153
+ }
1154
+
1155
+ // Open temp file
1156
+ $out = fopen( $fileinfo['filepath'] . '.part', $chunk == 0 ? "wb" : "ab" );
1157
+ if ( $out ) {
1158
+ // Read binary input stream and append it to temp file
1159
+ $in = fopen( $file_tmp, "rb" );
1160
+
1161
+ if ( $in ) {
1162
+ while ( ( $buff = fread( $in, 4096 ) ) ) {
1163
+ fwrite( $out, $buff );
1164
+ }
1165
+ } else {
1166
+ $return = array( "error" => array( "code" => 101, "message" => __( "Failed to open input stream.", 'grand-media' ) ), "id" => $fileinfo['basename'] );
1167
+
1168
+ return $return;
1169
+ }
1170
+ fclose( $in );
1171
+ fclose( $out );
1172
+ if ( strpos( $content_type, "multipart" ) !== false ) {
1173
+ @unlink( $file_tmp );
1174
+ }
1175
+ if ( ! $chunks || $chunk == ( $chunks - 1 ) ) {
1176
+ sleep( 1 );
1177
+ // Strip the temp .part suffix off
1178
+ rename( $fileinfo['filepath'] . '.part', $fileinfo['filepath'] );
1179
+
1180
+ $this->file_chmod( $fileinfo['filepath'] );
1181
+
1182
+ $size = false;
1183
+ $is_webimage = false;
1184
+ if ( 'image' == $fileinfo['dirname'] ) {
1185
+ /** WordPress Image Administration API */
1186
+ require_once( ABSPATH . 'wp-admin/includes/image.php' );
1187
+
1188
+ $size = @getimagesize( $fileinfo['filepath'] );
1189
+ if ( $size && file_is_displayable_image( $fileinfo['filepath'] ) ) {
1190
+ $extensions = array( '1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP' );
1191
+ if ( function_exists( 'memory_get_usage' ) ) {
1192
+ switch ( $extensions[ $size[2] ] ) {
1193
+ case 'GIF':
1194
+ $CHANNEL = 1;
1195
+ break;
1196
+ case 'JPG':
1197
+ $CHANNEL = $size['channels'];
1198
+ break;
1199
+ case 'PNG':
1200
+ $CHANNEL = 3;
1201
+ break;
1202
+ case 'BMP':
1203
+ default:
1204
+ $CHANNEL = 6;
1205
+ break;
1206
+ }
1207
+ $MB = 1048576; // number of bytes in 1M
1208
+ $K64 = 65536; // number of bytes in 64K
1209
+ $TWEAKFACTOR = 1.8; // Or whatever works for you
1210
+ $memoryNeeded = round( ( $size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64 ) * $TWEAKFACTOR );
1211
+ $memoryNeeded = memory_get_usage() + $memoryNeeded;
1212
+ $current_limit = @ini_get( 'memory_limit' );
1213
+ $current_limit_int = intval( $current_limit );
1214
+ if ( false !== strpos( $current_limit, 'M' ) ) {
1215
+ $current_limit_int *= $MB;
1216
+ }
1217
+ if ( false !== strpos( $current_limit, 'G' ) ) {
1218
+ $current_limit_int *= 1024;
1219
+ }
1220
+
1221
+ if ( - 1 != $current_limit && $memoryNeeded > $current_limit_int ) {
1222
+ $newLimit = $current_limit_int / $MB + ceil( ( $memoryNeeded - $current_limit_int ) / $MB );
1223
+ if ( $newLimit < 256 ) {
1224
+ $newLimit = 256;
1225
+ }
1226
+ @ini_set( 'memory_limit', $newLimit . 'M' );
1227
+ }
1228
+ }
1229
+
1230
+ if ( ! wp_mkdir_p( $fileinfo['dirpath_thumb'] ) ) {
1231
+ $return = array(
1232
+ "error" => array(
1233
+ "code" => 100,
1234
+ "message" => sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath_thumb'] ),
1235
+ ),
1236
+ "id" => $fileinfo['basename'],
1237
+ );
1238
+
1239
+ return $return;
1240
+ }
1241
+ if ( ! is_writable( $fileinfo['dirpath_thumb'] ) ) {
1242
+ @chmod( $fileinfo['dirpath_thumb'], 0755 );
1243
+ if ( ! is_writable( $fileinfo['dirpath_thumb'] ) ) {
1244
+ @unlink( $fileinfo['filepath'] );
1245
+ $return = array(
1246
+ "error" => array(
1247
+ "code" => 100,
1248
+ "message" => sprintf( __( 'Directory %s is not writable by the server.', 'grand-media' ), $fileinfo['dirpath_thumb'] ),
1249
+ ),
1250
+ "id" => $fileinfo['basename'],
1251
+ );
1252
+
1253
+ return $return;
1254
+ }
1255
+ }
1256
+ if ( ! wp_mkdir_p( $fileinfo['dirpath_original'] ) ) {
1257
+ $return = array(
1258
+ "error" => array(
1259
+ "code" => 100,
1260
+ "message" => sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath_original'] ),
1261
+ ),
1262
+ "id" => $fileinfo['basename'],
1263
+ );
1264
+
1265
+ return $return;
1266
+ }
1267
+ if ( ! is_writable( $fileinfo['dirpath_original'] ) ) {
1268
+ @chmod( $fileinfo['dirpath_original'], 0755 );
1269
+ if ( ! is_writable( $fileinfo['dirpath_original'] ) ) {
1270
+ @unlink( $fileinfo['filepath'] );
1271
+ $return = array(
1272
+ "error" => array(
1273
+ "code" => 100,
1274
+ "message" => sprintf( __( 'Directory %s is not writable by the server.', 'grand-media' ), $fileinfo['dirpath_original'] ),
1275
+ ),
1276
+ "id" => $fileinfo['basename'],
1277
+ );
1278
+
1279
+ return $return;
1280
+ }
1281
+ }
1282
+
1283
+ // Optimized image
1284
+ $webimg = $gmGallery->options['image'];
1285
+ $thumbimg = $gmGallery->options['thumb'];
1286
+
1287
+ $webimg['resize'] = ( ( $webimg['width'] < $size[0] ) || ( $webimg['height'] < $size[1] ) ) ? true : false;
1288
+
1289
+ if ( $webimg['resize'] ) {
1290
+ rename( $fileinfo['filepath'], $fileinfo['filepath_original'] );
1291
+ } else {
1292
+ copy( $fileinfo['filepath'], $fileinfo['filepath_original'] );
1293
+ }
1294
+
1295
+ $size_ratio = $size[0] / $size[1];
1296
+
1297
+ $angle = 0;
1298
+ $image_meta = @$this->wp_read_image_metadata( $fileinfo['filepath_original'] );
1299
+ if ( ! empty( $image_meta['orientation'] ) ) {
1300
+ switch ( $image_meta['orientation'] ) {
1301
+ case 3:
1302
+ $angle = 180;
1303
+ break;
1304
+ case 6:
1305
+ $angle = 270;
1306
+ $size_ratio = $size[1] / $size[0];
1307
+ break;
1308
+ case 8:
1309
+ $angle = 90;
1310
+ $size_ratio = $size[1] / $size[0];
1311
+ break;
1312
+ }
1313
+ }
1314
+
1315
+ $thumbimg['resize'] = ( ( ( 1 >= $size_ratio ) && ( $thumbimg['width'] > $size[0] ) ) || ( ( 1 <= $size_ratio ) && ( $thumbimg['height'] > $size[1] ) ) ) ? false : true;
1316
+
1317
+ $editor = wp_get_image_editor( $fileinfo['filepath_original'] );
1318
+ if ( is_wp_error( $editor ) ) {
1319
+ @unlink( $fileinfo['filepath'] );
1320
+ @unlink( $fileinfo['filepath_original'] );
1321
+ $return = array(
1322
+ "error" => array( "code" => $editor->get_error_code(), "message" => $editor->get_error_message() ),
1323
+ "id" => $fileinfo['basename'],
1324
+ "tip" => 'wp_get_image_editor',
1325
+ );
1326
+
1327
+ return $return;
1328
+ }
1329
+
1330
+ if ( $angle ) {
1331
+ $editor->rotate( $angle );
1332
+ }
1333
+
1334
+ $editor->set_quality( $webimg['quality'] );
1335
+
1336
+ if ( $webimg['resize'] ) {
1337
+ $resized = $editor->resize( $webimg['width'], $webimg['height'], $webimg['crop'] );
1338
+ if ( is_wp_error( $resized ) ) {
1339
+ @unlink( $fileinfo['filepath'] );
1340
+ @unlink( $fileinfo['filepath_original'] );
1341
+ $return = array(
1342
+ "error" => array( "code" => $resized->get_error_code(), "message" => $resized->get_error_message() ),
1343
+ "id" => $fileinfo['basename'],
1344
+ "tip" => "editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})",
1345
+ );
1346
+
1347
+ return $return;
1348
+ }
1349
+ }
1350
+
1351
+ $saved = $editor->save( $fileinfo['filepath'] );
1352
+ if ( is_wp_error( $saved ) ) {
1353
+ @unlink( $fileinfo['filepath'] );
1354
+ @unlink( $fileinfo['filepath_original'] );
1355
+ $return = array(
1356
+ "error" => array( "code" => $saved->get_error_code(), "message" => $saved->get_error_message() ),
1357
+ "id" => $fileinfo['basename'],
1358
+ "tip" => 'editor->save->webimage',
1359
+ );
1360
+
1361
+ return $return;
1362
+ }
1363
+
1364
+ if ( ( 'JPG' == $extensions[ $size[2] ] ) && ! ( extension_loaded( 'imagick' ) || class_exists( "Imagick" ) ) ) {
1365
+ $this->copy_exif( $fileinfo['filepath_original'], $fileinfo['filepath'] );
1366
+ }
1367
+
1368
+ // Thumbnail
1369
+ $editor->set_quality( $thumbimg['quality'] );
1370
+ if ( $thumbimg['resize'] ) {
1371
+ $ed_size = $editor->get_size();
1372
+ $ed_ratio = $ed_size['width'] / $ed_size['height'];
1373
+ if ( 1 > $ed_ratio ) {
1374
+ $resized = $editor->resize( $thumbimg['width'], 0, $thumbimg['crop'] );
1375
+ } else {
1376
+ $resized = $editor->resize( 0, $thumbimg['height'], $thumbimg['crop'] );
1377
+ }
1378
+ if ( is_wp_error( $resized ) ) {
1379
+ @unlink( $fileinfo['filepath'] );
1380
+ @unlink( $fileinfo['filepath_original'] );
1381
+ $return = array(
1382
+ "error" => array( "code" => $resized->get_error_code(), "message" => $resized->get_error_message() ),
1383
+ "id" => $fileinfo['basename'],
1384
+ "tip" => "editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})",
1385
+ );
1386
+
1387
+ return $return;
1388
+ }
1389
+ }
1390
+
1391
+ $saved = $editor->save( $fileinfo['filepath_thumb'] );
1392
+ if ( is_wp_error( $saved ) ) {
1393
+ @unlink( $fileinfo['filepath'] );
1394
+ @unlink( $fileinfo['filepath_original'] );
1395
+ $return = array(
1396
+ "error" => array( "code" => $saved->get_error_code(), "message" => $saved->get_error_message() ),
1397
+ "id" => $fileinfo['basename'],
1398
+ "tip" => 'editor->save->thumb',
1399
+ );
1400
+
1401
+ return $return;
1402
+ }
1403
+
1404
+ $is_webimage = true;
1405
+ } else {
1406
+ /*@unlink($fileinfo['filepath']);
1407
+ $return = array("error" => array("code" => 104, "message" => __("Could not read image size. Invalid image was deleted.", 'grand-media')),
1408
+ "id" => $fileinfo['basename_original']
1409
+ );
1410
+
1411
+ return $return;
1412
+ */
1413
+ }
1414
+ }
1415
+
1416
+ // Write media data to DB
1417
+ $title = '';
1418
+ $description = '';
1419
+ $link = '';
1420
+ $date = null;
1421
+ if ( ! isset( $post_data['set_title'] ) ) {
1422
+ $post_data['set_title'] = 'filename';
1423
+ }
1424
+ if ( ! isset( $post_data['set_status'] ) ) {
1425
+ $post_data['set_status'] = isset( $post_data['status'] ) ? $post_data['status'] : 'inherit';
1426
+ }
1427
+
1428
+ $keywords = array();
1429
+ // use image exif/iptc data for title and caption defaults if possible
1430
+ if ( $size ) {
1431
+ if ( ! empty( $image_meta ) ) {
1432
+ if ( 'exif' == $post_data['set_title'] ) {
1433
+ if ( ! empty( $image_meta['title'] ) && trim( $image_meta['title'] ) ) {
1434
+ $title = $image_meta['title'];
1435
+ }
1436
+ }
1437
+ if ( ! empty( $image_meta['caption'] ) && trim( $image_meta['caption'] ) ) {
1438
+ $description = $image_meta['caption'];
1439
+ }
1440
+ if ( ! empty( $image_meta['keywords'] ) ) {
1441
+ $keywords = $image_meta['keywords'];
1442
+ }
1443
+ }
1444
+ } else {
1445
+ $file_meta = $this->get_file_metadata( $fileinfo['filepath_original'], $fileinfo );
1446
+ if ( ! empty( $file_meta ) ) {
1447
+ if ( 'exif' == $post_data['set_title'] ) {
1448
+ if ( ! empty( $file_meta['title'] ) && trim( $file_meta['title'] ) ) {
1449
+ $title = $file_meta['title'];
1450
+ }
1451
+ }
1452
+ if ( ! empty( $file_meta['comment'] ) && trim( $file_meta['comment'] ) ) {
1453
+ $description = $file_meta['comment'];
1454
+ }
1455
+ if ( ! empty( $file_meta['album'] ) && ( ! isset( $post_data['terms']['gmedia_album'] ) || empty( $post_data['terms']['gmedia_album'] ) ) ) {
1456
+ $post_data['terms']['gmedia_album'] = array( $file_meta['album'] );
1457
+ }
1458
+ }
1459
+ }
1460
+ if ( ( 'empty' != $post_data['set_title'] ) && empty( $title ) ) {
1461
+ $title = $fileinfo['title'];
1462
+ }
1463
+
1464
+ if ( 'public' == $post_data['set_status'] ) {
1465
+ $post_data['set_status'] = 'publish';
1466
+ }
1467
+
1468
+ $status = $post_data['set_status'];
1469
+ if ( 'inherit' == $post_data['set_status'] ) {
1470
+ $gmedia_album = isset( $post_data['terms']['gmedia_album'] ) ? $post_data['terms']['gmedia_album'] : false;
1471
+ if ( $gmedia_album && $this->is_digit( $gmedia_album ) ) {
1472
+ $album = $gmDB->get_term( $gmedia_album );
1473
+ if ( empty( $album ) || is_wp_error( $album ) ) {
1474
+ $status = 'publish';
1475
+ } else {
1476
+ $status = $album->status;
1477
+ }
1478
+ } else {
1479
+ $status = 'publish';
1480
+ }
1481
+ }
1482
+
1483
+ unset( $post_data['gmuid'], $post_data['mime_type'], $post_data['set_title'], $post_data['set_status'] );
1484
+
1485
+ if ( isset( $post_data['terms']['gmedia_category'] ) && ! empty( $post_data['terms']['gmedia_category'] ) ) {
1486
+ if ( ! is_array( $post_data['terms']['gmedia_category'] ) ) {
1487
+ $post_data['terms']['gmedia_category'] = explode( ',', $post_data['terms']['gmedia_category'] );
1488
+ }
1489
+ } else {
1490
+ $post_data['terms']['gmedia_category'] = array();
1491
+ }
1492
+
1493
+ if ( isset( $post_data['terms']['gmedia_tag'] ) && ! empty( $post_data['terms']['gmedia_tag'] ) ) {
1494
+ if ( ! is_array( $post_data['terms']['gmedia_tag'] ) ) {
1495
+ $post_data['terms']['gmedia_tag'] = explode( ',', $post_data['terms']['gmedia_tag'] );
1496
+ }
1497
+ } else {
1498
+ $post_data['terms']['gmedia_tag'] = array();
1499
+ }
1500
+ if ( ! empty( $keywords ) ) {
1501
+ $post_data['terms']['gmedia_tag'] = array_unique( array_merge( $post_data['terms']['gmedia_tag'], $keywords ) );
1502
+ }
1503
+
1504
+ // Construct the media array
1505
+ $media_data = array(
1506
+ 'mime_type' => $fileinfo['mime_type'],
1507
+ 'gmuid' => $fileinfo['basename'],
1508
+ 'title' => $title,
1509
+ 'link' => $link,
1510
+ 'description' => $description,
1511
+ 'status' => $status,
1512
+ 'date' => $date,
1513
+ );
1514
+
1515
+ $media_data = $this->array_replace_recursive( $media_data, $post_data );
1516
+
1517
+ if ( ! current_user_can( 'gmedia_delete_others_media' ) ) {
1518
+ $media_data['author'] = get_current_user_id();
1519
+ }
1520
+
1521
+ // Save the data
1522
+ $id = $gmDB->insert_gmedia( $media_data );
1523
+
1524
+ $media_metadata = $gmDB->generate_gmedia_metadata( $id, $fileinfo );
1525
+ if ( $size && ! empty( $image_meta ) ) {
1526
+ if ( empty( $media_metadata['image_meta'] ) ) {
1527
+ $media_metadata['image_meta'] = $image_meta;
1528
+ }
1529
+ if ( ! empty( $image_meta['created_timestamp'] ) ) {
1530
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_created_timestamp', $image_meta['created_timestamp'] );
1531
+ }
1532
+ if ( ! empty( $image_meta['GPS'] ) ) {
1533
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_gps', $image_meta['GPS'] );
1534
+ }
1535
+ }
1536
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_metadata', $media_metadata );
1537
+ $hash_file = hash_file( 'md5', $fileinfo['filepath_original'] );
1538
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_hash', $hash_file );
1539
+ $file_size = filesize( $fileinfo['filepath_original'] );
1540
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_size', $file_size );
1541
+ $return = array(
1542
+ "success" => array( "code" => 200, "message" => sprintf( __( 'File uploaded successful. Assigned ID: %s', 'grand-media' ), $id ) ),
1543
+ "id" => $fileinfo['basename'],
1544
+ );
1545
+
1546
+ if ( (int) $gmGallery->options['delete_originals'] ) {
1547
+ @unlink( $fileinfo['filepath_original'] );
1548
+ }
1549
+
1550
+ return $return;
1551
+ } else {
1552
+ $return = array( "success" => array( "code" => 199, "message" => $chunk . '/' . $chunks ), "id" => $fileinfo['basename'] );
1553
+
1554
+ return $return;
1555
+ }
1556
+ } else {
1557
+ $return = array( "error" => array( "code" => 102, "message" => __( "Failed to open output stream.", 'grand-media' ) ), "id" => $fileinfo['basename'] );
1558
+
1559
+ return $return;
1560
+ }
1561
+ }
1562
+
1563
+ /**
1564
+ * Check REQUEST data
1565
+ *
1566
+ * @param string $var
1567
+ * @param mixed $def
1568
+ *
1569
+ * @return mixed
1570
+ */
1571
+ function _req( $var, $def = false ) {
1572
+ return isset( $_REQUEST[ $var ] ) ? $_REQUEST[ $var ] : $def;
1573
+ }
1574
+
1575
+ /** Set correct file permissions (chmod)
1576
+ *
1577
+ * @param string $new_file
1578
+ */
1579
+ function file_chmod( $new_file ) {
1580
+ $stat = stat( dirname( $new_file ) );
1581
+ $perms = $stat['mode'] & 0000666;
1582
+ @chmod( $new_file, $perms );
1583
+ }
1584
+
1585
+ /**
1586
+ * Get extended image metadata, exif or iptc as available.
1587
+ * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
1588
+ * created_timestamp, focal_length, shutter_speed, and title.
1589
+ * The IPTC metadata that is retrieved is APP13, credit, byline, created date
1590
+ * and time, caption, copyright, and title. Also includes FNumber, Model,
1591
+ * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
1592
+ *
1593
+ * @param string $file
1594
+ *
1595
+ * @return bool|array False on failure. Image metadata array on success.
1596
+ * @todo Try other exif libraries if available.
1597
+ * @since 2.5.0
1598
+ *
1599
+ */
1600
+ function wp_read_image_metadata( $file ) {
1601
+ if ( ! is_file( $file ) ) {
1602
+ return false;
1603
+ }
1604
+
1605
+ list( , , $sourceImageType ) = getimagesize( $file );
1606
+
1607
+ $meta = array();
1608
+
1609
+ /*
1610
  * Read IPTC first, since it might contain data not available in exif such
1611
  * as caption, description etc.
1612
  */
1613
+ if ( is_callable( 'iptcparse' ) ) {
1614
+ getimagesize( $file, $info );
1615
 
1616
+ if ( ! empty( $info['APP13'] ) ) {
1617
+ $iptc = iptcparse( $info['APP13'] );
1618
 
1619
+ // Headline, "A brief synopsis of the caption."
1620
+ if ( ! empty( $iptc['2#105'][0] ) ) {
1621
+ $meta['title'] = trim( $iptc['2#105'][0] );
1622
+ /*
1623
  * Title, "Many use the Title field to store the filename of the image,
1624
  * though the field may be used in many ways."
1625
  */
1626
+ } elseif ( ! empty( $iptc['2#005'][0] ) ) {
1627
+ $meta['title'] = trim( $iptc['2#005'][0] );
1628
+ }
1629
+
1630
+ if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
1631
+ $caption = trim( $iptc['2#120'][0] );
1632
+ if ( empty( $meta['title'] ) ) {
1633
+ mbstring_binary_safe_encoding();
1634
+ $caption_length = strlen( $caption );
1635
+ reset_mbstring_encoding();
1636
+
1637
+ // Assume the title is stored in 2:120 if it's short.
1638
+ if ( $caption_length < 80 ) {
1639
+ $meta['title'] = $caption;
1640
+ } else {
1641
+ $meta['caption'] = $caption;
1642
+ }
1643
+ } elseif ( $caption != $meta['title'] ) {
1644
+ $meta['caption'] = $caption;
1645
+ }
1646
+ }
1647
+
1648
+ if ( ! empty( $iptc['2#110'][0] ) ) // credit
1649
+ {
1650
+ $meta['credit'] = trim( $iptc['2#110'][0] );
1651
+ } elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
1652
+ {
1653
+ $meta['credit'] = trim( $iptc['2#080'][0] );
1654
+ }
1655
+
1656
+ if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time
1657
+ {
1658
+ $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
1659
+ }
1660
+
1661
+ if ( ! empty( $iptc['2#116'][0] ) ) // copyright
1662
+ {
1663
+ $meta['copyright'] = trim( $iptc['2#116'][0] );
1664
+ }
1665
+
1666
+ if ( ! empty( $iptc['2#025'] ) ) // keywords
1667
+ {
1668
+ $meta['keywords'] = $iptc['2#025'];
1669
+ }
1670
+ }
1671
+ }
1672
+
1673
+ /**
1674
+ * Filter the image types to check for exif data.
1675
+ *
1676
+ * @param array $image_types Image types to check for exif data.
1677
+ *
1678
+ * @since 2.5.0
1679
+ *
1680
+ */
1681
+ if ( is_callable( 'exif_read_data' ) && in_array( $sourceImageType, apply_filters( 'wp_read_image_metadata_types', array(
1682
+ IMAGETYPE_JPEG,
1683
+ IMAGETYPE_TIFF_II,
1684
+ IMAGETYPE_TIFF_MM,
1685
+ ) ) )
1686
+ ) {
1687
+ $exif = @exif_read_data( $file );
1688
+ unset( $exif['MakerNote'] );
1689
+
1690
+ // Title
1691
+ if ( empty( $meta['title'] ) && ! empty( $exif['Title'] ) ) {
1692
+ $meta['title'] = trim( $exif['Title'] );
1693
+ }
1694
+ // Descrioption
1695
+ if ( ! empty( $exif['ImageDescription'] ) ) {
1696
+ mbstring_binary_safe_encoding();
1697
+ $description_length = strlen( $exif['ImageDescription'] );
1698
+ reset_mbstring_encoding();
1699
+
1700
+ if ( empty( $meta['title'] ) && $description_length < 80 ) {
1701
+ // Assume the title is stored in ImageDescription
1702
+ $meta['title'] = trim( $exif['ImageDescription'] );
1703
+ if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] ) {
1704
+ $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
1705
+ }
1706
+ } elseif ( empty( $meta['caption'] ) && trim( $exif['ImageDescription'] ) != $meta['title'] ) {
1707
+ $meta['caption'] = trim( $exif['ImageDescription'] );
1708
+ }
1709
+ } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
1710
+ $meta['caption'] = trim( $exif['Comments'] );
1711
+ }
1712
+ // Credit
1713
+ if ( empty( $meta['credit'] ) ) {
1714
+ if ( ! empty( $exif['Artist'] ) ) {
1715
+ $meta['credit'] = trim( $exif['Artist'] );
1716
+ } elseif ( ! empty( $exif['Author'] ) ) {
1717
+ $meta['credit'] = trim( $exif['Author'] );
1718
+ }
1719
+ }
1720
+ // Copyright
1721
+ if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
1722
+ $meta['copyright'] = trim( $exif['Copyright'] );
1723
+ }
1724
+ // Camera Make
1725
+ if ( ! empty( $exif['Make'] ) ) {
1726
+ $meta['make'] = $exif['Make'];
1727
+ }
1728
+ // Camera Model
1729
+ if ( ! empty( $exif['Model'] ) ) {
1730
+ $meta['model'] = trim( $exif['Model'] );
1731
+ }
1732
+ // Exposure Time (shutter speed)
1733
+ if ( ! empty( $exif['ExposureTime'] ) ) {
1734
+ $meta['exposure'] = $exif['ExposureTime'] . 's';
1735
+ $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] ) . 's';
1736
+ }
1737
+ // Aperture
1738
+ if ( ! empty( $exif['COMPUTED']['ApertureFNumber'] ) ) {
1739
+ $meta['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
1740
+ } elseif ( ! empty( $exif['FNumber'] ) ) {
1741
+ $meta['aperture'] = 'f/' . (string) round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
1742
+ }
1743
+ // ISO
1744
+ if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
1745
+ $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
1746
+ $meta['iso'] = trim( $meta['iso'] );
1747
+ }
1748
+ // Date
1749
+ if ( ! empty( $exif['DateTime'] ) ) {
1750
+ $meta['date'] = $exif['DateTime'];
1751
+ }
1752
+ // Created TimeStamp
1753
+ if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
1754
+ $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
1755
+ }
1756
+ // Lens
1757
+ if ( ! empty( $exif['UndefinedTag:0xA434'] ) ) {
1758
+ $meta['lens'] = $exif['UndefinedTag:0xA434'];
1759
+ }
1760
+ // Focus Distance
1761
+ if ( ! empty( $exif['COMPUTED']['FocusDistance'] ) ) {
1762
+ $meta['distance'] = $exif['COMPUTED']['FocusDistance'];
1763
+ }
1764
+ // Focal Length
1765
+ if ( ! empty( $exif['FocalLength'] ) ) {
1766
+ $meta['focallength'] = (string) round( wp_exif_frac2dec( $exif['FocalLength'] ) ) . 'mm';
1767
+ }
1768
+ // Focal Length 35mm
1769
+ if ( ! empty( $exif['FocalLengthIn35mmFilm'] ) ) {
1770
+ $meta['focallength35'] = $exif['FocalLengthIn35mmFilm'] . 'mm';
1771
+ }
1772
+ // Flash data
1773
+ if ( ! empty( $exif['Flash'] ) ) {
1774
+ // we need to interpret the result - it's given as a number and we want a human-readable description.
1775
+ $fdata = $exif['Flash'];
1776
+
1777
+ switch ( $fdata ) {
1778
+ case 0 :
1779
+ $fdata = 'No Flash';
1780
+ break;
1781
+ case 1 :
1782
+ $fdata = 'Flash';
1783
+ break;
1784
+ case 5 :
1785
+ $fdata = 'Flash, strobe return light not detected';
1786
+ break;
1787
+ case 7 :
1788
+ $fdata = 'Flash, strob return light detected';
1789
+ break;
1790
+ case 9 :
1791
+ $fdata = 'Compulsory Flash';
1792
+ break;
1793
+ case 13:
1794
+ $fdata = 'Compulsory Flash, Return light not detected';
1795
+ break;
1796
+ case 15:
1797
+ $fdata = 'Compulsory Flash, Return light detected';
1798
+ break;
1799
+ case 16:
1800
+ $fdata = 'No Flash';
1801
+ break;
1802
+ case 24:
1803
+ $fdata = 'No Flash';
1804
+ break;
1805
+ case 25:
1806
+ $fdata = 'Flash, Auto-Mode';
1807
+ break;
1808
+ case 29:
1809
+ $fdata = 'Flash, Auto-Mode, Return light not detected';
1810
+ break;
1811
+ case 31:
1812
+ $fdata = 'Flash, Auto-Mode, Return light detected';
1813
+ break;
1814
+ case 32:
1815
+ $fdata = 'No Flash';
1816
+ break;
1817
+ case 65:
1818
+ $fdata = 'Red Eye';
1819
+ break;
1820
+ case 69:
1821
+ $fdata = 'Red Eye, Return light not detected';
1822
+ break;
1823
+ case 71:
1824
+ $fdata = 'Red Eye, Return light detected';
1825
+ break;
1826
+ case 73:
1827
+ $fdata = 'Red Eye, Compulsory Flash';
1828
+ break;
1829
+ case 77:
1830
+ $fdata = 'Red Eye, Compulsory Flash, Return light not detected';
1831
+ break;
1832
+ case 79:
1833
+ $fdata = 'Red Eye, Compulsory Flash, Return light detected';
1834
+ break;
1835
+ case 89:
1836
+ $fdata = 'Red Eye, Auto-Mode';
1837
+ break;
1838
+ case 93:
1839
+ $fdata = 'Red Eye, Auto-Mode, Return light not detected';
1840
+ break;
1841
+ case 95:
1842
+ $fdata = 'Red Eye, Auto-Mode, Return light detected';
1843
+ break;
1844
+ default:
1845
+ $fdata = 'Unknown: ' . $fdata;
1846
+ break;
1847
+ }
1848
+ $meta['flashdata'] = $fdata;
1849
+ }
1850
+ // Lens Make
1851
+ if ( ! empty( $exif['UndefinedTag:0xA433'] ) ) {
1852
+ $meta['lensmake'] = $exif['UndefinedTag:0xA433'];
1853
+ }
1854
+ // Software
1855
+ if ( ! empty( $exif['Software'] ) ) {
1856
+ $meta['software'] = $exif['Software'];
1857
+ }
1858
+ // Orientation
1859
+ if ( ! empty( $exif['Orientation'] ) ) {
1860
+ $meta['orientation'] = $exif['Orientation'];
1861
+ }
1862
+
1863
+ $exif_sections = @exif_read_data( $file, null, true );
1864
+ if ( isset( $exif_sections['GPS'] ) ) {
1865
+ $meta['GPS'] = $this->getGPSfromExif( $exif_sections['GPS'] );
1866
+ }
1867
+ unset( $exif_sections );
1868
+ //$meta['exif'] = $exif;
1869
+ }
1870
+
1871
+ foreach ( array( 'title', 'caption', 'credit', 'copyright', 'model', 'iso', 'software' ) as $key ) {
1872
+ if ( ! empty( $meta[ $key ] ) && ! seems_utf8( $meta[ $key ] ) ) {
1873
+ $meta[ $key ] = utf8_encode( $meta[ $key ] );
1874
+ }
1875
+ }
1876
+ if ( ! empty( $meta['keywords'] ) ) {
1877
+ foreach ( $meta['keywords'] as $i => $key ) {
1878
+ if ( ! seems_utf8( $key ) ) {
1879
+ $meta['keywords'][ $i ] = utf8_encode( $key );
1880
+ }
1881
+ }
1882
+ }
1883
+
1884
+ foreach ( $meta as &$value ) {
1885
+ if ( is_string( $value ) ) {
1886
+ $value = wp_kses_post( $value );
1887
+ }
1888
+ }
1889
+
1890
+ /**
1891
+ * Filter the array of meta data read from an image's exif data.
1892
+ *
1893
+ * @param array $meta Image meta data.
1894
+ * @param string $file Path to image file.
1895
+ * @param int $sourceImageType Type of image.
1896
+ *
1897
+ * @since 2.5.0
1898
+ *
1899
+ */
1900
+ return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
1901
+
1902
+ }
1903
+
1904
+ /** Get [latitude, longtitude] coordinates from EXIF
1905
+ *
1906
+ * @param array $gps Exif[GPS] array
1907
+ *
1908
+ * @return array
1909
+ */
1910
+ function getGPSfromExif( $gps ) {
1911
+ $lat = $this->getGPS( $gps['GPSLatitude'], $gps['GPSLatitudeRef'] );
1912
+ $lng = $this->getGPS( $gps['GPSLongitude'], $gps['GPSLongitudeRef'] );
1913
+
1914
+ return array( 'lat' => round( $lat, 4 ), 'lng' => round( $lng, 4 ) );
1915
+ }
1916
+
1917
+ /**
1918
+ * @param $coordinate
1919
+ * @param $hemisphere
1920
+ *
1921
+ * @return int
1922
+ */
1923
+ function getGPS( $coordinate, $hemisphere ) {
1924
+ for ( $i = 0; $i < 3; $i ++ ) {
1925
+ $part = explode( '/', $coordinate[ $i ] );
1926
+ if ( count( $part ) == 1 ) {
1927
+ $coordinate[ $i ] = $part[0];
1928
+ } elseif ( count( $part ) == 2 ) {
1929
+ $coordinate[ $i ] = floatval( $part[0] ) / floatval( $part[1] );
1930
+ } else {
1931
+ $coordinate[ $i ] = 0;
1932
+ }
1933
+ }
1934
+ list( $degrees, $minutes, $seconds ) = $coordinate;
1935
+ $sign = ( $hemisphere == 'W' || $hemisphere == 'S' ) ? - 1 : 1;
1936
+
1937
+ return $sign * ( $degrees + $minutes / 60 + $seconds / 3600 );
1938
+ }
1939
+
1940
+ /**
1941
+ * @param $from_file
1942
+ * @param $to_file
1943
+ */
1944
+ function copy_exif( $from_file, $to_file ) {
1945
+
1946
+ $size = @getimagesize( $to_file );
1947
+
1948
+ if ( $size ) {
1949
+ require_once( dirname( __FILE__ ) . '/pel/autoload.php' );
1950
+ try {
1951
+ Pel::setJPEGQuality( 100 );
1952
+ /*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1953
  * We want the raw JPEG data from $scaled. Luckily, one can create a
1954
  * PelJpeg object from an image resource directly:
1955
  */
1956
+ $input_jpeg = new PelJpeg( $from_file );
1957
+ /* Retrieve the original Exif data in $jpeg (if any). */
1958
+ $input_exif = $input_jpeg->getExif();
1959
+ /* If no Exif data was present, then $input_exif is null. */
1960
+ if ( $input_exif != null ) {
1961
+
1962
+ $input_tiff = $input_exif->getTiff();
1963
+ if ( $input_tiff == null ) {
1964
+ return;
1965
+ }
1966
+ $input_ifd0 = $input_tiff->getIfd();
1967
+ if ( $input_ifd0 == null ) {
1968
+ return;
1969
+ }
1970
+
1971
+ $input_exif_ifd = $input_ifd0->getSubIfd( PelIfd::EXIF );
1972
+ $input_inter_ifd = $input_ifd0->getSubIfd( PelIfd::INTEROPERABILITY );
1973
+
1974
+ $orientation = $input_ifd0->getEntry( PelTag::ORIENTATION );
1975
+ if ( $orientation != null ) {
1976
+ $orientation->setValue( 1 );
1977
+ }
1978
+
1979
+ if ( ! empty( $input_ifd0 ) ) {
1980
+ /*$x_resolution = $input_ifd0->getEntry( PelTag::X_RESOLUTION );
1981
  $y_resolution = $input_ifd0->getEntry( PelTag::Y_RESOLUTION );
1982
  if ( $x_resolution != null && $y_resolution != null ) {
1983
  //$x_res = $x_resolution->getValue();
1986
  $y_resolution->setValue( $x_res );
1987
  }*/
1988
 
1989
+ $image_width = $input_ifd0->getEntry( PelTag::IMAGE_WIDTH );
1990
+ $image_length = $input_ifd0->getEntry( PelTag::IMAGE_LENGTH );
1991
+ if ( $image_width != null && $image_length != null ) {
1992
+ $image_width->setValue( $size[0] );
1993
+ $image_length->setValue( $size[1] );
1994
+ }
1995
+ }
1996
+ if ( ! empty( $input_exif_ifd ) ) {
1997
+ $x_dimention = $input_exif_ifd->getEntry( PelTag::PIXEL_X_DIMENSION );
1998
+ $y_dimention = $input_exif_ifd->getEntry( PelTag::PIXEL_Y_DIMENSION );
1999
+ if ( $x_dimention != null && $y_dimention != null ) {
2000
+ $x_dimention->setValue( $size[0] );
2001
+ $y_dimention->setValue( $size[1] );
2002
+ }
2003
+ }
2004
+ if ( ! empty( $input_inter_ifd ) ) {
2005
+ $rel_image_width = $input_inter_ifd->getEntry( PelTag::RELATED_IMAGE_WIDTH );
2006
+ $rel_image_length = $input_inter_ifd->getEntry( PelTag::RELATED_IMAGE_LENGTH );
2007
+ if ( $rel_image_width != null && $rel_image_length != null ) {
2008
+ $rel_image_width->setValue( $size[0] );
2009
+ $rel_image_length->setValue( $size[1] );
2010
+ }
2011
+ }
2012
+
2013
+ $output_jpeg = new PelJpeg( $to_file );
2014
+ $output_jpeg->setExif( $input_exif );
2015
+
2016
+ /* We can now save the image with input_exif. */
2017
+ $output_jpeg->saveFile( $to_file );
2018
+ }
2019
+ } catch ( PelException $e ) {
2020
+ }
2021
+ }
2022
+ }
2023
+
2024
+ /** Get file metadata
2025
+ *
2026
+ * @param $file
2027
+ * @param $fileinfo
2028
+ *
2029
+ * @return mixed|void
2030
+ */
2031
+ function get_file_metadata( $file, $fileinfo = array() ) {
2032
+
2033
+ if ( empty( $fileinfo ) ) {
2034
+ $fileinfo = $this->fileinfo( $file, false );
2035
+ }
2036
+ $metadata = array();
2037
+ require_once( ABSPATH . 'wp-admin/includes/image.php' );
2038
+ if ( preg_match( '!^image/!', $fileinfo['mime_type'] ) && file_is_displayable_image( $fileinfo['filepath'] ) ) {
2039
+ $is_file_original = is_file( $fileinfo['filepath_original'] );
2040
+ $filepath_original = $is_file_original ? $fileinfo['filepath_original'] : $fileinfo['filepath'];
2041
+ $imagesize = getimagesize( $fileinfo['filepath_thumb'] );
2042
+ $metadata['thumb'] = array( 'width' => $imagesize[0], 'height' => $imagesize[1] );
2043
+ $imagesize = getimagesize( $fileinfo['filepath'] );
2044
+ $metadata['web'] = array( 'width' => $imagesize[0], 'height' => $imagesize[1] );
2045
+ if ( $is_file_original ) {
2046
+ $imagesize = getimagesize( $filepath_original );
2047
+ $metadata['original'] = array( 'width' => $imagesize[0], 'height' => $imagesize[1] );
2048
+ } else {
2049
+ $metadata['original'] = $metadata['web'];
2050
+ }
2051
+
2052
+ $metadata['file'] = $this->_gm_relative_upload_path( $fileinfo['filepath'] );
2053
+
2054
+ // fetch additional metadata from exif/iptc
2055
+ $image_meta = $this->wp_read_image_metadata( $filepath_original );
2056
+ if ( $image_meta ) {
2057
+ $metadata['image_meta'] = $image_meta;
2058
+ }
2059
+
2060
+ } elseif ( preg_match( '#^video/#', $fileinfo['mime_type'] ) ) {
2061
+ $metadata = $this->wp_read_video_metadata( $fileinfo['filepath'] );
2062
+ } elseif ( preg_match( '#^audio/#', $fileinfo['mime_type'] ) ) {
2063
+ $metadata = $this->wp_read_audio_metadata( $fileinfo['filepath'] );
2064
+ //unset($metadata['image']);
2065
+ }
2066
+
2067
+ return apply_filters( 'generate_file_metadata', $metadata );
2068
+ }
2069
+
2070
+ /** Automatic choose upload directory based on media type
2071
+ *
2072
+ * @param string $file
2073
+ * @param int $exists
2074
+ *
2075
+ * @return array|bool
2076
+ */
2077
+ function fileinfo( $file, $exists = 0 ) {
2078
+ global $gmGallery, $user_ID;
2079
+
2080
+ $file = basename( $file );
2081
+ $file_lower = strtolower( $file );
2082
+ $filetype = wp_check_filetype( $file_lower, $mimes = null );
2083
+ $title = pathinfo( $file, PATHINFO_FILENAME );
2084
+ $pathinfo = pathinfo( preg_replace( '/[^a-z0-9_\.-]+/i', '_', $file ) );
2085
+ $pathinfo['extension'] = strtolower( $pathinfo['extension'] );
2086
+ $suffix = ( ( false !== $exists ) && absint( $exists ) ) ? "_$exists" : '';
2087
+
2088
+ $fileinfo['extension'] = ( empty( $filetype['ext'] ) ) ? $pathinfo['extension'] : $filetype['ext'];
2089
+
2090
+ $allowed_ext = get_allowed_mime_types( $user_ID );
2091
+ $allowed_ext = array_keys( $allowed_ext );
2092
+ $allowed_ext = implode( '|', $allowed_ext );
2093
+ $allowed_ext = explode( '|', $allowed_ext );
2094
+ if ( ! in_array( $fileinfo['extension'], $allowed_ext ) ) {
2095
+ return false;
2096
+ }
2097
+
2098
+ $fileinfo['basename_original'] = $pathinfo['filename'] . '.' . $fileinfo['extension'];
2099
+ $fileinfo['filename'] = $pathinfo['filename'] . $suffix;
2100
+ $fileinfo['basename'] = $fileinfo['filename'] . '.' . $fileinfo['extension'];
2101
+ $fileinfo['title'] = str_replace( '_', ' ', esc_sql( $title ) );
2102
+ if ( (int) $gmGallery->options['name2title_capitalize'] ) {
2103
+ $fileinfo['title'] = $this->mb_ucwords_utf8( $fileinfo['title'] );
2104
+ }
2105
+ $fileinfo['mime_type'] = ( empty( $filetype['type'] ) ) ? 'application/' . $fileinfo['extension'] : $filetype['type'];
2106
+ list( $dirname ) = explode( '/', $fileinfo['mime_type'] );
2107
+ $fileinfo['dirname'] = $dirname;
2108
+ $fileinfo['dirpath'] = $this->upload['path'] . '/' . $gmGallery->options['folder'][ $dirname ];
2109
+ $fileinfo['dirpath_original'] = $this->upload['path'] . '/' . $gmGallery->options['folder'][ $dirname ];
2110
+ $fileinfo['dirurl'] = $this->upload['url'] . '/' . $gmGallery->options['folder'][ $dirname ];
2111
+ $fileinfo['dirurl_original'] = $this->upload['url'] . '/' . $gmGallery->options['folder'][ $dirname ];
2112
+ $fileinfo['filepath'] = $fileinfo['dirpath'] . '/' . $fileinfo['basename'];
2113
+ $fileinfo['filepath_original'] = $fileinfo['dirpath'] . '/' . $fileinfo['basename'];
2114
+ $fileinfo['fileurl'] = $fileinfo['dirurl'] . '/' . $fileinfo['basename'];
2115
+ $fileinfo['fileurl_original'] = $fileinfo['dirurl'] . '/' . $fileinfo['basename'];
2116
+ if ( 'image' == $dirname ) {
2117
+ $fileinfo['dirpath_original'] = $this->upload['path'] . '/' . $gmGallery->options['folder']['image_original'];
2118
+ $fileinfo['dirurl_original'] = $this->upload['url'] . '/' . $gmGallery->options['folder']['image_original'];
2119
+ $fileinfo['filepath_original'] = $fileinfo['dirpath_original'] . '/' . $fileinfo['basename'];
2120
+ $fileinfo['fileurl_original'] = $fileinfo['dirurl_original'] . '/' . $fileinfo['basename'];
2121
+ $fileinfo['dirpath_thumb'] = $this->upload['path'] . '/' . $gmGallery->options['folder']['image_thumb'];
2122
+ $fileinfo['dirurl_thumb'] = $this->upload['url'] . '/' . $gmGallery->options['folder']['image_thumb'];
2123
+ $fileinfo['filepath_thumb'] = $fileinfo['dirpath_thumb'] . '/' . $fileinfo['basename'];
2124
+ $fileinfo['fileurl_thumb'] = $fileinfo['dirurl_thumb'] . '/' . $fileinfo['basename'];
2125
+ }
2126
+
2127
+ if ( ( false !== $exists ) && is_file( $fileinfo['filepath'] ) ) {
2128
+ $exists = absint( $exists ) + 1;
2129
+ $fileinfo = $this->fileinfo( $file, $exists );
2130
+ }
2131
+
2132
+ return $fileinfo;
2133
+ }
2134
+
2135
+ /**
2136
+ * mb_convert_case alternative function
2137
+ *
2138
+ * @param $string
2139
+ *
2140
+ * @return string
2141
+ */
2142
+ function mb_ucwords_utf8( $string ) {
2143
+ $string = $this->mb_convert_encoding_utf8( $string );
2144
+ $string = ucwords( $string );
2145
+
2146
+ return $string;
2147
+ }
2148
+
2149
+ /**
2150
+ * mb_convert_encoding alternative function
2151
+ *
2152
+ * @param $string
2153
+ *
2154
+ * @return string
2155
+ */
2156
+ function mb_convert_encoding_utf8( $string ) {
2157
+ if ( function_exists( 'mb_convert_encoding' ) ) {
2158
+ $string = mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
2159
+ } else {
2160
+ $string = htmlspecialchars_decode( utf8_decode( htmlentities( $string, ENT_COMPAT, 'utf-8', false ) ) );
2161
+ }
2162
+
2163
+ return $string;
2164
+ }
2165
+
2166
+ /**
2167
+ * Return relative path to an uploaded file.
2168
+ * The path is relative to the current upload dir.
2169
+ *
2170
+ * @param string $path Full path to the file
2171
+ *
2172
+ * @return string relative path on success, unchanged path on failure.
2173
+ * @see _wp_relative_upload_path()
2174
+ * @uses apply_filters() Calls '_gm_relative_upload_path' on file path.
2175
+ *
2176
+ */
2177
+ function _gm_relative_upload_path( $path ) {
2178
+ $new_path = $path;
2179
+
2180
+ if ( ( false === $this->upload['error'] ) && ( 0 === strpos( $new_path, $this->upload['path'] ) ) ) {
2181
+ $new_path = str_replace( $this->upload['path'], '', $new_path );
2182
+ $new_path = ltrim( $new_path, '/' );
2183
+ }
2184
+
2185
+ return apply_filters( '_gm_relative_upload_path', $new_path, $path );
2186
+ }
2187
+
2188
+ /**
2189
+ * Retrieve metadata from a video file's ID3 tags
2190
+ *
2191
+ * @param string $file Path to file.
2192
+ *
2193
+ * @return array|boolean Returns array of metadata, if found.
2194
+ * @since 3.6.0
2195
+ *
2196
+ */
2197
+ function wp_read_video_metadata( $file ) {
2198
+ if ( ! is_file( $file ) ) {
2199
+ return false;
2200
+ }
2201
+
2202
+ $metadata = array();
2203
+
2204
+ if ( ! class_exists( 'getID3' ) ) {
2205
+ require( ABSPATH . WPINC . '/ID3/getid3.php' );
2206
+ }
2207
+ $id3 = new getID3();
2208
+ $data = $id3->analyze( $file );
2209
+
2210
+ if ( isset( $data['video']['lossless'] ) ) {
2211
+ $metadata['lossless'] = $data['video']['lossless'];
2212
+ }
2213
+ if ( ! empty( $data['video']['bitrate'] ) ) {
2214
+ $metadata['bitrate'] = (int) $data['video']['bitrate'];
2215
+ }
2216
+ if ( ! empty( $data['video']['bitrate_mode'] ) ) {
2217
+ $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
2218
+ }
2219
+ if ( ! empty( $data['filesize'] ) ) {
2220
+ $metadata['filesize'] = (int) $data['filesize'];
2221
+ }
2222
+ if ( ! empty( $data['mime_type'] ) ) {
2223
+ $metadata['mime_type'] = $data['mime_type'];
2224
+ }
2225
+ if ( ! empty( $data['playtime_seconds'] ) ) {
2226
+ $metadata['length'] = (int) ceil( $data['playtime_seconds'] );
2227
+ }
2228
+ if ( ! empty( $data['playtime_string'] ) ) {
2229
+ $metadata['length_formatted'] = $data['playtime_string'];
2230
+ }
2231
+ if ( ! empty( $data['video']['resolution_x'] ) ) {
2232
+ $metadata['width'] = (int) $data['video']['resolution_x'];
2233
+ }
2234
+ if ( ! empty( $data['video']['resolution_y'] ) ) {
2235
+ $metadata['height'] = (int) $data['video']['resolution_y'];
2236
+ }
2237
+ if ( ! empty( $data['fileformat'] ) ) {
2238
+ $metadata['fileformat'] = $data['fileformat'];
2239
+ }
2240
+ if ( ! empty( $data['video']['dataformat'] ) ) {
2241
+ $metadata['dataformat'] = $data['video']['dataformat'];
2242
+ }
2243
+ if ( ! empty( $data['video']['encoder'] ) ) {
2244
+ $metadata['encoder'] = $data['video']['encoder'];
2245
+ }
2246
+ if ( ! empty( $data['video']['codec'] ) ) {
2247
+ $metadata['codec'] = $data['video']['codec'];
2248
+ }
2249
+
2250
+ if ( ! empty( $data['audio'] ) ) {
2251
+ unset( $data['audio']['streams'] );
2252
+ $metadata['audio'] = $data['audio'];
2253
+ }
2254
+
2255
+ $this->wp_add_id3_tag_data( $metadata, $data );
2256
+
2257
+ return $metadata;
2258
+ }
2259
+
2260
+ /**
2261
+ * Parse ID3v2, ID3v1, and getID3 comments to extract usable data
2262
+ *
2263
+ * @param array $metadata An existing array with data
2264
+ * @param array $data Data supplied by ID3 tags
2265
+ *
2266
+ * @since 3.6.0
2267
+ *
2268
+ */
2269
+ function wp_add_id3_tag_data( &$metadata, $data ) {
2270
+ foreach ( array( 'id3v2', 'id3v1' ) as $version ) {
2271
+ if ( ! empty( $data[ $version ]['comments'] ) ) {
2272
+ foreach ( $data[ $version ]['comments'] as $key => $list ) {
2273
+ if ( ! empty( $list ) ) {
2274
+ $metadata[ $key ] = reset( $list );
2275
+ // fix bug in byte stream analysis
2276
+ if ( 'terms_of_use' === $key && 0 === strpos( $metadata[ $key ], 'yright notice.' ) ) {
2277
+ $metadata[ $key ] = 'Cop' . $metadata[ $key ];
2278
+ }
2279
+ }
2280
+ }
2281
+ break;
2282
+ }
2283
+ }
2284
+
2285
+ if ( ! empty( $data['id3v2']['APIC'] ) ) {
2286
+ $image = reset( $data['id3v2']['APIC'] );
2287
+ if ( ! empty( $image['data'] ) ) {
2288
+ $metadata['image'] = array(
2289
+ 'data' => $image['data'],
2290
+ 'mime' => $image['image_mime'],
2291
+ 'width' => $image['image_width'],
2292
+ 'height' => $image['image_height'],
2293
+ );
2294
+ }
2295
+ } elseif ( ! empty( $data['comments']['picture'] ) ) {
2296
+ $image = reset( $data['comments']['picture'] );
2297
+ if ( ! empty( $image['data'] ) ) {
2298
+ $metadata['image'] = array(
2299
+ 'data' => $image['data'],
2300
+ 'mime' => $image['image_mime'],
2301
+ );
2302
+ }
2303
+ }
2304
+ }
2305
+
2306
+ /**
2307
+ * Retrieve metadata from a audio file's ID3 tags
2308
+ *
2309
+ * @param string $file Path to file.
2310
+ *
2311
+ * @return array|boolean Returns array of metadata, if found.
2312
+ * @since 3.6.0
2313
+ *
2314
+ */
2315
+ function wp_read_audio_metadata( $file ) {
2316
+ if ( ! is_file( $file ) ) {
2317
+ return false;
2318
+ }
2319
+ $metadata = array();
2320
+
2321
+ if ( ! class_exists( 'getID3' ) ) {
2322
+ require( ABSPATH . WPINC . '/ID3/getid3.php' );
2323
+ }
2324
+ $id3 = new getID3();
2325
+ $data = $id3->analyze( $file );
2326
+
2327
+ if ( ! empty( $data['audio'] ) ) {
2328
+ unset( $data['audio']['streams'] );
2329
+ $metadata = $data['audio'];
2330
+ }
2331
+
2332
+ if ( ! empty( $data['fileformat'] ) ) {
2333
+ $metadata['fileformat'] = $data['fileformat'];
2334
+ }
2335
+ if ( ! empty( $data['filesize'] ) ) {
2336
+ $metadata['filesize'] = (int) $data['filesize'];
2337
+ }
2338
+ if ( ! empty( $data['mime_type'] ) ) {
2339
+ $metadata['mime_type'] = $data['mime_type'];
2340
+ }
2341
+ if ( ! empty( $data['playtime_seconds'] ) ) {
2342
+ $metadata['length'] = (int) ceil( $data['playtime_seconds'] );
2343
+ }
2344
+ if ( ! empty( $data['playtime_string'] ) ) {
2345
+ $metadata['length_formatted'] = $data['playtime_string'];
2346
+ }
2347
+
2348
+ $this->wp_add_id3_tag_data( $metadata, $data );
2349
+
2350
+ if ( isset( $metadata['image']['data'] ) && ! empty( $metadata['image']['data'] ) ) {
2351
+ $image = 'data:' . $metadata['image']['mime'] . ';charset=utf-8;base64,' . base64_encode( $metadata['image']['data'] );
2352
+ $metadata['image']['data'] = $image;
2353
+ }
2354
+
2355
+ return $metadata;
2356
+ }
2357
+
2358
+ /**
2359
+ * @param $base
2360
+ * @param $replacements
2361
+ *
2362
+ * @return mixed
2363
+ */
2364
+ function array_replace_recursive( $base, $replacements ) {
2365
+ if ( function_exists( 'array_replace_recursive' ) ) {
2366
+ return array_replace_recursive( $base, $replacements );
2367
+ }
2368
+
2369
+ foreach ( array_slice( func_get_args(), 1 ) as $replacements ) {
2370
+ $bref_stack = array( &$base );
2371
+ $head_stack = array( $replacements );
2372
+
2373
+ do {
2374
+ end( $bref_stack );
2375
+
2376
+ $bref = &$bref_stack[ key( $bref_stack ) ];
2377
+ $head = array_pop( $head_stack );
2378
+
2379
+ unset( $bref_stack[ key( $bref_stack ) ] );
2380
+
2381
+ foreach ( array_keys( $head ) as $key ) {
2382
+ if ( isset( $bref[ $key ] ) && is_array( $bref[ $key ] ) && is_array( $head[ $key ] ) ) {
2383
+ $bref_stack[] = &$bref[ $key ];
2384
+ $head_stack[] = $head[ $key ];
2385
+ } else {
2386
+ $bref[ $key ] = $head[ $key ];
2387
+ }
2388
+ }
2389
+ } while ( count( $head_stack ) );
2390
+ }
2391
+
2392
+ return $base;
2393
+ }
2394
+
2395
+ /**
2396
+ * @param $files
2397
+ * @param $_terms
2398
+ * @param $move
2399
+ * @param int|string $exists
2400
+ */
2401
+ function gmedia_import_files( $files, $_terms, $move, $exists = 0 ) {
2402
+ global $wpdb, $gmGallery, $gmDB;
2403
+
2404
+ if ( ob_get_level() == 0 ) {
2405
+ ob_start();
2406
+ }
2407
+ $eol = '</pre>' . PHP_EOL;
2408
+
2409
+ $gmedia_album = isset( $_terms['gmedia_album'] ) ? $_terms['gmedia_album'] : false;
2410
+ if ( $gmedia_album && $this->is_digit( $gmedia_album ) ) {
2411
+ $album = $gmDB->get_term( $gmedia_album );
2412
+ if ( empty( $album ) || is_wp_error( $album ) ) {
2413
+ $_status = 'publish';
2414
+ } else {
2415
+ $_status = $album->status;
2416
+ $album_name = $album->name;
2417
+ }
2418
+ } else {
2419
+ $_status = 'publish';
2420
+ }
2421
+
2422
+ if ( isset( $_terms['gmedia_album'] ) && ! empty( $_terms['gmedia_album'] ) ) {
2423
+ if ( is_array( $_terms['gmedia_album'] ) ) {
2424
+ $_terms['gmedia_album'] = trim( reset( $_terms['gmedia_album'] ) );
2425
+ }
2426
+ } else {
2427
+ $_terms['gmedia_album'] = '';
2428
+ }
2429
+ if ( isset( $_terms['gmedia_category'] ) && ! empty( $_terms['gmedia_category'] ) ) {
2430
+ if ( ! is_array( $_terms['gmedia_category'] ) ) {
2431
+ $_terms['gmedia_category'] = array_filter( array_map( 'trim', explode( ',', $_terms['gmedia_category'] ) ) );
2432
+ }
2433
+ } else {
2434
+ $_terms['gmedia_category'] = array();
2435
+ }
2436
+ if ( isset( $_terms['gmedia_tag'] ) && ! empty( $_terms['gmedia_tag'] ) ) {
2437
+ if ( ! is_array( $_terms['gmedia_tag'] ) ) {
2438
+ $_terms['gmedia_tag'] = array_filter( array_map( 'trim', explode( ',', $_terms['gmedia_tag'] ) ) );
2439
+ }
2440
+ } else {
2441
+ $_terms['gmedia_tag'] = array();
2442
+ }
2443
+
2444
+ $c = count( $files );
2445
+ $i = 0;
2446
+ foreach ( $files as $file ) {
2447
+
2448
+ $title = '';
2449
+ $description = '';
2450
+ $link = '';
2451
+ $status = $_status;
2452
+ $terms = $_terms;
2453
+
2454
+ if ( is_array( $file ) ) {
2455
+ if ( isset( $file['file'] ) ) {
2456
+ extract( $file );
2457
+ } else {
2458
+ _e( 'Something went wrong...', 'grand-media' );
2459
+ die();
2460
+ }
2461
+ }
2462
+
2463
+ wp_ob_end_flush_all();
2464
+ flush();
2465
+
2466
+ $i ++;
2467
+ $prefix = "\n<pre>$i/$c - ";
2468
+ $prefix_ko = "\n<pre class='ko'>$i/$c - ";
2469
+
2470
+ if ( ! is_file( $file ) ) {
2471
+ echo $prefix_ko . sprintf( __( 'File not exists: %s', 'grand-media' ), $file ) . $eol;
2472
+ continue;
2473
+ }
2474
+
2475
+ if ( 'skip' === $exists ) {
2476
+ $file_suffix = false;
2477
+ } else {
2478
+ $file_suffix = $exists;
2479
+ }
2480
+ $fileinfo = $this->fileinfo( $file, $file_suffix );
2481
+
2482
+ if ( ( 'skip' === $exists ) && is_file( $fileinfo['filepath'] ) ) {
2483
+ echo $prefix . $fileinfo['basename_original'] . ': ' . __( 'file with the same name already exists', 'grand-media' ) . $eol;
2484
+ continue;
2485
+ }
2486
+
2487
+
2488
+ // try to make grand-media dir if not exists
2489
+ if ( ! wp_mkdir_p( $fileinfo['dirpath'] ) ) {
2490
+ echo $prefix_ko . sprintf( __( 'Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath'] ) . $eol;
2491
+ continue;
2492
+ }
2493
+ // Check if grand-media dir is writable
2494
+ if ( ! is_writable( $fileinfo['dirpath'] ) ) {
2495
+ @chmod( $fileinfo['dirpath'], 0755 );
2496
+ if ( ! is_writable( $fileinfo['dirpath'] ) ) {
2497
+ echo $prefix_ko . sprintf( __( 'Directory `%s` or its subfolders are not writable by the server.', 'grand-media' ), dirname( $fileinfo['dirpath'] ) ) . $eol;
2498
+ continue;
2499
+ }
2500
+ }
2501
+
2502
+ if ( ( $file != $fileinfo['filepath'] ) && ! copy( $file, $fileinfo['filepath'] ) ) {
2503
+ echo $prefix_ko . sprintf( __( "Can't copy file from `%s` to `%s`", 'grand-media' ), $file, $fileinfo['filepath'] ) . $eol;
2504
+ continue;
2505
+ }
2506
+
2507
+ $this->file_chmod( $fileinfo['filepath'] );
2508
+
2509
+ $hash_file = hash_file( 'md5', $fileinfo['filepath'] );
2510
+ $duplicate_id = $wpdb->get_var( $wpdb->prepare( "SELECT gmedia_id FROM {$wpdb->prefix}gmedia_meta WHERE meta_key = '_hash' AND meta_value = %s LIMIT 1;", $hash_file ) );
2511
+ if ( $duplicate_id ) {
2512
+ @unlink( $fileinfo['filepath'] );
2513
+ echo $prefix_ko . $fileinfo['basename_original'] . ": " . sprintf( __( "Seems like it is duplicate of file with ID #%d", 'grand-media' ), $duplicate_id ) . $eol;
2514
+ continue;
2515
+ }
2516
+
2517
+ $size = false;
2518
+ $is_webimage = false;
2519
+ if ( 'image' == $fileinfo['dirname'] ) {
2520
+ /** WordPress Image Administration API */
2521
+ require_once( ABSPATH . 'wp-admin/includes/image.php' );
2522
+
2523
+ $size = @getimagesize( $fileinfo['filepath'] );
2524
+ if ( $size && file_is_displayable_image( $fileinfo['filepath'] ) ) {
2525
+ $extensions = array( '1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP' );
2526
+ if ( function_exists( 'memory_get_usage' ) ) {
2527
+ switch ( $extensions[ $size[2] ] ) {
2528
+ case 'GIF':
2529
+ $CHANNEL = 1;
2530
+ break;
2531
+ case 'JPG':
2532
+ $CHANNEL = $size['channels'];
2533
+ break;
2534
+ case 'PNG':
2535
+ $CHANNEL = 3;
2536
+ break;
2537
+ case 'BMP':
2538
+ default:
2539
+ $CHANNEL = 6;
2540
+ break;
2541
+ }
2542
+ $MB = 1048576; // number of bytes in 1M
2543
+ $K64 = 65536; // number of bytes in 64K
2544
+ $TWEAKFACTOR = 1.8; // Or whatever works for you
2545
+ $memoryNeeded = round( ( $size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64 ) * $TWEAKFACTOR );
2546
+ $memoryNeeded = memory_get_usage() + $memoryNeeded;
2547
+ $current_limit = @ini_get( 'memory_limit' );
2548
+ $current_limit_int = intval( $current_limit );
2549
+ if ( false !== strpos( $current_limit, 'M' ) ) {
2550
+ $current_limit_int *= $MB;
2551
+ }
2552
+ if ( false !== strpos( $current_limit, 'G' ) ) {
2553
+ $current_limit_int *= 1024;
2554
+ }
2555
+
2556
+ if ( - 1 != $current_limit && $memoryNeeded > $current_limit_int ) {
2557
+ $newLimit = $current_limit_int / $MB + ceil( ( $memoryNeeded - $current_limit_int ) / $MB );
2558
+ if ( $newLimit < 256 ) {
2559
+ $newLimit = 256;
2560
+ }
2561
+ @ini_set( 'memory_limit', $newLimit . 'M' );
2562
+ }
2563
+ }
2564
+
2565
+ if ( ! wp_mkdir_p( $fileinfo['dirpath_thumb'] ) ) {
2566
+ echo $prefix_ko . sprintf( __( 'Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath_thumb'] ) . $eol;
2567
+ continue;
2568
+ }
2569
+ if ( ! is_writable( $fileinfo['dirpath_thumb'] ) ) {
2570
+ @chmod( $fileinfo['dirpath_thumb'], 0755 );
2571
+ if ( ! is_writable( $fileinfo['dirpath_thumb'] ) ) {
2572
+ @unlink( $fileinfo['filepath'] );
2573
+ echo $prefix_ko . sprintf( __( 'Directory `%s` is not writable by the server.', 'grand-media' ), $fileinfo['dirpath_thumb'] ) . $eol;
2574
+ continue;
2575
+ }
2576
+ }
2577
+ if ( ! wp_mkdir_p( $fileinfo['dirpath_original'] ) ) {
2578
+ echo $prefix_ko . sprintf( __( 'Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media' ), $fileinfo['dirpath_original'] ) . $eol;
2579
+ continue;
2580
+ }
2581
+ if ( ! is_writable( $fileinfo['dirpath_original'] ) ) {
2582
+ @chmod( $fileinfo['dirpath_original'], 0755 );
2583
+ if ( ! is_writable( $fileinfo['dirpath_original'] ) ) {
2584
+ @unlink( $fileinfo['filepath'] );
2585
+ echo $prefix_ko . sprintf( __( 'Directory `%s` is not writable by the server.', 'grand-media' ), $fileinfo['dirpath_original'] ) . $eol;
2586
+ continue;
2587
+ }
2588
+ }
2589
+
2590
+ // Optimized image
2591
+ $webimg = $gmGallery->options['image'];
2592
+ $thumbimg = $gmGallery->options['thumb'];
2593
+
2594
+ $webimg['resize'] = ( ( $webimg['width'] < $size[0] ) || ( $webimg['height'] < $size[1] ) ) ? true : false;
2595
+
2596
+ if ( $webimg['resize'] ) {
2597
+ rename( $fileinfo['filepath'], $fileinfo['filepath_original'] );
2598
+ } else {
2599
+ copy( $fileinfo['filepath'], $fileinfo['filepath_original'] );
2600
+ }
2601
+
2602
+ $size_ratio = $size[0] / $size[1];
2603
+
2604
+ $angle = 0;
2605
+ $image_meta = @$this->wp_read_image_metadata( $fileinfo['filepath_original'] );
2606
+ if ( ! empty( $image_meta['orientation'] ) ) {
2607
+ switch ( $image_meta['orientation'] ) {
2608
+ case 3:
2609
+ $angle = 180;
2610
+ break;
2611
+ case 6:
2612
+ $angle = 270;
2613
+ $size_ratio = $size[1] / $size[0];
2614
+ break;
2615
+ case 8:
2616
+ $angle = 90;
2617
+ $size_ratio = $size[1] / $size[0];
2618
+ break;
2619
+ }
2620
+ }
2621
+
2622
+ $thumbimg['resize'] = ( ( ( 1 >= $size_ratio ) && ( $thumbimg['width'] > $size[0] ) ) || ( ( 1 <= $size_ratio ) && ( $thumbimg['height'] > $size[1] ) ) ) ? false : true;
2623
+
2624
+ if ( $webimg['resize'] || $thumbimg['resize'] || $angle ) {
2625
+ $editor = wp_get_image_editor( $fileinfo['filepath_original'] );
2626
+ if ( is_wp_error( $editor ) ) {
2627
+ @unlink( $fileinfo['filepath'] );
2628
+ @unlink( $fileinfo['filepath_original'] );
2629
+ echo $prefix_ko . $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message() . $eol;
2630
+ continue;
2631
+ }
2632
+
2633
+ if ( $angle ) {
2634
+ $editor->rotate( $angle );
2635
+ }
2636
+
2637
+ if ( $webimg['resize'] || $angle ) {
2638
+ $editor->set_quality( $webimg['quality'] );
2639
+
2640
+ if ( $webimg['resize'] ) {
2641
+ $resized = $editor->resize( $webimg['width'], $webimg['height'], $webimg['crop'] );
2642
+ if ( is_wp_error( $resized ) ) {
2643
+ @unlink( $fileinfo['filepath'] );
2644
+ @unlink( $fileinfo['filepath_original'] );
2645
+ echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message() . $eol;
2646
+ continue;
2647
+ }
2648
+ }
2649
+
2650
+ $saved = $editor->save( $fileinfo['filepath'] );
2651
+ if ( is_wp_error( $saved ) ) {
2652
+ @unlink( $fileinfo['filepath'] );
2653
+ @unlink( $fileinfo['filepath_original'] );
2654
+ echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message() . $eol;
2655
+ continue;
2656
+ }
2657
+
2658
+ if ( ( 'JPG' == $extensions[ $size[2] ] ) && ! ( extension_loaded( 'imagick' ) || class_exists( "Imagick" ) ) ) {
2659
+ $this->copy_exif( $fileinfo['filepath_original'], $fileinfo['filepath'] );
2660
+ }
2661
+
2662
+ }
2663
+
2664
+ // Thumbnail
2665
+ $editor->set_quality( $thumbimg['quality'] );
2666
+ if ( $thumbimg['resize'] ) {
2667
+ $ed_size = $editor->get_size();
2668
+ $ed_ratio = $ed_size['width'] / $ed_size['height'];
2669
+ if ( 1 > $ed_ratio ) {
2670
+ $resized = $editor->resize( $thumbimg['width'], 0, $thumbimg['crop'] );
2671
+ } else {
2672
+ $resized = $editor->resize( 0, $thumbimg['height'], $thumbimg['crop'] );
2673
+ }
2674
+ if ( is_wp_error( $resized ) ) {
2675
+ @unlink( $fileinfo['filepath'] );
2676
+ @unlink( $fileinfo['filepath_original'] );
2677
+ echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message() . $eol;
2678
+ continue;
2679
+ }
2680
+ }
2681
+
2682
+ $saved = $editor->save( $fileinfo['filepath_thumb'] );
2683
+ if ( is_wp_error( $saved ) ) {
2684
+ @unlink( $fileinfo['filepath'] );
2685
+ @unlink( $fileinfo['filepath_original'] );
2686
+ echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message() . $eol;
2687
+ continue;
2688
+ }
2689
+ } else {
2690
+ copy( $fileinfo['filepath'], $fileinfo['filepath_thumb'] );
2691
+ }
2692
+ $is_webimage = true;
2693
+ } else {
2694
+ @unlink( $fileinfo['filepath'] );
2695
+ echo $prefix_ko . $fileinfo['basename'] . ": " . __( "Could not read image size. Invalid image was deleted.", 'grand-media' ) . $eol;
2696
+ continue;
2697
+ }
2698
+ }
2699
+
2700
+ // Write media data to DB
2701
+ if ( $size ) {
2702
+ if ( ! empty( $image_meta ) ) {
2703
+ if ( empty( $title ) && ! empty( $image_meta['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
2704
+ $title = $image_meta['title'];
2705
+ }
2706
+ if ( empty( $description ) && ! empty( $image_meta['caption'] ) && trim( $image_meta['caption'] ) ) {
2707
+ $description = $image_meta['caption'];
2708
+ }
2709
+ if ( ! empty( $image_meta['keywords'] ) ) {
2710
+ $terms['gmedia_tag'] = array_unique( array_merge( (array) $_terms['gmedia_tag'], $image_meta['keywords'] ) );
2711
+ }
2712
+ }
2713
+ } else {
2714
+ $file_meta = $this->get_file_metadata( $fileinfo['filepath_original'], $fileinfo );
2715
+ if ( ! empty( $file_meta ) ) {
2716
+ if ( empty( $title ) && ! empty( $file_meta['title'] ) && trim( $file_meta['title'] ) && ! is_numeric( sanitize_title( $file_meta['title'] ) ) ) {
2717
+ $title = $file_meta['title'];
2718
+ }
2719
+ if ( empty( $description ) && ! empty( $file_meta['comment'] ) && trim( $file_meta['comment'] ) ) {
2720
+ $description = $file_meta['comment'];
2721
+ }
2722
+ if ( empty( $terms['gmedia_album'] ) && ! empty( $file_meta['album'] ) ) {
2723
+ $terms['gmedia_album'] = array( $file_meta['album'] );
2724
+ }
2725
+ }
2726
+ }
2727
+
2728
+ if ( empty( $title ) ) {
2729
+ $title = $fileinfo['title'];
2730
+ }
2731
+
2732
+ // Construct the media_data array
2733
+ $media_data = array(
2734
+ 'mime_type' => $fileinfo['mime_type'],
2735
+ 'gmuid' => $fileinfo['basename'],
2736
+ 'title' => $title,
2737
+ 'link' => $link,
2738
+ 'description' => $description,
2739
+ 'status' => $status,
2740
+ 'terms' => $terms,
2741
+ );
2742
+
2743
+ if ( ! empty( $file['auhtor'] ) ) {
2744
+ $media_data['author'] = (int) $file['auhtor'];
2745
+ } elseif ( ! current_user_can( 'gmedia_delete_others_media' ) ) {
2746
+ $media_data['author'] = get_current_user_id();
2747
+ }
2748
+
2749
+ // Save the data
2750
+ $id = $gmDB->insert_gmedia( $media_data );
2751
+
2752
+ $media_metadata = $gmDB->generate_gmedia_metadata( $id, $fileinfo );
2753
+ if ( $size && ! empty( $image_meta ) ) {
2754
+ if ( empty( $media_metadata['image_meta'] ) ) {
2755
+ $media_metadata['image_meta'] = $image_meta;
2756
+ }
2757
+ if ( ! empty( $image_meta['created_timestamp'] ) ) {
2758
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_created_timestamp', $image_meta['created_timestamp'] );
2759
+ }
2760
+ if ( ! empty( $image_meta['GPS'] ) ) {
2761
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_gps', $image_meta['GPS'] );
2762
+ }
2763
+ }
2764
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_metadata', $media_metadata );
2765
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_hash', $hash_file );
2766
+ $file_size = filesize( $fileinfo['filepath_original'] );
2767
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_size', $file_size );
2768
+
2769
+ echo $prefix . $fileinfo['basename'] . ': <span class="ok">' . sprintf( __( 'success (ID #%s)', 'grand-media' ), $id ) . '</span>' . $eol;
2770
+
2771
+ if ( (int) $gmGallery->options['delete_originals'] ) {
2772
+ @unlink( $fileinfo['filepath_original'] );
2773
+ }
2774
+ if ( $move ) {
2775
+ @unlink( $file );
2776
+ }
2777
+
2778
+ }
2779
+
2780
+ echo '<p><b>' . __( 'Category' ) . ':</b> ' . ( ! empty( $_terms['gmedia_category'] ) ? esc_html( implode( ', ', $_terms['gmedia_category'] ) ) : '-' ) . PHP_EOL;
2781
+ echo '<br /><b>' . __( 'Album' ) . ':</b> ' . ( ! empty( $_terms['gmedia_album'] ) ? ( isset( $album_name ) ? $album_name : esc_html( $_terms['gmedia_album'] ) ) : '-' ) . PHP_EOL;
2782
+ echo '<br /><b>' . __( 'Tags' ) . ':</b> ' . ( ! empty( $_terms['gmedia_tag'] ) ? esc_html( implode( ', ', $_terms['gmedia_tag'] ) ) : '-' ) . '</p>' . PHP_EOL;
2783
+
2784
+ wp_ob_end_flush_all();
2785
+ flush();
2786
+ }
2787
+
2788
+ /**
2789
+ * @param $gmid
2790
+ */
2791
+ function duplicate_gmedia( $gmid ) {
2792
+ global $gmDB;
2793
+
2794
+ $gmedia = $gmDB->get_gmedia( $gmid );
2795
+ if ( ! $gmedia || is_wp_error( $gmedia ) ) {
2796
+ return;
2797
+ }
2798
+
2799
+ $fileinfo = $this->fileinfo( $gmedia->gmuid );
2800
+
2801
+ if ( is_file( $fileinfo['dirpath_original'] . '/' . $gmedia->gmuid ) ) {
2802
+ $file = $fileinfo['dirpath_original'] . '/' . $gmedia->gmuid;
2803
+ copy( $file, $fileinfo['filepath_original'] );
2804
+ }
2805
+
2806
+ if ( 'image' == $fileinfo['dirname'] ) {
2807
+ copy( $fileinfo['dirpath'] . '/' . $gmedia->gmuid, $fileinfo['filepath'] );
2808
+ copy( $fileinfo['dirpath_thumb'] . '/' . $gmedia->gmuid, $fileinfo['filepath_thumb'] );
2809
+ }
2810
+
2811
+ // Construct the media_data array
2812
+ $media_data = array(
2813
+ 'mime_type' => $fileinfo['mime_type'],
2814
+ 'gmuid' => $fileinfo['basename'],
2815
+ 'title' => $gmedia->title,
2816
+ 'link' => $gmedia->link,
2817
+ 'description' => $gmedia->description,
2818
+ 'status' => $gmedia->status,
2819
+ 'terms' => array(
2820
+ 'gmedia_album' => $gmDB->get_gmedia_terms( $gmedia->ID, array( 'gmedia_album' ), array( 'fields' => 'ids' ) ),
2821
+ 'gmedia_category' => $gmDB->get_gmedia_terms( $gmedia->ID, array( 'gmedia_category' ), array( 'fields' => 'ids' ) ),
2822
+ 'gmedia_tag' => $gmDB->get_gmedia_terms( $gmedia->ID, array( 'gmedia_tag' ), array( 'fields' => 'ids', 'order' => 'term_order' ) ),
2823
+ ),
2824
+ );
2825
+
2826
+ $media_data['author'] = get_current_user_id();
2827
+
2828
+ // Save the data
2829
+ $id = $gmDB->insert_gmedia( $media_data );
2830
+
2831
+ $media_metadata = $gmDB->get_metadata( 'gmedia', $gmedia->ID );
2832
+ foreach ( $media_metadata as $key => $values ) {
2833
+ //if($this->is_protected_meta($key, 'gmedia')){
2834
+ foreach ( $values as $val ) {
2835
+ $gmDB->add_metadata( $meta_type = 'gmedia', $id, $key, $val );
2836
+ }
2837
+ //}
2838
+ }
2839
+
2840
+ }
2841
+
2842
+ /**
2843
+ * @param $gmid
2844
+ *
2845
+ * @return array
2846
+ */
2847
+ function recreate_images_from_original( $gmid ) {
2848
+ global $gmDB, $gmGallery;
2849
+
2850
+ $item = $gmDB->get_gmedia( $gmid );
2851
+ if ( ! empty( $item ) ) {
2852
+
2853
+ $type = explode( '/', $item->mime_type );
2854
+ $type = $type[0];
2855
+ if ( 'image' !== $type ) {
2856
+ $out = array( 'error' => $this->alert( 'danger', sprintf( __( '#%d: Not image type', 'grand-media' ), $item->ID ) ) );
2857
+
2858
+ return $out;
2859
+ }
2860
+
2861
+ $gmedia = array();
2862
+ $fail = '';
2863
+ $success = '';
2864
+
2865
+ if ( (int) $item->author != get_current_user_id() ) {
2866
+ if ( ! current_user_can( 'gmedia_edit_others_media' ) ) {
2867
+ $out = array( 'error' => $this->alert( 'danger', __( 'You are not allowed to edit others media', 'grand-media' ) ) );
2868
+
2869
+ return $out;
2870
+ }
2871
+ }
2872
+ $meta = $gmDB->get_metadata( 'gmedia', $item->ID );
2873
+ $metadata = $meta['_metadata'][0];
2874
+ $gmedia['ID'] = $gmid;
2875
+ $gmedia['date'] = $item->date;
2876
+ $gmedia['modified'] = current_time( 'mysql' );
2877
+ $gmedia['author'] = $item->author;
2878
+
2879
+ $webimg = $gmGallery->options['image'];
2880
+ $thumbimg = $gmGallery->options['thumb'];
2881
+
2882
+ $fileinfo = $this->fileinfo( $item->gmuid, false );
2883
+ $is_file_original = is_file( $fileinfo['filepath_original'] );
2884
+ $filepath_original = $is_file_original ? $fileinfo['filepath_original'] : ( is_file( $fileinfo['filepath'] ) ? $fileinfo['filepath'] : null );
2885
+ if ( ! $filepath_original ) {
2886
+ $out = array( 'error' => $this->alert( 'danger', __( 'Original file does not exists', 'grand-media' ) ) );
2887
+
2888
+ return $out;
2889
+ }
2890
+ $size = @getimagesize( $filepath_original );
2891
+
2892
+ do {
2893
+ $extensions = array( '1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP' );
2894
+ if ( function_exists( 'memory_get_usage' ) ) {
2895
+ switch ( $extensions[ $size[2] ] ) {
2896
+ case 'GIF':
2897
+ $CHANNEL = 1;
2898
+ break;
2899
+ case 'JPG':
2900
+ $CHANNEL = $size['channels'];
2901
+ break;
2902
+ case 'PNG':
2903
+ $CHANNEL = 3;
2904
+ break;
2905
+ case 'BMP':
2906
+ default:
2907
+ $CHANNEL = 6;
2908
+ break;
2909
+ }
2910
+ $MB = 1048576; // number of bytes in 1M
2911
+ $K64 = 65536; // number of bytes in 64K
2912
+ $TWEAKFACTOR = 1.8; // Or whatever works for you
2913
+ $memoryNeeded = round( ( $size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64 ) * $TWEAKFACTOR );
2914
+ $memoryNeeded = memory_get_usage() + $memoryNeeded;
2915
+ $current_limit = @ini_get( 'memory_limit' );
2916
+ $current_limit_int = intval( $current_limit );
2917
+ if ( false !== strpos( $current_limit, 'M' ) ) {
2918
+ $current_limit_int *= $MB;
2919
+ }
2920
+ if ( false !== strpos( $current_limit, 'G' ) ) {
2921
+ $current_limit_int *= 1024;
2922
+ }
2923
+
2924
+ if ( - 1 != $current_limit && $memoryNeeded > $current_limit_int ) {
2925
+ $newLimit = $current_limit_int / $MB + ceil( ( $memoryNeeded - $current_limit_int ) / $MB );
2926
+ if ( $newLimit < 256 ) {
2927
+ $newLimit = 256;
2928
+ }
2929
+ @ini_set( 'memory_limit', $newLimit . 'M' );
2930
+ }
2931
+ }
2932
+
2933
+ $size_ratio = $size[0] / $size[1];
2934
+
2935
+ $angle = 0;
2936
+ if ( $is_file_original ) {
2937
+ $image_meta = @$this->wp_read_image_metadata( $filepath_original );
2938
+ if ( ! empty( $image_meta['orientation'] ) ) {
2939
+ switch ( $image_meta['orientation'] ) {
2940
+ case 3:
2941
+ $angle = 180;
2942
+ break;
2943
+ case 6:
2944
+ $angle = 270;
2945
+ $size_ratio = $size[1] / $size[0];
2946
+ break;
2947
+ case 8:
2948
+ $angle = 90;
2949
+ $size_ratio = $size[1] / $size[0];
2950
+ break;
2951
+ }
2952
+ }
2953
+ $webimg['resize'] = ( ( $webimg['width'] < $size[0] ) || ( $webimg['height'] < $size[1] ) ) ? true : false;
2954
+ } else {
2955
+ $webimg['resize'] = false;
2956
+ }
2957
+
2958
+ $thumbimg['resize'] = ( ( ( 1 >= $size_ratio ) && ( $thumbimg['width'] > $size[0] ) ) || ( ( 1 <= $size_ratio ) && ( $thumbimg['height'] > $size[1] ) ) ) ? false : true;
2959
+
2960
+ if ( $webimg['resize'] || $thumbimg['resize'] || $angle ) {
2961
+
2962
+ $editor = wp_get_image_editor( $filepath_original );
2963
+ if ( is_wp_error( $editor ) ) {
2964
+ $fail = $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message();
2965
+ break;
2966
+ }
2967
+
2968
+ if ( $is_file_original ) {
2969
+ if ( $angle ) {
2970
+ $editor->rotate( $angle );
2971
+ }
2972
+
2973
+ if ( $webimg['resize'] || $angle ) {
2974
+ // Web-image
2975
+ $editor->set_quality( $webimg['quality'] );
2976
+
2977
+ if ( $webimg['resize'] ) {
2978
+ $resized = $editor->resize( $webimg['width'], $webimg['height'], $webimg['crop'] );
2979
+ if ( is_wp_error( $resized ) ) {
2980
+ $fail = $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message();
2981
+ break;
2982
+ }
2983
+ }
2984
+
2985
+ $saved = $editor->save( $fileinfo['filepath'] );
2986
+ if ( is_wp_error( $saved ) ) {
2987
+ $fail = $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message();
2988
+ break;
2989
+ }
2990
+ if ( ( 'JPG' == $extensions[ $size[2] ] ) && ! ( extension_loaded( 'imagick' ) || class_exists( "Imagick" ) ) ) {
2991
+ $this->copy_exif( $filepath_original, $fileinfo['filepath'] );
2992
+ }
2993
+ } else {
2994
+ @copy( $filepath_original, $fileinfo['filepath'] );
2995
+ }
2996
+ }
2997
+
2998
+ // Thumbnail
2999
+ $editor->set_quality( $thumbimg['quality'] );
3000
+ if ( $thumbimg['resize'] ) {
3001
+ $ed_size = $editor->get_size();
3002
+ $ed_ratio = $ed_size['width'] / $ed_size['height'];
3003
+ if ( 1 > $ed_ratio ) {
3004
+ $resized = $editor->resize( $thumbimg['width'], 0, $thumbimg['crop'] );
3005
+ } else {
3006
+ $resized = $editor->resize( 0, $thumbimg['height'], $thumbimg['crop'] );
3007
+ }
3008
+ if ( is_wp_error( $resized ) ) {
3009
+ $fail = $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message();
3010
+ break;
3011
+ }
3012
+ }
3013
+
3014
+ $saved = $editor->save( $fileinfo['filepath_thumb'] );
3015
+ if ( is_wp_error( $saved ) ) {
3016
+ $fail = $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message();
3017
+ break;
3018
+ }
3019
+
3020
+ } else {
3021
+ if ( $is_file_original ) {
3022
+ @copy( $filepath_original, $fileinfo['filepath'] );
3023
+ }
3024
+ @copy( $filepath_original, $fileinfo['filepath_thumb'] );
3025
+ }
3026
+
3027
+ $id = $gmDB->insert_gmedia( $gmedia );
3028
+
3029
+ $new_metadata = $gmDB->generate_gmedia_metadata( $id, $fileinfo );
3030
+ $metadata['thumb'] = $new_metadata['thumb'];
3031
+ $metadata['web'] = $new_metadata['web'];
3032
+ $metadata['original'] = $new_metadata['original'];
3033
+
3034
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_metadata', $metadata );
3035
+ $gmDB->update_metadata( $meta_type = 'gmedia', $id, $meta_key = '_modified', 0 );
3036
+
3037
+ $success = sprintf( __( 'Image "%d" restored from backup and saved', 'grand-media' ), $id );
3038
+ } while ( 0 );
3039
+
3040
+ if ( empty( $fail ) ) {
3041
+ $out = array( 'msg' => $this->alert( 'info', $success ), 'modified' => $gmedia['modified'] );
3042
+ } else {
3043
+ $out = array( 'error' => $this->alert( 'danger', $fail ) );
3044
+ }
3045
+
3046
+ } else {
3047
+ $out = array( 'error' => $this->alert( 'danger', sprintf( __( '#%d: No image in database', 'grand-media' ), $gmid ) ) );
3048
+ }
3049
+
3050
+ return $out;
3051
+ }
3052
+
3053
+ /**
3054
+ * @param string $type
3055
+ * @param string $content
3056
+ *
3057
+ * @return string
3058
+ */
3059
+ public function alert( $type = 'info', $content = '' ) {
3060
+ if ( empty( $content ) ) {
3061
+ return '';
3062
+ } elseif ( is_array( $content ) ) {
3063
+ $content = array_filter( $content );
3064
+ $content = implode( '<br />', $content );
3065
+ }
3066
+ $alert = '<div class="alert alert-' . $type . ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' . $content . '</div>';
3067
+
3068
+ return $alert;
3069
+ }
3070
+
3071
+ /**
3072
+ * @param string $service
3073
+ *
3074
+ * @return array|bool json
3075
+ */
3076
+ function app_service( $service ) {
3077
+ global $gmGallery, $gmDB, $wp_version;
3078
+
3079
+ if ( empty( $_SERVER['HTTP_X_REAL_IP'] ) && ( '127.0.0.1' == $_SERVER['REMOTE_ADDR'] || '::1' == $_SERVER['REMOTE_ADDR'] ) ) {
3080
+ return false;
3081
+ }
3082
+ if ( ! current_user_can( 'manage_options' ) ) {
3083
+ die( '-1' );
3084
+ }
3085
+ if ( ! $service ) {
3086
+ die( '0' );
3087
+ }
3088
+
3089
+ $result = array();
3090
+ $data = array();
3091
+ $options = $gmGallery->options;
3092
+
3093
+ if ( $service == 'app_deactivate' ) {
3094
+ $options['mobile_app'] = 0;
3095
+ }
3096
+
3097
+ $data['site_email'] = get_option( 'admin_email' );
3098
+ if ( in_array( $service, array( 'app_updateinfo' ) ) && ! is_email( $data['site_email'] ) ) {
3099
+ $result['error'][] = __( 'Invalid email', 'grand-media' );
3100
+ } else {
3101
+
3102
+ $url = home_url();
3103
+ $post_data = array( 'url' => $url );
3104
+
3105
+ if ( in_array( $service, array( 'app_deactivateplugin', 'app_uninstallplugin' ) ) ) {
3106
+ if ( ! empty( $options['site_ID'] ) ) {
3107
+ $post_data['site_id'] = $options['site_ID'];
3108
+ wp_remote_post( 'https://gmediaservice.codeasily.com/?gmService=' . $service, array(
3109
+ 'method' => 'POST',
3110
+ 'timeout' => 5,
3111
+ 'blocking' => false,
3112
+ 'sslverify' => false,
3113
+ 'body' => $post_data,
3114
+
3115
+ ) );
3116
+ }
3117
+
3118
+ return false;
3119
+ }
3120
+
3121
+ $hash = 'gmedia_' . wp_generate_password( '6', false );
3122
+
3123
+ if ( in_array( $service, array( 'app_activate', 'app_updateinfo' ) ) ) {
3124
+ $status = 1;
3125
+ } else {
3126
+ $status = $options['mobile_app'];
3127
+ }
3128
+ $install_date = get_option( 'gmediaInstallDate' );
3129
+
3130
+ $data['service'] = $service;
3131
+ $data['site_hash'] = $hash;
3132
+ $data['site_ID'] = $options['site_ID'];
3133
+ $data['title'] = get_bloginfo( 'name' );
3134
+ $data['description'] = get_bloginfo( 'description' );
3135
+ $data['url'] = $url;
3136
+ $data['license'] = $options['license_key'];
3137
+ $data['status'] = $status;
3138
+ $data['install_date'] = (int) $install_date;
3139
+ $data['counters'] = $gmDB->count_gmedia();
3140
+ $data['php_version'] = phpversion();
3141
+ $data['wp_version'] = $wp_version;
3142
+ $data['gmedia_version'] = GMEDIA_VERSION;
3143
+ $data['locale'] = get_locale();
3144
+
3145
+ $theme = wp_get_theme();
3146
+ $data['theme'] = array(
3147
+ 'name' => $theme->get( 'Name' ),
3148
+ 'version' => $theme->get( 'Version' ),
3149
+ 'theme_uri' => $theme->get( 'ThemeURI' ),
3150
+ );
3151
+
3152
+ if ( ! function_exists( 'get_plugins' ) ) {
3153
+ require_once ABSPATH . 'wp-admin/includes/plugin.php';
3154
+ }
3155
+ $active_plugins = get_option( 'active_plugins' );
3156
+ $plugins = get_plugins();
3157
+ $data['plugins'] = array();
3158
+ foreach ( $active_plugins as $p ) {
3159
+ if ( isset( $plugins[ $p ] ) ) {
3160
+ $data['plugins'][ $p ] = array(
3161
+ 'name' => $plugins[ $p ]['Name'],
3162
+ 'version' => $plugins[ $p ]['Version'],
3163
+ 'plugin_uri' => $plugins[ $p ]['PluginURI'],
3164
+ );
3165
+ }
3166
+ }
3167
+
3168
+ $tagslist = $gmDB->get_terms( 'gmedia_tag', array(
3169
+ 'hide_empty' => true,
3170
+ 'fields' => 'names_count',
3171
+ 'orderby' => 'count',
3172
+ 'order' => 'DESC',
3173
+ 'no_found_rows' => true,
3174
+ ) );
3175
+ $data['tags'] = array();
3176
+ if ( ! is_wp_error( $tagslist ) ) {
3177
+ foreach ( $tagslist as $tag ) {
3178
+ if ( $tag['count'] < 10 ) {
3179
+ break;
3180
+ }
3181
+ $data['tags'][] = $tag['name'];
3182
+ }
3183
+ }
3184
+
3185
+ set_transient( $hash, $data, 45 );
3186
+
3187
+ $post_data['hash'] = $hash;
3188
+ $gms_post = wp_remote_post( 'https://gmediaservice.codeasily.com/?gmService=' . $service, array(
3189
+ 'method' => 'POST',
3190
+ 'timeout' => 45,
3191
+ //'blocking' => false,
3192
+ 'sslverify' => false,
3193
+ 'body' => $post_data,
3194
+ ) );
3195
+ if ( is_wp_error( $gms_post ) ) {
3196
+ $result['error'][] = $gms_post->get_error_message();
3197
+ }
3198
+ $gms_post_body = wp_remote_retrieve_body( $gms_post );
3199
+ $_result = (array) json_decode( $gms_post_body );
3200
+ if ( isset( $_result['error'] ) ) {
3201
+ if ( ! isset( $result['error'] ) ) {
3202
+ $result['error'] = array();
3203
+ }
3204
+ $_result['error'] = (array) $_result['error'];
3205
+ $_result['error'] = array_filter( $_result['error'], 'is_string' );
3206
+ $result['error'] = array_merge( $result['error'], $_result['error'] );
3207
+ } else {
3208
+ $result = array_merge( $_result, $result );
3209
  // $result['gms_the_data'] = $data;
3210
  // $result['gms_post'] = $gms_post;
3211
  // $result['gms_post_body'] = $gms_post_body;
3212
+ if ( isset( $result['message'] ) ) {
3213
+ $result['message'] = $this->alert( 'info', $result['message'] );
3214
+ }
3215
+
3216
+ if ( isset( $result['site_ID'] ) ) {
3217
+ $options['site_ID'] = $result['site_ID'];
3218
+ }
3219
+ if ( isset( $result['mobile_app'] ) ) {
3220
+ $options['mobile_app'] = $result['mobile_app'];
3221
+ }
3222
+ }
3223
+ if ( isset( $result['error'] ) ) {
3224
+ $result['error'] = $this->alert( 'danger', $result['error'] );
3225
+ }
3226
+ }
3227
+ update_option( 'gmediaOptions', $options );
3228
+
3229
+ if ( in_array( $service, array( 'app_activate', 'app_updateinfo' ) ) ) {
3230
+ wp_clear_scheduled_hook( 'gmedia_app_cronjob' );
3231
+ wp_schedule_event( time(), 'gmedia_app', 'gmedia_app_cronjob' );
3232
+ }
3233
+
3234
+ return $result;
3235
+ }
3236
+
3237
+ /**
3238
+ * @param null $modules
3239
+ */
3240
+ function modules_update( $modules = null ) {
3241
+ $wp_installing = (bool) ( defined( 'WP_INSTALLING' ) && WP_INSTALLING );
3242
+ if ( $wp_installing ) {
3243
+ return;
3244
+ }
3245
+
3246
+ if ( ! is_array( $modules ) ) {
3247
+ $modules = get_gmedia_modules();
3248
+ }
3249
+ if ( isset( $modules['error'] ) ) {
3250
+ return;
3251
+ }
3252
+
3253
+ global $gmGallery;
3254
+ $modules_update_count = 0;
3255
+
3256
+ foreach ( $modules['in'] as $module ) {
3257
+ if ( ! empty( $module['update'] ) && 'remote' != $module['place'] ) {
3258
+ $modules_update_count ++;
3259
+ }
3260
+ }
3261
+
3262
+ $gmGallery->options = get_option( 'gmediaOptions' );
3263
+ $gmGallery->options['modules_update'] = $modules_update_count;
3264
+ $gmGallery->options['modules_new'] = isset( $modules['out'] ) ? count( $modules['out'] ) : 0;
3265
+
3266
+ update_option( 'gmediaOptions', $gmGallery->options );
3267
+ }
3268
+
3269
+ /**
3270
+ * Display custom fields form fields.
3271
+ *
3272
+ * @param int $gmedia_id
3273
+ * @param string $meta_type
3274
+ *
3275
+ * @since 1.6.3
3276
+ *
3277
+ */
3278
+ function gmedia_custom_meta_box( $gmedia_id, $meta_type = 'gmedia' ) {
3279
+ global $gmDB;
3280
+
3281
+ if ( empty( $gmedia_id ) ) {
3282
+ return;
3283
+ }
3284
+
3285
+ if ( ! in_array( $meta_type, array( 'gmedia', 'gmedia_term' ) ) ) {
3286
+ $meta_type = 'gmedia';
3287
+ }
3288
+ ?>
3289
+ <fieldset id="gmediacustomstuff_<?php echo $gmedia_id; ?>" class="gmediacustomstuff" data-metatype="<?php echo $meta_type; ?>">
3290
+ <legend class="label label-default" style="font-size:85%;"><?php _e( 'Custom Fields', 'grand-media' ); ?></legend>
3291
+ <?php
3292
+ $metadata = $gmDB->has_meta( $gmedia_id, $meta_type );
3293
+ foreach ( $metadata as $key => $value ) {
3294
+ if ( $this->is_protected_meta( $metadata[ $key ]['meta_key'], $meta_type ) ) {
3295
+ unset( $metadata[ $key ] );
3296
+ }
3297
+ } ?>
3298
+ <div class="row">
3299
+ <?php if ( ! empty( $metadata ) ) {
3300
+ //$count = 0;
3301
+ foreach ( $metadata as $entry ) {
3302
+ echo $this->_list_meta_item( $entry, $meta_type );
3303
+ }
3304
+ } ?>
3305
+ </div>
3306
+ <a href="#newCustomFieldModal" data-gmid="<?php echo $gmedia_id; ?>" class="newcustomfield-modal label label-primary"><?php _e( 'Add New Custom Field', 'grand-media' ) ?></a>
3307
+ </fieldset>
3308
+ <p><?php _e( 'Custom fields can be used to add extra metadata to a gmedia item that developer can use in their templates.' ); ?></p>
3309
+ <?php
3310
+ } // add_meta
3311
+
3312
+ /**
3313
+ * Determine whether a meta key is protected.
3314
+ *
3315
+ * @param string $meta_key Meta key
3316
+ * @param string|null $meta_type
3317
+ *
3318
+ * @return bool True if the key is protected, false otherwise.
3319
+ */
3320
+ function is_protected_meta( $meta_key, $meta_type = null ) {
3321
+ $protected = ( '_' == $meta_key[0] );
3322
+
3323
+ return apply_filters( 'is_protected_gmedia_meta', $protected, $meta_key, $meta_type );
3324
+ }
3325
+
3326
+ /**
3327
+ * @param $entry
3328
+ * @param string $meta_type
3329
+ *
3330
+ * @return string|void
3331
+ * @since 1.6.3
3332
+ *
3333
+ */
3334
+ function _list_meta_item( $entry, $meta_type = 'gmedia' ) {
3335
+ if ( is_serialized( $entry['meta_value'] ) ) {
3336
+ if ( is_serialized_string( $entry['meta_value'] ) ) {
3337
+ // This is a serialized string, so we should display it.
3338
+ $entry['meta_value'] = maybe_unserialize( $entry['meta_value'] );
3339
+ } else {
3340
+ // This is a serialized array/object so we should NOT display it.
3341
+ return;
3342
+ }
3343
+ }
3344
+
3345
+ $entry['meta_key'] = esc_attr( $entry['meta_key'] );
3346
+ $entry['meta_value'] = esc_textarea( $entry['meta_value'] ); // using a <textarea />
3347
+ $entry['meta_id'] = (int) $entry['meta_id'];
3348
+
3349
+ $colsm = ( 'gmedia' == $meta_type ) ? 6 : 4;
3350
+ //$delete_nonce = wp_create_nonce( 'gmedia_custom_field', '_wpnonce_custom_field' );
3351
+ $item = '
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3352
  <div class="form-group col-sm-' . $colsm . ' gm-custom-meta-' . $entry['meta_id'] . '">
3353
  <span class="delete-custom-field glyphicon glyphicon-remove pull-right text-danger"></span>
3354
  <label>' . $entry['meta_key'] . '</label>
3355
+ <textarea name="meta[' . $entry['meta_id'] . ']" class="gmedia-custom-field gm-custom-field-' . $entry['meta_id'] . ' vert form-control input-sm" style="height:30px;" placeholder="' . __( 'Value', 'grand-media' ) . '" rows="1" cols="30">' . $entry['meta_value'] . '</textarea>
3356
  </div>
3357
  ';
3358
 
3359
+ return $item;
3360
+ }
3361
+
3362
+ /**
3363
+ * Prints the form in the Custom Fields meta box.
3364
+ *
3365
+ * @param string $meta_type
3366
+ *
3367
+ * @return string
3368
+ * @since 1.6.3
3369
+ *
3370
+ */
3371
+ function meta_form( $meta_type = 'gmedia' ) {
3372
+ global $wpdb;
3373
+
3374
+ if ( ! in_array( $meta_type, array( 'gmedia', 'gmedia_term' ) ) ) {
3375
+ $meta_type = 'gmedia';
3376
+ }
3377
+
3378
+ /**
3379
+ * Filter the number of custom fields to retrieve for the drop-down
3380
+ * in the Custom Fields meta box.
3381
+ *
3382
+ * @param int $limit Number of custom fields to retrieve. Default 30.
3383
+ */
3384
+ $limit = apply_filters( 'gmediameta_form_limit', 30 );
3385
+ $sql = "SELECT meta_key
3386
  FROM {$wpdb->prefix}{$meta_type}_meta
3387
  GROUP BY meta_key
3388
  HAVING meta_key NOT LIKE %s
3389
  ORDER BY meta_key
3390
  LIMIT %d";
3391
+ $keys = $wpdb->get_col( $wpdb->prepare( $sql, addcslashes( '_', '_%\\' ) . '%', $limit ) );
3392
 
3393
+ $meta_form = '
3394
  <div id="newmeta" class="newmeta">
3395
  <div class="row">
3396
  <div class="form-group col-sm-6">
3397
+ <label>' . _x( 'Name', 'meta name' ) . '</label>';
3398
+ if ( $keys ) {
3399
+ natcasesort( $keys );
3400
+ $meta_form .= '
3401
  <select class="metakeyselect form-control input-sm" name="metakeyselect">
3402
+ <option value="">' . __( '&mdash; Select &mdash;' ) . '</option>';
3403
+ foreach ( $keys as $key ) {
3404
+ if ( $this->is_protected_meta( $key, $meta_type ) ) {
3405
+ continue;
3406
+ }
3407
+ $meta_form .= '
3408
+ <option value="' . esc_attr( $key ) . '">' . esc_html( $key ) . '</option>';
3409
+ }
3410
+ $meta_form .= '
3411
  </select>
3412
  <input type="text" class="metakeyinput hide-if-js form-control input-sm" name="metakeyinput" value="" />
3413
  <a href="#gmediacustomstuff" class="hide-if-no-js gmediacustomstuff" onclick="jQuery(\'.metakeyinput, .metakeyselect, .enternew, .cancelnew\', \'#newmeta\').toggle();jQuery(this).parent().toggleClass(\'newcfield\');return false;">
3414
+ <span class="enternew">' . __( 'Enter new', 'grand-media' ) . '</span>
3415
+ <span class="cancelnew" style="display:none;">' . __( 'Cancel', 'grand-media' ) . '</span></a>';
3416
+ } else {
3417
+ $meta_form .= '
3418
  <input type="text" class="metakeyinput form-control input-sm" name="metakeyinput" value="" />';
3419
+ }
3420
+ $meta_form .= '
3421
  </div>
3422
  <div class="form-group col-sm-6">
3423
+ <label>' . __( 'Value', 'grand-media' ) . '</label>
3424
  <textarea class="metavalue vert form-control input-sm" name="metavalue" rows="2" cols="25"></textarea>
3425
  </div>
3426
  </div>
3427
  </div>';
3428
 
3429
 
3430
+ return $meta_form;
3431
+ }
3432
 
3433
+ /**
3434
+ * @param int $gmedia_ID
3435
+ * @param string $meta_type
3436
+ *
3437
+ * @return bool|int
3438
+ * @since 1.6.3
3439
+ *
3440
+ */
3441
+ function add_meta( $gmedia_ID, $meta_type = 'gmedia' ) {
3442
+ global $gmDB;
3443
+
3444
+ if ( ! in_array( $meta_type, array( 'gmedia', 'gmedia_term' ) ) ) {
3445
+ $meta_type = 'gmedia';
3446
+ }
3447
+
3448
+ $gmedia_ID = (int) $gmedia_ID;
3449
+
3450
+ $metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
3451
+ $metakeyinput = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
3452
+ $metavalue = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
3453
+ if ( is_string( $metavalue ) ) {
3454
+ $metavalue = trim( $metavalue );
3455
+ }
3456
+
3457
+ if ( ( '0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ! empty( $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty ( $metakeyinput ) ) ) {
3458
+ /*
3459
  * We have a key/value pair. If both the select and the input
3460
  * for the key have data, the input takes precedence.
3461
  */
3462
+ $metakey = $metakeyselect;
3463
+
3464
+ if ( $metakeyinput ) {
3465
+ $metakey = $metakeyinput;
3466
+ } // default
3467
+
3468
+ if ( $this->is_protected_meta( $metakey, $meta_type ) ) {
3469
+ return false;
3470
+ }
3471
+
3472
+ $metakey = wp_slash( $metakey );
3473
+
3474
+ return $gmDB->add_metadata( $meta_type, $gmedia_ID, $metakey, $metavalue );
3475
+ }
3476
+
3477
+ return false;
3478
+ }
3479
+
3480
+ /** Get item Meta Text
3481
+ *
3482
+ * @param int $id
3483
+ *
3484
+ * @return string Meta text;
3485
+ */
3486
+ function metadata_text( $id ) {
3487
+ $metatext = '';
3488
+ if ( ( $metadata = $this->metadata_info( $id ) ) ) {
3489
+ foreach ( $metadata as $meta ) {
3490
+ if ( $meta['name'] == 'Image' ) {
3491
+ continue;
3492
+ }
3493
+ $metatext .= "<b>{$meta['name']}:</b>";
3494
+ if ( ! is_array( $meta['value'] ) ) {
3495
+ $metatext .= " {$meta['value']}\n";
3496
+ } else {
3497
+ $value = $meta['value'];
3498
+ $this->meta_value_array_show( $metatext, $value );
3499
+ }
3500
+ }
3501
+ }
3502
+
3503
+ return $metatext;
3504
+ }
3505
+
3506
+ /** Get item Meta
3507
+ *
3508
+ * @param int|object $item
3509
+ *
3510
+ * @return array metadata[key] = array(name, value);
3511
+ */
3512
+ function metadata_info( $item ) {
3513
+ global $gmDB;
3514
+
3515
+ if ( is_object( $item ) ) {
3516
+ $item_id = $item->ID;
3517
+ } elseif ( $this->is_digit( $item ) ) {
3518
+ $item_id = (int) $item;
3519
+ } else {
3520
+ return null;
3521
+ }
3522
+
3523
+ $metadata = array();
3524
+
3525
+ $meta = $gmDB->get_metadata( 'gmedia', $item_id, '_metadata', true );
3526
+ if ( $meta ) {
3527
+ if ( isset( $meta['image_meta'] ) ) {
3528
+ $metainfo = $meta['image_meta'];
3529
+ } else {
3530
+ $metainfo = $meta;
3531
+ if ( is_array( $metainfo ) ) {
3532
+ unset( $metainfo['web'], $metainfo['original'], $metainfo['thumb'], $metainfo['file'] );
3533
+ }
3534
+ }
3535
+
3536
+ if ( ! empty( $metainfo ) ) {
3537
+ foreach ( $metainfo as $key => $value ) {
3538
+ if ( empty( $value ) ) {
3539
+ continue;
3540
+ }
3541
+ $key_name = $this->i18n_exif_name( $key );
3542
+ $key_name = $this->mb_ucwords_utf8( str_replace( '_', ' ', $key_name ) );
3543
+ $value = $this->sanitize_meta_value( $value );
3544
+ $metadata[ $key ] = array( 'name' => $key_name, 'value' => $value );
3545
+ }
3546
+ }
3547
+ }
3548
+
3549
+ return $metadata;
3550
+ }
3551
+
3552
+ /**
3553
+ * @param $key
3554
+ *
3555
+ * @return mixed
3556
+ */
3557
+ function i18n_exif_name( $key ) {
3558
+ $_key = strtolower( $key );
3559
+ $tagnames = array(
3560
+ 'aperture' => __( 'Aperture', 'grand-media' ),
3561
+ 'credit' => __( 'Credit', 'grand-media' ),
3562
+ 'camera' => __( 'Camera', 'grand-media' ),
3563
+ 'model' => __( 'Camera', 'grand-media' ),
3564
+ 'lens' => __( 'Lens', 'grand-media' ),
3565
+ 'lensmake' => __( 'Lens Make', 'grand-media' ),
3566
+ 'caption' => __( 'Caption', 'grand-media' ),
3567
+ 'date' => __( 'Date/Time', 'grand-media' ),
3568
+ 'created_timestamp' => __( 'Timestamp', 'grand-media' ),
3569
+ 'created_date' => __( 'Date Created', 'grand-media' ),
3570
+ 'created_time' => __( 'Time Created', 'grand-media' ),
3571
+ 'copyright' => __( 'Copyright', 'grand-media' ),
3572
+ 'focallength' => __( 'Focal length', 'grand-media' ),
3573
+ 'focallength35' => __( 'Focal length in 35mm Film', 'grand-media' ),
3574
+ 'iso' => __( 'ISO', 'grand-media' ),
3575
+ 'exposure' => __( 'Exposure Time', 'grand-media' ),
3576
+ 'shutter_speed' => __( 'Shutter speed', 'grand-media' ),
3577
+ 'title' => __( 'Title', 'grand-media' ),
3578
+ 'author' => __( 'Author', 'grand-media' ),
3579
+ 'tags' => __( 'Tags', 'grand-media' ),
3580
+ 'subject' => __( 'Subject', 'grand-media' ),
3581
+ 'make' => __( 'Make', 'grand-media' ),
3582
+ 'status' => __( 'Edit Status', 'grand-media' ),
3583
+ 'category' => __( 'Category', 'grand-media' ),
3584
+ 'keywords' => __( 'Keywords', 'grand-media' ),
3585
+ 'position' => __( 'Author Position', 'grand-media' ),
3586
+ 'GPS' => __( 'GPS', 'grand-media' ),
3587
+ 'lat' => __( 'Latitude', 'grand-media' ),
3588
+ 'lng' => __( 'Longtitude', 'grand-media' ),
3589
+ 'city' => __( 'City', 'grand-media' ),
3590
+ 'location' => __( 'Location', 'grand-media' ),
3591
+ 'state' => __( 'Province/State', 'grand-media' ),
3592
+ 'country_code' => __( 'Country code', 'grand-media' ),
3593
+ 'country' => __( 'Country', 'grand-media' ),
3594
+ 'headline' => __( 'Headline', 'grand-media' ),
3595
+ 'source' => __( 'Source', 'grand-media' ),
3596
+ 'contact' => __( 'Contact', 'grand-media' ),
3597
+ 'last_modfied' => __( 'Last modified', 'grand-media' ),
3598
+ 'tool' => __( 'Program tool', 'grand-media' ),
3599
+ 'software' => __( 'Software', 'grand-media' ),
3600
+ 'format' => __( 'Format', 'grand-media' ),
3601
+ 'width' => __( 'Width', 'grand-media' ),
3602
+ 'height' => __( 'Height', 'grand-media' ),
3603
+ 'flash' => __( 'Flash', 'grand-media' ),
3604
+ 'flashdata' => __( 'Flash', 'grand-media' ),
3605
+ 'orientation' => __( 'Orientation', 'grand-media' ),
3606
+ );
3607
+
3608
+ if ( isset( $tagnames[ $_key ] ) ) {
3609
+ $key = $tagnames[ $_key ];
3610
+ }
3611
+
3612
+ return ( $key );
3613
+ }
3614
+
3615
+ /**
3616
+ * @param $value
3617
+ *
3618
+ * @return array
3619
+ */
3620
+ function sanitize_meta_value( $value ) {
3621
+ if ( is_array( $value ) && (bool) count( array_filter( array_keys( $value ), 'is_string' ) ) ) {
3622
+ $value_return = array();
3623
+ foreach ( $value as $key => $val ) {
3624
+ if ( empty( $value ) ) {
3625
+ continue;
3626
+ }
3627
+ $key_name = $this->i18n_exif_name( $key );
3628
+ $key_name = $this->mb_ucwords_utf8( str_replace( '_', ' ', $key_name ) );
3629
+ if ( is_array( $val ) ) {
3630
+ $val = $this->sanitize_meta_value( $val );
3631
+ }
3632
+ $value_return[ $key ] = array( 'name' => $key_name, 'value' => $val );
3633
+ }
3634
+ } else {
3635
+ $value_return = $value;
3636
+ }
3637
+
3638
+ return $value_return;
3639
+ }
3640
+
3641
+ /**
3642
+ * @param $metatext
3643
+ * @param $value
3644
+ * @param int $pad
3645
+ */
3646
+ function meta_value_array_show( &$metatext, $value, $pad = 0 ) {
3647
+ if ( (bool) count( array_filter( array_keys( $value ), 'is_string' ) ) ) {
3648
+ $pad ++;
3649
+ foreach ( $value as $val ) {
3650
+ $metatext .= "\n" . str_pad( '&nbsp;', $pad ) . "- <b>{$val['name']}:</b> ";
3651
+ if ( is_array( $val['value'] ) ) {
3652
+ $this->meta_value_array_show( $metatext, $val['value'], $pad );
3653
+ } else {
3654
+ $metatext .= $val['value'];
3655
+ }
3656
+ }
3657
+ } else {
3658
+ $metatext .= ' ' . implode( ', ', $value );
3659
+ }
3660
+ $metatext .= "\n";
3661
+ }
3662
+
3663
+ /**
3664
+ * Update media meta in the database
3665
+ *
3666
+ * @param $gmID
3667
+ * @param $meta
3668
+ *
3669
+ * @return mixed
3670
+ */
3671
+ function gm_hitcounter( $gmID, $meta ) {
3672
+ /** @var wpdb $wpdb */
3673
+ global $gmDB;
3674
+
3675
+ $like = $this->_post( 'vote' );
3676
+ $like = $this->_post( 'like', $like );
3677
+ if ( (int) $like == 1 ) {
3678
+ $meta['likes'] += 1;
3679
+ $gmDB->update_metadata( 'gmedia', $gmID, 'likes', $meta['likes'] );
3680
+ do_action( 'gmedia_like', $gmID );
3681
+ } else {
3682
+ $meta['views'] += 1;
3683
+ $gmDB->update_metadata( 'gmedia', $gmID, 'views', $meta['views'] );
3684
+ do_action( 'gmedia_view', $gmID );
3685
+ }
3686
+
3687
+ return $meta;
3688
+ }
3689
+
3690
+ /**
3691
+ * Check POST data
3692
+ *
3693
+ * @param string $var
3694
+ * @param bool|mixed $def
3695
+ *
3696
+ * @return mixed
3697
+ */
3698
+
3699
+ function _post( $var, $def = false ) {
3700
+ return isset( $_POST[ $var ] ) ? $_POST[ $var ] : $def;
3701
+ }
3702
+
3703
+ /**
3704
+ * Replace keys of an array based on a key map array
3705
+ *
3706
+ * @param $array
3707
+ * @param $keymap
3708
+ *
3709
+ * @return array
3710
+ * @throws Exception
3711
+ */
3712
+ function replace_array_keys( &$array, $keymap ) {
3713
+ $replaced_keys = array();
3714
+ $skipped = $keymap;
3715
+ do {
3716
+ $keymap = $skipped;
3717
+ foreach ( $keymap as $new_key => $original_key ) {
3718
+ if ( isset( $array[ $original_key ] ) ) {
3719
+ if ( ! isset( $array[ $new_key ] ) || ( isset( $replaced_keys[ $new_key ] ) && ! isset( $replaced_keys[ $original_key ] ) ) ) {
3720
+ $array[ $new_key ] = $array[ $original_key ];
3721
+ unset( $array[ $original_key ] );
3722
+ $replaced_keys[ $original_key ] = $new_key;
3723
+ unset( $skipped[ $new_key ] );
3724
+ } elseif ( isset( $array[ $new_key ] ) && array_search( $new_key, $keymap ) === false ) {
3725
+ throw new Exception( 'Trying to replace an array key with an already existing array key, without providing a new position for the existing array key in replace_array_keys().' );
3726
+ } elseif ( isset( $array[ $new_key ] ) && $keymap[ $original_key ] == $new_key && ! isset( $replaced_keys[ $original_key ] ) ) {
3727
+ //switch places.
3728
+ $temp = $array[ $new_key ];
3729
+ $array[ $new_key ] = $array[ $original_key ];
3730
+ $array[ $original_key ] = $temp;
3731
+ $replaced_keys[ $new_key ] = $original_key;
3732
+ $replaced_keys[ $original_key ] = $new_key;
3733
+ unset( $skipped[ $new_key ] );
3734
+ unset( $skipped[ $original_key ] );
3735
+ }
3736
+ } else {
3737
+ unset( $skipped[ $new_key ] );
3738
+ }
3739
+ }
3740
+ } while ( ! empty( $skipped ) );
3741
+
3742
+ return $replaced_keys;
3743
+ }
3744
+
3745
+ /**
3746
+ * @return array Gmedia Capabilities
3747
+ */
3748
+ function modules_order() {
3749
+ return array(
3750
+ 'photoblog' => '',
3751
+ 'cicerone' => '',
3752
+ 'albumsListMasonry' => '',
3753
+ 'albumsList' => '',
3754
+ 'woowslider' => '',
3755
+ 'albums-switcher' => '',
3756
+ 'photocluster' => '',
3757
+ 'albumsview' => '',
3758
+ 'albumsgrid' => '',
3759
+ 'phantom-pro' => '',
3760
+ 'albums-stripes' => '',
3761
+ 'cubik' => '',
3762
+ 'desire' => '',
3763
+ 'phototravlr' => '',
3764
+ 'realslider' => '',
3765
+ 'mosaic' => '',
3766
+ 'photobox' => '',
3767
+ 'amron' => '',
3768
+ 'wavesurfer' => '',
3769
+ 'flipgrid' => '',
3770
+ 'phantom' => '',
3771
+ 'cubik-lite' => '',
3772
+ 'photomania' => '',
3773
+ 'jq-mplayer' => '',
3774
+ 'wp-videoplayer' => '',
3775
+
3776
+ 'photo-pro' => '',
3777
+ 'optima' => '',
3778
+ 'afflux' => '',
3779
+ 'slider' => '',
3780
+ 'green-style' => '',
3781
+ 'photo-blog' => '',
3782
+ 'minima' => '',
3783
+ 'sphere' => '',
3784
+ 'cube' => '',
3785
+ 'flatwall' => '',
3786
+ );
3787
+ }
3788
+
3789
+ /**
3790
+ * Clear the caches!
3791
+ */
3792
+ function clear_cache() {
3793
+ // Delete cache transients.
3794
+ gmedia_delete_transients( 'gm_cache' );
3795
+
3796
+ // if W3 Total Cache is being used, clear the cache
3797
+ if ( function_exists( 'w3tc_pgcache_flush' ) ) {
3798
+ w3tc_pgcache_flush();
3799
+ } // if WP Super Cache is being used, clear the cache
3800
+ elseif ( function_exists( 'wp_cache_clean_cache' ) ) {
3801
+ global $file_prefix, $supercachedir;
3802
+ if ( empty( $supercachedir ) && function_exists( 'get_supercache_dir' ) ) {
3803
+ $supercachedir = get_supercache_dir();
3804
+ }
3805
+ wp_cache_clean_cache( $file_prefix );
3806
+ } elseif ( class_exists( 'WpeCommon' ) ) {
3807
+ //be extra careful, just in case 3rd party changes things on us
3808
+ if ( method_exists( 'WpeCommon', 'purge_memcached' ) ) {
3809
+ WpeCommon::purge_memcached();
3810
+ }
3811
+ if ( method_exists( 'WpeCommon', 'purge_memcached' ) ) {
3812
+ WpeCommon::clear_maxcdn_cache();
3813
+ }
3814
+ if ( method_exists( 'WpeCommon', 'purge_memcached' ) ) {
3815
+ WpeCommon::purge_varnish_cache();
3816
+ }
3817
+ } elseif ( class_exists( 'WpFastestCache' ) ) {
3818
+ global $wp_fastest_cache;
3819
+ if ( method_exists( 'WpFastestCache', 'deleteCache' ) && ! empty( $wp_fastest_cache ) ) {
3820
+ $wp_fastest_cache->deleteCache();
3821
+ }
3822
+ }
3823
+ }
3824
+
3825
+ /**
3826
+ * Filter the gmedia terms (private and draft) for frontend and admin panel
3827
+ *
3828
+ * @param $terms
3829
+ * @param $gmedia_id
3830
+ * @param $taxonomy
3831
+ *
3832
+ * @return mixed
3833
+ */
3834
+ function get_the_gmedia_terms( $terms, $gmedia_id, $taxonomy ) {
3835
+ if ( 'gmedia_album' === $taxonomy ) {
3836
+ if ( ! is_user_logged_in() ) {
3837
+ foreach ( $terms as $key => $term ) {
3838
+ if ( 'publish' !== $term->status ) {
3839
+ unset( $terms[ $key ] );
3840
+ }
3841
+ }
3842
+ } else {
3843
+ global $user_ID;
3844
+ foreach ( $terms as $key => $term ) {
3845
+ if ( 'draft' === $term->status ) {
3846
+ if ( ! is_admin() || ( $user_ID != $term->global && ! gm_user_can( 'edit_others_media' ) ) ) {
3847
+ unset( $terms[ $key ] );
3848
+ }
3849
+ } elseif ( 'private' === $term->status ) {
3850
+ if ( $user_ID != $term->global && ! gm_user_can( 'show_others_media' ) ) {
3851
+ unset( $terms[ $key ] );
3852
+ }
3853
+ }
3854
+ }
3855
+ }
3856
+ }
3857
+
3858
+ return $terms;
3859
+ }
3860
+
3861
+ /**
3862
+ * Converts IDN in given url address to its ASCII form, also known as punycode, if possible.
3863
+ * This function silently returns unmodified address if:
3864
+ * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
3865
+ * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
3866
+ * or fails for any reason (e.g. domain has characters not allowed in an IDN)
3867
+ *
3868
+ * @param string $url The url to convert
3869
+ *
3870
+ * @return string The encoded url in ASCII form
3871
+ * @see PHPMailer::$CharSet
3872
+ *
3873
+ */
3874
+ public function punyencode( $url ) {
3875
+ $url_host = parse_url( $url, PHP_URL_HOST );
3876
+
3877
+ if ( (boolean) preg_match( '/[\x80-\xFF]/', $url_host ) ) {
3878
+ $host = $this->mb_convert_encoding_utf8( $url_host );
3879
+ if ( function_exists( 'idn_to_ascii' ) ) {
3880
+ $options = 0;
3881
+ if ( ( $punycode = defined( 'INTL_IDNA_VARIANT_UTS46' ) ? idn_to_ascii( $host, $options, INTL_IDNA_VARIANT_UTS46 ) : idn_to_ascii( $host ) ) !== false ) {
3882
+ $new_url = str_replace( $url_host, $punycode, $url );
3883
+
3884
+ return $new_url;
3885
+ }
3886
+ }
3887
+
3888
+ require_once( dirname( __FILE__ ) . '/punycode.php' );
3889
+ $gmPunycode = new gmPunycode();
3890
+ $punycode = $gmPunycode->encode( $host );
3891
+ $new_url = str_replace( $url_host, $punycode, $url );
3892
+
3893
+ return $new_url;
3894
+ }
3895
+
3896
+ return $url;
3897
+ }
3898
+
3899
+ /**
3900
+ * Sanitizes a hex color
3901
+ *
3902
+ * @param $color
3903
+ * @param $def
3904
+ *
3905
+ * @return string
3906
+ */
3907
+ function sanitize_hex_color( $color, $def = '' ) {
3908
+ $hash = $color[0] === '#' ? '#' : '';
3909
+ $color = ltrim( $color, '#' );
3910
+ if ( '' === $color ) {
3911
+ return $def;
3912
+ }
3913
+
3914
+ // 3 or 6 hex digits, or the empty string.
3915
+ if ( preg_match( '|^([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
3916
+ return $hash . $color;
3917
+ }
3918
+
3919
+ return $def;
3920
+ }
3921
+
3922
+ /**
3923
+ * Convert a hex color to rgb
3924
+ *
3925
+ * @param $hex
3926
+ *
3927
+ * @return array [r ,g, b]
3928
+ */
3929
+ function hex2rgb( $hex ) {
3930
+ require_once( dirname( __FILE__ ) . '/color.php' );
3931
+
3932
+ $color = new gmColor( $hex );
3933
+ $rgb = $color->getRgb();
3934
+
3935
+ return array( $rgb['R'], $rgb['G'], $rgb['B'] );
3936
+ }
3937
+
3938
+ /**
3939
+ * Return gmColor class
3940
+ *
3941
+ * @param $hex
3942
+ *
3943
+ * @return object class
3944
+ */
3945
+ function color( $hex = null ) {
3946
+ require_once( dirname( __FILE__ ) . '/color.php' );
3947
+
3948
+ return new gmColor( $hex );
3949
+ }
3950
+
3951
+ /**
3952
+ * Log Views
3953
+ *
3954
+ * @param $id
3955
+ */
3956
+ function log_views_handler( $id ) {
3957
+ global $wpdb, $user_ID, $gmDB;
3958
+
3959
+ $gmedia = $gmDB->get_gmedia( $id );
3960
+ if ( ! empty( $gmedia->ID ) ) {
3961
+ $data = array(
3962
+ 'log' => 'view',
3963
+ 'ID' => $gmedia->ID,
3964
+ 'log_author' => (int) $user_ID,
3965
+ 'log_date' => current_time( 'mysql' ),
3966
+ 'log_data' => '1',
3967
+ 'ip_address' => preg_replace( '/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip() ),
3968
+ );
3969
+ $id = $wpdb->insert( $wpdb->prefix . 'gmedia_log', $data );
3970
+ }
3971
+ }
3972
+
3973
+ /**
3974
+ * Get IP address
3975
+ */
3976
+ function ip() {
3977
+ //Test if it is a shared client
3978
+ if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
3979
+ $ip = $_SERVER['HTTP_CLIENT_IP'];
3980
+ //Is it a proxy address
3981
+ } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
3982
+ $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
3983
+ } else {
3984
+ $ip = $_SERVER['REMOTE_ADDR'];
3985
+ }
3986
+
3987
+ return $ip;
3988
+ }
3989
+
3990
+ /**
3991
+ * Log Likes
3992
+ *
3993
+ * @param $id
3994
+ */
3995
+ function log_likes_handler( $id ) {
3996
+ global $wpdb, $user_ID, $gmDB;
3997
+
3998
+ $gmedia = $gmDB->get_gmedia( $id );
3999
+ if ( ! empty( $gmedia->ID ) ) {
4000
+ $data = array(
4001
+ 'log' => 'like',
4002
+ 'ID' => $gmedia->ID,
4003
+ 'log_author' => (int) $user_ID,
4004
+ 'log_date' => current_time( 'mysql' ),
4005
+ 'log_data' => '1',
4006
+ 'ip_address' => preg_replace( '/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip() ),
4007
+ );
4008
+ $wpdb->insert( $wpdb->prefix . 'gmedia_log', $data );
4009
+ }
4010
+ }
4011
+
4012
+ /**
4013
+ * Log Rating
4014
+ *
4015
+ * @param $id
4016
+ * @param $val
4017
+ */
4018
+ function log_rates_handler( $id, $val ) {
4019
+ global $wpdb, $user_ID, $gmDB;
4020
+
4021
+ $gmedia = $gmDB->get_gmedia( $id );
4022
+ if ( ! empty( $gmedia->ID ) ) {
4023
+ $data = array(
4024
+ 'log' => 'rate',
4025
+ 'ID' => $gmedia->ID,
4026
+ 'log_author' => (int) $user_ID,
4027
+ 'log_date' => current_time( 'mysql' ),
4028
+ 'log_data' => $val,
4029
+ 'ip_address' => preg_replace( '/(?!\d{1,3}\.\d{1,3}\.)\d/', '*', $this->ip() ),
4030
+ );
4031
+ $wpdb->insert( $wpdb->prefix . 'gmedia_log', $data );
4032
+ }
4033
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4034
  }
4035
 
4036
  global $gmCore;
inc/db.connect.php CHANGED
@@ -1,4247 +1,4250 @@
1
- <?php
2
-
3
- /**
4
- * Gmedia Database Class
5
- */
6
- class GmediaDB{
7
-
8
- var $query; // User passed query
9
- var $sql_query; // User passed query
10
- var $filter = array(); // is there filter for get_gmedias()
11
- var $filter_tax = array(); // is there filter by taxonomy for get_gmedias()
12
- var $resultLimited = 0; // Total records for limited query (with offset)
13
- var $resultPerPage = 0; // Total records in each pages
14
- var $hardlimit = 0; // Hard limit query
15
- var $trueTotalResult = 0; // Total records in DB without limit
16
- var $totalResult = 0; // Total records in DB
17
- var $pages = 0; // Total number of pages required
18
- var $perPages = 0; // per page query
19
- var $openPage = 0; // currently opened page
20
- var $clauses; // query clauses
21
- var $gmedia; // first gmedia object
22
-
23
- /**
24
- * Get Wordpress Media
25
- *
26
- * @param array $arg
27
- *
28
- * @return object
29
- */
30
- function get_wp_media_lib($arg){
31
- /** @var $wpdb wpdb */
32
- global $wpdb, $gmCore;
33
- $default_arg = array('mime_type' => '', 'orderby' => 'ID', 'order' => '', 'limit' => '0', 'filter' => '', 'selected' => false, 's' => '');
34
- $arg = array_merge($default_arg, $arg);
35
- /** @var $mime_type
36
- * @var $orderby
37
- * @var $order
38
- * @var $limit
39
- * @var $filter
40
- * @var $s
41
- * @var $selected
42
- */
43
- extract($arg);
44
- $and = '';
45
- $ord = '';
46
- $lim = '';
47
- $search = '';
48
- $sel_ids = array();
49
- if($selected){
50
- $sel_ids = wp_parse_id_list($selected);
51
- } else{
52
- $ckey = "gmedia_library:wpmedia";
53
- if(isset($_COOKIE[ $ckey ])){
54
- $sel_ids = array_filter(explode('.', $_COOKIE[ $ckey ]), 'is_numeric');
55
- }
56
- }
57
- switch($mime_type){
58
- case 'image':
59
- $and .= " AND post_mime_type REGEXP '^image(.*)'";
60
- break;
61
- case 'audio':
62
- $and .= " AND post_mime_type REGEXP '^audio(.*)'";
63
- break;
64
- case 'video':
65
- $and .= " AND post_mime_type REGEXP '^video(.*)'";
66
- break;
67
- case 'application':
68
- $and .= " AND post_mime_type NOT REGEXP 'image|audio|video'";
69
- break;
70
- }
71
- if(!empty($mime_type)){
72
- $this->filter['mime_type'] = (array)$mime_type;
73
- }
74
- // If a search pattern is specified, load the posts that match
75
- if(!empty($s)){
76
- // added slashes screw with quote grouping when done early, so done later
77
- $s = stripslashes($s);
78
-
79
- // split the words it a array if seperated by a space or comma
80
- preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
81
- $search_terms = array_map(function($a){ return trim($a, "\"'\n\r "); }, $matches[0]);
82
-
83
- $n = '%';
84
- $searchand = '';
85
-
86
- foreach((array)$search_terms as $term){
87
- $term = addslashes_gpc($term);
88
- $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
89
- $searchand = ' AND ';
90
- }
91
-
92
- $term = esc_sql($s);
93
- if(count($search_terms) > 1 && $search_terms[0] != $s){
94
- $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";
95
- }
96
-
97
- if(!empty($search)){
98
- $search = " AND ({$search}) ";
99
- $this->filter['s'] = (array)$search_terms;
100
- }
101
- }
102
- if($orderby){
103
- switch($orderby){
104
- case 'ID':
105
- $orderby = 'ID';
106
- if(!$order){
107
- $order = 'DESC';
108
- }
109
- break;
110
- case 'filename':
111
- $orderby = 'post_name';
112
- break;
113
- case 'title':
114
- $orderby = 'post_title';
115
- break;
116
- case 'date':
117
- $orderby = 'post_modified';
118
- break;
119
- case 'selected':
120
- if(count($sel_ids) > 1){
121
- $orderby = 'FIELD(ID, ' . join(', ', $sel_ids) . ')';
122
- } else{
123
- $orderby = 'ID';
124
- }
125
- break;
126
- default:
127
- $orderby = preg_replace('/[^a-z_]/', ' ', $orderby);
128
- break;
129
- }
130
- $ord .= " ORDER BY {$orderby}";
131
- $ord .= ($order == 'DESC')? ' DESC' : ' ASC';
132
- }
133
- switch($filter){
134
- case 'selected':
135
- if(count($sel_ids)){
136
- $and .= ' AND ID IN (' . join(', ', $sel_ids) . ')';
137
- $this->filter['post__in'] = $sel_ids;
138
- break;
139
- } else{
140
- $and .= ' AND ID = 0';
141
- // todo: selected query error: No selected items
142
- }
143
- break;
144
- default:
145
- //$and .= "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
146
- break;
147
- }
148
- $this->openPage = $gmCore->_get('pager', '1');
149
- $limit = intval($limit);
150
- if($limit > 0){
151
- $offset = ($this->openPage - 1) * $limit;
152
- $lim = " LIMIT {$offset}, {$limit}";
153
- }
154
- $this->sql_query = "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE post_type = 'attachment' {$and} {$search} GROUP BY ID {$ord} {$lim}";
155
- $this->query = $wpdb->get_results($this->sql_query);
156
- $this->totalResult = (int)$wpdb->get_var("SELECT FOUND_ROWS()");
157
- if((1 > $limit) || (0 == $this->totalResult)){
158
- $limit = $this->totalResult;
159
- $this->pages = 1;
160
- } else{
161
- $this->pages = ceil($this->totalResult / $limit);
162
- }
163
- if($this->openPage > $this->pages){
164
- $this->openPage = $this->pages;
165
- if($limit > 0){
166
- $limit = intval($limit);
167
- $offset = ($this->openPage - 1) * $limit;
168
- $lim = " LIMIT {$offset}, {$limit}";
169
- }
170
- $this->sql_query = "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE post_type = 'attachment' {$and} {$search} GROUP BY ID {$ord} {$lim}";
171
- $this->query = $wpdb->get_results($this->sql_query);
172
- }
173
- $this->resultPerPage = count($this->query);
174
-
175
- return $this->query;
176
- }
177
-
178
- /**
179
- * @param $arg
180
- *
181
- * @return mixed
182
- */
183
- function count_wp_media($arg){
184
- /** @var $wpdb wpdb */
185
- global $wpdb;
186
- /** @var $filter
187
- * @var $selected
188
- * @var $s
189
- */
190
- extract($arg);
191
- $search = '';
192
- if(isset($selected)){
193
- $sel_ids = wp_parse_id_list($selected);
194
- } elseif(isset($_COOKIE["gmedia_library:wpmedia"])){
195
- $sel_ids = array_filter(explode('.', $_COOKIE["gmedia_library:wpmedia"]), 'is_numeric');
196
- } else{
197
- $sel_ids = array();
198
- }
199
-
200
- switch($filter){
201
- case 'selected':
202
- if(count($sel_ids)){
203
- $filter = ' AND ID IN (' . join(', ', $sel_ids) . ')';
204
- break;
205
- }
206
- default:
207
- //$filter = "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
208
- $filter = '';
209
- break;
210
- }
211
- // If a search pattern is specified, load the posts that match
212
- if(!empty($s)){
213
- // added slashes screw with quote grouping when done early, so done later
214
- $s = stripslashes($s);
215
-
216
- // split the words it a array if seperated by a space or comma
217
- preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
218
- $search_terms = array_map(function($a){ return trim($a, "\"'\n\r "); }, $matches[0]);
219
-
220
- $n = '%';
221
- $searchand = '';
222
-
223
- foreach((array)$search_terms as $term){
224
- $term = addslashes_gpc($term);
225
- $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
226
- $searchand = ' AND ';
227
- }
228
-
229
- $term = esc_sql($s);
230
- if(count($search_terms) > 1 && $search_terms[0] != $s){
231
- $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";
232
- }
233
-
234
- if(!empty($search)){
235
- $search = " AND ({$search}) ";
236
- }
237
-
238
- }
239
- $count = $wpdb->get_results("SELECT COUNT(*) as total,
240
- SUM(CASE WHEN post_mime_type LIKE 'image%' THEN 1 ELSE 0 END) as image,
241
- SUM(CASE WHEN post_mime_type LIKE 'audio%' THEN 1 ELSE 0 END) as audio,
242
- SUM(CASE WHEN post_mime_type LIKE 'video%' THEN 1 ELSE 0 END) as video,
243
- SUM(CASE WHEN post_mime_type LIKE 'text%' THEN 1 ELSE 0 END) as text,
244
- SUM(CASE WHEN post_mime_type LIKE 'application%' THEN 1 ELSE 0 END) as application
245
- FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} {$search}", ARRAY_A);
246
-
247
- //$count[0]['hidden'] = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key = '_gmedia_hidden' {$search}" );
248
- $count[0]['other'] = (int)$count[0]['text'] + (int)$count[0]['application'];
249
-
250
- return $count[0];
251
- }
252
-
253
- /**
254
- * @return mixed
255
- */
256
- function count_gmedia(){
257
- /** @var $wpdb wpdb */
258
- global $wpdb;
259
- /**
260
- * @var $whichauthor
261
- * @var $whichmimetype
262
- * @var $groupby
263
- * @var $orderby
264
- * @var $limits
265
- */
266
- $join = '';
267
- $where = '';
268
- $whichauthor = '';
269
- if($this->clauses){
270
- extract($this->clauses, EXTR_OVERWRITE);
271
- }
272
-
273
- $count = $wpdb->get_results("SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) as total,
274
- (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'image%' $where $whichauthor) as image,
275
- (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'audio%' $where $whichauthor) as audio,
276
- (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'video%' $where $whichauthor) as video,
277
- (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'text%' $where $whichauthor) as text,
278
- (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'application%' $where $whichauthor) as application
279
- FROM {$wpdb->prefix}gmedia $join WHERE 1=1 $where $whichauthor
280
- ", ARRAY_A);
281
-
282
- if($count){
283
- $count = $count[0];
284
- $count['other'] = (int)$count['text'] + (int)$count['application'];
285
- $count['total'] = (int)$count['image'] + (int)$count['audio'] + (int)$count['video'] + (int)$count['other'];
286
- } else{
287
- $count = array('image' => 0,
288
- 'audio' => 0,
289
- 'video' => 0,
290
- 'text' => 0,
291
- 'application' => 0,
292
- 'other' => 0,
293
- 'total' => 0
294
- );
295
- }
296
-
297
- return $count;
298
- }
299
-
300
- /**
301
- * function to display the pagination
302
- * @return string
303
- */
304
- function query_pager(){
305
- if(empty($this->pages) || $this->pages == 1 || $this->resultLimited){
306
- return '';
307
- }
308
- $params = $_GET;
309
- foreach ($params as $key => $value) {
310
- if (strpos($key, '_wpnonce') !== false) {
311
- unset($params[$key]);
312
- }
313
- }
314
- unset($params['pager'], $params['do_gmedia'], $params['did_gmedia'], $params['do_gmedia_terms'], $params['did_gmedia_terms'], $params['ids'], $params['doing_wp_cron']);
315
- $new_query_string = http_build_query($params);
316
- //$self = admin_url( 'admin.php?' . $new_query_string );
317
- $self = '?' . $new_query_string;
318
- if($this->openPage <= 0){
319
- $next = 2;
320
- } else{
321
- $next = $this->openPage + 1;
322
- }
323
- $prev = $this->openPage - 1;
324
- $last = $this->pages;
325
- //$total = $this->totalResult;
326
- $result = '<div class="btn-toolbar pull-right gmedia-pager">';
327
- $result .= '<div class="btn-group btn-group-xs">';
328
-
329
- $li_class = ($this->openPage > 1)? '' : ' disabled';
330
- $result .= "<a class='btn btn-default{$li_class}' href='{$self}'><span class='glyphicon glyphicon-fast-backward'></span></a>";
331
- $result .= "<a class='btn btn-default{$li_class}' href='{$self}&pager=$prev'><span class='glyphicon glyphicon-step-backward'></span></a>";
332
-
333
- $result .= '</div>';
334
-
335
- $result .= '<form name="gmedia-pager" method="get" id="gmedia-pager" class="input-group btn-group input-group-xs" action="">';
336
- $result .= '<span class="input-group-addon">' . __("Page", "grand-media") . '</span>';
337
- foreach($params as $key => $value){
338
- $result .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
339
- }
340
- $result .= '<input class="form-control pager_current_page allow-key-enter" name="pager" type="text" value="' . $this->openPage . '" /><span class="input-group-addon">' . __("of", "grand-media") . ' ' . $this->pages . '</span>';
341
- $result .= '</form>';
342
-
343
- $result .= '<div class="btn-group btn-group-xs">';
344
- $li_class = ($this->openPage < $this->pages)? '' : ' disabled';
345
- $result .= "<a class='btn btn-default{$li_class}' href='{$self}&amp;pager=$next'><span class='glyphicon glyphicon-step-forward'></span></a>";
346
- $result .= "<a class='btn btn-default{$li_class}' href='{$self}&amp;pager=$last'><span class='glyphicon glyphicon-fast-forward'></span></a>";
347
- $result .= '</div>';
348
-
349
- $result .= '</div>';
350
-
351
- return $result;
352
- }
353
-
354
- /**
355
- * Insert media.
356
- * If you set the 'ID' in the $object parameter, it will mean that you are
357
- * updating and attempt to update the media. You can also set the
358
- * media url or title by setting the key 'gmuid' or 'title'.
359
- * You can set the dates for the media manually by setting the 'date' key value.
360
- * The $object parameter can have the following:
361
- * 'author' - Default is current user ID. The ID of the user, who added the attachment.
362
- * 'mime_type' - Will be set to media. Do not override!!!
363
- * 'gmuid' - Filename.
364
- * 'description' - Media content.
365
- * 'date' - Date.
366
- * 'modified' - Date modified.
367
- * 'link' - Media external link.
368
- * 'status' - Status.
369
- * @uses $wpdb
370
- * @uses $user_ID
371
- * @uses do_action() Calls 'edit_gmedia' on $post_ID if this is an update.
372
- * @uses do_action() Calls 'add_gmedia' on $post_ID if this is not an update.
373
- * @see wp_insert_attachment().
374
- *
375
- * @param string|array $object Arguments to override defaults.
376
- *
377
- * @return int Media ID.
378
- */
379
- function insert_gmedia($object){
380
- /** @var $wpdb wpdb */
381
- global $wpdb, $user_ID, $gmCore, $gmGallery;
382
-
383
- // TODO media status (vip, password?)
384
- $defaults = array('ID' => false, 'author' => $user_ID);
385
- $object = wp_parse_args($object, $defaults);
386
- if(isset($object['title'])){
387
- $object['title'] = strip_tags($object['title'], '<span>');
388
- $object['title'] = $gmCore->mb_convert_encoding_utf8($object['title']);
389
- }
390
- if(isset($object['description'])){
391
- $object['description'] = $gmCore->clean_input($object['description']);
392
- $object['description'] = $gmCore->mb_convert_encoding_utf8($object['description']);
393
- }
394
- if(isset($object['link'])){
395
- $object['link'] = esc_url_raw($object['link']);
396
- }
397
- if(!isset($object['status']) || empty($object['status'])){
398
- $object['status'] = 'publish';
399
- }
400
-
401
- // export array as variables
402
- extract($object, EXTR_SKIP);
403
-
404
- // Are we updating or creating?
405
- $media_ID = 0;
406
- $update = false;
407
- if(!empty($ID)){
408
- $media_ID = (int)$ID;
409
- $update = true;
410
- if(isset($date) && empty($date)){
411
- unset($date);
412
- }
413
- $modified = current_time('mysql');
414
- } else{
415
- if(empty($date)){
416
- $date = current_time('mysql');
417
- }
418
- $modified = $date;
419
- }
420
-
421
- // expected_slashed (everything!)
422
- $data = compact(array('author', 'date', 'description', 'title', 'gmuid', 'modified', 'mime_type', 'link', 'status'));
423
- $data = stripslashes_deep($data);
424
-
425
- if($update){
426
- $wpdb->update($wpdb->prefix . 'gmedia', $data, array('ID' => $media_ID));
427
- } else{
428
- $wpdb->insert($wpdb->prefix . 'gmedia', $data);
429
- $media_ID = (int)$wpdb->insert_id;
430
- }
431
-
432
- wp_cache_delete($media_ID, 'gmedias');
433
-
434
- $gmedia = $this->get_gmedia($media_ID);
435
- $post_ID = $gmedia->post_id;
436
- $post_data = array('post_author' => $gmedia->author,
437
- 'post_content' => $gmedia->description,
438
- 'post_title' => (trim($gmedia->title)? $gmedia->title : $gmedia->gmuid),
439
- 'post_status' => $gmedia->status,
440
- 'post_type' => 'gmedia',
441
- 'post_name' => $gmedia->gmuid,
442
- 'post_date' => $gmedia->date,
443
- 'post_modified' => $gmedia->modified,
444
- 'post_mime_type' => $gmedia->mime_type
445
- );
446
-
447
- if(!empty($comment_status)){
448
- $post_data['comment_status'] = $comment_status;
449
- } elseif(!$update){
450
- $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
451
- }
452
-
453
- if(!empty($post_ID)){
454
- $post_data['ID'] = $post_ID;
455
- if(!wp_update_post($post_data)){
456
- unset($post_data['ID']);
457
- $post_ID = wp_insert_post($post_data);
458
- if($post_ID){
459
- add_metadata('post', $post_ID, '_gmedia_ID', $media_ID);
460
- $wpdb->update($wpdb->prefix . 'gmedia', array('post_id' => $post_ID), array('ID' => $media_ID));
461
- wp_cache_delete($media_ID, 'gmedias');
462
- }
463
- }
464
- } else{
465
- $post_ID = wp_insert_post($post_data);
466
- if($post_ID){
467
- add_metadata('post', $post_ID, '_gmedia_ID', $media_ID);
468
- $wpdb->update($wpdb->prefix . 'gmedia', array('post_id' => $post_ID), array('ID' => $media_ID));
469
- wp_cache_delete($media_ID, 'gmedias');
470
- }
471
- }
472
-
473
- if(isset($terms) && is_array($terms) && count($terms)){
474
- foreach($terms as $taxonomy => $_terms){
475
- $taxonomy = trim($taxonomy);
476
- if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category')) && !is_array($_terms)){
477
- $_terms = explode(',', $_terms);
478
- } else{
479
- $_terms = (array)$_terms;
480
- }
481
- if(!empty($taxonomy)){
482
- $this->set_gmedia_terms($media_ID, $_terms, $taxonomy, $append = 0);
483
- }
484
- }
485
- }
486
-
487
- wp_cache_delete($media_ID, 'gmedia_meta');
488
- if(!empty($post_ID)){
489
- wp_cache_delete($post_ID, 'wpgmedias');
490
- }
491
-
492
- $this->clean_object_term_cache($media_ID);
493
-
494
- do_action('clean_gmedia_cache', $media_ID);
495
-
496
- if($update){
497
- do_action('edit_gmedia', $media_ID);
498
- } else{
499
- do_action('add_gmedia', $media_ID);
500
- }
501
-
502
- return $media_ID;
503
- }
504
-
505
- /**
506
- * Trashes or deletes gmedia.
507
- * When gmedia is deleted, the file will also be removed.
508
- * Deletion removes all gmedia meta fields, taxonomy, comments, etc. associated
509
- * with the gmedia.
510
- * @see wp_delete_attachment()
511
- * @uses $wpdb
512
- * @uses do_action() Calls 'delete_gmedia' hook on gmedia ID.
513
- *
514
- * @param int $gmedia_id Gmedia ID.
515
- * @param bool $delete_original_file delete oroginal image?
516
- *
517
- * @return mixed False on failure. Gmedia data on success.
518
- */
519
- function delete_gmedia($gmedia_id, $delete_original_file = true){
520
- /** @var $wpdb wpdb */
521
- global $wpdb, $gmGallery, $gmCore;
522
-
523
- if(!$gmedia = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}gmedia WHERE ID = %d", $gmedia_id))){
524
- return $gmedia;
525
- }
526
-
527
- $this->delete_gmedia_term_relationships($gmedia_id, array('gmedia_album', 'gmedia_tag', 'gmedia_category'));
528
-
529
- $gmedia_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->prefix}gmedia_meta WHERE gmedia_id = %d ", $gmedia_id));
530
- if(!empty($gmedia_meta_ids)){
531
- do_action('delete_gmedia_meta', $gmedia_meta_ids);
532
- $in_gmedia_meta_ids = "'" . implode("', '", $gmedia_meta_ids) . "'";
533
- $wpdb->query("DELETE FROM {$wpdb->prefix}gmedia_meta WHERE meta_id IN($in_gmedia_meta_ids)");
534
- do_action('deleted_gmedia_meta', $gmedia_meta_ids);
535
- }
536
-
537
- do_action('delete_gmedia', $gmedia_id);
538
- $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia WHERE ID = %d", $gmedia_id));
539
- if(!empty($gmedia->post_id)){
540
- wp_delete_post($gmedia->post_id, true);
541
- }
542
- do_action('deleted_gmedia', $gmedia_id);
543
-
544
-
545
- if(!empty($files)){
546
- foreach($files as $cachefile){
547
- $cachefile = apply_filters('gm_delete_file', $cachefile);
548
- @unlink($cachefile);
549
- }
550
- }
551
-
552
- $type = strtok($gmedia->mime_type, '/');
553
- if('image' == $type){
554
- $folders = array($gmGallery->options['folder']['image'],
555
- $gmGallery->options['folder']['image_thumb']
556
- );
557
- if($delete_original_file){
558
- $folders[] = $gmGallery->options['folder']['image_original'];
559
- }
560
- foreach($folders as $dir){
561
- $file = apply_filters('gm_delete_file', $gmCore->upload['path'] . '/' . $dir . '/' . $gmedia->gmuid);
562
- @unlink($file);
563
- }
564
- } else{
565
- if($delete_original_file){
566
- $dir = $gmCore->upload['path'] . '/' . $gmGallery->options['folder'][ $type ];
567
-
568
- $filepath = $dir . '/' . $gmedia->gmuid;
569
- $file = apply_filters('gm_delete_file', $filepath);
570
- @unlink($file);
571
- }
572
-
573
- /*
574
- $files = glob( $filepath . '*', GLOB_NOSORT);
575
- if(!empty($files)){
576
- foreach($files as $file){
577
- $file = apply_filters('gm_delete_file', $file);
578
- @unlink($file);
579
- }
580
- }
581
- */
582
- }
583
-
584
- wp_cache_delete($gmedia_id, 'gmedias');
585
- wp_cache_delete($gmedia_id, 'gmedia_meta');
586
- if(!empty($gmedia->post_id)){
587
- wp_cache_delete($gmedia->post_id, 'wpgmedias');
588
- }
589
- $this->clean_object_term_cache($gmedia_id);
590
-
591
- do_action('clean_gmedia_cache', $gmedia_id);
592
-
593
- return $gmedia;
594
- }
595
-
596
- /**
597
- * Will unlink the object from the taxonomy or taxonomies.
598
- * Will remove all relationships between the object and any terms in
599
- * a particular taxonomy or taxonomies. Does not remove the term or
600
- * taxonomy itself.
601
- * @see wp_delete_object_term_relationships()
602
- * @uses $wpdb
603
- *
604
- * @param int $object_id The term Object Id that refers to the term
605
- * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
606
- */
607
- function delete_gmedia_term_relationships($object_id, $taxonomies){
608
- /** @var $wpdb wpdb */
609
- global $wpdb;
610
-
611
- $object_id = (int)$object_id;
612
-
613
- if(!is_array($taxonomies)){
614
- $taxonomies = array($taxonomies);
615
- }
616
-
617
- foreach((array)$taxonomies as $taxonomy){
618
- $term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids'));
619
- $in_term_ids = "'" . implode("', '", $term_ids) . "'";
620
- do_action('delete_gmedia_term_relationships', $object_id, $term_ids);
621
- $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id IN ($in_term_ids)", $object_id));
622
- do_action('deleted_gmedia_term_relationships', $object_id, $term_ids);
623
- $this->update_term_count($term_ids);
624
- }
625
- }
626
-
627
- /**
628
- * Generate gmedia meta data.
629
- * @see wp_generate_attachment_metadata()
630
- *
631
- * @param int $media_id Gmedia Id to process.
632
- * @param array $fileinfo from fileinfo() function
633
- *
634
- * @return mixed Metadata for media.
635
- */
636
- function generate_gmedia_metadata($media_id, $fileinfo = array()){
637
- global $gmCore;
638
- $media = $this->get_gmedia($media_id);
639
- $metadata = $gmCore->get_file_metadata($media->gmuid, $fileinfo);
640
-
641
- return apply_filters('generate_gmedia_metadata', $metadata, $media_id);
642
-
643
- }
644
-
645
- /**
646
- * Retrieves gmedia data given a gmedia ID or gmedia object.
647
- * @see get_post()
648
- * @uses $wpdb
649
- *
650
- * @param int|object $media Gmedia ID or gmedia object.
651
- * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
652
- *
653
- * @return mixed Gmedia data
654
- */
655
- function get_gmedia($media, $output = OBJECT){
656
- /** @var $wpdb wpdb */
657
- global $wpdb;
658
- $null = null;
659
-
660
- if(empty($media)){
661
- return $null;
662
- } elseif(is_object($media)){
663
- $_media = $media;
664
- wp_cache_add($media->ID, $_media, 'gmedias');
665
- if(!empty($media->post_id)){
666
- wp_cache_add($media->post_id, $_media, 'wpgmedias');
667
- }
668
- } else{
669
- $media_id = (int)$media;
670
- if(!$_media = wp_cache_get($media_id, 'gmedias')){
671
- $_media = $wpdb->get_row($wpdb->prepare("SELECT {$wpdb->prefix}gmedia.*, wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count FROM {$wpdb->prefix}gmedia LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID) WHERE {$wpdb->prefix}gmedia.ID = %d LIMIT 1", $media_id));
672
- if(!$_media){
673
- return $null;
674
- }
675
- wp_cache_add($_media->ID, $_media, 'gmedias');
676
- if(!empty($_media->post_id)){
677
- wp_cache_add($_media->post_id, $_media, 'wpgmedias');
678
- }
679
- }
680
- }
681
-
682
- if($output == OBJECT){
683
- return $_media;
684
- } elseif($output == ARRAY_A){
685
- $__media = get_object_vars($_media);
686
-
687
- return $__media;
688
- } elseif($output == ARRAY_N){
689
- $__media = array_values(get_object_vars($_media));
690
-
691
- return $__media;
692
- } else{
693
- return $_media;
694
- }
695
- }
696
-
697
- /**
698
- * Retrieves gmedia data given a post ID or post object.
699
- * @uses $wpdb
700
- *
701
- * @param int|object $post Post ID or gmedia post object.
702
- * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
703
- *
704
- * @return mixed Gmedia data
705
- */
706
- function get_post_gmedia($post, $output = OBJECT){
707
- /** @var $wpdb wpdb */
708
- global $wpdb;
709
- $null = null;
710
-
711
- if(empty($post)){
712
- return $null;
713
- }
714
-
715
- if(is_object($post)){
716
- $post_id = $post->ID;
717
- } else{
718
- $post_id = (int)$post;
719
- }
720
-
721
- if(!$_media = wp_cache_get($post_id, 'wpgmedias')){
722
- $_media = $wpdb->get_row($wpdb->prepare("SELECT {$wpdb->prefix}gmedia.*, wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count FROM {$wpdb->prefix}gmedia LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID) WHERE {$wpdb->prefix}gmedia.post_id = %d LIMIT 1", $post_id));
723
- if(!$_media){
724
- return $null;
725
- }
726
- wp_cache_add($_media->ID, $_media, 'gmedias');
727
- if(!empty($_media->post_id)){
728
- wp_cache_add($_media->post_id, $_media, 'wpgmedias');
729
- }
730
- }
731
-
732
- if($output == OBJECT){
733
- return $_media;
734
- } elseif($output == ARRAY_A){
735
- $__media = get_object_vars($_media);
736
-
737
- return $__media;
738
- } elseif($output == ARRAY_N){
739
- $__media = array_values(get_object_vars($_media));
740
-
741
- return $__media;
742
- } else{
743
- return $_media;
744
- }
745
- }
746
-
747
- /**
748
- * Retrieve the gmedia posts based on query variables.
749
- * There are a few filters and actions that can be used to modify the gmedia
750
- * database query.
751
- * 'status' (string|array) - Gmedia status
752
- * 'author' (int) - Display or Exclude gmedias from several specific authors
753
- * 'author_name' (string) - Author name (nice_name)
754
- * 'cat' (int) - comma separated list of positive or negative category IDs. Display posts that have this category(ies)
755
- * 'category_name' (string) - Display posts that have this category, using category name
756
- * 'category__in' (array) - use category id. Same as 'cat', but does not accept negative values
757
- * 'category__not_in (array) - use category id. Exclude multiple categories
758
- * 'alb' (int) - comma separated list of positive or negative album IDs. Display posts that have this album(s)
759
- * 'album_name' (string) - Display posts that have this album, using album name
760
- * 'album__in' (array) - use album id. Same as 'alb'
761
- * 'album__not_in (array) - use album id. Exclude multiple albums
762
- * 'tag' (string) - use tag name. Display posts that have "either" of tags separated by comma.
763
- * Display posts that have "all" of tags separated by '+'
764
- * 'tag_id' (int) - use tag id.
765
- * 'tag__and' (array) - use tag ids. Display posts that are tagged with all listed tags in array
766
- * 'tag__in' (array) - use tag ids. To display posts from either tags listed in array. Same as 'tag'
767
- * 'tag__not_in' (array) - use tag ids. Display posts that do not have any of the listed tag ids
768
- * 'tag_name__and' (array) - use tag names.
769
- * 'tag_name__in' (array) - use tag names.
770
- * 'terms_relation' (string) - allows you to describe the boolean relationship between the taxonomy queries.
771
- * Possible values are 'OR', 'AND'.
772
- * 'gmedia_id' (int) - use gmedia id.
773
- * 'wppost_id' (int) - use gmedia id.
774
- * 'name' (string) - use gmedia title.
775
- * 'gmedia__in' (array) - use gmedia ids. Specify posts to retrieve.
776
- * 'gmedia__not_in' (array) - use gmedia ids. Specify post NOT to retrieve.
777
- * 'wppost__in' (array) - use gmedia ids. Specify posts to retrieve.
778
- * 'wppost__not_in' (array) - use gmedia ids. Specify post NOT to retrieve.
779
- * 'per_page' (int) - number of post to show per page. Use 'per_page'=>-1 to show all posts.
780
- * 'nopaging' (bool) - show all posts or use pagination. Default value is 'false', use paging.
781
- * 'page' (int) - number of page. Show the posts that would normally show up just on page X.
782
- * 'offset' (int) - number of post to displace or pass over. Note: Setting offset parameter will ignore the 'page' parameter.
783
- * 'order' (string) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'
784
- * 'orderby' (string) - Sort retrieved posts by parameter. Defaults to 'ID'
785
- * - 'none' - No order.
786
- * - 'ID' - Order by gmedia id. Note the captialization.
787
- * - 'author' - Order by author.
788
- * - 'title' - Order by title.
789
- * - 'date' - Order by date.
790
- * - 'modified' - Order by last modified date.
791
- * - 'rand' - Random order.
792
- * - 'gmedia__in' - Order by 'gmedia__in' parameter. Note: 'gmedia__in' parameter must be specified.
793
- * - 'wppost__in' - Order by 'wppost__in' parameter. Note: 'wppost__in' parameter must be specified.
794
- * - 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be
795
- * alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers
796
- * (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
797
- * - 'meta_value_num' - Order by numeric meta value. Also note that a 'meta_key=keyname' must also be present in the query.
798
- * This value allows for numerical sorting as noted above in 'meta_value'.
799
- * 'm' (int) - Up to 14 numbers. YEAR(4) MONTH(2) DAYOFMONTH(2) HOUR(2) MINUTE(2) SECOND(2).
800
- * Also you can query with 'year' (int) - 4 digit year; 'monthnum' (int) - Month number (from 1 to 12);
801
- * 'w' (int) - Week of the year (from 0 to 53); 'day' (int) - Day of the month (from 1 to 31);
802
- * 'hour' (int) - Hour (from 0 to 23); 'minute' (int) - Minute (from 0 to 60); 'second' (int) - Second (0 to 60).
803
- * 'meta_key' (string) - Custom field key.
804
- * 'meta_value' (string) - Custom field value.
805
- * 'meta_value_num' (number) - Custom field value.
806
- * 'meta_compare' (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='.
807
- * 'meta_query' (array) - Custom field parameters (array of associative arrays):
808
- * - 'key' (string) The meta key
809
- * - 'value' (string|array) - The meta value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN')
810
- * - 'compare' (string) - (optional) How to compare the key to the value.
811
- * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
812
- * Default: '='
813
- * - 'type' (string) - (optional) The type of the value.
814
- * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
815
- * Default: 'CHAR'
816
- * 's' (string) - search string or terms separated by comma. Search exactly string if 'exact' parameter set to true
817
- * 'fields' (string) - 'ids': return an array of gmedia IDs; 'post_ids': return an array of gmedia IDs and post_id's
818
- * 'robots' - bool Default is empty
819
- * @see get_posts()
820
- * @return array List of posts.
821
- */
822
- function get_gmedias(){
823
- /** @var $wpdb wpdb */
824
- global $wpdb, $_wp_using_ext_object_cache;
825
-
826
- // First let's clear some variables
827
- $whichmimetype = '';
828
- $whichstatus = '';
829
- $whichauthor = '';
830
- $where = '';
831
- $countwhere = '';
832
- $limits = '';
833
- $join = '';
834
- $search = '';
835
- $groupby = '';
836
- $fields = '';
837
- $page = 1;
838
- $album = array('order' => false,
839
- 'alias' => ''
840
- );
841
- $array = array('null_tags' => false
842
- );
843
-
844
- $keys = array('error',
845
- 'status',
846
- 'author',
847
- 'author_name',
848
- 'cat',
849
- 'category_name',
850
- 'alb',
851
- 'album_name',
852
- 'tag',
853
- 'tag_id',
854
- 'terms_relation',
855
- 'gmedia_id',
856
- 'wppost_id',
857
- 'name',
858
- 'page',
859
- 'offset',
860
- 'm',
861
- 'year',
862
- 'monthnum',
863
- 'w',
864
- 'day',
865
- 'hour',
866
- 'minute',
867
- 'second',
868
- 'meta_key',
869
- 'meta_value',
870
- 's',
871
- 'fields',
872
- 'robots'
873
- );
874
-
875
- foreach($keys as $key){
876
- if(!isset($array[ $key ])){
877
- $array[ $key ] = '';
878
- }
879
- }
880
-
881
- $array_keys = array('category__in',
882
- 'category__not_in',
883
- 'category__and',
884
- 'album__in',
885
- 'album__not_in',
886
- 'gmedia__in',
887
- 'gmedia__not_in',
888
- 'wppost__in',
889
- 'wppost__not_in',
890
- 'tag__in',
891
- 'tag__not_in',
892
- 'tag__and',
893
- 'tag_name__in',
894
- 'tag_name__and',
895
- 'author__in',
896
- 'author__not_in',
897
- 'meta_query'
898
- );
899
-
900
- foreach($array_keys as $key){
901
- if(!isset($array[ $key ])){
902
- $array[ $key ] = array();
903
- }
904
- }
905
-
906
- $args = func_get_args();
907
- if(isset($args[0])){
908
- $q = array_merge($array, $args[0]);
909
- } else{
910
- $q = $array;
911
- }
912
-
913
- if(!empty($q['robots'])){
914
- $is_robots = true;
915
- }
916
-
917
- $q['gmedia_id'] = absint($q['gmedia_id']);
918
- $q['wppost_id'] = absint($q['wppost_id']);
919
- $q['year'] = absint($q['year']);
920
- $q['monthnum'] = absint($q['monthnum']);
921
- $q['day'] = absint($q['day']);
922
- $q['w'] = absint($q['w']);
923
- $q['m'] = absint($q['m']);
924
- $q['page'] = absint($q['page']);
925
- $q['cat'] = preg_replace('|[^0-9,-]|', '', $q['cat']); // comma separated list of positive or negative integers
926
- $q['alb'] = preg_replace('|[^0-9,-]|', '', $q['alb']); // comma separated list of positive or negative integers
927
- $q['name'] = trim($q['name']);
928
- if('' !== $q['hour']){
929
- $q['hour'] = absint($q['hour']);
930
- }
931
- if('' !== $q['minute']){
932
- $q['minute'] = absint($q['minute']);
933
- }
934
- if('' !== $q['second']){
935
- $q['second'] = absint($q['second']);
936
- }
937
-
938
-
939
- if(!isset($q['limit']) || empty($q['limit'])){
940
- $q['limit'] = 0;
941
- }
942
- $q['limit'] = absint($q['limit']);
943
-
944
- if(!isset($q['per_page']) || empty($q['per_page'])){
945
- $q['per_page'] = - 1;
946
- }
947
- if(!isset($q['nopaging'])){
948
- if($q['per_page'] == - 1){
949
- $q['nopaging'] = true;
950
- } else{
951
- $q['nopaging'] = false;
952
- }
953
- }
954
- $q['per_page'] = (int)$q['per_page'];
955
- if($q['per_page'] < - 1){
956
- $q['per_page'] = abs($q['per_page']);
957
- }
958
-
959
- // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
960
- if(isset($q['no_found_rows'])){
961
- $q['no_found_rows'] = (bool)$q['no_found_rows'];
962
- } else{
963
- $q['no_found_rows'] = false;
964
- }
965
-
966
- switch($q['fields']){
967
- case 'ids':
968
- $fields = "{$wpdb->prefix}gmedia.ID";
969
- break;
970
- case 'post_ids':
971
- $fields = "{$wpdb->prefix}gmedia.ID, {$wpdb->prefix}gmedia.post_id";
972
- break;
973
- default:
974
- $fields = "{$wpdb->prefix}gmedia.*";
975
- $fields .= ", wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count";
976
- }
977
- $join .= " LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID)";
978
-
979
- // If a month is specified in the querystring, load that month
980
- if($q['m']){
981
- $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
982
- $where .= " AND YEAR({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 0, 4);
983
- if(strlen($q['m']) > 5){
984
- $where .= " AND MONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 4, 2);
985
- }
986
- if(strlen($q['m']) > 7){
987
- $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 6, 2);
988
- }
989
- if(strlen($q['m']) > 9){
990
- $where .= " AND HOUR({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 8, 2);
991
- }
992
- if(strlen($q['m']) > 11){
993
- $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 10, 2);
994
- }
995
- if(strlen($q['m']) > 13){
996
- $where .= " AND SECOND({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 12, 2);
997
- }
998
- $this->filter['m'] = $q['m'];
999
- }
1000
-
1001
- if('' !== $q['hour']){
1002
- $where .= " AND HOUR({$wpdb->prefix}gmedia.date)='" . $q['hour'] . "'";
1003
- $this->filter['hour'] = $q['hour'];
1004
- }
1005
-
1006
- if('' !== $q['minute']){
1007
- $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)='" . $q['minute'] . "'";
1008
- $this->filter['minute'] = $q['minute'];
1009
- }
1010
-
1011
- if('' !== $q['second']){
1012
- $where .= " AND SECOND({$wpdb->prefix}gmedia.date)='" . $q['second'] . "'";
1013
- $this->filter['second'] = $q['second'];
1014
- }
1015
-
1016
- if($q['year']){
1017
- $where .= " AND YEAR({$wpdb->prefix}gmedia.date)='" . $q['year'] . "'";
1018
- $this->filter['year'] = $q['year'];
1019
- }
1020
-
1021
- if($q['monthnum']){
1022
- $where .= " AND MONTH({$wpdb->prefix}gmedia.date)='" . $q['monthnum'] . "'";
1023
- $this->filter['monthnum'] = $q['monthnum'];
1024
- }
1025
-
1026
- if($q['day']){
1027
- $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)='" . $q['day'] . "'";
1028
- $this->filter['day'] = $q['day'];
1029
- }
1030
-
1031
- if($q['w']){
1032
- $where .= ' AND ' . _wp_mysql_week("`{$wpdb->prefix}gmedia`.`date`") . " = '" . $q['w'] . "'";
1033
- $this->filter['w'] = $q['w'];
1034
- }
1035
-
1036
- if('' != $q['name']){
1037
- $q['name'] = esc_sql($q['name']);
1038
- $where .= " AND {$wpdb->prefix}gmedia.title = '" . $q['name'] . "'";
1039
- $this->filter['name'] = $q['name'];
1040
- }
1041
-
1042
- // If a gmedia number is specified, load that gmedia
1043
- if($q['gmedia_id']){
1044
- $where .= " AND {$wpdb->prefix}gmedia.ID = " . $q['gmedia_id'];
1045
- $this->filter['gmedia__in'] = (array)$q['gmedia_id'];
1046
- } elseif($q['gmedia__in']){
1047
- if(!is_array($q['gmedia__in'])){
1048
- $q['gmedia__in'] = explode(',', $q['gmedia__in']);
1049
- }
1050
- $gmedia__in = array_filter(array_map('absint', $q['gmedia__in']));
1051
- $this->filter['gmedia__in'] = $gmedia__in;
1052
- $gmedia__in = implode(',', $gmedia__in);
1053
- if($gmedia__in){
1054
- $where .= " AND {$wpdb->prefix}gmedia.ID IN ($gmedia__in)";
1055
- }
1056
- } elseif($q['gmedia__not_in']){
1057
- if(!is_array($q['gmedia__not_in'])){
1058
- $q['gmedia__not_in'] = explode(',', $q['gmedia__not_in']);
1059
- }
1060
- $gmedia__not_in = array_filter(array_map('absint', $q['gmedia__not_in']));
1061
- $this->filter['gmedia__not_in'] = $gmedia__not_in;
1062
- $gmedia__not_in = implode(',', $gmedia__not_in);
1063
- if($gmedia__not_in){
1064
- $where .= " AND {$wpdb->prefix}gmedia.ID NOT IN ($gmedia__not_in)";
1065
- }
1066
- }
1067
-
1068
- // If a linked wp post number is specified, load that gmedia
1069
- if($q['wppost_id']){
1070
- $where .= " AND {$wpdb->prefix}gmedia.post_id = " . $q['wppost_id'];
1071
- $this->filter['wppost__in'] = (array)$q['wppost_id'];
1072
- } elseif($q['wppost__in']){
1073
- if(!is_array($q['wppost__in'])){
1074
- $q['wppost__in'] = explode(',', $q['wppost__in']);
1075
- }
1076
- $wppost__in = array_filter(array_map('absint', $q['wppost__in']));
1077
- $this->filter['wppost__in'] = $wppost__in;
1078
- $wppost__in = implode(',', $wppost__in);
1079
- if($wppost__in){
1080
- $where .= " AND {$wpdb->prefix}gmedia.post_id IN ($wppost__in)";
1081
- }
1082
- } elseif($q['wppost__not_in']){
1083
- if(!is_array($q['wppost__not_in'])){
1084
- $q['wppost__not_in'] = explode(',', $q['wppost__not_in']);
1085
- }
1086
- $wppost__not_in = array_filter(array_map('absint', $q['wppost__not_in']));
1087
- $this->filter['wppost__not_in'] = $wppost__not_in;
1088
- $wppost__not_in = implode(',', $wppost__not_in);
1089
- if($wppost__not_in){
1090
- $where .= " AND {$wpdb->prefix}gmedia.post_id NOT IN ($wppost__not_in)";
1091
- }
1092
- }
1093
-
1094
- // If a search pattern is specified, load the posts that match
1095
- if(!empty($q['s'])){
1096
- // added slashes screw with quote grouping when done early, so done later
1097
- $q['s'] = stripslashes($q['s']);
1098
- if(empty($q['exact'])){
1099
- $q['search_terms'] = array_filter(array_map('trim', explode(' ', $q['s'])));
1100
- } else{
1101
- $q['search_terms'] = $q['s'];
1102
- }
1103
- $n = '%';
1104
- $searchand = '';
1105
- foreach((array)$q['search_terms'] as $term){
1106
- $term = esc_sql(addcslashes($term, '_%\\'));
1107
- $search .= "{$searchand}(({$wpdb->prefix}gmedia.title LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.description LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.gmuid LIKE '{$n}{$term}{$n}'))";
1108
- $searchand = ' AND ';
1109
- }
1110
-
1111
- if(!empty($search)){
1112
- $search = " AND ({$search}) ";
1113
- /* TODO not display private media when user not logged in
1114
- if ( !is_user_logged_in() )
1115
- $search .= " AND ({$wpdb->prefix}gmedia_meta.password = '') ";
1116
- */
1117
- $this->filter['s'] = (array)$q['search_terms'];
1118
- }
1119
- }
1120
-
1121
- // Category stuff
1122
- $this->gmedias_category_stuff($q);
1123
-
1124
- if(!empty($q['category__and']) && 1 === count((array)$q['category__and'])){
1125
- $q['category__and'] = (array)$q['category__and'];
1126
- if(!isset($q['category__in'])){
1127
- $q['category__in'] = array();
1128
- }
1129
- $q['category__in'][] = absint(reset($q['category__and']));
1130
- unset($q['category__and']);
1131
- }
1132
-
1133
- if(!empty($q['category__in'])){
1134
- $tax_query[] = array('taxonomy' => 'gmedia_category',
1135
- 'terms' => $q['category__in'],
1136
- 'operator' => 'IN'
1137
- );
1138
- }
1139
-
1140
- if(!empty($q['category__not_in'])){
1141
- $tax_query[] = array('taxonomy' => 'gmedia_category',
1142
- 'terms' => $q['category__not_in'],
1143
- 'operator' => 'NOT IN'
1144
- );
1145
- }
1146
-
1147
- if(!empty($q['category__and'])){
1148
- $tax_query[] = array('taxonomy' => 'gmedia_category',
1149
- 'terms' => $q['category__and'],
1150
- 'operator' => 'AND'
1151
- );
1152
- }
1153
-
1154
- // Album stuff
1155
- $this->gmedias_album_stuff($q);
1156
-
1157
- if(!empty($q['album__in'])){
1158
- $tax_query[] = array('taxonomy' => 'gmedia_album',
1159
- 'terms' => $q['album__in'],
1160
- 'operator' => 'IN'
1161
- );
1162
- if(1 == count($q['album__in'])){
1163
- $album['order'] = true;
1164
- }
1165
- }
1166
-
1167
- if(!empty($q['album__not_in'])){
1168
- $tax_query[] = array('taxonomy' => 'gmedia_album',
1169
- 'terms' => $q['album__not_in'],
1170
- 'operator' => 'NOT IN'
1171
- );
1172
- }
1173
-
1174
- // Tag stuff
1175
- $this->gmedias_tag_stuff($q);
1176
-
1177
- if(!empty($q['tag__in'])){
1178
- $tax_query[] = array('taxonomy' => 'gmedia_tag',
1179
- 'terms' => $q['tag__in'],
1180
- 'operator' => 'IN'
1181
- );
1182
- }
1183
-
1184
- if(!empty($q['tag__not_in'])){
1185
- $tax_query[] = array('taxonomy' => 'gmedia_tag',
1186
- 'terms' => $q['tag__not_in'],
1187
- 'operator' => 'NOT IN'
1188
- );
1189
- }
1190
-
1191
- if(!empty($q['tag__and'])){
1192
- $tax_query[] = array('taxonomy' => 'gmedia_tag',
1193
- 'terms' => $q['tag__and'],
1194
- 'operator' => 'AND'
1195
- );
1196
- }
1197
-
1198
- if(!empty($q['tag_name__in']) || (isset($q['tag_name__in_null']) && $q['null_tags'])){
1199
- $tax_query[] = array('taxonomy' => 'gmedia_tag',
1200
- 'terms' => $q['tag_name__in'],
1201
- 'operator' => 'IN'
1202
- );
1203
- }
1204
-
1205
- if(!empty($q['tag_name__and']) || (isset($q['tag_name__and_null']) && $q['null_tags'])){
1206
- $tax_query[] = array('taxonomy' => 'gmedia_tag',
1207
- 'terms' => $q['tag_name__and'],
1208
- 'operator' => 'AND'
1209
- );
1210
- }
1211
-
1212
- if(!empty($tax_query)){
1213
- if(isset($q['terms_relation']) && strtoupper($q['terms_relation']) == 'AND'){
1214
- $terms_relation = 'AND';
1215
- } else{
1216
- $terms_relation = 'OR';
1217
- }
1218
- $clauses['join'] = '';
1219
- $clauses['where'] = array();
1220
- $i = 0;
1221
- foreach($tax_query as $query){
1222
- /** @var $taxonomy
1223
- * @var $terms
1224
- * @var $field
1225
- * @var $operator
1226
- * @var $include_children
1227
- */
1228
- extract($query);
1229
-
1230
- $taxterm = str_replace('gmedia_', '', $taxonomy);
1231
-
1232
- if('IN' == $operator){
1233
-
1234
- if(empty($terms)){
1235
- continue;
1236
- }
1237
-
1238
- $this->filter["{$taxterm}__in"] = $terms;
1239
- $terms = implode(',', $terms);
1240
-
1241
- $alias = $i? 'tr' . $i : 'tr';
1242
-
1243
- $clauses['join'] .= " INNER JOIN {$wpdb->prefix}gmedia_term_relationships AS $alias";
1244
- $clauses['join'] .= " ON ({$wpdb->prefix}gmedia.ID = $alias.gmedia_id)";
1245
-
1246
- $clauses['where'][] = "$alias.gmedia_term_id $operator ($terms)";
1247
-
1248
- if($album['order'] && ('gmedia_album' == $taxonomy)){
1249
- $album['alias'] = $alias;
1250
- if('ids' != $q['fields'] || 'post_ids' != $q['fields']){
1251
- $fields .= ", $alias.*";
1252
- }
1253
- }
1254
- } elseif('NOT IN' == $operator){
1255
-
1256
- if(empty($terms)){
1257
- continue;
1258
- }
1259
-
1260
- $this->filter["{$taxterm}__not_in"] = $terms;
1261
- $terms = implode(',', $terms);
1262
-
1263
- $clauses['where'][] = "{$wpdb->prefix}gmedia.ID NOT IN (
1264
- SELECT gmedia_id
1265
- FROM {$wpdb->prefix}gmedia_term_relationships
1266
- WHERE gmedia_term_id IN ($terms)
1267
- )";
1268
- } elseif('AND' == $operator){
1269
-
1270
- if(empty($terms)){
1271
- continue;
1272
- }
1273
-
1274
- $num_terms = count($terms);
1275
-
1276
- $this->filter["{$taxterm}__and"] = $terms;
1277
- $terms = implode(',', $terms);
1278
-
1279
- $clauses['where'][] = "(
1280
- SELECT COUNT(1)
1281
- FROM {$wpdb->prefix}gmedia_term_relationships
1282
- WHERE gmedia_term_id IN ($terms)
1283
- AND gmedia_id = {$wpdb->prefix}gmedia.ID
1284
- ) = $num_terms";
1285
- }
1286
-
1287
- $i ++;
1288
- }
1289
-
1290
- if(!empty($clauses['where'])){
1291
- $clauses['where'] = ' AND ( ' . implode(" $terms_relation ", $clauses['where']) . ' )';
1292
- } else{
1293
- $clauses['where'] = '';
1294
- }
1295
-
1296
- $join .= $clauses['join'];
1297
- $where .= $clauses['where'];
1298
- }
1299
-
1300
- // Meta stuff
1301
- $meta_query = array();
1302
- // Simple query needs to be first for orderby=meta_value to work correctly
1303
- foreach(array('key', 'compare', 'type') as $key){
1304
- if(!empty($q["meta_$key"])){
1305
- $meta_query[0][ $key ] = $q["meta_$key"];
1306
- }
1307
- }
1308
- // Query sets 'meta_value' = '' by default
1309
- if(isset($q['meta_value']) && !empty($q['meta_value'])){
1310
- $meta_query[0]['value'] = $q['meta_value'];
1311
- }
1312
-
1313
- if(!empty($q['meta_query']) && is_array($q['meta_query'])){
1314
- $meta_query = array_merge($meta_query, $q['meta_query']);
1315
- }
1316
- if(!empty($meta_query)){
1317
- $primary_table = $wpdb->prefix . 'gmedia';
1318
- $primary_id_column = 'ID';
1319
- $meta_table = $wpdb->prefix . 'gmedia_meta';
1320
- $meta_id_column = 'gmedia_id';
1321
-
1322
- if(isset($meta_query['relation']) && strtoupper($meta_query['relation']) == 'OR'){
1323
- $relation = 'OR';
1324
- } else{
1325
- $relation = 'AND';
1326
- }
1327
- $meta_query = array_filter($meta_query, 'is_array');
1328
-
1329
- $clauses['join'] = array();
1330
- $clauses['where'] = array();
1331
-
1332
- foreach($meta_query as $key => $query){
1333
- if(!isset($query['key']) || empty($query['key'])){
1334
- continue;
1335
- }
1336
- $meta_key = trim($query['key']);
1337
- $meta_type = isset($query['type'])? strtoupper($query['type']) : 'CHAR';
1338
-
1339
- if('NUMERIC' == $meta_type){
1340
- $meta_type = 'SIGNED';
1341
- } elseif(!in_array($meta_type, array('BINARY',
1342
- 'CHAR',
1343
- 'DATE',
1344
- 'DATETIME',
1345
- 'DECIMAL',
1346
- 'SIGNED',
1347
- 'TIME',
1348
- 'UNSIGNED'
1349
- ))
1350
- ){
1351
- $meta_type = 'CHAR';
1352
- }
1353
-
1354
- $i = count($clauses['join']);
1355
- $alias = $i? 'mt' . $i : $meta_table;
1356
-
1357
- // Set JOIN
1358
- $clauses['join'][ $i ] = "INNER JOIN $meta_table";
1359
- $clauses['join'][ $i ] .= $i? " AS $alias" : '';
1360
- $clauses['join'][ $i ] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
1361
-
1362
- $clauses['where'][ $key ] = '';
1363
- if(!empty($meta_key)){
1364
- $clauses['where'][ $key ] = $wpdb->prepare("$alias.meta_key = %s", $meta_key);
1365
- }
1366
-
1367
- if(!isset($query['value'])){
1368
- if(empty($clauses['where'][ $key ])){
1369
- unset($clauses['join'][ $i ]);
1370
- }
1371
- continue;
1372
- }
1373
-
1374
- $meta_value = $query['value'];
1375
-
1376
- $meta_compare = is_array($meta_value)? 'IN' : '=';
1377
- if(isset($query['compare'])){
1378
- $meta_compare = strtoupper($query['compare']);
1379
- }
1380
-
1381
- if(!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))){
1382
- $meta_compare = '=';
1383
- }
1384
-
1385
- if(in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))){
1386
- if(!is_array($meta_value)){
1387
- $meta_value = preg_split('/[,\s]+/', $meta_value);
1388
- }
1389
-
1390
- if(empty($meta_value)){
1391
- unset($clauses['join'][ $i ]);
1392
- continue;
1393
- }
1394
- } else{
1395
- $meta_value = trim($meta_value);
1396
- }
1397
-
1398
- if('IN' == substr($meta_compare, - 2)){
1399
- $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')';
1400
- } elseif('BETWEEN' == substr($meta_compare, - 7)){
1401
- $meta_value = array_slice($meta_value, 0, 2);
1402
- $meta_compare_string = '%s AND %s';
1403
- } elseif('LIKE' == substr($meta_compare, - 4)){
1404
- $meta_value = '%' . addcslashes($meta_value, '_%\\') . '%';
1405
- $meta_compare_string = '%s';
1406
- } else{
1407
- $meta_compare_string = '%s';
1408
- }
1409
-
1410
- if(!empty($clauses['where'][ $key ])){
1411
- $clauses['where'][ $key ] .= ' AND ';
1412
- }
1413
-
1414
- $clauses['where'][ $key ] = ' (' . $clauses['where'][ $key ] . $wpdb->prepare("CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value);
1415
- }
1416
-
1417
- $clauses['where'] = array_filter($clauses['where']);
1418
-
1419
- if(empty($clauses['where'])){
1420
- $clauses['where'] = '';
1421
- } else{
1422
- $clauses['where'] = ' AND (' . implode("\n{$relation} ", $clauses['where']) . ' )';
1423
- }
1424
-
1425
- $clauses['join'] = implode("\n", $clauses['join']);
1426
- if(!empty($clauses['join'])){
1427
- $clauses['join'] = ' ' . $clauses['join'];
1428
- }
1429
-
1430
- $join .= $clauses['join'];
1431
- $where .= $clauses['where'];
1432
-
1433
- $this->filter['meta_query'] = $meta_query;
1434
- }
1435
- unset($clauses);
1436
-
1437
- if(!empty($tax_query) || !empty($meta_query)){
1438
- $groupby = "{$wpdb->prefix}gmedia.ID";
1439
- }
1440
-
1441
- // Status
1442
- if($q['status']){
1443
- $q['status'] = array_map('esc_sql', array_unique((array)$q['status']));
1444
- $this->filter['status'] = $q['status'];
1445
- $status = "'" . str_replace(",", "','", implode(",", $q['status'])) . "'";
1446
- $whichstatus .= " AND {$wpdb->prefix}gmedia.status IN ({$status})";
1447
- }
1448
-
1449
- // Author/user stuff for ID
1450
- if(!empty($q['author']) && $q['author'] != '0'){
1451
- $q['author'] = addslashes_gpc('' . urldecode($q['author']));
 
1452
  $authors = array_unique(array_map('intval', preg_split('/[,\s]+/', $q['author'])));
1453
- foreach($authors as $author){
1454
- $key = $author > 0? 'author__in' : 'author__not_in';
1455
- $q[ $key ][] = abs($author);
1456
- }
1457
- $q['author'] = implode(',', $authors);
1458
- }
1459
-
1460
- if(!empty($q['author__not_in'])){
1461
- $author__not_in = array_map('absint', array_unique(wp_parse_id_list($q['author__not_in'])));
1462
- $this->filter['author__not_in'] = $author__not_in;
1463
- $author__not_in = implode(',', $author__not_in);
1464
- $whichauthor .= " AND {$wpdb->prefix}gmedia.author NOT IN ($author__not_in) ";
1465
- } elseif(!empty($q['author__in'])){
1466
- $author__in = array_map('absint', array_unique(wp_parse_id_list($q['author__in'])));
1467
- $this->filter['author__in'] = $author__in;
1468
- $author__in = implode(',', $author__in);
1469
- $whichauthor .= " AND {$wpdb->prefix}gmedia.author IN ($author__in) ";
1470
- }
1471
-
1472
- // Author stuff for name
1473
- if('' != $q['author_name']){
1474
- $q['author_name'] = esc_sql($q['author_name']);
1475
- $author = get_user_by('slug', $q['author_name']);
1476
- if($author){
1477
- $q['author'] = $author->ID;
1478
- $whichauthor .= " AND ({$wpdb->prefix}gmedia.author = " . absint($q['author']) . ')';
1479
- $this->filter['author__in'] = $q['author'];
1480
- }
1481
- }
1482
-
1483
- // MIME-Type stuff
1484
- if(isset($q['mime_type']) && !empty($q['mime_type'])){
1485
- if(is_string($q['mime_type'])){
1486
- $q['mime_type'] = array_map('trim', explode(',', $q['mime_type']));
1487
- }
1488
- $whichmimetype = $this->gmedia_mime_type_where($q['mime_type'], $wpdb->prefix . 'gmedia');
1489
- $this->filter['mime_type'] = $q['mime_type'];
1490
- }
1491
-
1492
- $where .= $whichstatus . $search;
1493
-
1494
- $empty_order = empty($q['order']);
1495
- if($empty_order || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))){
1496
- $q['order'] = 'DESC';
1497
- }
1498
-
1499
- // Order by
1500
- if(empty($q['orderby']) || ('none' == $q['orderby'])){
1501
- $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
1502
- } else{
1503
- // Used to filter values
1504
- $allowed_keys = array('ID', 'author', 'date', 'title', 'filename', 'gmuid', 'modified', 'mime_type', 'gmedia__in', 'rand', 'comment_count');
1505
- if($album['order'] && !empty($album['alias'])){
1506
- $allowed_keys[] = 'custom';
1507
- }
1508
- $q['orderby'] = urldecode($q['orderby']);
1509
- $q['orderby'] = addslashes_gpc($q['orderby']);
1510
- if(in_array($q['orderby'], array('_created_timestamp', 'views', 'likes', '_size'))){
1511
- $q['meta_key'] = $q['orderby'];
1512
- $q['orderby'] = 'meta_value_num';
1513
- $join .= " LEFT JOIN {$wpdb->prefix}gmedia_meta ON ({$wpdb->prefix}gmedia.ID = {$wpdb->prefix}gmedia_meta.gmedia_id AND " . $wpdb->prepare("{$wpdb->prefix}gmedia_meta.meta_key = %s", $q['meta_key']) . ")";
1514
- }
1515
- if(!empty($q['meta_key'])){
1516
- $allowed_keys[] = $q['meta_key'];
1517
- $allowed_keys[] = 'meta_value';
1518
- $allowed_keys[] = 'meta_value_num';
1519
- }
1520
- if(in_array($q['orderby'], array('custom', 'title', 'date', 'modified', 'comment_count', 'meta_value', 'meta_value_num'))){
1521
- $q['orderby'] .= ' ID.DESC';
1522
- $allowed_keys[] = 'ID.DESC';
1523
- }
1524
- $orderby_array = array();
1525
- foreach(explode(' ', $q['orderby']) as $_orderby){
1526
- // Only allow certain values for safety
1527
- if(!in_array($_orderby, $allowed_keys)){
1528
- continue;
1529
- }
1530
-
1531
- switch($_orderby){
1532
- case 'rand':
1533
- $orderby = 'RAND()';
1534
- break;
1535
- case $q['meta_key']:
1536
- case 'meta_value':
1537
- $orderby = "{$wpdb->prefix}gmedia_meta.meta_value";
1538
- break;
1539
- case 'meta_value_num':
1540
- $orderby = "{$wpdb->prefix}gmedia_meta.meta_value+0";
1541
- break;
1542
- case 'gmedia__in':
1543
- if(count($q['gmedia__in']) > 1){
1544
- $orderby = "FIELD({$wpdb->prefix}gmedia.ID, " . join(', ', $q['gmedia__in']) . ")";
1545
- } else{
1546
- $orderby = "{$wpdb->prefix}gmedia.ID";
1547
- }
1548
- if($empty_order) {
1549
- $q['order'] = 'ASC';
1550
- }
1551
- break;
1552
- case 'filename':
1553
- $orderby = "{$wpdb->prefix}gmedia.gmuid";
1554
- break;
1555
- case 'custom':
1556
- $orderby = "{$album['alias']}.gmedia_order";
1557
- break;
1558
- case 'comment_count':
1559
- $orderby = "wp.comment_count";
1560
- break;
1561
- case 'ID.DESC':
1562
- $orderby = "{$wpdb->prefix}gmedia.ID";
1563
- break;
1564
- default:
1565
- $orderby = "{$wpdb->prefix}gmedia." . $_orderby;
1566
- }
1567
-
1568
- if('ID.DESC' !== $_orderby){
1569
- $orderby .= " {$q['order']}";
1570
- } else{
1571
- $orderby .= " DESC";
1572
- }
1573
- $orderby_array[] = $orderby;
1574
- }
1575
- $orderby = implode(', ', $orderby_array);
1576
-
1577
- if(empty($orderby)){
1578
- $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
1579
- }
1580
- }
1581
-
1582
- // Paging
1583
- $page = $q['page'];
1584
- if(empty($page)){
1585
- $page = 1;
1586
- }
1587
- if(empty($q['nopaging'])){
1588
- if($q['limit'] && ($q['per_page'] > $q['limit'])){
1589
- $q['per_page'] = $q['limit'];
1590
- }
1591
- if(empty($q['offset']) && ((0 != $q['offset']) || ('0' != $q['offset']))){
1592
- $per_page = $q['per_page'];
1593
- $offset = ($page - 1) * $per_page;
1594
- if($q['limit'] && (($offset + $per_page) > $q['limit'])){
1595
- $per_page = $q['limit'] - $offset;
1596
- if(0 > $per_page){
1597
- $per_page = 0;
1598
- }
1599
- }
1600
- $pgstrt = $offset . ', ';
1601
- $limits = 'LIMIT ' . $pgstrt . $per_page;
1602
- } else{ // we're ignoring $page and using 'offset'
1603
- $q['offset'] = absint($q['offset']);
1604
- $pgstrt = $q['offset'] . ', ';
1605
- $limits = 'LIMIT ' . $pgstrt . $q['per_page'];
1606
- $this->resultLimited = true;
1607
- }
1608
- } elseif($q['limit']){
1609
- $limits = 'LIMIT ' . $q['limit'];
1610
- }
1611
-
1612
- // Announce current selection parameters. For use by caching plugins.
1613
- do_action('gmedia_selection', $where . $whichauthor . $whichmimetype . $groupby . $orderby . $limits . $join);
1614
-
1615
- if(!empty($groupby)){
1616
- $groupby = 'GROUP BY ' . $groupby;
1617
- }
1618
- if(!empty($orderby)){
1619
- $orderby = 'ORDER BY ' . $orderby;
1620
- }
1621
-
1622
- $found_rows = '';
1623
- if(!$q['no_found_rows'] && !empty($limits)){
1624
- $found_rows = 'SQL_CALC_FOUND_ROWS';
1625
- }
1626
-
1627
- $this->sql_query = "SELECT $found_rows $fields FROM {$wpdb->prefix}gmedia $join WHERE 1=1 $where $whichauthor $whichmimetype $groupby $orderby $limits";
1628
-
1629
- $clauses = compact('join', 'where', 'whichauthor', 'whichmimetype', 'groupby', 'orderby', 'limits');
1630
- $this->clauses = $clauses;
1631
-
1632
- if('ids' == $q['fields']){
1633
- $gmedias = $wpdb->get_col($this->sql_query);
1634
-
1635
- return $gmedias;
1636
- }
1637
-
1638
- $gmedias = $wpdb->get_results($this->sql_query);
1639
-
1640
- if('post_ids' == $q['fields']){
1641
-
1642
- return $gmedias;
1643
- }
1644
-
1645
- $gmedia_count = count($gmedias);
1646
-
1647
- if(!$q['no_found_rows'] && !empty($limits)){
1648
- $this->totalResult = (int)$wpdb->get_var('SELECT FOUND_ROWS()');
1649
- if($q['limit']){
1650
- $this->hardlimit = $q['limit'];
1651
- $this->trueTotalResult = $this->totalResult;
1652
- if($this->totalResult > $q['limit']){
1653
- $this->totalResult = $q['limit'];
1654
- }
1655
- }
1656
- } else{
1657
- $this->totalResult = $gmedia_count;
1658
- $this->trueTotalResult = $this->totalResult;
1659
- }
1660
- if($q['per_page'] && (- 1 != $q['per_page'])){
1661
- $this->pages = ceil($this->totalResult / $q['per_page']);
1662
- $this->perPages = (int)$q['per_page'];
1663
- } else{
1664
- $this->pages = 1;
1665
- $this->perPages = $gmedia_count;
1666
- }
1667
- $this->openPage = $page;
1668
- $this->resultPerPage = $gmedia_count;
1669
-
1670
- if(!isset($q['cache_results'])){
1671
- if($_wp_using_ext_object_cache){
1672
- $q['cache_results'] = false;
1673
- } else{
1674
- $q['cache_results'] = true;
1675
- }
1676
- }
1677
-
1678
- if(!isset($q['update_gmedia_term_cache'])){
1679
- $q['update_gmedia_term_cache'] = true;
1680
- }
1681
-
1682
- if(!isset($q['update_gmedia_meta_cache'])){
1683
- $q['update_gmedia_meta_cache'] = true;
1684
- }
1685
-
1686
- if($q['cache_results']){
1687
- $this->update_gmedia_caches($gmedias, $q['update_gmedia_term_cache'], $q['update_gmedia_meta_cache']);
1688
- }
1689
-
1690
- if($gmedia_count > 0){
1691
- $this->gmedia = $gmedias[0];
1692
- }
1693
- $this->query = $gmedias;
1694
-
1695
- return $gmedias;
1696
- }
1697
-
1698
- /**
1699
- * @return array
1700
- */
1701
- public function get_duplicates(){
1702
- global $wpdb;
1703
-
1704
- // $sql = "SELECT gmedia_id, meta_value, COUNT(*) AS dups FROM {$wpdb->prefix}gmedia_meta GROUP BY meta_value HAVING dups > 1";
1705
- $sql = "SELECT DISTINCT g.gmedia_id, g.meta_value, g2.dupe_count
1706
- FROM {$wpdb->prefix}gmedia_meta AS g
1707
- JOIN (
1708
- SELECT count(*) AS dupe_count, meta_value
1709
- FROM {$wpdb->prefix}gmedia_meta
1710
- WHERE meta_key = '_hash'
1711
- GROUP BY meta_value
1712
- HAVING dupe_count > 1
1713
- ) AS g2 ON g.meta_value = g2.meta_value ORDER BY g.meta_value, g.gmedia_id ASC;";
1714
-
1715
- $duplicate_ids = array();
1716
- $duplicate_hashes = array();
1717
- $duplicate_select = array();
1718
-
1719
- $duplicates = $wpdb->get_results($sql);
1720
-
1721
- if($duplicates){
1722
- foreach($duplicates as $dups){
1723
- $duplicate_ids[] = $dups->gmedia_id;
1724
- if(!isset($duplicate_hashes[ $dups->meta_value ])){
1725
- $duplicate_hashes[ $dups->meta_value ] = $dups->dupe_count;
1726
- } else{
1727
- $duplicate_select[] = $dups->gmedia_id;
1728
- }
1729
- }
1730
- $duplicate_ids = array_reverse($duplicate_ids);
1731
- }
1732
-
1733
- return compact('duplicate_ids', 'duplicate_select', 'duplicate_hashes');
1734
- }
1735
-
1736
- /**
1737
- * Category stuff for gmedia query.
1738
- *
1739
- * @param $q
1740
- */
1741
- function gmedias_category_stuff(&$q){
1742
- global $wpdb;
1743
-
1744
- if(isset($q['category_name']) && !empty($q['category_name'])){
1745
- $q['category_name'] = "'" . esc_sql($q['category_name']) . "'";
1746
- $cat = $wpdb->get_var("
1747
- SELECT term_id
1748
- FROM {$wpdb->prefix}gmedia_term
1749
- WHERE taxonomy = 'gmedia_category'
1750
- AND name = {$q['category_name']}
1751
- ");
1752
- if($cat){
1753
- unset($q['category_name']);
1754
- $q['category__in'][] = $cat;
1755
- }
1756
- }
1757
- if(isset($q['cat'])){
1758
- if(!empty($q['cat']) && ('0' !== $q['cat']) && (0 !== $q['cat'])){
1759
- $q['cat'] = '' . urldecode($q['cat']) . '';
1760
- $q['cat'] = addslashes_gpc($q['cat']);
1761
- $cat_array = preg_split('/[,\s]+/', $q['cat']);
1762
- $q['cat'] = '';
1763
- $req_cats = array();
1764
- foreach((array)$cat_array as $cat){
1765
- $cat = intval($cat);
1766
- $req_cats[] = $cat;
1767
- $in = ($cat >= 0);
1768
- $cat = abs($cat);
1769
- if($in){
1770
- $q['category__in'][] = $cat;
1771
- } else{
1772
- $q['category__not_in'][] = $cat;
1773
- }
1774
- }
1775
- $q['cat'] = implode(',', $req_cats);
1776
- } elseif(('0' === $q['cat']) || (0 === $q['cat'])){
1777
- $q['category__not_in'] = $this->get_terms('gmedia_category', array('fields' => 'ids'));
1778
- $q['without_category'] = true;
1779
- }
1780
- }
1781
-
1782
- if(isset($q['category__in']) && (!empty($q['category__in']) || ('0' === $q['category__in']) || (0 === $q['category__in']))){
1783
- $q['category__in'] = wp_parse_id_list($q['category__in']);
1784
- if(in_array(0, $q['category__in'])){
1785
- $q['category__in'] = array_filter($q['category__in']);
1786
- $q['category__not_in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__in']);
1787
- $q['without_category'] = true;
1788
- if(!empty($q['category__in'])){
1789
- $q['with_category__in'] = $q['category__in'];
1790
- }
1791
- $q['category__in'] = array();
1792
- }
1793
- }
1794
- if(isset($q['category__not_in']) && (!empty($q['category__not_in']) || ('0' === $q['category__not_in']) || (0 === $q['category__not_in']))){
1795
- $q['category__not_in'] = wp_parse_id_list($q['category__not_in']);
1796
- if(in_array(0, $q['category__not_in'])){
1797
- $q['category__not_in'] = array_filter($q['category__not_in']);
1798
- $q['category__in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__not_in']);
1799
- $q['within_category'] = true;
1800
- if(!empty($q['category__not_in'])){
1801
- $q['with_category__not_in'] = $q['category__not_in'];
1802
- }
1803
- $q['category__not_in'] = array();
1804
- }
1805
- }
1806
- if(isset($q['category__and']) && !empty($q['category__and'])){
1807
- $q['category__and'] = wp_parse_id_list($q['category__and']);
1808
- }
1809
-
1810
- }
1811
-
1812
- /**
1813
- * Album stuff for gmedia query.
1814
- *
1815
- * @param $q
1816
- */
1817
- function gmedias_album_stuff(&$q){
1818
- global $wpdb;
1819
-
1820
- $date_order = false;
1821
- if ( ! empty( $q['albums_order'] ) ) {
1822
- $order_by = explode( '_', $q['albums_order'] );
1823
- $albums_orderby = $order_by[0];
1824
- if ( 'date' === $albums_orderby ) {
1825
- $albums_orderby = 'id';
1826
- $date_order = true;
1827
- }
1828
- $albums_order = ( isset( $order_by[1] ) && 'desc' === $order_by[1] ) ? 'DESC' : 'ASC';
1829
- } else {
1830
- $albums_orderby = 'include';
1831
- $albums_order = 'ASC';
1832
- }
1833
-
1834
- if(isset($q['album_name']) && !empty($q['album_name'])){
1835
- $q['album_name'] = "'" . esc_sql($q['album_name']) . "'";
1836
- $alb = $wpdb->get_var("
1837
- SELECT term_id
1838
- FROM {$wpdb->prefix}gmedia_term
1839
- WHERE taxonomy = 'gmedia_album'
1840
- AND name = {$q['album_name']}
1841
- ");
1842
- if($alb){
1843
- unset($q['album_name']);
1844
- $q['album__in'][] = $alb;
1845
- }
1846
- }
1847
- if(isset($q['alb'])){
1848
- if(!empty($q['alb']) && ('0' !== $q['alb']) && (0 !== $q['alb'])){
1849
- $q['alb'] = '' . urldecode($q['alb']) . '';
1850
- $q['alb'] = addslashes_gpc($q['alb']);
1851
- $alb_array = preg_split('/[,\s]+/', $q['alb']);
1852
- $q['alb'] = '';
1853
- $req_albs = array();
1854
- foreach((array)$alb_array as $alb){
1855
- if(!($alb = intval($alb))){
1856
- continue;
1857
- }
1858
- $in = ($alb >= 0);
1859
- $alb = abs($alb);
1860
- if($in){
1861
- /*if(isset($q['album__status'])){
1862
- $alb_obj = $this->get_term($alb, 'gmedia_album');
1863
- if(empty($alb_obj) || (is_wp_error($alb_obj) || !in_array($alb_obj->status, (array) $q['album__status']))){
1864
- continue;
1865
- }
1866
- }*/
1867
- $q['album__in'][] = $alb;
1868
- $req_albs[] = $alb;
1869
- } else{
1870
- $q['album__not_in'][] = $alb;
1871
- $req_albs[] = - $alb;
1872
- }
1873
- }
1874
- $q['alb'] = implode(',', $req_albs);
1875
- } elseif(('0' === $q['alb']) || (0 === $q['alb'])){
1876
- $q['album__not_in'] = $this->get_terms('gmedia_album', array('fields' => 'ids'));
1877
- $q['without_album'] = true;
1878
- }
1879
- }
1880
-
1881
- if(isset($q['album__in']) && (!empty($q['album__in']) || ('0' === $q['album__in']) || (0 === $q['album__in']))){
1882
- $q['album__in'] = wp_parse_id_list($q['album__in']);
1883
- $without_album = in_array(0, $q['album__in'])? true : false;
1884
- if(isset($q['album__status'])){
1885
- $q['album__in'] = $this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'include' => $q['album__in'], 'status' => $q['album__status']));
1886
- } elseif('include' !== $albums_orderby && 'id' !== $albums_orderby) {
1887
- $q['album__in'] = $this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'include' => $q['album__in']));
1888
- } elseif('id' === $albums_orderby) {
1889
- if('ASC' === $albums_order) {
1890
- sort( $q['album__in'] );
1891
- } else {
1892
- rsort( $q['album__in'] );
1893
- }
1894
- }
1895
- if($without_album){
1896
- $q['album__in'] = array_filter($q['album__in']);
1897
- $q['album__not_in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids')), $q['album__in']);
1898
- $q['without_album'] = true;
1899
- if(!empty($q['album__in'])){
1900
- $q['with_album__in'] = $q['album__in'];
1901
- }
1902
- $q['album__in'] = array();
1903
- }
1904
- }
1905
- if(isset($q['album__not_in']) && (!empty($q['album__not_in']) || ('0' === $q['album__not_in']) || (0 === $q['album__not_in']))){
1906
- $q['album__not_in'] = wp_parse_id_list($q['album__not_in']);
1907
- if(in_array(0, $q['album__not_in'])){
1908
- $q['album__not_in'] = array_filter($q['album__not_in']);
1909
- if(isset($q['album__status'])){
1910
- $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'status' => $q['album__status'])), $q['album__not_in']);
1911
- } else{
1912
- $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order)), $q['album__not_in']);
1913
- }
1914
- $q['within_album'] = true;
1915
- if(!empty($q['album__not_in'])){
1916
- $q['with_album__not_in'] = $q['album__not_in'];
1917
- }
1918
- $q['album__not_in'] = array();
1919
- }
1920
- }
1921
-
1922
- if ( $date_order && ! empty( $q['album__in'] ) ) {
1923
- $gmedia_albums = get_posts( array(
1924
- 'posts_per_page' => -1,
1925
- 'post_type' => 'gmedia_album',
1926
- 'post_status' => 'any',
1927
- 'order_by' => 'post_date',
1928
- 'order' => $albums_order,
1929
- 'meta_key' => '_gmedia_term_ID',
1930
- 'meta_compare' => 'IN',
1931
- 'meta_value' => $q['album__in'],
1932
- 'suppress_filters' => true,
1933
- ) );
1934
- $alb_in_by_date = array();
1935
- foreach ( $gmedia_albums as $gm_alb ) {
1936
- $alb_in_by_date[] = (int) get_post_meta( $gm_alb->ID, '_gmedia_term_ID', true );
1937
- }
1938
- $q['album__in'] = array_unique( array_merge( $alb_in_by_date, $q['album__in'] ) );
1939
- }
1940
- }
1941
-
1942
- /**
1943
- * Tag stuff for gmedia query.
1944
- *
1945
- * @param $q
1946
- */
1947
- function gmedias_tag_stuff(&$q){
1948
- global $wpdb;
1949
-
1950
- if(isset($q['tag']) && '' != $q['tag']){
1951
- if(strpos($q['tag'], ',') !== false){
1952
- $tags = preg_split('/[,\s]+/', $q['tag']);
1953
- foreach((array)$tags as $tag){
1954
- $q['tag_name__in'][] = $tag;
1955
- }
1956
- } else if(preg_match('/[+\s]+/', $q['tag']) || !empty($q['alb'])){
1957
- $tags = preg_split('/[+\s]+/', $q['tag']);
1958
- foreach((array)$tags as $tag){
1959
- $q['tag_name__and'][] = $tag;
1960
- }
1961
- } else{
1962
- $q['tag_name__in'][] = $q['tag'];
1963
- }
1964
- }
1965
-
1966
- if(isset($q['tag_name__in']) && !empty($q['tag_name__in'])){
1967
- $q['tag_name__in'] = "'" . implode("','", array_map('esc_sql', array_unique((array)$q['tag_name__in']))) . "'";
1968
- $tag__in = $wpdb->get_col("
1969
- SELECT term_id
1970
- FROM {$wpdb->prefix}gmedia_term
1971
- WHERE taxonomy = 'gmedia_tag'
1972
- AND name IN ({$q['tag_name__in']})
1973
- ");
1974
- if(!empty($tag__in)){
1975
- unset($q['tag_name__in']);
1976
- $q['tag__in'] = $tag__in;
1977
- }
1978
- }
1979
-
1980
- if(isset($q['tag_name__and']) && !empty($q['tag_name__and'])){
1981
- $q['tag_name__and'] = "'" . implode("','", array_map('esc_sql', array_unique((array)$q['tag_name__and']))) . "'";
1982
- $tag__and = $wpdb->get_col("
1983
- SELECT term_id
1984
- FROM {$wpdb->prefix}gmedia_term
1985
- WHERE taxonomy = 'gmedia_tag'
1986
- AND name IN ({$q['tag_name__and']})
1987
- ");
1988
- if(!empty($tag__and)){
1989
- unset($q['tag_name__and']);
1990
- $q['tag__and'] = $tag__and;
1991
- }
1992
- }
1993
-
1994
- if(isset($q['tag__in']) && !empty($q['tag__in'])){
1995
- $q['tag__in'] = wp_parse_id_list($q['tag__in']);
1996
- } elseif(isset($q['tag_id']) && !empty($q['tag_id'])){
1997
- $q['tag__in'] = array(absint($q['tag_id']));
1998
- }
1999
-
2000
-
2001
- if(isset($q['tag__not_in']) && !empty($q['tag__not_in'])){
2002
- $q['tag__not_in'] = wp_parse_id_list($q['tag__not_in']);
2003
- }
2004
-
2005
- if(isset($q['tag__and']) && !empty($q['tag__and'])){
2006
- $q['tag__and'] = wp_parse_id_list($q['tag__and']);
2007
- }
2008
- }
2009
-
2010
- /**
2011
- * Convert MIME types into SQL.
2012
- * @see wp_post_mime_type_where()
2013
- *
2014
- * @param string|array $mime_types List of mime types or comma separated string of mime types.
2015
- * @param string $table_alias Optional. Specify a table alias, if needed.
2016
- *
2017
- * @return string The SQL AND clause for mime searching.
2018
- */
2019
- function gmedia_mime_type_where($mime_types, $table_alias = ''){
2020
- $where = '';
2021
- $wildcards = array('', '%', '%/%');
2022
- if(is_string($mime_types)){
2023
- $mime_types = array_map('trim', explode(',', $mime_types));
2024
- }
2025
- foreach((array)$mime_types as $mime_type){
2026
- $mime_type = preg_replace('/\s/', '', $mime_type);
2027
- $slashpos = strpos($mime_type, '/');
2028
- if(false !== $slashpos){
2029
- $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2030
- $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2031
- if(empty($mime_subgroup)){
2032
- $mime_subgroup = '*';
2033
- } else{
2034
- $mime_subgroup = str_replace('/', '', $mime_subgroup);
2035
- }
2036
- $mime_pattern = "$mime_group/$mime_subgroup";
2037
- } else{
2038
- $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2039
- if(false === strpos($mime_pattern, '*')){
2040
- $mime_pattern .= '/*';
2041
- }
2042
- }
2043
-
2044
- $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2045
-
2046
- if(in_array($mime_type, $wildcards)){
2047
- return '';
2048
- }
2049
-
2050
- if(false !== strpos($mime_pattern, '%')){
2051
- $wheres[] = empty($table_alias)? "mime_type LIKE '$mime_pattern'" : "$table_alias.mime_type LIKE '$mime_pattern'";
2052
- } else{
2053
- $wheres[] = empty($table_alias)? "mime_type = '$mime_pattern'" : "$table_alias.mime_type = '$mime_pattern'";
2054
- }
2055
- }
2056
- if(!empty($wheres)){
2057
- $where = ' AND (' . join(' OR ', $wheres) . ') ';
2058
- }
2059
-
2060
- return $where;
2061
- }
2062
-
2063
- /**
2064
- * Some postmeta stuff.
2065
- *
2066
- * @param int $gmedia
2067
- * @param string $meta_type
2068
- *
2069
- * @return mixed
2070
- */
2071
- function has_meta($gmedia, $meta_type = 'gmedia'){
2072
- global $wpdb;
2073
-
2074
- if(!in_array($meta_type, array('gmedia', 'gmedia_term'))){
2075
- $meta_type = 'gmedia';
2076
- }
2077
-
2078
- return $wpdb->get_results($wpdb->prepare("SELECT *
2079
- FROM {$wpdb->prefix}{$meta_type}_meta WHERE {$meta_type}_id = %d
2080
- ORDER BY meta_key,meta_id", $gmedia), ARRAY_A);
2081
- }
2082
-
2083
- /**
2084
- * Add metadata for the specified object.
2085
- * @see add_metadata()
2086
- * @uses $wpdb WordPress database object for queries.
2087
- * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry,
2088
- * object ID, meta key, and meta value
2089
- *
2090
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2091
- * @param int $object_id ID of the object metadata is for
2092
- * @param string $meta_key Metadata key
2093
- * @param string $meta_value Metadata value
2094
- * @param bool $unique Optional, default is false. Whether the specified metadata key should be
2095
- * unique for the object. If true, and the object already has a value for the specified
2096
- * metadata key, no change will be made
2097
- *
2098
- * @return bool The meta ID on successful update, false on failure.
2099
- */
2100
- function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false){
2101
- if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2102
- return false;
2103
- }
2104
-
2105
- if(!$object_id = absint($object_id)){
2106
- return false;
2107
- }
2108
-
2109
- /** @var $wpdb wpdb */
2110
- global $wpdb;
2111
-
2112
- $table = $wpdb->prefix . $meta_type . '_meta';
2113
-
2114
- $column = esc_sql($meta_type . '_id');
2115
-
2116
- // expected_slashed ($meta_key)
2117
- $meta_key = wp_unslash($meta_key);
2118
- $meta_value = wp_unslash($meta_value);
2119
- $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2120
-
2121
- $check = apply_filters("{$meta_type}_add_metadata", null, $object_id, $meta_key, $meta_value, $unique);
2122
- if(null !== $check){
2123
- return $check;
2124
- }
2125
-
2126
- if($unique && $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id))){
2127
- return false;
2128
- }
2129
-
2130
- $_meta_value = $meta_value;
2131
- $meta_value = maybe_serialize($meta_value);
2132
-
2133
- do_action("{$meta_type}_add_meta", $object_id, $meta_key, $_meta_value);
2134
-
2135
- $result = $wpdb->insert($table, array($column => $object_id,
2136
- 'meta_key' => $meta_key,
2137
- 'meta_value' => $meta_value
2138
- ));
2139
-
2140
- if(!$result){
2141
- return false;
2142
- }
2143
-
2144
- $mid = (int)$wpdb->insert_id;
2145
-
2146
- wp_cache_delete($object_id, $meta_type . '_meta');
2147
-
2148
- do_action("{$meta_type}_added_meta", $mid, $object_id, $meta_key, $_meta_value);
2149
-
2150
- return $mid;
2151
- }
2152
-
2153
- /**
2154
- * Update metadata for the specified object. If no value already exists for the specified object
2155
- * ID and metadata key, the metadata will be added.
2156
- * @see update_metadata()
2157
- * @uses $wpdb WordPress database object for queries.
2158
- * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
2159
- * metadata entry to update, object ID, meta key, and meta value
2160
- * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
2161
- * updated metadata entry, object ID, meta key, and meta value
2162
- *
2163
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2164
- * @param int $object_id ID of the object metadata is for
2165
- * @param string $meta_key Metadata key
2166
- * @param string|array $meta_value Metadata value
2167
- * @param string $prev_value Optional. If specified, only update existing metadata entries with
2168
- * the specified value. Otherwise, update all entries.
2169
- *
2170
- * @return bool True on successful update, false on failure.
2171
- */
2172
- function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = ''){
2173
- if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2174
- return false;
2175
- }
2176
-
2177
- if(!$object_id = absint($object_id)){
2178
- return false;
2179
- }
2180
-
2181
- /** @var $wpdb wpdb */
2182
- global $wpdb;
2183
-
2184
- $table = $wpdb->prefix . $meta_type . '_meta';
2185
-
2186
- $column = esc_sql($meta_type . '_id');
2187
- $id_column = 'meta_id';
2188
-
2189
- // expected_slashed ($meta_key)
2190
- $meta_key = stripslashes($meta_key);
2191
- $passed_value = $meta_value;
2192
- $meta_value = stripslashes_deep($meta_value);
2193
- $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2194
-
2195
- $check = apply_filters("{$meta_type}_update_metadata", null, $object_id, $meta_key, $meta_value, $prev_value);
2196
- if(null !== $check){
2197
- return (bool)$check;
2198
- }
2199
-
2200
- if(!$meta_id = $wpdb->get_var($wpdb->prepare("SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id))){
2201
- return $this->add_metadata($meta_type, $object_id, $meta_key, $passed_value);
2202
- }
2203
-
2204
- // Compare existing value to new value if no prev value given and the key exists only once.
2205
- if(empty($prev_value)){
2206
- $old_value = $this->get_metadata($meta_type, $object_id, $meta_key);
2207
- if(count($old_value) == 1){
2208
- if($old_value[0] === $meta_value){
2209
- return false;
2210
- }
2211
- }
2212
- }
2213
-
2214
- $_meta_value = $meta_value;
2215
- $meta_value = maybe_serialize($meta_value);
2216
-
2217
- $data = compact('meta_value');
2218
- $where = array($column => $object_id, 'meta_key' => $meta_key);
2219
-
2220
- if(!empty($prev_value)){
2221
- $prev_value = maybe_serialize($prev_value);
2222
- $where['meta_value'] = $prev_value;
2223
- }
2224
-
2225
- do_action("{$meta_type}_update_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2226
-
2227
- $wpdb->update($table, $data, $where);
2228
-
2229
- wp_cache_delete($object_id, $meta_type . '_meta');
2230
-
2231
- do_action("{$meta_type}_updated_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2232
-
2233
- return true;
2234
- }
2235
-
2236
- /**
2237
- * Delete metadata for the specified object.
2238
- * @see delete_metadata()
2239
- * @uses $wpdb WordPress database object for queries.
2240
- * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
2241
- * deleted metadata entries, object ID, meta key, and meta value
2242
- *
2243
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2244
- * @param int $object_id ID of the object metadata is for
2245
- * @param string $meta_key Metadata key
2246
- * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries
2247
- * with this value. Otherwise, delete all entries with the specified meta_key.
2248
- * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
2249
- * for all objects, ignoring the specified object_id. Otherwise, only delete matching
2250
- * metadata entries for the specified object_id.
2251
- *
2252
- * @return bool True on successful delete, false on failure.
2253
- */
2254
- function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false){
2255
- if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2256
- return false;
2257
- }
2258
-
2259
- if((!$object_id = absint($object_id)) && !$delete_all){
2260
- return false;
2261
- }
2262
-
2263
- /** @var $wpdb wpdb */
2264
- global $wpdb;
2265
-
2266
- $table = $wpdb->prefix . $meta_type . '_meta';
2267
-
2268
- $type_column = esc_sql($meta_type . '_id');
2269
- $id_column = 'meta_id';
2270
- // expected_slashed ($meta_key)
2271
- $meta_key = stripslashes($meta_key);
2272
- $meta_value = stripslashes_deep($meta_value);
2273
-
2274
- $check = apply_filters("{$meta_type}_delete_metadata", null, $object_id, $meta_key, $meta_value, $delete_all);
2275
- if(null !== $check){
2276
- return (bool)$check;
2277
- }
2278
-
2279
- $_meta_value = $meta_value;
2280
- $meta_value = maybe_serialize($meta_value);
2281
-
2282
- $query = $wpdb->prepare("SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key);
2283
-
2284
- if(!$delete_all){
2285
- $query .= $wpdb->prepare(" AND $type_column = %d", $object_id);
2286
- }
2287
-
2288
- if($meta_value){
2289
- $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value);
2290
- }
2291
-
2292
- $meta_ids = $wpdb->get_col($query);
2293
- if(!count($meta_ids)){
2294
- return false;
2295
- }
2296
-
2297
- /** @var $object_ids */
2298
- if($delete_all){
2299
- $object_ids = $wpdb->get_col($wpdb->prepare("SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key));
2300
- }
2301
-
2302
- do_action("delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value);
2303
-
2304
- $query = "DELETE FROM $table WHERE $id_column IN( " . implode(',', $meta_ids) . " )";
2305
-
2306
- $count = $wpdb->query($query);
2307
-
2308
- if(!$count){
2309
- return false;
2310
- }
2311
-
2312
- if($delete_all){
2313
- foreach((array)$object_ids as $o_id){
2314
- wp_cache_delete($o_id, $meta_type . '_meta');
2315
- }
2316
- } else{
2317
- wp_cache_delete($object_id, $meta_type . '_meta');
2318
- }
2319
-
2320
- do_action("{$meta_type}_deleted_meta", $meta_ids, $object_id, $meta_key, $_meta_value);
2321
-
2322
- return true;
2323
- }
2324
-
2325
- /**
2326
- * Retrieve metadata for the specified object.
2327
- * @see get_metadata()
2328
- *
2329
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, or gmedia_term)
2330
- * @param int $object_id ID of the object metadata is for
2331
- * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
2332
- * the specified object.
2333
- * @param bool $single Optional, default is false. If true, return only the first value of the
2334
- * specified meta_key. This parameter has no effect if meta_key is not specified.
2335
- *
2336
- * @return string|array Single metadata value, or array of values
2337
- */
2338
- function get_metadata($meta_type, $object_id, $meta_key = '', $single = false){
2339
- if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2340
- return false;
2341
- }
2342
-
2343
- if(!$object_id = absint($object_id)){
2344
- return false;
2345
- }
2346
-
2347
- $check = apply_filters("{$meta_type}_get_metadata", null, $object_id, $meta_key, $single);
2348
- if(null !== $check){
2349
- if($single && is_array($check)){
2350
- return $check[0];
2351
- } else{
2352
- return $check;
2353
- }
2354
- }
2355
-
2356
- $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
2357
-
2358
- if(!$meta_cache){
2359
- $meta_cache = $this->update_meta_cache($meta_type, array($object_id));
2360
- $meta_cache = $meta_cache[ $object_id ];
2361
- }
2362
-
2363
- if(!$meta_key){
2364
- global $gmCore;
2365
- $meta_cache = $gmCore->array_map_recursive('maybe_unserialize', $meta_cache);
2366
-
2367
- return $meta_cache;
2368
- }
2369
-
2370
- if(isset($meta_cache[ $meta_key ])){
2371
- if($single){
2372
- return maybe_unserialize($meta_cache[ $meta_key ][0]);
2373
- } else{
2374
- return array_map('maybe_unserialize', $meta_cache[ $meta_key ]);
2375
- }
2376
- }
2377
-
2378
- if($single){
2379
- return '';
2380
- } else{
2381
- return array();
2382
- }
2383
- }
2384
-
2385
- /**
2386
- * Get meta data by meta ID
2387
- * @since 1.6.3
2388
- *
2389
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2390
- * @param int $meta_id ID for a specific meta row
2391
- *
2392
- * @return object Meta object or false.
2393
- */
2394
- function get_metadata_by_mid($meta_type, $meta_id){
2395
- global $wpdb;
2396
-
2397
- if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2398
- return false;
2399
- }
2400
-
2401
- $meta_id = absint($meta_id);
2402
- if(!$meta_id){
2403
- return false;
2404
- }
2405
-
2406
- $table = $wpdb->prefix . $meta_type . '_meta';
2407
-
2408
- $meta = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE meta_id = %d", $meta_id));
2409
-
2410
- if(empty($meta)){
2411
- return false;
2412
- }
2413
-
2414
- if(isset($meta->meta_value)){
2415
- $meta->meta_value = maybe_unserialize($meta->meta_value);
2416
- }
2417
-
2418
- return $meta;
2419
- }
2420
-
2421
- /**
2422
- * Update meta data by meta ID
2423
- * @since 1.6.3
2424
- *
2425
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2426
- * @param int $meta_id ID for a specific meta row
2427
- * @param string $meta_value Metadata value
2428
- * @param string|bool $meta_key Optional, you can provide a meta key to update it
2429
- *
2430
- * @return bool True on successful update, false on failure.
2431
- */
2432
- function update_metadata_by_mid($meta_type, $meta_id, $meta_value, $meta_key = false){
2433
- global $wpdb;
2434
-
2435
- // Make sure everything is valid.
2436
- if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2437
- return false;
2438
- }
2439
-
2440
- $meta_id = absint($meta_id);
2441
- if(!$meta_id){
2442
- return false;
2443
- }
2444
-
2445
- $table = $wpdb->prefix . $meta_type . '_meta';
2446
-
2447
- $column = sanitize_key($meta_type . '_id');
2448
- $id_column = 'meta_id';
2449
-
2450
- // Fetch the meta and go on if it's found.
2451
- if(($meta = $this->get_metadata_by_mid($meta_type, $meta_id))){
2452
- $original_key = $meta->meta_key;
2453
- $object_id = $meta->{$column};
2454
-
2455
- // If a new meta_key (last parameter) was specified, change the meta key,
2456
- // otherwise use the original key in the update statement.
2457
- if(false === $meta_key){
2458
- $meta_key = $original_key;
2459
- } elseif(!is_string($meta_key)){
2460
- return false;
2461
- }
2462
-
2463
- // Sanitize the meta
2464
- $_meta_value = $meta_value;
2465
- $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2466
- $meta_value = maybe_serialize($meta_value);
2467
-
2468
- // Format the data query arguments.
2469
- $data = array('meta_key' => $meta_key,
2470
- 'meta_value' => $meta_value
2471
- );
2472
-
2473
- // Format the where query arguments.
2474
- $where = array();
2475
- $where[ $id_column ] = $meta_id;
2476
-
2477
- do_action("{$meta_type}_update_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2478
-
2479
- // Run the update query, all fields in $data are %s, $where is a %d.
2480
- $result = $wpdb->update($table, $data, $where, '%s', '%d');
2481
- if(!$result){
2482
- return false;
2483
- }
2484
-
2485
- // Clear the caches.
2486
- wp_cache_delete($object_id, $meta_type . '_meta');
2487
-
2488
- do_action("{$meta_type}_updated_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2489
-
2490
- return true;
2491
- }
2492
-
2493
- // And if the meta was not found.
2494
- return false;
2495
- }
2496
-
2497
- /**
2498
- * Delete meta data by meta ID
2499
- * @since 1.6.3
2500
- *
2501
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2502
- * @param int $meta_id ID for a specific meta row
2503
- *
2504
- * @return bool True on successful delete, false on failure.
2505
- */
2506
- function delete_metadata_by_mid($meta_type, $meta_id){
2507
- global $wpdb;
2508
-
2509
- // Make sure everything is valid.
2510
- if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2511
- return false;
2512
- }
2513
-
2514
- $meta_id = absint($meta_id);
2515
- if(!$meta_id){
2516
- return false;
2517
- }
2518
-
2519
- $table = $wpdb->prefix . $meta_type . '_meta';
2520
-
2521
- // object and id columns
2522
- $column = sanitize_key($meta_type . '_id');
2523
- $id_column = 'meta_id';
2524
-
2525
- // Fetch the meta and go on if it's found.
2526
- if(($meta = $this->get_metadata_by_mid($meta_type, $meta_id))){
2527
- $object_id = $meta->{$column};
2528
-
2529
- do_action("{$meta_type}_delete_meta", (array)$meta_id, $object_id, $meta->meta_key, $meta->meta_value);
2530
-
2531
- // Run the query, will return true if deleted, false otherwise
2532
- $result = (bool)$wpdb->delete($table, array($id_column => $meta_id));
2533
-
2534
- // Clear the caches.
2535
- wp_cache_delete($object_id, $meta_type . '_meta');
2536
-
2537
- do_action("{$meta_type}_deleted_meta", (array)$meta_id, $object_id, $meta->meta_key, $meta->meta_value);
2538
-
2539
- return $result;
2540
- }
2541
-
2542
- // Meta id was not found.
2543
- return false;
2544
- }
2545
-
2546
- /**
2547
- * Determine if a meta key is set for a given object
2548
- * @see metadata_exists()
2549
- *
2550
- * @param string $meta_type Type of object metadata is for (e.g., gmedia or gmedia_term)
2551
- * @param int $object_id ID of the object metadata is for
2552
- * @param string $meta_key Metadata key.
2553
- *
2554
- * @return boolean true of the key is set, false if not.
2555
- */
2556
- function metadata_exists($meta_type, $object_id, $meta_key){
2557
- if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2558
- return false;
2559
- }
2560
-
2561
- if(!$object_id = absint($object_id)){
2562
- return false;
2563
- }
2564
-
2565
- $check = apply_filters("{$meta_type}_get_metadata", null, $object_id, $meta_key, true);
2566
- if(null !== $check){
2567
- return true;
2568
- }
2569
-
2570
- $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
2571
-
2572
- if(!$meta_cache){
2573
- $meta_cache = $this->update_meta_cache($meta_type, array($object_id));
2574
- $meta_cache = $meta_cache[ $object_id ];
2575
- }
2576
-
2577
- if(isset($meta_cache[ $meta_key ])){
2578
- return true;
2579
- }
2580
-
2581
- return false;
2582
- }
2583
-
2584
- /**
2585
- * Get all Term data from database by Term ID.
2586
- * The usage of the get_term function is to apply filters to a term object. It
2587
- * is possible to get a term object from the database before applying the
2588
- * filters.
2589
- * There are two hooks, one is specifically for each term, named 'get_gmedia_term', and
2590
- * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
2591
- * term object, and the taxonomy name as parameters. Both hooks are expected to
2592
- * return a Term object.
2593
- * 'get_gmedia_term' hook - Takes two parameters the term Object and the taxonomy name.
2594
- * Must return term object. Used in get_term() as a catch-all filter for every
2595
- * $term.
2596
- * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
2597
- * name. Must return term object. $taxonomy will be the taxonomy name, so for
2598
- * example, if 'gmedia_album', it would be 'get_gmedia_album' as the filter name. Useful
2599
- * for custom taxonomies or plugging into default taxonomies.
2600
- * @uses $wpdb
2601
- * @see get_term()
2602
- *
2603
- * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
2604
- * @param string|array $args Taxonomy name that $term is part of or args with user_id and taxonomy.
2605
- * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
2606
- *
2607
- * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty.
2608
- */
2609
- function get_term($term, $args = null, $output = OBJECT){
2610
- /** @var $wpdb wpdb */
2611
- global $wpdb, $user_ID, $gmCore;
2612
- $null = null;
2613
-
2614
- if(empty($term)){
2615
- $error = new WP_Error('invalid_term', __('Empty Term'));
2616
-
2617
- return $error;
2618
- }
2619
-
2620
- if(is_object($term)){
2621
- $term = $term->term_id;
2622
- $taxonomy = $term->taxonomy;
2623
- }
2624
-
2625
- if($gmCore->is_digit($term)){
2626
- $term = (int)$term;
2627
- if(!$_term = wp_cache_get($term, 'gmedia_term')){
2628
- $_term = $wpdb->get_row($wpdb->prepare("SELECT t.* FROM {$wpdb->prefix}gmedia_term AS t WHERE t.term_id = %d LIMIT 1", $term));
2629
- if(!$_term){
2630
- return $null;
2631
- }
2632
- wp_cache_add($term, $_term, 'gmedia_term');
2633
- }
2634
- } else{
2635
- $global = $user_ID;
2636
- $taxonomy = is_string($args)? $args : false;
2637
- if(is_array($args)){
2638
- if(isset($args['global'])){
2639
- $global = (int)$args['global'];
2640
- }
2641
- if(isset($args['taxonomy'])){
2642
- $taxonomy = $args['taxonomy'];
2643
- }
2644
- }
2645
- if($taxonomy){
2646
- $_term = $wpdb->get_row($wpdb->prepare("SELECT t.* FROM {$wpdb->prefix}gmedia_term AS t WHERE t.taxonomy = %s AND t.name = %s AND t.global = %d LIMIT 1", $taxonomy, $term, $global));
2647
- if(!$_term){
2648
- return $null;
2649
- }
2650
- wp_cache_add($_term->term_id, $_term, 'gmedia_term');
2651
- } else{
2652
- return $null;
2653
- }
2654
- }
2655
-
2656
- $_term = apply_filters('get_gmedia_term', $_term, $_term->taxonomy);
2657
- $_term = apply_filters("get_{$_term->taxonomy}", $_term, $_term->taxonomy);
2658
- //$_term = sanitize_term($_term, $_term->taxonomy, $filter); // TODO sanitize_term after applying filters
2659
-
2660
- if($output == OBJECT){
2661
- return $_term;
2662
- } elseif($output == ARRAY_A){
2663
- $__term = get_object_vars($_term);
2664
-
2665
- return $__term;
2666
- } elseif($output == ARRAY_N){
2667
- $__term = array_values(get_object_vars($_term));
2668
-
2669
- return $__term;
2670
- } else{
2671
- return $_term;
2672
- }
2673
- }
2674
-
2675
- /**
2676
- * Updates Terms to Taxonomy in cache.
2677
- *
2678
- * @param array $terms List of term objects to change.
2679
- */
2680
- function update_term_cache($terms){
2681
- foreach((array)$terms as $term){
2682
- // Create a copy in case the array was passed by reference.
2683
- $_term = clone $term;
2684
-
2685
- // Object ID should not be cached.
2686
- unset($_term->object_id);
2687
-
2688
- wp_cache_add($term->term_id, $_term, 'gmedia_term');
2689
- }
2690
- }
2691
-
2692
- /**
2693
- * Get Taxonomy by Term ID.
2694
- * @uses $wpdb
2695
- *
2696
- * @param int $term_id
2697
- *
2698
- * @return string $taxonomy
2699
- */
2700
- function get_tax_by_term_id($term_id){
2701
- /** @var $wpdb wpdb */
2702
- global $wpdb, $gmCore;
2703
- $null = null;
2704
-
2705
- if(!$gmCore->is_digit($term_id)){
2706
- return $null;
2707
- }
2708
- $taxonomy = $wpdb->get_var($wpdb->prepare("SELECT taxonomy FROM {$wpdb->prefix}gmedia_term WHERE term_id = %d", $term_id));
2709
-
2710
- return $taxonomy;
2711
- }
2712
-
2713
- /**
2714
- * Retrieve the name of a term.
2715
- * @see get_cat_name()
2716
- *
2717
- * @param object|int $term
2718
- *
2719
- * @return string Term name, or an empty string if term doesn't exist.
2720
- */
2721
- function get_term_name($term){
2722
- if(is_object($term)){
2723
- return $term->name;
2724
- }
2725
- $term = $this->get_term((int)$term);
2726
- if(!$term || is_wp_error($term)){
2727
- return '';
2728
- }
2729
-
2730
- return $term->name;
2731
- }
2732
-
2733
- /**
2734
- * Retrieve the terms in a given taxonomy or list of taxonomies.
2735
- * You can fully inject any customizations to the query before it is sent, as
2736
- * well as control the output with a filter.
2737
- * The 'get_gmedia_terms' filter will be called when the cache has the term and will
2738
- * pass the found term along with the array of $taxonomies and array of $args.
2739
- * This filter is also called before the array of terms is passed and will pass
2740
- * the array of terms, along with the $taxonomies and $args.
2741
- * The 'get_gmedia_terms_orderby' filter passes the ORDER BY clause for the query
2742
- * along with the $args array.
2743
- * The 'get_gmedia_terms_fields' filter passes the fields for the SELECT query
2744
- * along with the $args array.
2745
- * The list of arguments that $args can contain, which will overwrite the defaults:
2746
- * orderby - Default is 'name'. Can be name, count, global, description or nothing
2747
- * (will use term_id), Passing a custom value other than these will cause it to
2748
- * order based on the custom value.
2749
- * order - Default is ASC. Can use DESC.
2750
- * hide_empty - Default is false. Will return empty terms, which means
2751
- * terms whose count is 0 according to the given taxonomy.
2752
- * exclude - Default is an empty array. An array, comma- or space-delimited string
2753
- * of term ids to exclude from the return array. If 'include' is non-empty,
2754
- * 'exclude' is ignored.
2755
- * include - Default is an empty array. An array, comma- or space-delimited string
2756
- * of term ids to include in the return array.
2757
- * number - The maximum number of terms to return. Default is to return them all.
2758
- * offset - The number by which to offset the terms query.
2759
- * status - can be used generaly for albums. Defaults: 'publish', 'private', 'draft'.
2760
- * fields - Default is 'all', which returns an array of term objects.
2761
- * If 'fields' is 'ids' or 'names', returns an array of
2762
- * integers or strings, respectively.
2763
- * search - Returned terms' names will contain the value of 'search',
2764
- * case-insensitive. Default is an empty string.
2765
- * name__like - Returned terms' names will begin with the value of 'name__like',
2766
- * case-insensitive. Default is empty string.
2767
- * The 'get' argument, if set to 'all' instead of its default empty string,
2768
- * returns terms regardless of ancestry or whether the terms are empty.
2769
- * The 'global' argument, when used, should be set to the integer of a term ID. Its default is
2770
- * the empty string '', which has a different meaning from the integer 0.
2771
- * If set to an integer value, all returned terms will have as an immediate
2772
- * ancestor the term whose ID is specified by that integer according to the given taxonomy.
2773
- * The 'global' argument is different from 'child_of' in that a term X is considered a 'global'
2774
- * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
2775
- * @uses $wpdb
2776
- * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
2777
- * @see get_terms()
2778
- *
2779
- * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
2780
- * @param string|array $args The values of what to search for when returning terms
2781
- *
2782
- * @return array|WP_Error List of Term Objects. Will return WP_Error, if any of $taxonomies does not exist.
2783
- */
2784
- function get_terms($taxonomies, $args = array()){
2785
- /** @var $wpdb wpdb */
2786
- global $wpdb;
2787
-
2788
- if(!is_array($taxonomies)){
2789
- $taxonomies = array($taxonomies);
2790
- }
2791
-
2792
- $defaults = array('orderby' => 'name',
2793
- 'order' => 'ASC',
2794
- 'hide_empty' => false,
2795
- 'exclude' => array(),
2796
- 'include' => array(),
2797
- 'get' => '',
2798
- 'number' => '',
2799
- 'fields' => 'all',
2800
- 'name__like' => '',
2801
- 'offset' => '',
2802
- 'search' => '',
2803
- 'global' => '',
2804
- 'status' => '',
2805
- 'page' => 1,
2806
- 'no_found_rows' => false
2807
- );
2808
- // $args can be whatever, only use the args defined in defaults
2809
- $args = array_intersect_key((array)$args, $defaults);
2810
- $args = wp_parse_args($args, $defaults);
2811
- $args['number'] = absint($args['number']);
2812
- $args['offset'] = absint($args['offset']);
2813
-
2814
- if('all' == $args['get']){
2815
- $args['hide_empty'] = false;
2816
- }
2817
-
2818
- $args = apply_filters('gmedia_get_terms_args', $args, $taxonomies);
2819
-
2820
- /** @var $orderby
2821
- * @var $order
2822
- * @var $hide_empty
2823
- * @var $exclude
2824
- * @var $include
2825
- * @var $number
2826
- * @var $fields
2827
- * @var $get
2828
- * @var $name_like
2829
- * @var $offset
2830
- * @var $search
2831
- * @var $global
2832
- * @var $status
2833
- * @var $page
2834
- * @var $no_found_rows
2835
- * */
2836
- extract($args, EXTR_SKIP);
2837
-
2838
- $key = md5(serialize(compact(array_keys($defaults))) . serialize($taxonomies));
2839
- $last_changed = wp_cache_get('last_changed', 'gmedia_terms');
2840
- if(!$last_changed){
2841
- $last_changed = time();
2842
- wp_cache_set('last_changed', $last_changed, 'gmedia_terms');
2843
- }
2844
- $cache_key = "gmedia_get_terms:$key:$last_changed";
2845
- $cache = wp_cache_get($cache_key, 'gmedia_terms');
2846
- if(false !== $cache){
2847
- $cache_tax = wp_cache_get($cache_key, 'gmedia_terms_counts');
2848
- if(false != $cache_tax){
2849
- $this->openPage = $cache_tax['openPage'];
2850
- $this->resultPerPage = $cache_tax['resultPerPage'];
2851
- $this->totalResult = $cache_tax['totalResult'];
2852
- $this->pages = $cache_tax['pages'];
2853
- $this->filter_tax = $cache_tax['filter_tax'];
2854
- }
2855
- $args['terms_counts'] = $cache_tax;
2856
-
2857
- $cache = apply_filters('gmedia_get_terms', $cache, $taxonomies, $args);
2858
-
2859
- return $cache;
2860
- }
2861
-
2862
- $order = strtoupper($order);
2863
- if('' !== $order && !in_array($order, array('ASC', 'DESC'))){
2864
- $order = 'ASC';
2865
- }
2866
-
2867
- $_orderby = strtolower($orderby);
2868
- if('count' == $_orderby){
2869
- $orderby = "ORDER BY t.count $order, t.term_id $order";
2870
- } else if('name' == $_orderby){
2871
- $orderby = "ORDER BY t.name $order";
2872
- } else if('description' == $_orderby){
2873
- $orderby = "ORDER BY t.description $order, t.term_id $order";
2874
- } else if('include' == $_orderby && !empty($args['include'])){
2875
- $include = implode(',', array_map('absint', $args['include']));
2876
- $orderby = "ORDER BY FIELD( t.term_id, $include )";
2877
- } else if('global' == $_orderby){
2878
- $orderby = "ORDER BY t.global ASC, t.term_id $order";
2879
- } else if('global_desc_name' == $_orderby){
2880
- $orderby = "ORDER BY t.global DESC, t.name $order";
2881
- } else if('global_asc_name' == $_orderby){
2882
- $orderby = "ORDER BY t.global ASC, t.name $order";
2883
- } else if('rand' == $_orderby){
2884
- $orderby = 'ORDER BY RAND()';
2885
- } else if('none' == $_orderby){
2886
- $orderby = '';
2887
- } elseif(empty($_orderby) || 'id' == $_orderby){
2888
- $orderby = "ORDER BY t.term_id $order";
2889
- } else{
2890
- $orderby = "ORDER BY t.name $order";
2891
- }
2892
-
2893
- $orderby = apply_filters('gmedia_get_terms_orderby', $orderby, $args);
2894
-
2895
- $where_ = "t.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
2896
- $where = '';
2897
- $inclusions = '';
2898
- if(!empty($include)){
2899
- $exclude = '';
2900
- $include = wp_parse_id_list($include);
2901
- $inclusions = implode(',', $include);
2902
- $this->filter_tax['term__in'] = $include;
2903
- }
2904
-
2905
- if(!empty($inclusions)){
2906
- $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
2907
- $where .= $inclusions;
2908
- }
2909
-
2910
- $exclusions = '';
2911
- if(!empty($exclude)){
2912
- $exterms = wp_parse_id_list($exclude);
2913
- $this->filter_tax['term__not_in'] = $exterms;
2914
- if(empty($exclusions)){
2915
- $exclusions = implode(',', $exterms);
2916
- } else{
2917
- $exclusions .= ', ' . implode(',', $exterms);
2918
- }
2919
- }
2920
-
2921
- if(!empty($exclusions)){
2922
- $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
2923
- }
2924
-
2925
- $exclusions = apply_filters('list_gmedia_terms_exclusions', $exclusions, $args);
2926
- if(!empty($exclusions)){
2927
- $where .= $exclusions;
2928
- }
2929
-
2930
- if(!empty($name__like)){
2931
- $this->filter_tax['name__like'] = $name__like;
2932
- $name__like = addcslashes($name__like, '_%\\');
2933
- $where .= $wpdb->prepare(" AND t.name LIKE %s", $name__like . '%');
2934
- }
2935
-
2936
- if(!empty($global) || '0' === $global || 0 === $global){
2937
- $global = wp_parse_id_list($global);
2938
- $this->filter_tax['global'] = $global;
2939
- $where .= " AND t.global IN ('" . implode("', '", $global) . "')";
2940
- }
2941
-
2942
- if($hide_empty){
2943
- $where .= ' AND t.count > 0';
2944
- }
2945
-
2946
- if(!empty($number)){
2947
- if(!empty($page)){
2948
- $page = (int)$page? (int)$page : 1;
2949
- $offset = ($page - 1) * $number;
2950
- }
2951
- if($offset){
2952
- $limits = 'LIMIT ' . $offset . ',' . $number;
2953
- } else{
2954
- $limits = 'LIMIT ' . $number;
2955
- }
2956
- } else{
2957
- $limits = '';
2958
- }
2959
-
2960
- if(!empty($search)){
2961
- $search = addcslashes($search, '_%\\');
2962
- $where .= $wpdb->prepare(" AND (t.name LIKE %s)", '%' . $search . '%');
2963
- }
2964
-
2965
- if(!empty($status)){
2966
- if(is_array($status)){
2967
- $arr_status = array();
2968
- foreach($status as $_status){
2969
- $arr_status[] = $wpdb->prepare("t.status = %s", $_status);
2970
- }
2971
- $where .= ' AND (' . implode(' OR ', $arr_status) . ')';
2972
- } else{
2973
- $where .= $wpdb->prepare(" AND t.status = %s", $status);
2974
- }
2975
- }
2976
-
2977
- switch($fields){
2978
- case 'ids':
2979
- case 'id=>global':
2980
- $selects = array('t.term_id', 't.global');
2981
- break;
2982
- case 'names':
2983
- $selects = array('t.name');
2984
- break;
2985
- case 'id=>names':
2986
- $selects = array('t.term_id', 't.name');
2987
- break;
2988
- case 'names_count':
2989
- $selects = array('t.term_id', 't.name', 't.count');
2990
- break;
2991
- case 'count':
2992
- $orderby = '';
2993
- $selects = array('COUNT(*)');
2994
- break;
2995
- case 'all':
2996
- default:
2997
- $selects = array('t.*');
2998
- break;
2999
- }
3000
-
3001
- $_fields = $fields;
3002
-
3003
- $fields = implode(', ', apply_filters('gmedia_get_terms_fields', $selects, $args, $taxonomies));
3004
-
3005
- $join = "";
3006
-
3007
- $pieces = array('fields', 'join', 'where', 'orderby', 'order', 'limits');
3008
- $clauses = apply_filters('gmedia_terms_clauses', compact($pieces), $taxonomies, $args);
3009
- foreach($pieces as $piece){
3010
- $$piece = isset($clauses[ $piece ])? $clauses[ $piece ] : '';
3011
- }
3012
-
3013
- $found_rows = '';
3014
- if(!$no_found_rows && !empty($limits)){
3015
- $found_rows = 'SQL_CALC_FOUND_ROWS';
3016
- }
3017
-
3018
- $where_where = $where_ . $where;
3019
- $this->sql_query = "SELECT $found_rows $fields FROM {$wpdb->prefix}gmedia_term AS t $join WHERE $where_where $orderby $limits";
3020
-
3021
- $fields = $_fields;
3022
-
3023
- if('count' == $fields){
3024
- $term_count = $wpdb->get_var($this->sql_query);
3025
-
3026
- return $term_count;
3027
- }
3028
-
3029
- $terms = $wpdb->get_results($this->sql_query);
3030
-
3031
- $this->openPage = $page;
3032
- $this->resultPerPage = count($terms);
3033
- if(!$no_found_rows){
3034
- if(!empty($limits)){
3035
- $this->totalResult = $wpdb->get_var('SELECT FOUND_ROWS()');
3036
- $this->pages = ceil($this->totalResult / $number);
3037
- $this->perPages = (int)$number;
3038
- } else{
3039
- $this->totalResult = $this->resultPerPage;
3040
- $this->pages = 1;
3041
- $this->perPages = $this->resultPerPage;
3042
- }
3043
- }
3044
- $terms_counts = array('openPage' => $this->openPage,
3045
- 'resultPerPage' => $this->resultPerPage,
3046
- 'totalResult' => $this->totalResult,
3047
- 'pages' => $this->pages,
3048
- 'perPages' => $this->perPages,
3049
- 'filter_tax' => $this->filter_tax
3050
- );
3051
-
3052
- if('all' == $fields){
3053
- $this->update_term_cache($terms);
3054
- }
3055
-
3056
- if(empty($terms)){
3057
- wp_cache_add($cache_key, array(), 'gmedia_terms', 86400); // one day
3058
- wp_cache_add($cache_key, array(), 'gmedia_terms_counts', 86400); // one day
3059
- $terms = apply_filters('gmedia_get_terms', array(), $taxonomies, $args);
3060
-
3061
- return $terms;
3062
- }
3063
-
3064
- reset($terms);
3065
- $_terms = array();
3066
- if('id=>global' == $fields){
3067
- while(($term = array_shift($terms))){
3068
- $_terms[ $term->term_id ] = $term->global;
3069
- }
3070
- $terms = $_terms;
3071
- } elseif('ids' == $fields){
3072
- while(($term = array_shift($terms))){
3073
- $_terms[] = $term->term_id;
3074
- }
3075
- $terms = $_terms;
3076
- } elseif('names' == $fields){
3077
- while(($term = array_shift($terms))){
3078
- $_terms[] = $term->name;
3079
- }
3080
- $terms = $_terms;
3081
- } elseif('id=>names' == $fields){
3082
- while(($term = array_shift($terms))){
3083
- $_terms[ $term->term_id ] = $term->name;
3084
- }
3085
- $terms = $_terms;
3086
- } elseif('name=>all' == $fields){
3087
- while(($term = array_shift($terms))){
3088
- $_terms[ $term->name ] = $term;
3089
- }
3090
- $terms = $_terms;
3091
- } elseif('names_count' == $fields){
3092
- while(($term = array_shift($terms))){
3093
- $_terms[ $term->term_id ] = array('name' => $term->name, 'count' => $term->count, 'term_id' => $term->term_id);
3094
- }
3095
- $terms = $_terms;
3096
- }
3097
-
 
 
3098
  if(0 < $number && intval(@count($terms)) > $number){
3099
- $terms = array_slice($terms, $offset, $number);
3100
- }
3101
-
3102
- wp_cache_add($cache_key, $terms, 'gmedia_terms', 86400); // one day
3103
- wp_cache_add($cache_key, $terms_counts, 'gmedia_terms_counts', 86400); // one day
3104
- $args['terms_counts'] = $terms_counts;
3105
-
3106
- $terms = apply_filters('gmedia_get_terms', $terms, $taxonomies, $args);
3107
-
3108
- return $terms;
3109
- }
3110
-
3111
- /**
3112
- * Adds a new term to the database. Optionally marks it as an alias of an existing term.
3113
- * Error handling is assigned for the nonexistence of the $taxonomy and $term
3114
- * parameters before inserting. If both the term id and taxonomy exist
3115
- * previously, then an array will be returned that contains the term id and the
3116
- * contents of what is returned. The keys of the array are 'term_id' containing numeric values.
3117
- * It is assumed that the term does not yet exist or the above will apply. The
3118
- * term will be first added to the term table and related to the taxonomy
3119
- * if everything is well. If everything is correct, then several actions will be
3120
- * run prior to a filter and then several actions will be run after the filter
3121
- * is run.
3122
- * The arguments decide how the term is handled based on the $args parameter.
3123
- * The following is a list of the available overrides and the defaults.
3124
- * 'description'. There is no default. If exists, will be added to the database
3125
- * along with the term. Expected to be a string.
3126
- * 'global'. Expected to be numeric and default is 0 (zero). Will assign value
3127
- * of 'global' to the term.
3128
- * @see wp_insert_term()
3129
- * @uses $wpdb
3130
- * @uses apply_filters() Calls 'pre_insert_gmedia_term' hook with term and taxonomy as parameters.
3131
- * @uses do_action() Calls 'create_gmedia_term' hook with the term id and taxonomy id as parameters.
3132
- * @uses do_action() Calls 'created_gmedia_term' hook with the term id and taxonomy id as parameters.
3133
- *
3134
- * @param string $term The term to add or update.
3135
- * @param string $taxonomy The taxonomy to which to add the term
3136
- * @param array|string $args Change the values of the inserted term
3137
- *
3138
- * @return int|WP_Error The Term ID array('term_id'=>$term_id)
3139
- */
3140
- function insert_term($term, $taxonomy, $args = array()){
3141
- /** @var $wpdb wpdb */
3142
- global $wpdb, $gmGallery, $gmCore, $user_ID;
3143
-
3144
- $term = apply_filters('pre_insert_gmedia_term', $term, $taxonomy);
3145
- if(is_wp_error($term)){
3146
- return $term;
3147
- }
3148
-
3149
- if(is_int($term) && 0 == $term){
3150
- return new WP_Error('gm_invalid_term_id', __('Invalid term ID'));
3151
- }
3152
-
3153
- if('' == trim($term)){
3154
- return new WP_Error('gm_empty_term_name', __('A name is required for this term'));
3155
- }
3156
-
3157
- $defaults = array('description' => '', 'global' => intval($user_ID), 'status' => 'publish');
3158
- $taxterm = str_replace('gmedia_', '', $taxonomy);
3159
- switch($taxterm){
3160
- case 'album':
3161
- $defaults['status'] = $gmGallery->options['in_album_status'];
3162
- $defaults['meta']['_orderby'] = $gmGallery->options['in_album_orderby'];
3163
- $defaults['meta']['_order'] = $gmGallery->options['in_album_order'];
3164
- break;
3165
- case 'category':
3166
- $defaults['meta']['_orderby'] = $gmGallery->options['in_category_orderby'];
3167
- $defaults['meta']['_order'] = $gmGallery->options['in_category_order'];
3168
- break;
3169
- }
3170
- $args = wp_parse_args($args, $defaults);
3171
- $args['name'] = $term;
3172
- $args['taxonomy'] = $taxonomy;
3173
- // TODO $args = sanitize_term($args, $taxonomy, 'db');
3174
- /** @var $name
3175
- * @var $description
3176
- * @var $global
3177
- * @var $status
3178
- * @var $comment_status
3179
- * @var $slug
3180
- * @var $meta
3181
- */
3182
- extract($args, EXTR_SKIP);
3183
-
3184
- // expected_slashed ($name)
3185
- $name = stripslashes($name);
3186
- $name = $gmCore->mb_convert_encoding_utf8($name);
3187
- if('gmedia_module' == $taxonomy){
3188
- $description = maybe_serialize($description);
3189
- } else{
3190
- $description = stripslashes($description);
3191
- $description = $gmCore->mb_convert_encoding_utf8($description);
3192
- if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category'))){
3193
- $global = 0;
3194
- }
3195
- }
3196
-
3197
- if(($term_id = $this->term_exists($name, $taxonomy, $global))){
3198
- // Same name, same global.
3199
- return new WP_Error('gm_term_exists', __('A term with the name provided already exists.'), $term_id);
3200
- }
3201
-
3202
- do_action("create_gmedia_term", $term_id, $taxonomy);
3203
-
3204
- // This term does not exist, Create it.
3205
- if(false === $wpdb->insert($wpdb->prefix . 'gmedia_term', compact('name', 'taxonomy', 'description', 'global', 'status') + array('count' => 0))){
3206
- return new WP_Error('gm_db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
3207
- }
3208
- $term_id = (int)$wpdb->insert_id;
3209
-
3210
- if(isset($meta) && is_array($meta) && !empty($meta)){
3211
- $meta_type = 'gmedia_term';
3212
- foreach($meta as $key => $value){
3213
- if(in_array($key, array('_cover', '_orderby', '_order', '_module_preset'))){
3214
- $value = ltrim($value, '#');
3215
- $this->add_metadata($meta_type, $term_id, $key, $value);
3216
- continue;
3217
- }
3218
- $key = trim($key);
3219
- if(!empty($key) && !$gmCore->is_digit($key) && !empty($value) && !$gmCore->is_protected_meta($key, $meta_type)){
3220
- $this->add_metadata($meta_type, $term_id, $key, $value);
3221
- }
3222
- }
3223
- }
3224
-
3225
- if(in_array($taxonomy, array('gmedia_album', 'gmedia_gallery'))){
3226
- $post_data = array('post_author' => $global,
3227
- 'post_content' => $description,
3228
- 'post_title' => $name,
3229
- 'post_status' => $status,
3230
- 'post_type' => $taxonomy
3231
- );
3232
- if(isset($slug) && !empty($slug)){
3233
- $post_data['post_name'] = $slug;
3234
- }
3235
- if(!empty($comment_status)){
3236
- $post_data['comment_status'] = $comment_status;
3237
- } else{
3238
- $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
3239
- }
3240
- $_post_ID = wp_insert_post($post_data);
3241
- if($_post_ID){
3242
- add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3243
- $this->add_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3244
- }
3245
-
3246
- }
3247
-
3248
- $this->clean_term_cache($term_id);
3249
-
3250
- do_action("created_gmedia_term", $term_id, $taxonomy);
3251
-
3252
- return $term_id;
3253
- }
3254
-
3255
- /**
3256
- * Update term based on arguments provided.
3257
- * The $args will indiscriminately override all values with the same field name.
3258
- * Care must be taken to not override important information need to update or
3259
- * update will fail (or perhaps create a new term, neither would be acceptable).
3260
- * @see wp_update_term()
3261
- * @uses $wpdb
3262
- * @uses do_action() Will call both 'edit_gmedia_term' and 'edit_$taxonomy'.
3263
- *
3264
- * @param int $term_id The ID of the term
3265
- * @param array|string $args Overwrite term field values
3266
- *
3267
- * @return int|WP_Error Returns Term ID
3268
- */
3269
- function update_term($term_id, $args = array()){
3270
- /** @var $wpdb wpdb */
3271
- global $wpdb, $gmCore, $gmGallery;
3272
-
3273
- $term_id = (int)$term_id;
3274
-
3275
- // First, get all of the original args
3276
- $term = $this->get_term($term_id, null, ARRAY_A);
3277
-
3278
- if(is_wp_error($term) || empty($term)){
3279
- return $term;
3280
- }
3281
-
3282
- // Escape data pulled from DB.
3283
- $term = add_magic_quotes($term);
3284
- $taxonomy = $term['taxonomy'];
3285
-
3286
- // Merge old and new args with new args overwriting old ones.
3287
- $args = array_merge($term, $args);
3288
-
3289
- $defaults = array('global' => $term['global'], 'name' => $term['name'], 'description' => '', 'status' => 'publish', 'meta' => array());
3290
- $args = wp_parse_args($args, $defaults);
3291
-
3292
- /** @var $name
3293
- * @var $description
3294
- * @var $status
3295
- * @var $global
3296
- * @var $meta
3297
- */
3298
- extract($args, EXTR_SKIP);
3299
-
3300
- // expected_slashed ($name)
3301
- $name = stripslashes($name);
3302
- $name = $gmCore->mb_convert_encoding_utf8($name);
3303
- if('' == trim($name)){
3304
- return new WP_Error('gm_empty_term_name', __('A name is required for term'));
3305
- }
3306
-
3307
- if(current_user_can('gmedia_edit_others_media')){
3308
- $global = (int)$global;
3309
- } else{
3310
- $global = $term['global'];
3311
- }
3312
-
3313
- if('gmedia_module' == $taxonomy){
3314
- $description = maybe_serialize($description);
3315
- } else{
3316
- $description = stripslashes($description);
3317
- $description = $gmCore->mb_convert_encoding_utf8($description);
3318
- if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category'))){
3319
- $global = 0;
3320
- }
3321
- }
3322
-
3323
- $term_id = $wpdb->get_var($wpdb->prepare("SELECT t.term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE t.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id));
3324
- do_action("edit_gmedia_term", $term_id, $taxonomy);
3325
- $wpdb->update($wpdb->prefix . 'gmedia_term', compact('term_id', 'name', 'taxonomy', 'description', 'global', 'status'), array('term_id' => $term_id));
3326
-
3327
- if(('gmedia_album' == $taxonomy)){
3328
- $default_meta = array('_orderby' => 'ID',
3329
- '_order' => 'DESC'
3330
- );
3331
- $meta = array_merge($default_meta, $meta);
3332
- if(isset($status_global)){
3333
- $db_gmedia_ids = $this->get_gmedias(array('no_found_rows' => true, 'album__in' => $term_id, 'fields' => 'post_ids'));
3334
- if(!empty($db_gmedia_ids)){
3335
- $values = array('gm' => array(), 'wp' => array());
3336
- foreach($db_gmedia_ids as $gmids){
3337
- $values['gm'][] = $wpdb->prepare("%d", $gmids->ID);
3338
- wp_cache_delete($gmids->ID, 'gmedias');
3339
- if(!empty($gmids->post_id)){
3340
- $values['wp'][] = $wpdb->prepare("%d", $gmids->post_id);
3341
- wp_cache_delete($gmids->post_id, 'wpgmedias');
3342
- wp_cache_delete($gmids->post_id, 'posts');
3343
- }
3344
- }
3345
- if(!empty($values['gm'])){
3346
- $status = esc_sql($status);
3347
- if(false === $wpdb->query("UPDATE {$wpdb->prefix}gmedia SET status = '{$status}' WHERE ID IN (" . join(',', $values['gm']) . ")")){
3348
- return new WP_Error('db_insert_error', __('Could not update statuses for gmedia items in the database'), $wpdb->last_error);
3349
- }
3350
- if(!empty($values['wp'])){
3351
- $wpdb->query("UPDATE $wpdb->posts SET post_status = '{$status}' WHERE ID IN (" . join(',', $values['wp']) . ")");
3352
- }
3353
- }
3354
- }
3355
- }
3356
- }
3357
-
3358
- if(!empty($meta) && is_array($meta)){
3359
- $meta_type = 'gmedia_term';
3360
- foreach($meta as $key => $value){
3361
- if(in_array($key, array('_cover', '_orderby', '_order', '_module_preset'))){
3362
- $value = ltrim($value, '#');
3363
- $this->update_metadata($meta_type, $term_id, $key, $value);
3364
- } elseif($gmCore->is_digit($key)){
3365
- $mid = (int)$key;
3366
- //$value = wp_unslash( $value );
3367
- if(!($meta = $this->get_metadata_by_mid('gmedia_term', $mid))){
3368
- continue;
3369
- }
3370
- if('' == trim($value)){
3371
- $this->delete_metadata_by_mid($meta_type, $key);
3372
- continue;
3373
- }
3374
- if($meta->meta_value != $value){
3375
- $this->update_metadata_by_mid($meta_type, $mid, $value);
3376
- }
3377
- }
3378
- }
3379
- }
3380
-
3381
- if(in_array($taxonomy, array('gmedia_album', 'gmedia_gallery'))){
3382
- $post_data = array('post_author' => $global,
3383
- 'post_content' => $description,
3384
- 'post_title' => $name,
3385
- 'post_status' => $status,
3386
- 'post_type' => $taxonomy
3387
- );
3388
- if(!empty($slug)){
3389
- $post_data['post_name'] = $slug;
3390
- }
3391
- if(!empty($comment_status)){
3392
- $post_data['comment_status'] = $comment_status;
3393
- } else{
3394
- $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
3395
- }
3396
- $_post_ID = $this->get_metadata('gmedia_term', $term_id, '_post_ID', true);
3397
- if($_post_ID){
3398
- $post_data['ID'] = $_post_ID;
3399
-
3400
- if ( ! empty( $post_date ) ) {
3401
- $post_data['post_date'] = $post_date;
3402
- $post_data['post_date_gmt'] = get_gmt_from_date( $post_date );
3403
- }
3404
-
3405
- if(!wp_update_post($post_data)){
3406
- unset($post_data['ID']);
3407
- $_post_ID = wp_insert_post($post_data);
3408
- if($_post_ID){
3409
- add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3410
- $this->update_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3411
- }
3412
- }
3413
- } else{
3414
- $_post_ID = wp_insert_post($post_data);
3415
- if($_post_ID){
3416
- add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3417
- $this->update_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3418
- }
3419
- }
3420
- }
3421
-
3422
- do_action("edit_$taxonomy", $term_id);
3423
-
3424
- $term_id = apply_filters('gmedia_term_id_filter', $term_id);
3425
-
3426
- $this->clean_term_cache($term_id);
3427
-
3428
- do_action("edited_gmedia_term", $term_id, $taxonomy);
3429
- do_action("edited_$taxonomy", $term_id);
3430
-
3431
- return $term_id;
3432
- }
3433
-
3434
- /**
3435
- * Update term's items sort order based on arguments provided.
3436
- * @uses $wpdb
3437
- * @uses do_action() Will call both 'sort_gmedia_term' and 'sort_$taxonomy'.
3438
- *
3439
- * @param int $term_id The ID of the term
3440
- * @param array $gm_ids_order
3441
- *
3442
- * @return int|WP_Error Returns Term ID
3443
- */
3444
- function update_term_sortorder($term_id, $gm_ids_order = array()){
3445
- /** @var $wpdb wpdb */
3446
- global $wpdb;
3447
-
3448
- $term_id = $this->term_exists($term_id);
3449
- if(!$term_id){
3450
- return new WP_Error('gm_invalid_term_id', __('Invalid term ID'));
3451
- }
3452
-
3453
- do_action("sort_gmedia_term", $term_id);
3454
-
3455
- if(empty($gm_ids_order)){
3456
- $term_meta = $this->get_metadata('gmedia_term', $term_id);
3457
- $_orderby = isset($term_meta['_orderby'][0])? $term_meta['_orderby'][0] : 'ID';
3458
- $_order = isset($term_meta['_order'][0])? $term_meta['_order'][0] : 'DESC';
3459
- if($_orderby == 'custom'){
3460
- $_orderby = 'ID';
3461
- $_order = 'DESC';
3462
- }
3463
- $gm_ids_order = $this->get_gmedias(array('no_found_rows' => true,
3464
- 'album__in' => $term_id,
3465
- 'orderby' => $_orderby,
3466
- 'order' => $_order,
3467
- 'fields' => 'ids'
3468
- ));
3469
- $gm_ids_order = array_merge(array(0), $gm_ids_order);
3470
- unset($gm_ids_order[0]);
3471
- $gm_ids_order = array_flip($gm_ids_order);
3472
- }
3473
-
3474
- $final_gmedia_ids = array();
3475
- if(!empty($gm_ids_order)){
3476
- $_db_gmedia_ids = $this->get_gmedias(array('no_found_rows' => true, 'album__in' => $term_id, 'orderby' => 'custom', 'order' => 'ASC', 'fields' => 'ids'));
3477
- $db_gmedia_ids = array_merge(array(0), $_db_gmedia_ids);
3478
- unset($db_gmedia_ids[0]);
3479
- $db_gmedia_ids = array_flip($db_gmedia_ids);
3480
-
3481
- if($gm_ids_order != $db_gmedia_ids){
3482
- $final_gmedia_ids = array_intersect_key($gm_ids_order, $db_gmedia_ids) + $db_gmedia_ids;
3483
- asort($final_gmedia_ids, SORT_NUMERIC);
3484
- $final_gmedia_ids = array_keys($final_gmedia_ids);
3485
- $final_gmedia_ids = array_diff_assoc($final_gmedia_ids, $_db_gmedia_ids);
3486
-
3487
- $values = array();
3488
- foreach($final_gmedia_ids as $gmedia_order => $gmedia_id){
3489
- $values[] = $wpdb->prepare("(%d, %d, %d)", $gmedia_id, $term_id, ($gmedia_order + 1));
3490
- }
3491
- if($values){
3492
- if(false === $wpdb->query("INSERT INTO {$wpdb->prefix}gmedia_term_relationships (gmedia_id, gmedia_term_id, gmedia_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE gmedia_order = VALUES(gmedia_order)")){
3493
- return new WP_Error('db_insert_error', __('Could not insert gmedia term relationship into the database'), $wpdb->last_error);
3494
- }
3495
- }
3496
- $this->clean_object_term_cache($final_gmedia_ids);
3497
- }
3498
- }
3499
-
3500
- $this->clean_term_cache($term_id);
3501
-
3502
- do_action("sorted_gmedia_term", $term_id);
3503
-
3504
- return $final_gmedia_ids;
3505
- }
3506
-
3507
- /**
3508
- * Check if Term exists.
3509
- * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
3510
- * @see term_exists()
3511
- * @uses $wpdb
3512
- *
3513
- * @param int|string $term The term to check
3514
- * @param string $taxonomy The taxonomy name to use
3515
- * @param bool|int $global global parameter under which to confine the exists search.
3516
- *
3517
- * @return int Get the term id or Term Object, if exists.
3518
- */
3519
- function term_exists($term, $taxonomy = '', $global = false){
3520
- /** @var $wpdb wpdb */
3521
- global $wpdb, $gmCore;
3522
-
3523
- $select = "SELECT term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE ";
3524
-
3525
- if($gmCore->is_digit($term)){
3526
- if(0 == $term){
3527
- return 0;
3528
- }
3529
- $where = 't.term_id = %d';
3530
- if(!empty($taxonomy)){
3531
- return $wpdb->get_var($wpdb->prepare($select . $where . " AND t.taxonomy = %s", $term, $taxonomy));
3532
- } else{
3533
- return $wpdb->get_var($wpdb->prepare($select . $where, $term));
3534
- }
3535
- }
3536
-
3537
- if('' === $term = trim(stripslashes($term))){
3538
- return 0;
3539
- }
3540
-
3541
- $where = 't.name = %s';
3542
- $where_fields = array($term);
3543
- if(!empty($taxonomy)){
3544
- if(false !== $global){
3545
- $global = (int)$global;
3546
- $where_fields[] = $global;
3547
- $where .= ' AND t.global = %d';
3548
- }
3549
-
3550
- $where_fields[] = $taxonomy;
3551
-
3552
- return $wpdb->get_var($wpdb->prepare("SELECT t.term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE $where AND t.taxonomy = %s", $where_fields));
3553
- }
3554
-
3555
- return $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE $where", $where_fields));
3556
- }
3557
-
3558
- /**
3559
- * Create Term and Taxonomy Relationships.
3560
- * Relates an object to a term and taxonomy type. Creates the
3561
- * term and taxonomy relationship if it doesn't already exist. Creates a term if
3562
- * it doesn't exist.
3563
- * A relationship means that the term is grouped in or belongs to the taxonomy.
3564
- * A term has no meaning until it is given context by defining which taxonomy it
3565
- * exists under.
3566
- * @see wp_set_object_terms()
3567
- * @uses $wpdb
3568
- *
3569
- * @param int $object_id The object to relate to.
3570
- * @param array|int|string $terms The slug or id of the term, will replace all existing
3571
- * related terms in this taxonomy.
3572
- * @param array|string $taxonomy The context in which to relate the term to the object.
3573
- * @param int $append If 1, don't delete existing tags, just add on. If 0, replace the tags with the new tags. If -1, remove given tags.
3574
- *
3575
- * @return array|WP_Error Affected Term IDs
3576
- */
3577
- function set_gmedia_terms($object_id, $terms, $taxonomy, $append = 0){
3578
- /** @var $wpdb wpdb */
3579
- global $wpdb, $gmCore;
3580
-
3581
- $object_id = (int)$object_id;
3582
-
3583
- if(!is_array($terms)){
3584
- $terms = array($terms);
3585
- }
3586
- $terms = array_filter(array_map('trim', (array)$terms));
3587
-
3588
- if($append == 0){
3589
- if(empty($terms)){
3590
- $this->delete_gmedia_term_relationships($object_id, $taxonomy);
3591
-
3592
- return 0;
3593
- }
3594
- $old_term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
3595
- } else{
3596
- $old_term_ids = array();
3597
- }
3598
-
3599
- $term_ids = array();
3600
- $new_term_ids = array();
3601
- if(!empty($terms)){
3602
- foreach($terms as $term){
3603
- if(!strlen(trim($term))){
3604
- continue;
3605
- }
3606
- if(('gmedia_album' == $taxonomy) && !$gmCore->is_digit($term)){
3607
- $global = get_current_user_id();
3608
- } else{
3609
- $global = false;
3610
- }
3611
- if(!$term_id = $this->term_exists($term, $taxonomy, $global)){
3612
- // Skip if a non-existent term ID is passed or if taxonomy is category or if user is not allowed to add new terms.
3613
- if($gmCore->is_digit($term) || ($append < 0) || !current_user_can($taxonomy . '_manage')){
3614
- continue;
3615
- }
3616
- if($global){
3617
- $args = array('global' => $global);
3618
- } else{
3619
- $args = array();
3620
- }
3621
- $term_id = $this->insert_term($term, $taxonomy, $args);
3622
- if(is_wp_error($term_id)){
3623
- return $term_id;
3624
- }
3625
- } else{
3626
- if(in_array($taxonomy, array('gmedia_album')) && !current_user_can('gmedia_edit_others_media')){
3627
- $alb = $this->get_term($term_id);
3628
- if($alb->global && ($alb->global != get_current_user_id())){
3629
- continue;
3630
- }
3631
- }
3632
- }
3633
- $term_ids[] = $term_id;
3634
-
3635
- if($append < 0){
3636
- continue;
3637
- }
3638
-
3639
- if($wpdb->get_var($wpdb->prepare("SELECT gmedia_term_id FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id = %d", $object_id, $term_id))){
3640
- continue;
3641
- }
3642
- do_action('add_gmedia_term_relationships', $object_id, $term_id);
3643
- $wpdb->insert($wpdb->prefix . 'gmedia_term_relationships', array('gmedia_id' => $object_id, 'gmedia_term_id' => $term_id));
3644
- do_action('added_gmedia_term_relationships', $object_id, $term_id);
3645
- $new_term_ids[] = $term_id;
3646
- }
3647
- }
3648
-
3649
- if(!empty($new_term_ids)){
3650
- $this->update_term_count($term_ids);
3651
- }
3652
-
3653
- if($append < 1){
3654
- if($append == 0){
3655
- $delete_terms = array_diff($old_term_ids, $term_ids);
3656
- } else{
3657
- $delete_terms = $term_ids;
3658
- }
3659
- if(!empty($delete_terms)){
3660
- $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
3661
- do_action('delete_gmedia_term_relationships', $object_id, $delete_terms);
3662
- $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id IN ($in_delete_terms)", $object_id));
3663
- do_action('deleted_gmedia_term_relationships', $object_id, $delete_terms);
3664
- $this->update_term_count($delete_terms);
3665
- }
3666
- }
3667
-
3668
- // TODO sort terms (albums)
3669
- $sort = ('gmedia_tag' == $taxonomy)? true : false;
3670
- if(!$append && $sort){
3671
- $values = array();
3672
- $term_order = 0;
3673
- $final_term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids'));
3674
- foreach($term_ids as $term_id){
3675
- if(in_array($term_id, $final_term_ids)){
3676
- $values[] = $wpdb->prepare("(%d, %d, %d)", $object_id, $term_id, ++ $term_order);
3677
- }
3678
- }
3679
- if($values){
3680
- if(false === $wpdb->query("INSERT INTO {$wpdb->prefix}gmedia_term_relationships (gmedia_id, gmedia_term_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)")){
3681
- return new WP_Error('db_insert_error', __('Could not insert gmedia term relationship into the database'), $wpdb->last_error);
3682
- }
3683
- }
3684
- }
3685
-
3686
- wp_cache_delete($object_id, $taxonomy . '_relationships');
3687
-
3688
- do_action('set_gmedia_terms', $object_id, $terms, $term_ids, $taxonomy, $append, $old_term_ids);
3689
-
3690
- return $term_ids;
3691
- }
3692
-
3693
- /**
3694
- * Retrieve the terms of the taxonomy that are attached to the gmedia.
3695
- * @see get_the_terms()
3696
- *
3697
- * @param int $id gmedia ID
3698
- * @param string $taxonomy Taxonomy name.
3699
- *
3700
- * @return array|bool False on failure. Array of term objects on success.
3701
- */
3702
- function get_the_gmedia_terms($id, $taxonomy){
3703
- $id = (int)$id;
3704
-
3705
- if(!$id){
3706
- return false;
3707
- }
3708
-
3709
- $terms = wp_cache_get($id, "{$taxonomy}_relationships");
3710
- if(false === $terms){
3711
- $terms = $this->get_gmedia_terms($id, $taxonomy);
3712
- wp_cache_add($id, $terms, $taxonomy . '_relationships');
3713
- }
3714
-
3715
- $terms = apply_filters('get_the_gmedia_terms', $terms, $id, $taxonomy);
3716
-
3717
- if(empty($terms)){
3718
- return false;
3719
- }
3720
-
3721
- return $terms;
3722
- }
3723
-
3724
- /**
3725
- * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
3726
- * The following information has to do the $args parameter and for what can be
3727
- * contained in the string or array of that parameter, if it exists.
3728
- * The first argument is called, 'orderby' and has the default value of 'name'.
3729
- * The other value that is supported is 'count'.
3730
- * The second argument is called, 'order' and has the default value of 'ASC'.
3731
- * The only other value that will be acceptable is 'DESC'.
3732
- * The final argument supported is called, 'fields' and has the default value of
3733
- * 'all'. There are multiple other options that can be used instead. Supported
3734
- * values are as follows: 'all', 'ids', 'names', and finally
3735
- * 'all_with_object_id'.
3736
- * The fields argument also decides what will be returned. If 'all' or
3737
- * 'all_with_object_id' is chosen or the default kept intact, then all matching
3738
- * terms objects will be returned. If either 'ids' or 'names' is used, then an
3739
- * array of all matching term ids or term names will be returned respectively.
3740
- * @see wp_get_object_terms()
3741
- * @uses $wpdb
3742
- *
3743
- * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
3744
- * @param string|array $taxonomies The taxonomies to retrieve terms from.
3745
- * @param array|string $args Change what is returned
3746
- *
3747
- * @return array The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
3748
- */
3749
- function get_gmedia_terms($object_ids, $taxonomies, $args = array()){
3750
- /** @var $wpdb wpdb */
3751
- global $wpdb;
3752
-
3753
- if(!is_array($taxonomies)){
3754
- $taxonomies = array($taxonomies);
3755
- }
3756
-
3757
- if(!is_array($object_ids)){
3758
- $object_ids = array($object_ids);
3759
- }
3760
- $object_ids = array_map('intval', $object_ids);
3761
-
3762
- $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all', 'unique' => true);
3763
- $args = wp_parse_args($args, $defaults);
3764
-
3765
- $terms = array();
3766
-
3767
- /** @var $orderby
3768
- * @var $order
3769
- * @var $fields
3770
- * @var $unique
3771
- */
3772
- extract($args, EXTR_SKIP);
3773
-
3774
- if($unique){
3775
- $groupby = 'GROUP BY t.term_id';
3776
- } else{
3777
- $groupby = '';
3778
- }
3779
-
3780
- if('count' == $orderby){
3781
- $orderby = 't.count';
3782
- } else if('name' == $orderby){
3783
- $orderby = 't.name';
3784
- } else if('global' == $orderby){
3785
- $orderby = 't.global';
3786
- } else if('term_order' == $orderby){
3787
- $orderby = 'tr.term_order';
3788
- } else if('none' == $orderby){
3789
- $orderby = '';
3790
- $order = '';
3791
- } else{
3792
- $orderby = 't.term_id';
3793
- }
3794
-
3795
- if(!empty($orderby)){
3796
- $orderby = "ORDER BY $orderby";
3797
- }
3798
-
3799
- $taxonomies = "'" . implode("', '", $taxonomies) . "'";
3800
- $object_ids = implode(', ', $object_ids);
3801
-
3802
- $select_this = '';
3803
- if('all' == $fields){
3804
- $select_this = 't.*, tr.term_order, tr.gmedia_order';
3805
- } else if('ids' == $fields){
3806
- $select_this = 't.term_id';
3807
- } else if('names' == $fields){
3808
- $select_this = 't.name';
3809
- } else if('all_with_object_id' == $fields){
3810
- $select_this = 't.*, tr.gmedia_id, tr.term_order, tr.gmedia_order';
3811
- $groupby = '';
3812
- }
3813
-
3814
- $query = "SELECT $select_this FROM {$wpdb->prefix}gmedia_term AS t INNER JOIN {$wpdb->prefix}gmedia_term_relationships AS tr ON tr.gmedia_term_id = t.term_id WHERE t.taxonomy IN ($taxonomies) AND tr.gmedia_id IN ($object_ids) $groupby $orderby $order";
3815
-
3816
- if('all' == $fields || 'all_with_object_id' == $fields){
3817
- $terms = array_merge($terms, $wpdb->get_results($query));
3818
- $this->update_term_cache($terms);
3819
- } else if('ids' == $fields || 'names' == $fields){
3820
- $terms = array_merge($terms, $wpdb->get_col($query));
3821
- }
3822
-
3823
- if(!$terms){
3824
- $terms = array();
3825
- }
3826
-
3827
- return apply_filters('get_gmedia_terms', $terms, $object_ids, $taxonomies, $args);
3828
- }
3829
-
3830
- /**
3831
- * Removes a term from the database.
3832
- * If the term is a parent of other terms, then the children will be updated to
3833
- * that term's parent.
3834
- * The $args 'default' will only override the terms found, if there is only one
3835
- * term found. Any other and the found terms are used.
3836
- * The $args 'force_default' will force the term supplied as default to be
3837
- * assigned even if the object was not going to be termless
3838
- * @see wp_delete_term()
3839
- * @uses $wpdb
3840
- * @uses do_action() Calls both 'delete_gmedia_term' and 'gm_delete_$taxonomy' action
3841
- * hooks, passing term object, term id. 'gm_delete_term' gets an additional
3842
- * parameter with the $taxonomy parameter.
3843
- *
3844
- * @param int $term_id Term ID
3845
- * @param array|string $args Optional. Change 'default' term id and override found term ids.
3846
- *
3847
- * @return bool|WP_Error Returns false if not term; term_id if completes delete action.
3848
- */
3849
- function delete_term($term_id, $args = array()){
3850
- /** @var $wpdb wpdb */
3851
- global $wpdb;
3852
-
3853
- $term_id = (int)$term_id;
3854
-
3855
- if(!$term_id = $this->term_exists($term_id)){
3856
- return false;
3857
- }
3858
- if(is_wp_error($term_id)){
3859
- return $term_id;
3860
- }
3861
-
3862
- extract($args, EXTR_SKIP);
3863
-
3864
- if(!isset($taxonomy)){
3865
- $taxonomy = $this->get_tax_by_term_id($term_id);
3866
- }
3867
-
3868
- $objects = $wpdb->get_col($wpdb->prepare("SELECT gmedia_id FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_term_id = %d", $term_id));
3869
-
3870
- foreach((array)$objects as $object){
3871
- $terms = $this->get_gmedia_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
3872
- $terms = array_diff($terms, array($term_id));
3873
- $terms = array_map('intval', $terms);
3874
- $this->set_gmedia_terms($object, $terms, $taxonomy);
3875
- }
3876
-
3877
- $_post_ID = $this->get_metadata('gmedia_term', $term_id, '_post_ID', true);
3878
- $gmedia_term_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->prefix}gmedia_term_meta WHERE gmedia_term_id = %d ", $term_id));
3879
- if(!empty($gmedia_term_meta_ids)){
3880
- do_action('delete_gmedia_term_meta', $gmedia_term_meta_ids);
3881
- $in_gmedia_term_meta_ids = "'" . implode("', '", $gmedia_term_meta_ids) . "'";
3882
- $wpdb->query("DELETE FROM {$wpdb->prefix}gmedia_term_meta WHERE meta_id IN($in_gmedia_term_meta_ids)");
3883
- do_action('deleted_gmedia_term_meta', $gmedia_term_meta_ids);
3884
- }
3885
-
3886
- do_action('delete_gmedia_term', $term_id);
3887
- $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term WHERE term_id = %d", $term_id));
3888
- if($_post_ID){
3889
- wp_delete_post($_post_ID, true);
3890
- }
3891
- do_action('deleted_gmedia_term', $term_id);
3892
-
3893
- $this->clean_term_cache($term_id);
3894
-
3895
- do_action("delete_$taxonomy", $term_id);
3896
-
3897
- return $term_id;
3898
- }
3899
-
3900
- /**
3901
- * Will remove all of the term ids from the cache.
3902
- * @uses $wpdb
3903
- * @see clean_term_cache()
3904
- *
3905
- * @param int|array $ids Single or list of Term IDs
3906
- */
3907
- function clean_term_cache($ids){
3908
- if(!is_array($ids)){
3909
- $ids = array($ids);
3910
- }
3911
-
3912
- foreach($ids as $id){
3913
- wp_cache_delete($id, 'gmedia_term');
3914
- }
3915
-
3916
- do_action('gmedia_clean_term_cache', $ids);
3917
-
3918
- wp_cache_set('last_changed', time(), 'gmedia_terms');
3919
- }
3920
-
3921
-
3922
- /**
3923
- * Call major cache updating functions for list of Post objects.
3924
- * @see update_post_caches()
3925
- *
3926
- * @param array $gmedias Array of gmedia objects
3927
- * @param bool $update_term_cache Whether to update the term cache. Default is true.
3928
- * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
3929
- *
3930
- * @return null if we didn't match any gmedia objects
3931
- */
3932
- function update_gmedia_caches(&$gmedias, $update_term_cache = true, $update_meta_cache = true){
3933
- // No point in doing all this work if we didn't match any gmedia objects.
3934
- if(!$gmedias){
3935
- return null;
3936
- }
3937
-
3938
- foreach($gmedias as $gmedia){
3939
- wp_cache_add($gmedia->ID, $gmedia, 'gmedias');
3940
- if(!empty($gmedia->post_id)){
3941
- wp_cache_add($gmedia->post_id, $gmedia, 'wpgmedias');
3942
- }
3943
- }
3944
-
3945
- $gmedia_ids = array();
3946
- foreach($gmedias as $gmedia){
3947
- $gmedia_ids[] = $gmedia->ID;
3948
- }
3949
-
3950
- if($update_term_cache){
3951
- $gmedia_ids = array_map('intval', $gmedia_ids);
3952
- $taxonomies = array('gmedia_album', 'gmedia_category', 'gmedia_tag');
3953
-
3954
- $ids = array();
3955
- foreach((array)$gmedia_ids as $id){
3956
- foreach($taxonomies as $taxonomy){
3957
- if(false === wp_cache_get($id, "{$taxonomy}_relationships")){
3958
- $ids[] = $id;
3959
- break;
3960
- }
3961
- }
3962
- }
3963
-
3964
- if(!empty($ids)){
3965
- $terms = $this->get_gmedia_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
3966
-
3967
- $object_terms = array();
3968
- foreach((array)$terms as $term){
3969
- $object_terms[ $term->gmedia_id ][ $term->taxonomy ][ $term->term_id ] = $term;
3970
- }
3971
-
3972
- foreach($ids as $id){
3973
- foreach($taxonomies as $taxonomy){
3974
- if(!isset($object_terms[ $id ][ $taxonomy ])){
3975
- if(!isset($object_terms[ $id ])){
3976
- $object_terms[ $id ] = array();
3977
- }
3978
- $object_terms[ $id ][ $taxonomy ] = array();
3979
- }
3980
- }
3981
- }
3982
-
3983
- foreach($object_terms as $id => $value){
3984
- foreach($value as $taxonomy => $terms){
3985
- wp_cache_set($id, $terms, "{$taxonomy}_relationships");
3986
- }
3987
- }
3988
- }
3989
- }
3990
-
3991
- if($update_meta_cache){
3992
- $this->update_meta_cache('gmedia', $gmedia_ids);
3993
- }
3994
-
3995
- }
3996
-
3997
- /**
3998
- * Update the metadata cache for the specified objects.
3999
- * @see update_meta_cache()
4000
- * @uses $wpdb WordPress database object for queries.
4001
- *
4002
- * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
4003
- * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
4004
- *
4005
- * @return mixed Metadata cache for the specified objects, or false on failure.
4006
- */
4007
- function update_meta_cache($meta_type, $object_ids){
4008
- /** @var $wpdb wpdb */
4009
- global $wpdb;
4010
-
4011
- if(empty($meta_type) || empty($object_ids) || !in_array($meta_type, array('gmedia', 'gmedia_term'))){
4012
- return false;
4013
- }
4014
-
4015
- $table = $wpdb->prefix . $meta_type . '_meta';
4016
-
4017
- $column = esc_sql($meta_type . '_id');
4018
-
4019
- if(!is_array($object_ids)){
4020
- $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
4021
- $object_ids = explode(',', $object_ids);
4022
- }
4023
-
4024
- $object_ids = array_map('intval', $object_ids);
4025
-
4026
- $cache_key = $meta_type . '_meta';
4027
- $ids = array();
4028
- $cache = array();
4029
- foreach($object_ids as $id){
4030
- $cached_object = wp_cache_get($id, $cache_key);
4031
- if(false === $cached_object){
4032
- $ids[] = $id;
4033
- } else{
4034
- $cache[ $id ] = $cached_object;
4035
- }
4036
- }
4037
-
4038
- if(empty($ids)){
4039
- return $cache;
4040
- }
4041
-
4042
- // Get meta info
4043
- $id_list = join(',', $ids);
4044
- $meta_list = $wpdb->get_results("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)", ARRAY_A);
4045
-
4046
- if(!empty($meta_list)){
4047
- foreach($meta_list as $metarow){
4048
- $mpid = intval($metarow[ $column ]);
4049
- $mkey = $metarow['meta_key'];
4050
- $mval = $metarow['meta_value'];
4051
-
4052
- // Force subkeys to be array type:
4053
- if(!isset($cache[ $mpid ]) || !is_array($cache[ $mpid ])){
4054
- $cache[ $mpid ] = array();
4055
- }
4056
- if(!isset($cache[ $mpid ][ $mkey ]) || !is_array($cache[ $mpid ][ $mkey ])){
4057
- $cache[ $mpid ][ $mkey ] = array();
4058
- }
4059
-
4060
- // Add a value to the current pid/key:
4061
- $cache[ $mpid ][ $mkey ][] = $mval;
4062
- }
4063
- }
4064
-
4065
- foreach($ids as $id){
4066
- if(!isset($cache[ $id ])){
4067
- $cache[ $id ] = array();
4068
- }
4069
- wp_cache_add($id, $cache[ $id ], $cache_key);
4070
- }
4071
-
4072
- return $cache;
4073
- }
4074
-
4075
- /**
4076
- * Removes the taxonomy relationship to terms from the cache.
4077
- * Will remove the entire taxonomy relationship containing term $object_id.
4078
- * @see clean_object_term_cache()
4079
- * @see get_object_taxonomies() for more on $object_type
4080
- * @uses do_action() Will call action hook named, 'gmedia_clean_object_term_cache' after completion.
4081
- * Passes, function params in same order.
4082
- *
4083
- * @param int|array $object_ids Single or list of term object ID(s)
4084
- * @param array $taxonomies
4085
- */
4086
- function clean_object_term_cache($object_ids, $taxonomies = array()){
4087
- if(!is_array($object_ids)){
4088
- $object_ids = array($object_ids);
4089
- }
4090
- if(empty($taxonomies)){
4091
- $taxonomies = array('gmedia_album', 'gmedia_category', 'gmedia_tag');
4092
- }
4093
-
4094
- foreach($object_ids as $id){
4095
- foreach($taxonomies as $taxonomy){
4096
- wp_cache_delete($id, "{$taxonomy}_relationships");
4097
- }
4098
- }
4099
-
4100
- do_action('gmedia_clean_object_term_cache', $object_ids, $taxonomies);
4101
- }
4102
-
4103
- /**
4104
- * Will update term count based on number of objects.
4105
- * @see wp_update_term_count()
4106
- * @uses $wpdb
4107
- *
4108
- * @param array $terms List of Term taxonomy IDs
4109
- *
4110
- * @return bool Always true when complete.
4111
- */
4112
- function update_term_count($terms){
4113
- /** @var $wpdb wpdb */
4114
- global $wpdb;
4115
-
4116
- if(!is_array($terms)){
4117
- $terms = array($terms);
4118
- }
4119
-
4120
- foreach((array)$terms as $term_id){
4121
- $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_term_id = %d", $term_id));
4122
-
4123
- do_action('update_gmedia_term_count', $term_id);
4124
- $wpdb->update($wpdb->prefix . 'gmedia_term', compact('count'), array('term_id' => $term_id));
4125
- do_action('updated_gmedia_term_count', $term_id);
4126
- }
4127
-
4128
- $this->clean_term_cache($terms);
4129
-
4130
- return true;
4131
- }
4132
-
4133
- /**
4134
- * This function returns all roles, sorted by user level (lowest to highest)
4135
- * @return array
4136
- */
4137
- function get_sorted_roles(){
4138
- global $wp_roles;
4139
- $roles = $wp_roles->role_objects;
4140
- $sorted = array();
4141
-
4142
- if(class_exists('RoleManager')){
4143
- foreach($roles as $role_key => $role_name){
4144
- $role = get_role($role_key);
4145
- if(empty($role)){
4146
- continue;
4147
- }
4148
- $role_user_level = array_reduce(array_keys($role->capabilities), array('WP_User', 'level_reduction'), 0);
4149
- $sorted[ $role_user_level ] = $role;
4150
- }
4151
- $sorted = array_values($sorted);
4152
- } else{
4153
- $role_order = array("subscriber", "contributor", "author", "editor", "administrator");
4154
- foreach($role_order as $role_key){
4155
- $sorted[ $role_key ] = get_role($role_key);
4156
- }
4157
- }
4158
-
4159
- return $sorted;
4160
- }
4161
-
4162
- /**
4163
- * This function return the lowest roles which has the capabilities
4164
- *
4165
- * @param $capability
4166
- *
4167
- * @return bool
4168
- */
4169
- function get_role($capability){
4170
- $check_order = $this->get_sorted_roles();
4171
-
4172
- $args = array_slice(func_get_args(), 1);
4173
- $args = array_merge(array($capability), $args);
4174
-
4175
- foreach($check_order as $check_role){
4176
- if(empty($check_role)){
4177
- return false;
4178
- }
4179
-
4180
- if(call_user_func_array(array(&$check_role, 'has_cap'), $args)){
4181
- return $check_role->name;
4182
- }
4183
- }
4184
-
4185
- return false;
4186
- }
4187
-
4188
- /**
4189
- * This function set or remove the $capability
4190
- *
4191
- * @param $lowest_role
4192
- * @param $capability
4193
- */
4194
- function set_capability($lowest_role, $capability){
4195
- $check_order = $this->get_sorted_roles();
4196
-
4197
- $add_capability = false;
4198
-
4199
- foreach($check_order as $the_role){
4200
- $role = $the_role->name;
4201
-
4202
- if($lowest_role == $role){
4203
- $add_capability = true;
4204
- }
4205
-
4206
- // If you rename the roles, the please use the role manager plugin
4207
- if(empty($the_role)){
4208
- continue;
4209
- }
4210
-
4211
- /** @noinspection PhpUndefinedMethodInspection */
4212
- $add_capability? $the_role->add_cap($capability) : $the_role->remove_cap($capability);
4213
- }
4214
-
4215
- }
4216
-
4217
- /**
4218
- * Reassign media to other blog user
4219
- *
4220
- * @param $user_id
4221
- * @param $reassign
4222
- */
4223
- function reassign_media($user_id, $reassign){
4224
- $gmedias = $this->get_gmedias(array('nopaging' => true, 'author' => $user_id));
4225
- $taxonomies = $this->get_terms(array('gmedia_album', 'gmedia_gallery', 'gmedia_module'), array('global' => $user_id));
4226
- if(empty($reassign)){
4227
- $reassign = get_current_user_id();
4228
- }
4229
- if(!empty($gmedias)){
4230
- $modified = current_time('mysql');
4231
- foreach($gmedias as $item){
4232
- $item->author = $reassign;
4233
- $item->modified = $modified;
4234
- $this->insert_gmedia($item);
4235
- }
4236
- }
4237
- if(!empty($taxonomies)){
4238
- foreach($taxonomies as $item){
4239
- $this->update_term($item->term_id, array('global' => $reassign));
4240
- }
4241
- }
4242
- }
4243
-
4244
- }
4245
-
4246
- global $gmDB;
4247
- $gmDB = new GmediaDB;
1
+ <?php
2
+
3
+ /**
4
+ * Gmedia Database Class
5
+ */
6
+ class GmediaDB{
7
+
8
+ var $query; // User passed query
9
+ var $sql_query; // User passed query
10
+ var $filter = array(); // is there filter for get_gmedias()
11
+ var $filter_tax = array(); // is there filter by taxonomy for get_gmedias()
12
+ var $resultLimited = 0; // Total records for limited query (with offset)
13
+ var $resultPerPage = 0; // Total records in each pages
14
+ var $hardlimit = 0; // Hard limit query
15
+ var $trueTotalResult = 0; // Total records in DB without limit
16
+ var $totalResult = 0; // Total records in DB
17
+ var $pages = 0; // Total number of pages required
18
+ var $perPages = 0; // per page query
19
+ var $openPage = 0; // currently opened page
20
+ var $clauses; // query clauses
21
+ var $gmedia; // first gmedia object
22
+
23
+ /**
24
+ * Get Wordpress Media
25
+ *
26
+ * @param array $arg
27
+ *
28
+ * @return object
29
+ */
30
+ function get_wp_media_lib($arg){
31
+ /** @var $wpdb wpdb */
32
+ global $wpdb, $gmCore;
33
+ $default_arg = array('mime_type' => '', 'orderby' => 'ID', 'order' => '', 'limit' => '0', 'filter' => '', 'selected' => false, 's' => '');
34
+ $arg = array_merge($default_arg, $arg);
35
+ /** @var $mime_type
36
+ * @var $orderby
37
+ * @var $order
38
+ * @var $limit
39
+ * @var $filter
40
+ * @var $s
41
+ * @var $selected
42
+ */
43
+ extract($arg);
44
+ $and = '';
45
+ $ord = '';
46
+ $lim = '';
47
+ $search = '';
48
+ $sel_ids = array();
49
+ if($selected){
50
+ $sel_ids = wp_parse_id_list($selected);
51
+ } else{
52
+ $ckey = "gmedia_library:wpmedia";
53
+ if(isset($_COOKIE[ $ckey ])){
54
+ $sel_ids = array_filter(explode('.', $_COOKIE[ $ckey ]), 'is_numeric');
55
+ }
56
+ }
57
+ switch($mime_type){
58
+ case 'image':
59
+ $and .= " AND post_mime_type REGEXP '^image(.*)'";
60
+ break;
61
+ case 'audio':
62
+ $and .= " AND post_mime_type REGEXP '^audio(.*)'";
63
+ break;
64
+ case 'video':
65
+ $and .= " AND post_mime_type REGEXP '^video(.*)'";
66
+ break;
67
+ case 'application':
68
+ $and .= " AND post_mime_type NOT REGEXP 'image|audio|video'";
69
+ break;
70
+ }
71
+ if(!empty($mime_type)){
72
+ $this->filter['mime_type'] = (array)$mime_type;
73
+ }
74
+ // If a search pattern is specified, load the posts that match
75
+ if(!empty($s)){
76
+ // added slashes screw with quote grouping when done early, so done later
77
+ $s = stripslashes($s);
78
+
79
+ // split the words it a array if seperated by a space or comma
80
+ preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
81
+ $search_terms = array_map(function($a){ return trim($a, "\"'\n\r "); }, $matches[0]);
82
+
83
+ $n = '%';
84
+ $searchand = '';
85
+
86
+ foreach((array)$search_terms as $term){
87
+ $term = addslashes_gpc($term);
88
+ $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
89
+ $searchand = ' AND ';
90
+ }
91
+
92
+ $term = esc_sql($s);
93
+ if(count($search_terms) > 1 && $search_terms[0] != $s){
94
+ $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";
95
+ }
96
+
97
+ if(!empty($search)){
98
+ $search = " AND ({$search}) ";
99
+ $this->filter['s'] = (array)$search_terms;
100
+ }
101
+ }
102
+ if($orderby){
103
+ switch($orderby){
104
+ case 'ID':
105
+ $orderby = 'ID';
106
+ if(!$order){
107
+ $order = 'DESC';
108
+ }
109
+ break;
110
+ case 'filename':
111
+ $orderby = 'post_name';
112
+ break;
113
+ case 'title':
114
+ $orderby = 'post_title';
115
+ break;
116
+ case 'date':
117
+ $orderby = 'post_modified';
118
+ break;
119
+ case 'selected':
120
+ if(count($sel_ids) > 1){
121
+ $orderby = 'FIELD(ID, ' . join(', ', $sel_ids) . ')';
122
+ } else{
123
+ $orderby = 'ID';
124
+ }
125
+ break;
126
+ default:
127
+ $orderby = preg_replace('/[^a-z_]/', ' ', $orderby);
128
+ break;
129
+ }
130
+ $ord .= " ORDER BY {$orderby}";
131
+ $ord .= ($order == 'DESC')? ' DESC' : ' ASC';
132
+ }
133
+ switch($filter){
134
+ case 'selected':
135
+ if(count($sel_ids)){
136
+ $and .= ' AND ID IN (' . join(', ', $sel_ids) . ')';
137
+ $this->filter['post__in'] = $sel_ids;
138
+ break;
139
+ } else{
140
+ $and .= ' AND ID = 0';
141
+ // todo: selected query error: No selected items
142
+ }
143
+ break;
144
+ default:
145
+ //$and .= "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
146
+ break;
147
+ }
148
+ $this->openPage = $gmCore->_get('pager', '1');
149
+ $limit = intval($limit);
150
+ if($limit > 0){
151
+ $offset = ($this->openPage - 1) * $limit;
152
+ $lim = " LIMIT {$offset}, {$limit}";
153
+ }
154
+ $this->sql_query = "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE post_type = 'attachment' {$and} {$search} GROUP BY ID {$ord} {$lim}";
155
+ $this->query = $wpdb->get_results($this->sql_query);
156
+ $this->totalResult = (int)$wpdb->get_var("SELECT FOUND_ROWS()");
157
+ if((1 > $limit) || (0 == $this->totalResult)){
158
+ $limit = $this->totalResult;
159
+ $this->pages = 1;
160
+ } else{
161
+ $this->pages = ceil($this->totalResult / $limit);
162
+ }
163
+ if($this->openPage > $this->pages){
164
+ $this->openPage = $this->pages;
165
+ if($limit > 0){
166
+ $limit = intval($limit);
167
+ $offset = ($this->openPage - 1) * $limit;
168
+ $lim = " LIMIT {$offset}, {$limit}";
169
+ }
170
+ $this->sql_query = "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE post_type = 'attachment' {$and} {$search} GROUP BY ID {$ord} {$lim}";
171
+ $this->query = $wpdb->get_results($this->sql_query);
172
+ }
173
+ $this->resultPerPage = count($this->query);
174
+
175
+ return $this->query;
176
+ }
177
+
178
+ /**
179
+ * @param $arg
180
+ *
181
+ * @return mixed
182
+ */
183
+ function count_wp_media($arg){
184
+ /** @var $wpdb wpdb */
185
+ global $wpdb;
186
+ /** @var $filter
187
+ * @var $selected
188
+ * @var $s
189
+ */
190
+ extract($arg);
191
+ $search = '';
192
+ if(isset($selected)){
193
+ $sel_ids = wp_parse_id_list($selected);
194
+ } elseif(isset($_COOKIE["gmedia_library:wpmedia"])){
195
+ $sel_ids = array_filter(explode('.', $_COOKIE["gmedia_library:wpmedia"]), 'is_numeric');
196
+ } else{
197
+ $sel_ids = array();
198
+ }
199
+
200
+ switch($filter){
201
+ case 'selected':
202
+ if(count($sel_ids)){
203
+ $filter = ' AND ID IN (' . join(', ', $sel_ids) . ')';
204
+ break;
205
+ }
206
+ default:
207
+ //$filter = "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
208
+ $filter = '';
209
+ break;
210
+ }
211
+ // If a search pattern is specified, load the posts that match
212
+ if(!empty($s)){
213
+ // added slashes screw with quote grouping when done early, so done later
214
+ $s = stripslashes($s);
215
+
216
+ // split the words it a array if seperated by a space or comma
217
+ preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
218
+ $search_terms = array_map(function($a){ return trim($a, "\"'\n\r "); }, $matches[0]);
219
+
220
+ $n = '%';
221
+ $searchand = '';
222
+
223
+ foreach((array)$search_terms as $term){
224
+ $term = addslashes_gpc($term);
225
+ $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
226
+ $searchand = ' AND ';
227
+ }
228
+
229
+ $term = esc_sql($s);
230
+ if(count($search_terms) > 1 && $search_terms[0] != $s){
231
+ $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";
232
+ }
233
+
234
+ if(!empty($search)){
235
+ $search = " AND ({$search}) ";
236
+ }
237
+
238
+ }
239
+ $count = $wpdb->get_results("SELECT COUNT(*) as total,
240
+ SUM(CASE WHEN post_mime_type LIKE 'image%' THEN 1 ELSE 0 END) as image,
241
+ SUM(CASE WHEN post_mime_type LIKE 'audio%' THEN 1 ELSE 0 END) as audio,
242
+ SUM(CASE WHEN post_mime_type LIKE 'video%' THEN 1 ELSE 0 END) as video,
243
+ SUM(CASE WHEN post_mime_type LIKE 'text%' THEN 1 ELSE 0 END) as text,
244
+ SUM(CASE WHEN post_mime_type LIKE 'application%' THEN 1 ELSE 0 END) as application
245
+ FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} {$search}", ARRAY_A);
246
+
247
+ //$count[0]['hidden'] = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key = '_gmedia_hidden' {$search}" );
248
+ $count[0]['other'] = (int)$count[0]['text'] + (int)$count[0]['application'];
249
+
250
+ return $count[0];
251
+ }
252
+
253
+ /**
254
+ * @return mixed
255
+ */
256
+ function count_gmedia(){
257
+ /** @var $wpdb wpdb */
258
+ global $wpdb;
259
+ /**
260
+ * @var $whichauthor
261
+ * @var $whichmimetype
262
+ * @var $groupby
263
+ * @var $orderby
264
+ * @var $limits
265
+ */
266
+ $join = '';
267
+ $where = '';
268
+ $whichauthor = '';
269
+ if($this->clauses){
270
+ extract($this->clauses, EXTR_OVERWRITE);
271
+ }
272
+
273
+ $count = $wpdb->get_results("SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) as total,
274
+ (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'image%' $where $whichauthor) as image,
275
+ (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'audio%' $where $whichauthor) as audio,
276
+ (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'video%' $where $whichauthor) as video,
277
+ (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'text%' $where $whichauthor) as text,
278
+ (SELECT count(DISTINCT {$wpdb->prefix}gmedia.ID) FROM {$wpdb->prefix}gmedia $join WHERE {$wpdb->prefix}gmedia.mime_type LIKE 'application%' $where $whichauthor) as application
279
+ FROM {$wpdb->prefix}gmedia $join WHERE 1=1 $where $whichauthor
280
+ ", ARRAY_A);
281
+
282
+ if($count){
283
+ $count = $count[0];
284
+ $count['other'] = (int)$count['text'] + (int)$count['application'];
285
+ $count['total'] = (int)$count['image'] + (int)$count['audio'] + (int)$count['video'] + (int)$count['other'];
286
+ } else{
287
+ $count = array('image' => 0,
288
+ 'audio' => 0,
289
+ 'video' => 0,
290
+ 'text' => 0,
291
+ 'application' => 0,
292
+ 'other' => 0,
293
+ 'total' => 0
294
+ );
295
+ }
296
+
297
+ return $count;
298
+ }
299
+
300
+ /**
301
+ * function to display the pagination
302
+ * @return string
303
+ */
304
+ function query_pager(){
305
+ if(empty($this->pages) || $this->pages == 1 || $this->resultLimited){
306
+ return '';
307
+ }
308
+ $params = $_GET;
309
+ foreach ($params as $key => $value) {
310
+ if (strpos($key, '_wpnonce') !== false) {
311
+ unset($params[$key]);
312
+ }
313
+ }
314
+ unset($params['pager'], $params['do_gmedia'], $params['did_gmedia'], $params['do_gmedia_terms'], $params['did_gmedia_terms'], $params['ids'], $params['doing_wp_cron']);
315
+ $new_query_string = http_build_query($params);
316
+ //$self = admin_url( 'admin.php?' . $new_query_string );
317
+ $self = '?' . $new_query_string;
318
+ if($this->openPage <= 0){
319
+ $next = 2;
320
+ } else{
321
+ $next = $this->openPage + 1;
322
+ }
323
+ $prev = $this->openPage - 1;
324
+ $last = $this->pages;
325
+ //$total = $this->totalResult;
326
+ $result = '<div class="btn-toolbar pull-right gmedia-pager">';
327
+ $result .= '<div class="btn-group btn-group-xs">';
328
+
329
+ $li_class = ($this->openPage > 1)? '' : ' disabled';
330
+ $result .= "<a class='btn btn-default{$li_class}' href='{$self}'><span class='glyphicon glyphicon-fast-backward'></span></a>";
331
+ $result .= "<a class='btn btn-default{$li_class}' href='{$self}&pager=$prev'><span class='glyphicon glyphicon-step-backward'></span></a>";
332
+
333
+ $result .= '</div>';
334
+
335
+ $result .= '<form name="gmedia-pager" method="get" id="gmedia-pager" class="input-group btn-group input-group-xs" action="">';
336
+ $result .= '<span class="input-group-addon">' . __("Page", "grand-media") . '</span>';
337
+ foreach($params as $key => $value){
338
+ $result .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
339
+ }
340
+ $result .= '<input class="form-control pager_current_page allow-key-enter" name="pager" type="text" value="' . $this->openPage . '" /><span class="input-group-addon">' . __("of", "grand-media") . ' ' . $this->pages . '</span>';
341
+ $result .= '</form>';
342
+
343
+ $result .= '<div class="btn-group btn-group-xs">';
344
+ $li_class = ($this->openPage < $this->pages)? '' : ' disabled';
345
+ $result .= "<a class='btn btn-default{$li_class}' href='{$self}&amp;pager=$next'><span class='glyphicon glyphicon-step-forward'></span></a>";
346
+ $result .= "<a class='btn btn-default{$li_class}' href='{$self}&amp;pager=$last'><span class='glyphicon glyphicon-fast-forward'></span></a>";
347
+ $result .= '</div>';
348
+
349
+ $result .= '</div>';
350
+
351
+ return $result;
352
+ }
353
+
354
+ /**
355
+ * Insert media.
356
+ * If you set the 'ID' in the $object parameter, it will mean that you are
357
+ * updating and attempt to update the media. You can also set the
358
+ * media url or title by setting the key 'gmuid' or 'title'.
359
+ * You can set the dates for the media manually by setting the 'date' key value.
360
+ * The $object parameter can have the following:
361
+ * 'author' - Default is current user ID. The ID of the user, who added the attachment.
362
+ * 'mime_type' - Will be set to media. Do not override!!!
363
+ * 'gmuid' - Filename.
364
+ * 'description' - Media content.
365
+ * 'date' - Date.
366
+ * 'modified' - Date modified.
367
+ * 'link' - Media external link.
368
+ * 'status' - Status.
369
+ * @uses $wpdb
370
+ * @uses $user_ID
371
+ * @uses do_action() Calls 'edit_gmedia' on $post_ID if this is an update.
372
+ * @uses do_action() Calls 'add_gmedia' on $post_ID if this is not an update.
373
+ * @see wp_insert_attachment().
374
+ *
375
+ * @param string|array $object Arguments to override defaults.
376
+ *
377
+ * @return int Media ID.
378
+ */
379
+ function insert_gmedia($object){
380
+ /** @var $wpdb wpdb */
381
+ global $wpdb, $user_ID, $gmCore, $gmGallery;
382
+
383
+ // TODO media status (vip, password?)
384
+ $defaults = array('ID' => false, 'author' => $user_ID);
385
+ $object = wp_parse_args($object, $defaults);
386
+ if(isset($object['title'])){
387
+ $object['title'] = strip_tags($object['title'], '<span>');
388
+ $object['title'] = $gmCore->mb_convert_encoding_utf8($object['title']);
389
+ }
390
+ if(isset($object['description'])){
391
+ $object['description'] = $gmCore->clean_input($object['description']);
392
+ $object['description'] = $gmCore->mb_convert_encoding_utf8($object['description']);
393
+ }
394
+ if(isset($object['link'])){
395
+ $object['link'] = esc_url_raw($object['link']);
396
+ }
397
+ if(!isset($object['status']) || empty($object['status'])){
398
+ $object['status'] = 'publish';
399
+ }
400
+
401
+ // export array as variables
402
+ extract($object, EXTR_SKIP);
403
+
404
+ // Are we updating or creating?
405
+ $media_ID = 0;
406
+ $update = false;
407
+ if(!empty($ID)){
408
+ $media_ID = (int)$ID;
409
+ $update = true;
410
+ if(isset($date) && empty($date)){
411
+ unset($date);
412
+ }
413
+ $modified = current_time('mysql');
414
+ } else{
415
+ if(empty($date)){
416
+ $date = current_time('mysql');
417
+ }
418
+ $modified = $date;
419
+ }
420
+
421
+ // expected_slashed (everything!)
422
+ $data = compact(array('author', 'date', 'description', 'title', 'gmuid', 'modified', 'mime_type', 'link', 'status'));
423
+ $data = stripslashes_deep($data);
424
+
425
+ if($update){
426
+ $wpdb->update($wpdb->prefix . 'gmedia', $data, array('ID' => $media_ID));
427
+ } else{
428
+ $wpdb->insert($wpdb->prefix . 'gmedia', $data);
429
+ $media_ID = (int)$wpdb->insert_id;
430
+ }
431
+
432
+ wp_cache_delete($media_ID, 'gmedias');
433
+
434
+ $gmedia = $this->get_gmedia($media_ID);
435
+ $post_ID = $gmedia->post_id;
436
+ $post_data = array('post_author' => $gmedia->author,
437
+ 'post_content' => $gmedia->description,
438
+ 'post_title' => (trim($gmedia->title)? $gmedia->title : $gmedia->gmuid),
439
+ 'post_status' => $gmedia->status,
440
+ 'post_type' => 'gmedia',
441
+ 'post_name' => $gmedia->gmuid,
442
+ 'post_date' => $gmedia->date,
443
+ 'post_modified' => $gmedia->modified,
444
+ 'post_mime_type' => $gmedia->mime_type
445
+ );
446
+
447
+ if(!empty($comment_status)){
448
+ $post_data['comment_status'] = $comment_status;
449
+ } elseif(!$update){
450
+ $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
451
+ }
452
+
453
+ if(!empty($post_ID)){
454
+ $post_data['ID'] = $post_ID;
455
+ if(!wp_update_post($post_data)){
456
+ unset($post_data['ID']);
457
+ $post_ID = wp_insert_post($post_data);
458
+ if($post_ID){
459
+ add_metadata('post', $post_ID, '_gmedia_ID', $media_ID);
460
+ $wpdb->update($wpdb->prefix . 'gmedia', array('post_id' => $post_ID), array('ID' => $media_ID));
461
+ wp_cache_delete($media_ID, 'gmedias');
462
+ }
463
+ }
464
+ } else{
465
+ $post_ID = wp_insert_post($post_data);
466
+ if($post_ID){
467
+ add_metadata('post', $post_ID, '_gmedia_ID', $media_ID);
468
+ $wpdb->update($wpdb->prefix . 'gmedia', array('post_id' => $post_ID), array('ID' => $media_ID));
469
+ wp_cache_delete($media_ID, 'gmedias');
470
+ }
471
+ }
472
+
473
+ if(isset($terms) && is_array($terms) && count($terms)){
474
+ foreach($terms as $taxonomy => $_terms){
475
+ $taxonomy = trim($taxonomy);
476
+ if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category')) && !is_array($_terms)){
477
+ $_terms = explode(',', $_terms);
478
+ } else{
479
+ $_terms = (array)$_terms;
480
+ }
481
+ if(!empty($taxonomy)){
482
+ $this->set_gmedia_terms($media_ID, $_terms, $taxonomy, $append = 0);
483
+ }
484
+ }
485
+ }
486
+
487
+ wp_cache_delete($media_ID, 'gmedia_meta');
488
+ if(!empty($post_ID)){
489
+ wp_cache_delete($post_ID, 'wpgmedias');
490
+ }
491
+
492
+ $this->clean_object_term_cache($media_ID);
493
+
494
+ do_action('clean_gmedia_cache', $media_ID);
495
+
496
+ if($update){
497
+ do_action('edit_gmedia', $media_ID);
498
+ } else{
499
+ do_action('add_gmedia', $media_ID);
500
+ }
501
+
502
+ return $media_ID;
503
+ }
504
+
505
+ /**
506
+ * Trashes or deletes gmedia.
507
+ * When gmedia is deleted, the file will also be removed.
508
+ * Deletion removes all gmedia meta fields, taxonomy, comments, etc. associated
509
+ * with the gmedia.
510
+ * @see wp_delete_attachment()
511
+ * @uses $wpdb
512
+ * @uses do_action() Calls 'delete_gmedia' hook on gmedia ID.
513
+ *
514
+ * @param int $gmedia_id Gmedia ID.
515
+ * @param bool $delete_original_file delete oroginal image?
516
+ *
517
+ * @return mixed False on failure. Gmedia data on success.
518
+ */
519
+ function delete_gmedia($gmedia_id, $delete_original_file = true){
520
+ /** @var $wpdb wpdb */
521
+ global $wpdb, $gmGallery, $gmCore;
522
+
523
+ if(!$gmedia = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}gmedia WHERE ID = %d", $gmedia_id))){
524
+ return $gmedia;
525
+ }
526
+
527
+ $this->delete_gmedia_term_relationships($gmedia_id, array('gmedia_album', 'gmedia_tag', 'gmedia_category'));
528
+
529
+ $gmedia_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->prefix}gmedia_meta WHERE gmedia_id = %d ", $gmedia_id));
530
+ if(!empty($gmedia_meta_ids)){
531
+ do_action('delete_gmedia_meta', $gmedia_meta_ids);
532
+ $in_gmedia_meta_ids = "'" . implode("', '", $gmedia_meta_ids) . "'";
533
+ $wpdb->query("DELETE FROM {$wpdb->prefix}gmedia_meta WHERE meta_id IN($in_gmedia_meta_ids)");
534
+ do_action('deleted_gmedia_meta', $gmedia_meta_ids);
535
+ }
536
+
537
+ do_action('delete_gmedia', $gmedia_id);
538
+ $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia WHERE ID = %d", $gmedia_id));
539
+ if(!empty($gmedia->post_id)){
540
+ wp_delete_post($gmedia->post_id, true);
541
+ }
542
+ do_action('deleted_gmedia', $gmedia_id);
543
+
544
+
545
+ if(!empty($files)){
546
+ foreach($files as $cachefile){
547
+ $cachefile = apply_filters('gm_delete_file', $cachefile);
548
+ @unlink($cachefile);
549
+ }
550
+ }
551
+
552
+ $type = strtok($gmedia->mime_type, '/');
553
+ if('image' == $type){
554
+ $folders = array($gmGallery->options['folder']['image'],
555
+ $gmGallery->options['folder']['image_thumb']
556
+ );
557
+ if($delete_original_file){
558
+ $folders[] = $gmGallery->options['folder']['image_original'];
559
+ }
560
+ foreach($folders as $dir){
561
+ $file = apply_filters('gm_delete_file', $gmCore->upload['path'] . '/' . $dir . '/' . $gmedia->gmuid);
562
+ @unlink($file);
563
+ }
564
+ } else{
565
+ if($delete_original_file){
566
+ $dir = $gmCore->upload['path'] . '/' . $gmGallery->options['folder'][ $type ];
567
+
568
+ $filepath = $dir . '/' . $gmedia->gmuid;
569
+ $file = apply_filters('gm_delete_file', $filepath);
570
+ @unlink($file);
571
+ }
572
+
573
+ /*
574
+ $files = glob( $filepath . '*', GLOB_NOSORT);
575
+ if(!empty($files)){
576
+ foreach($files as $file){
577
+ $file = apply_filters('gm_delete_file', $file);
578
+ @unlink($file);
579
+ }
580
+ }
581
+ */
582
+ }
583
+
584
+ wp_cache_delete($gmedia_id, 'gmedias');
585
+ wp_cache_delete($gmedia_id, 'gmedia_meta');
586
+ if(!empty($gmedia->post_id)){
587
+ wp_cache_delete($gmedia->post_id, 'wpgmedias');
588
+ }
589
+ $this->clean_object_term_cache($gmedia_id);
590
+
591
+ do_action('clean_gmedia_cache', $gmedia_id);
592
+
593
+ return $gmedia;
594
+ }
595
+
596
+ /**
597
+ * Will unlink the object from the taxonomy or taxonomies.
598
+ * Will remove all relationships between the object and any terms in
599
+ * a particular taxonomy or taxonomies. Does not remove the term or
600
+ * taxonomy itself.
601
+ * @see wp_delete_object_term_relationships()
602
+ * @uses $wpdb
603
+ *
604
+ * @param int $object_id The term Object Id that refers to the term
605
+ * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
606
+ */
607
+ function delete_gmedia_term_relationships($object_id, $taxonomies){
608
+ /** @var $wpdb wpdb */
609
+ global $wpdb;
610
+
611
+ $object_id = (int)$object_id;
612
+
613
+ if(!is_array($taxonomies)){
614
+ $taxonomies = array($taxonomies);
615
+ }
616
+
617
+ foreach((array)$taxonomies as $taxonomy){
618
+ $term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids'));
619
+ $in_term_ids = "'" . implode("', '", $term_ids) . "'";
620
+ do_action('delete_gmedia_term_relationships', $object_id, $term_ids);
621
+ $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id IN ($in_term_ids)", $object_id));
622
+ do_action('deleted_gmedia_term_relationships', $object_id, $term_ids);
623
+ $this->update_term_count($term_ids);
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Generate gmedia meta data.
629
+ * @see wp_generate_attachment_metadata()
630
+ *
631
+ * @param int $media_id Gmedia Id to process.
632
+ * @param array $fileinfo from fileinfo() function
633
+ *
634
+ * @return mixed Metadata for media.
635
+ */
636
+ function generate_gmedia_metadata($media_id, $fileinfo = array()){
637
+ global $gmCore;
638
+ $media = $this->get_gmedia($media_id);
639
+ $metadata = $gmCore->get_file_metadata($media->gmuid, $fileinfo);
640
+
641
+ return apply_filters('generate_gmedia_metadata', $metadata, $media_id);
642
+
643
+ }
644
+
645
+ /**
646
+ * Retrieves gmedia data given a gmedia ID or gmedia object.
647
+ * @see get_post()
648
+ * @uses $wpdb
649
+ *
650
+ * @param int|object $media Gmedia ID or gmedia object.
651
+ * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
652
+ *
653
+ * @return mixed Gmedia data
654
+ */
655
+ function get_gmedia($media, $output = OBJECT){
656
+ /** @var $wpdb wpdb */
657
+ global $wpdb;
658
+ $null = null;
659
+
660
+ if(empty($media)){
661
+ return $null;
662
+ } elseif(is_object($media)){
663
+ $_media = $media;
664
+ wp_cache_add($media->ID, $_media, 'gmedias');
665
+ if(!empty($media->post_id)){
666
+ wp_cache_add($media->post_id, $_media, 'wpgmedias');
667
+ }
668
+ } else{
669
+ $media_id = (int)$media;
670
+ if(!$_media = wp_cache_get($media_id, 'gmedias')){
671
+ $_media = $wpdb->get_row($wpdb->prepare("SELECT {$wpdb->prefix}gmedia.*, wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count FROM {$wpdb->prefix}gmedia LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID) WHERE {$wpdb->prefix}gmedia.ID = %d LIMIT 1", $media_id));
672
+ if(!$_media){
673
+ return $null;
674
+ }
675
+ wp_cache_add($_media->ID, $_media, 'gmedias');
676
+ if(!empty($_media->post_id)){
677
+ wp_cache_add($_media->post_id, $_media, 'wpgmedias');
678
+ }
679
+ }
680
+ }
681
+
682
+ if($output == OBJECT){
683
+ return $_media;
684
+ } elseif($output == ARRAY_A){
685
+ $__media = get_object_vars($_media);
686
+
687
+ return $__media;
688
+ } elseif($output == ARRAY_N){
689
+ $__media = array_values(get_object_vars($_media));
690
+
691
+ return $__media;
692
+ } else{
693
+ return $_media;
694
+ }
695
+ }
696
+
697
+ /**
698
+ * Retrieves gmedia data given a post ID or post object.
699
+ * @uses $wpdb
700
+ *
701
+ * @param int|object $post Post ID or gmedia post object.
702
+ * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
703
+ *
704
+ * @return mixed Gmedia data
705
+ */
706
+ function get_post_gmedia($post, $output = OBJECT){
707
+ /** @var $wpdb wpdb */
708
+ global $wpdb;
709
+ $null = null;
710
+
711
+ if(empty($post)){
712
+ return $null;
713
+ }
714
+
715
+ if(is_object($post)){
716
+ $post_id = $post->ID;
717
+ } else{
718
+ $post_id = (int)$post;
719
+ }
720
+
721
+ if(!$_media = wp_cache_get($post_id, 'wpgmedias')){
722
+ $_media = $wpdb->get_row($wpdb->prepare("SELECT {$wpdb->prefix}gmedia.*, wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count FROM {$wpdb->prefix}gmedia LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID) WHERE {$wpdb->prefix}gmedia.post_id = %d LIMIT 1", $post_id));
723
+ if(!$_media){
724
+ return $null;
725
+ }
726
+ wp_cache_add($_media->ID, $_media, 'gmedias');
727
+ if(!empty($_media->post_id)){
728
+ wp_cache_add($_media->post_id, $_media, 'wpgmedias');
729
+ }
730
+ }
731
+
732
+ if($output == OBJECT){
733
+ return $_media;
734
+ } elseif($output == ARRAY_A){
735
+ $__media = get_object_vars($_media);
736
+
737
+ return $__media;
738
+ } elseif($output == ARRAY_N){
739
+ $__media = array_values(get_object_vars($_media));
740
+
741
+ return $__media;
742
+ } else{
743
+ return $_media;
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Retrieve the gmedia posts based on query variables.
749
+ * There are a few filters and actions that can be used to modify the gmedia
750
+ * database query.
751
+ * 'status' (string|array) - Gmedia status
752
+ * 'author' (int) - Display or Exclude gmedias from several specific authors
753
+ * 'author_name' (string) - Author name (nice_name)
754
+ * 'cat' (int) - comma separated list of positive or negative category IDs. Display posts that have this category(ies)
755
+ * 'category_name' (string) - Display posts that have this category, using category name
756
+ * 'category__in' (array) - use category id. Same as 'cat', but does not accept negative values
757
+ * 'category__not_in (array) - use category id. Exclude multiple categories
758
+ * 'alb' (int) - comma separated list of positive or negative album IDs. Display posts that have this album(s)
759
+ * 'album_name' (string) - Display posts that have this album, using album name
760
+ * 'album__in' (array) - use album id. Same as 'alb'
761
+ * 'album__not_in (array) - use album id. Exclude multiple albums
762
+ * 'tag' (string) - use tag name. Display posts that have "either" of tags separated by comma.
763
+ * Display posts that have "all" of tags separated by '+'
764
+ * 'tag_id' (int) - use tag id.
765
+ * 'tag__and' (array) - use tag ids. Display posts that are tagged with all listed tags in array
766
+ * 'tag__in' (array) - use tag ids. To display posts from either tags listed in array. Same as 'tag'
767
+ * 'tag__not_in' (array) - use tag ids. Display posts that do not have any of the listed tag ids
768
+ * 'tag_name__and' (array) - use tag names.
769
+ * 'tag_name__in' (array) - use tag names.
770
+ * 'terms_relation' (string) - allows you to describe the boolean relationship between the taxonomy queries.
771
+ * Possible values are 'OR', 'AND'.
772
+ * 'gmedia_id' (int) - use gmedia id.
773
+ * 'wppost_id' (int) - use gmedia id.
774
+ * 'name' (string) - use gmedia title.
775
+ * 'gmedia__in' (array) - use gmedia ids. Specify posts to retrieve.
776
+ * 'gmedia__not_in' (array) - use gmedia ids. Specify post NOT to retrieve.
777
+ * 'wppost__in' (array) - use gmedia ids. Specify posts to retrieve.
778
+ * 'wppost__not_in' (array) - use gmedia ids. Specify post NOT to retrieve.
779
+ * 'per_page' (int) - number of post to show per page. Use 'per_page'=>-1 to show all posts.
780
+ * 'nopaging' (bool) - show all posts or use pagination. Default value is 'false', use paging.
781
+ * 'page' (int) - number of page. Show the posts that would normally show up just on page X.
782
+ * 'offset' (int) - number of post to displace or pass over. Note: Setting offset parameter will ignore the 'page' parameter.
783
+ * 'order' (string) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'
784
+ * 'orderby' (string) - Sort retrieved posts by parameter. Defaults to 'ID'
785
+ * - 'none' - No order.
786
+ * - 'ID' - Order by gmedia id. Note the captialization.
787
+ * - 'author' - Order by author.
788
+ * - 'title' - Order by title.
789
+ * - 'date' - Order by date.
790
+ * - 'modified' - Order by last modified date.
791
+ * - 'rand' - Random order.
792
+ * - 'gmedia__in' - Order by 'gmedia__in' parameter. Note: 'gmedia__in' parameter must be specified.
793
+ * - 'wppost__in' - Order by 'wppost__in' parameter. Note: 'wppost__in' parameter must be specified.
794
+ * - 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be
795
+ * alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers
796
+ * (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
797
+ * - 'meta_value_num' - Order by numeric meta value. Also note that a 'meta_key=keyname' must also be present in the query.
798
+ * This value allows for numerical sorting as noted above in 'meta_value'.
799
+ * 'm' (int) - Up to 14 numbers. YEAR(4) MONTH(2) DAYOFMONTH(2) HOUR(2) MINUTE(2) SECOND(2).
800
+ * Also you can query with 'year' (int) - 4 digit year; 'monthnum' (int) - Month number (from 1 to 12);
801
+ * 'w' (int) - Week of the year (from 0 to 53); 'day' (int) - Day of the month (from 1 to 31);
802
+ * 'hour' (int) - Hour (from 0 to 23); 'minute' (int) - Minute (from 0 to 60); 'second' (int) - Second (0 to 60).
803
+ * 'meta_key' (string) - Custom field key.
804
+ * 'meta_value' (string) - Custom field value.
805
+ * 'meta_value_num' (number) - Custom field value.
806
+ * 'meta_compare' (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='.
807
+ * 'meta_query' (array) - Custom field parameters (array of associative arrays):
808
+ * - 'key' (string) The meta key
809
+ * - 'value' (string|array) - The meta value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN')
810
+ * - 'compare' (string) - (optional) How to compare the key to the value.
811
+ * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
812
+ * Default: '='
813
+ * - 'type' (string) - (optional) The type of the value.
814
+ * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
815
+ * Default: 'CHAR'
816
+ * 's' (string) - search string or terms separated by comma. Search exactly string if 'exact' parameter set to true
817
+ * 'fields' (string) - 'ids': return an array of gmedia IDs; 'post_ids': return an array of gmedia IDs and post_id's
818
+ * 'robots' - bool Default is empty
819
+ * @see get_posts()
820
+ * @return array List of posts.
821
+ */
822
+ function get_gmedias(){
823
+ /** @var $wpdb wpdb */
824
+ global $wpdb, $_wp_using_ext_object_cache;
825
+
826
+ // First let's clear some variables
827
+ $whichmimetype = '';
828
+ $whichstatus = '';
829
+ $whichauthor = '';
830
+ $where = '';
831
+ $countwhere = '';
832
+ $limits = '';
833
+ $join = '';
834
+ $search = '';
835
+ $groupby = '';
836
+ $fields = '';
837
+ $page = 1;
838
+ $album = array('order' => false,
839
+ 'alias' => ''
840
+ );
841
+ $array = array('null_tags' => false
842
+ );
843
+
844
+ $keys = array('error',
845
+ 'status',
846
+ 'author',
847
+ 'author_name',
848
+ 'cat',
849
+ 'category_name',
850
+ 'alb',
851
+ 'album_name',
852
+ 'tag',
853
+ 'tag_id',
854
+ 'terms_relation',
855
+ 'gmedia_id',
856
+ 'wppost_id',
857
+ 'name',
858
+ 'page',
859
+ 'offset',
860
+ 'm',
861
+ 'year',
862
+ 'monthnum',
863
+ 'w',
864
+ 'day',
865
+ 'hour',
866
+ 'minute',
867
+ 'second',
868
+ 'meta_key',
869
+ 'meta_value',
870
+ 's',
871
+ 'fields',
872
+ 'limit',
873
+ 'robots'
874
+ );
875
+
876
+ foreach($keys as $key){
877
+ if(!isset($array[ $key ])){
878
+ $array[ $key ] = '';
879
+ }
880
+ }
881
+
882
+ $array_keys = array('category__in',
883
+ 'category__not_in',
884
+ 'category__and',
885
+ 'album__in',
886
+ 'album__not_in',
887
+ 'gmedia__in',
888
+ 'gmedia__not_in',
889
+ 'wppost__in',
890
+ 'wppost__not_in',
891
+ 'tag__in',
892
+ 'tag__not_in',
893
+ 'tag__and',
894
+ 'tag_name__in',
895
+ 'tag_name__and',
896
+ 'author__in',
897
+ 'author__not_in',
898
+ 'meta_query'
899
+ );
900
+
901
+ foreach($array_keys as $key){
902
+ if(!isset($array[ $key ])){
903
+ $array[ $key ] = array();
904
+ }
905
+ }
906
+
907
+ $args = func_get_args();
908
+ if(isset($args[0])){
909
+ $q = array_merge($array, $args[0]);
910
+ } else{
911
+ $q = $array;
912
+ }
913
+
914
+ if(!empty($q['robots'])){
915
+ $is_robots = true;
916
+ }
917
+
918
+ $q['gmedia_id'] = absint($q['gmedia_id']);
919
+ $q['wppost_id'] = absint($q['wppost_id']);
920
+ $q['year'] = absint($q['year']);
921
+ $q['monthnum'] = absint($q['monthnum']);
922
+ $q['day'] = absint($q['day']);
923
+ $q['w'] = absint($q['w']);
924
+ $q['m'] = absint($q['m']);
925
+ $q['page'] = absint($q['page']);
926
+ $q['cat'] = preg_replace('|[^0-9,-]|', '', $q['cat']); // comma separated list of positive or negative integers
927
+ $q['alb'] = preg_replace('|[^0-9,-]|', '', $q['alb']); // comma separated list of positive or negative integers
928
+ $q['name'] = trim($q['name']);
929
+ if('' !== $q['hour']){
930
+ $q['hour'] = absint($q['hour']);
931
+ }
932
+ if('' !== $q['minute']){
933
+ $q['minute'] = absint($q['minute']);
934
+ }
935
+ if('' !== $q['second']){
936
+ $q['second'] = absint($q['second']);
937
+ }
938
+
939
+
940
+ if(!isset($q['limit']) || empty($q['limit'])){
941
+ $q['limit'] = 0;
942
+ }
943
+ $q['limit'] = absint($q['limit']);
944
+
945
+ if(!isset($q['per_page']) || empty($q['per_page'])){
946
+ $q['per_page'] = - 1;
947
+ }
948
+ if(!isset($q['nopaging'])){
949
+ if($q['per_page'] == - 1){
950
+ $q['nopaging'] = true;
951
+ } else{
952
+ $q['nopaging'] = false;
953
+ }
954
+ }
955
+ $q['per_page'] = (int)$q['per_page'];
956
+ if($q['per_page'] < - 1){
957
+ $q['per_page'] = abs($q['per_page']);
958
+ }
959
+
960
+ // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
961
+ if(isset($q['no_found_rows'])){
962
+ $q['no_found_rows'] = (bool)$q['no_found_rows'];
963
+ } else{
964
+ $q['no_found_rows'] = false;
965
+ }
966
+
967
+ switch($q['fields']){
968
+ case 'ids':
969
+ $fields = "{$wpdb->prefix}gmedia.ID";
970
+ break;
971
+ case 'post_ids':
972
+ $fields = "{$wpdb->prefix}gmedia.ID, {$wpdb->prefix}gmedia.post_id";
973
+ break;
974
+ default:
975
+ $fields = "{$wpdb->prefix}gmedia.*";
976
+ $fields .= ", wp.ID as post_id, wp.post_name, wp.post_password, wp.comment_status, wp.comment_count";
977
+ }
978
+ $join .= " LEFT JOIN {$wpdb->posts} AS wp ON ({$wpdb->prefix}gmedia.post_id = wp.ID)";
979
+
980
+ // If a month is specified in the querystring, load that month
981
+ if($q['m']){
982
+ $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
983
+ $where .= " AND YEAR({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 0, 4);
984
+ if(strlen($q['m']) > 5){
985
+ $where .= " AND MONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 4, 2);
986
+ }
987
+ if(strlen($q['m']) > 7){
988
+ $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 6, 2);
989
+ }
990
+ if(strlen($q['m']) > 9){
991
+ $where .= " AND HOUR({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 8, 2);
992
+ }
993
+ if(strlen($q['m']) > 11){
994
+ $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 10, 2);
995
+ }
996
+ if(strlen($q['m']) > 13){
997
+ $where .= " AND SECOND({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 12, 2);
998
+ }
999
+ $this->filter['m'] = $q['m'];
1000
+ }
1001
+
1002
+ if('' !== $q['hour']){
1003
+ $where .= " AND HOUR({$wpdb->prefix}gmedia.date)='" . $q['hour'] . "'";
1004
+ $this->filter['hour'] = $q['hour'];
1005
+ }
1006
+
1007
+ if('' !== $q['minute']){
1008
+ $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)='" . $q['minute'] . "'";
1009
+ $this->filter['minute'] = $q['minute'];
1010
+ }
1011
+
1012
+ if('' !== $q['second']){
1013
+ $where .= " AND SECOND({$wpdb->prefix}gmedia.date)='" . $q['second'] . "'";
1014
+ $this->filter['second'] = $q['second'];
1015
+ }
1016
+
1017
+ if($q['year']){
1018
+ $where .= " AND YEAR({$wpdb->prefix}gmedia.date)='" . $q['year'] . "'";
1019
+ $this->filter['year'] = $q['year'];
1020
+ }
1021
+
1022
+ if($q['monthnum']){
1023
+ $where .= " AND MONTH({$wpdb->prefix}gmedia.date)='" . $q['monthnum'] . "'";
1024
+ $this->filter['monthnum'] = $q['monthnum'];
1025
+ }
1026
+
1027
+ if($q['day']){
1028
+ $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)='" . $q['day'] . "'";
1029
+ $this->filter['day'] = $q['day'];
1030
+ }
1031
+
1032
+ if($q['w']){
1033
+ $where .= ' AND ' . _wp_mysql_week("`{$wpdb->prefix}gmedia`.`date`") . " = '" . $q['w'] . "'";
1034
+ $this->filter['w'] = $q['w'];
1035
+ }
1036
+
1037
+ if('' != $q['name']){
1038
+ $q['name'] = esc_sql($q['name']);
1039
+ $where .= " AND {$wpdb->prefix}gmedia.title = '" . $q['name'] . "'";
1040
+ $this->filter['name'] = $q['name'];
1041
+ }
1042
+
1043
+ // If a gmedia number is specified, load that gmedia
1044
+ if($q['gmedia_id']){
1045
+ $where .= " AND {$wpdb->prefix}gmedia.ID = " . $q['gmedia_id'];
1046
+ $this->filter['gmedia__in'] = (array)$q['gmedia_id'];
1047
+ } elseif($q['gmedia__in']){
1048
+ if(!is_array($q['gmedia__in'])){
1049
+ $q['gmedia__in'] = explode(',', $q['gmedia__in']);
1050
+ }
1051
+ $gmedia__in = array_filter(array_map('absint', $q['gmedia__in']));
1052
+ $this->filter['gmedia__in'] = $gmedia__in;
1053
+ $gmedia__in = implode(',', $gmedia__in);
1054
+ if($gmedia__in){
1055
+ $where .= " AND {$wpdb->prefix}gmedia.ID IN ($gmedia__in)";
1056
+ }
1057
+ } elseif($q['gmedia__not_in']){
1058
+ if(!is_array($q['gmedia__not_in'])){
1059
+ $q['gmedia__not_in'] = explode(',', $q['gmedia__not_in']);
1060
+ }
1061
+ $gmedia__not_in = array_filter(array_map('absint', $q['gmedia__not_in']));
1062
+ $this->filter['gmedia__not_in'] = $gmedia__not_in;
1063
+ $gmedia__not_in = implode(',', $gmedia__not_in);
1064
+ if($gmedia__not_in){
1065
+ $where .= " AND {$wpdb->prefix}gmedia.ID NOT IN ($gmedia__not_in)";
1066
+ }
1067
+ }
1068
+
1069
+ // If a linked wp post number is specified, load that gmedia
1070
+ if($q['wppost_id']){
1071
+ $where .= " AND {$wpdb->prefix}gmedia.post_id = " . $q['wppost_id'];
1072
+ $this->filter['wppost__in'] = (array)$q['wppost_id'];
1073
+ } elseif($q['wppost__in']){
1074
+ if(!is_array($q['wppost__in'])){
1075
+ $q['wppost__in'] = explode(',', $q['wppost__in']);
1076
+ }
1077
+ $wppost__in = array_filter(array_map('absint', $q['wppost__in']));
1078
+ $this->filter['wppost__in'] = $wppost__in;
1079
+ $wppost__in = implode(',', $wppost__in);
1080
+ if($wppost__in){
1081
+ $where .= " AND {$wpdb->prefix}gmedia.post_id IN ($wppost__in)";
1082
+ }
1083
+ } elseif($q['wppost__not_in']){
1084
+ if(!is_array($q['wppost__not_in'])){
1085
+ $q['wppost__not_in'] = explode(',', $q['wppost__not_in']);
1086
+ }
1087
+ $wppost__not_in = array_filter(array_map('absint', $q['wppost__not_in']));
1088
+ $this->filter['wppost__not_in'] = $wppost__not_in;
1089
+ $wppost__not_in = implode(',', $wppost__not_in);
1090
+ if($wppost__not_in){
1091
+ $where .= " AND {$wpdb->prefix}gmedia.post_id NOT IN ($wppost__not_in)";
1092
+ }
1093
+ }
1094
+
1095
+ // If a search pattern is specified, load the posts that match
1096
+ if(!empty($q['s'])){
1097
+ // added slashes screw with quote grouping when done early, so done later
1098
+ $q['s'] = stripslashes($q['s']);
1099
+ if(empty($q['exact'])){
1100
+ $q['search_terms'] = array_filter(array_map('trim', explode(' ', $q['s'])));
1101
+ } else{
1102
+ $q['search_terms'] = $q['s'];
1103
+ }
1104
+ $n = '%';
1105
+ $searchand = '';
1106
+ foreach((array)$q['search_terms'] as $term){
1107
+ $term = esc_sql(addcslashes($term, '_%\\'));
1108
+ $search .= "{$searchand}(({$wpdb->prefix}gmedia.title LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.description LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.gmuid LIKE '{$n}{$term}{$n}'))";
1109
+ $searchand = ' AND ';
1110
+ }
1111
+
1112
+ if(!empty($search)){
1113
+ $search = " AND ({$search}) ";
1114
+ /* TODO not display private media when user not logged in
1115
+ if ( !is_user_logged_in() )
1116
+ $search .= " AND ({$wpdb->prefix}gmedia_meta.password = '') ";
1117
+ */
1118
+ $this->filter['s'] = (array)$q['search_terms'];
1119
+ }
1120
+ }
1121
+
1122
+ // Category stuff
1123
+ $this->gmedias_category_stuff($q);
1124
+
1125
+ if(!empty($q['category__and']) && 1 === count((array)$q['category__and'])){
1126
+ $q['category__and'] = (array)$q['category__and'];
1127
+ if(!isset($q['category__in'])){
1128
+ $q['category__in'] = array();
1129
+ }
1130
+ $q['category__in'][] = absint(reset($q['category__and']));
1131
+ unset($q['category__and']);
1132
+ }
1133
+
1134
+ if(!empty($q['category__in'])){
1135
+ $tax_query[] = array('taxonomy' => 'gmedia_category',
1136
+ 'terms' => $q['category__in'],
1137
+ 'operator' => 'IN'
1138
+ );
1139
+ }
1140
+
1141
+ if(!empty($q['category__not_in'])){
1142
+ $tax_query[] = array('taxonomy' => 'gmedia_category',
1143
+ 'terms' => $q['category__not_in'],
1144
+ 'operator' => 'NOT IN'
1145
+ );
1146
+ }
1147
+
1148
+ if(!empty($q['category__and'])){
1149
+ $tax_query[] = array('taxonomy' => 'gmedia_category',
1150
+ 'terms' => $q['category__and'],
1151
+ 'operator' => 'AND'
1152
+ );
1153
+ }
1154
+
1155
+ // Album stuff
1156
+ $this->gmedias_album_stuff($q);
1157
+
1158
+ if(!empty($q['album__in'])){
1159
+ $tax_query[] = array('taxonomy' => 'gmedia_album',
1160
+ 'terms' => $q['album__in'],
1161
+ 'operator' => 'IN'
1162
+ );
1163
+ if(1 == count($q['album__in'])){
1164
+ $album['order'] = true;
1165
+ }
1166
+ }
1167
+
1168
+ if(!empty($q['album__not_in'])){
1169
+ $tax_query[] = array('taxonomy' => 'gmedia_album',
1170
+ 'terms' => $q['album__not_in'],
1171
+ 'operator' => 'NOT IN'
1172
+ );
1173
+ }
1174
+
1175
+ // Tag stuff
1176
+ $this->gmedias_tag_stuff($q);
1177
+
1178
+ if(!empty($q['tag__in'])){
1179
+ $tax_query[] = array('taxonomy' => 'gmedia_tag',
1180
+ 'terms' => $q['tag__in'],
1181
+ 'operator' => 'IN'
1182
+ );
1183
+ }
1184
+
1185
+ if(!empty($q['tag__not_in'])){
1186
+ $tax_query[] = array('taxonomy' => 'gmedia_tag',
1187
+ 'terms' => $q['tag__not_in'],
1188
+ 'operator' => 'NOT IN'
1189
+ );
1190
+ }
1191
+
1192
+ if(!empty($q['tag__and'])){
1193
+ $tax_query[] = array('taxonomy' => 'gmedia_tag',
1194
+ 'terms' => $q['tag__and'],
1195
+ 'operator' => 'AND'
1196
+ );
1197
+ }
1198
+
1199
+ if(!empty($q['tag_name__in']) || (isset($q['tag_name__in_null']) && $q['null_tags'])){
1200
+ $tax_query[] = array('taxonomy' => 'gmedia_tag',
1201
+ 'terms' => $q['tag_name__in'],
1202
+ 'operator' => 'IN'
1203
+ );
1204
+ }
1205
+
1206
+ if(!empty($q['tag_name__and']) || (isset($q['tag_name__and_null']) && $q['null_tags'])){
1207
+ $tax_query[] = array('taxonomy' => 'gmedia_tag',
1208
+ 'terms' => $q['tag_name__and'],
1209
+ 'operator' => 'AND'
1210
+ );
1211
+ }
1212
+
1213
+ if(!empty($tax_query)){
1214
+ if(isset($q['terms_relation']) && strtoupper($q['terms_relation']) == 'AND'){
1215
+ $terms_relation = 'AND';
1216
+ } else{
1217
+ $terms_relation = 'OR';
1218
+ }
1219
+ $clauses['join'] = '';
1220
+ $clauses['where'] = array();
1221
+ $i = 0;
1222
+ foreach($tax_query as $query){
1223
+ /** @var $taxonomy
1224
+ * @var $terms
1225
+ * @var $field
1226
+ * @var $operator
1227
+ * @var $include_children
1228
+ */
1229
+ extract($query);
1230
+
1231
+ $taxterm = str_replace('gmedia_', '', $taxonomy);
1232
+
1233
+ if('IN' == $operator){
1234
+
1235
+ if(empty($terms)){
1236
+ continue;
1237
+ }
1238
+
1239
+ $this->filter["{$taxterm}__in"] = $terms;
1240
+ $terms = implode(',', $terms);
1241
+
1242
+ $alias = $i? 'tr' . $i : 'tr';
1243
+
1244
+ $clauses['join'] .= " INNER JOIN {$wpdb->prefix}gmedia_term_relationships AS $alias";
1245
+ $clauses['join'] .= " ON ({$wpdb->prefix}gmedia.ID = $alias.gmedia_id)";
1246
+
1247
+ $clauses['where'][] = "$alias.gmedia_term_id $operator ($terms)";
1248
+
1249
+ if($album['order'] && ('gmedia_album' == $taxonomy)){
1250
+ $album['alias'] = $alias;
1251
+ if('ids' != $q['fields'] || 'post_ids' != $q['fields']){
1252
+ $fields .= ", $alias.*";
1253
+ }
1254
+ }
1255
+ } elseif('NOT IN' == $operator){
1256
+
1257
+ if(empty($terms)){
1258
+ continue;
1259
+ }
1260
+
1261
+ $this->filter["{$taxterm}__not_in"] = $terms;
1262
+ $terms = implode(',', $terms);
1263
+
1264
+ $clauses['where'][] = "{$wpdb->prefix}gmedia.ID NOT IN (
1265
+ SELECT gmedia_id
1266
+ FROM {$wpdb->prefix}gmedia_term_relationships
1267
+ WHERE gmedia_term_id IN ($terms)
1268
+ )";
1269
+ } elseif('AND' == $operator){
1270
+
1271
+ if(empty($terms)){
1272
+ continue;
1273
+ }
1274
+
1275
+ $num_terms = count($terms);
1276
+
1277
+ $this->filter["{$taxterm}__and"] = $terms;
1278
+ $terms = implode(',', $terms);
1279
+
1280
+ $clauses['where'][] = "(
1281
+ SELECT COUNT(1)
1282
+ FROM {$wpdb->prefix}gmedia_term_relationships
1283
+ WHERE gmedia_term_id IN ($terms)
1284
+ AND gmedia_id = {$wpdb->prefix}gmedia.ID
1285
+ ) = $num_terms";
1286
+ }
1287
+
1288
+ $i ++;
1289
+ }
1290
+
1291
+ if(!empty($clauses['where'])){
1292
+ $clauses['where'] = ' AND ( ' . implode(" $terms_relation ", $clauses['where']) . ' )';
1293
+ } else{
1294
+ $clauses['where'] = '';
1295
+ }
1296
+
1297
+ $join .= $clauses['join'];
1298
+ $where .= $clauses['where'];
1299
+ }
1300
+
1301
+ // Meta stuff
1302
+ $meta_query = array();
1303
+ // Simple query needs to be first for orderby=meta_value to work correctly
1304
+ foreach(array('key', 'compare', 'type') as $key){
1305
+ if(!empty($q["meta_$key"])){
1306
+ $meta_query[0][ $key ] = $q["meta_$key"];
1307
+ }
1308
+ }
1309
+ // Query sets 'meta_value' = '' by default
1310
+ if(isset($q['meta_value']) && !empty($q['meta_value'])){
1311
+ $meta_query[0]['value'] = $q['meta_value'];
1312
+ }
1313
+
1314
+ if(!empty($q['meta_query']) && is_array($q['meta_query'])){
1315
+ $meta_query = array_merge($meta_query, $q['meta_query']);
1316
+ }
1317
+ if(!empty($meta_query)){
1318
+ $primary_table = $wpdb->prefix . 'gmedia';
1319
+ $primary_id_column = 'ID';
1320
+ $meta_table = $wpdb->prefix . 'gmedia_meta';
1321
+ $meta_id_column = 'gmedia_id';
1322
+
1323
+ if(isset($meta_query['relation']) && strtoupper($meta_query['relation']) == 'OR'){
1324
+ $relation = 'OR';
1325
+ } else{
1326
+ $relation = 'AND';
1327
+ }
1328
+ $meta_query = array_filter($meta_query, 'is_array');
1329
+
1330
+ $clauses['join'] = array();
1331
+ $clauses['where'] = array();
1332
+
1333
+ foreach($meta_query as $key => $query){
1334
+ if(!isset($query['key']) || empty($query['key'])){
1335
+ continue;
1336
+ }
1337
+ $meta_key = trim($query['key']);
1338
+ $meta_type = isset($query['type'])? strtoupper($query['type']) : 'CHAR';
1339
+
1340
+ if('NUMERIC' == $meta_type){
1341
+ $meta_type = 'SIGNED';
1342
+ } elseif(!in_array($meta_type, array('BINARY',
1343
+ 'CHAR',
1344
+ 'DATE',
1345
+ 'DATETIME',
1346
+ 'DECIMAL',
1347
+ 'SIGNED',
1348
+ 'TIME',
1349
+ 'UNSIGNED'
1350
+ ))
1351
+ ){
1352
+ $meta_type = 'CHAR';
1353
+ }
1354
+
1355
+ $i = count($clauses['join']);
1356
+ $alias = $i? 'mt' . $i : $meta_table;
1357
+
1358
+ // Set JOIN
1359
+ $clauses['join'][ $i ] = "INNER JOIN $meta_table";
1360
+ $clauses['join'][ $i ] .= $i? " AS $alias" : '';
1361
+ $clauses['join'][ $i ] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
1362
+
1363
+ $clauses['where'][ $key ] = '';
1364
+ if(!empty($meta_key)){
1365
+ $clauses['where'][ $key ] = $wpdb->prepare("$alias.meta_key = %s", $meta_key);
1366
+ }
1367
+
1368
+ if(!isset($query['value'])){
1369
+ if(empty($clauses['where'][ $key ])){
1370
+ unset($clauses['join'][ $i ]);
1371
+ }
1372
+ continue;
1373
+ }
1374
+
1375
+ $meta_value = $query['value'];
1376
+
1377
+ $meta_compare = is_array($meta_value)? 'IN' : '=';
1378
+ if(isset($query['compare'])){
1379
+ $meta_compare = strtoupper($query['compare']);
1380
+ }
1381
+
1382
+ if(!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))){
1383
+ $meta_compare = '=';
1384
+ }
1385
+
1386
+ if(in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))){
1387
+ if(!is_array($meta_value)){
1388
+ $meta_value = preg_split('/[,\s]+/', $meta_value);
1389
+ }
1390
+
1391
+ if(empty($meta_value)){
1392
+ unset($clauses['join'][ $i ]);
1393
+ continue;
1394
+ }
1395
+ } else{
1396
+ $meta_value = trim($meta_value);
1397
+ }
1398
+
1399
+ if('IN' == substr($meta_compare, - 2)){
1400
+ $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')';
1401
+ } elseif('BETWEEN' == substr($meta_compare, - 7)){
1402
+ $meta_value = array_slice($meta_value, 0, 2);
1403
+ $meta_compare_string = '%s AND %s';
1404
+ } elseif('LIKE' == substr($meta_compare, - 4)){
1405
+ $meta_value = '%' . addcslashes($meta_value, '_%\\') . '%';
1406
+ $meta_compare_string = '%s';
1407
+ } else{
1408
+ $meta_compare_string = '%s';
1409
+ }
1410
+
1411
+ if(!empty($clauses['where'][ $key ])){
1412
+ $clauses['where'][ $key ] .= ' AND ';
1413
+ }
1414
+
1415
+ $clauses['where'][ $key ] = ' (' . $clauses['where'][ $key ] . $wpdb->prepare("CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value);
1416
+ }
1417
+
1418
+ $clauses['where'] = array_filter($clauses['where']);
1419
+
1420
+ if(empty($clauses['where'])){
1421
+ $clauses['where'] = '';
1422
+ } else{
1423
+ $clauses['where'] = ' AND (' . implode("\n{$relation} ", $clauses['where']) . ' )';
1424
+ }
1425
+
1426
+ $clauses['join'] = implode("\n", $clauses['join']);
1427
+ if(!empty($clauses['join'])){
1428
+ $clauses['join'] = ' ' . $clauses['join'];
1429
+ }
1430
+
1431
+ $join .= $clauses['join'];
1432
+ $where .= $clauses['where'];
1433
+
1434
+ $this->filter['meta_query'] = $meta_query;
1435
+ }
1436
+ unset($clauses);
1437
+
1438
+ if(!empty($tax_query) || !empty($meta_query)){
1439
+ $groupby = "{$wpdb->prefix}gmedia.ID";
1440
+ }
1441
+
1442
+ // Status
1443
+ if($q['status']){
1444
+ $q['status'] = array_map('esc_sql', array_unique((array)$q['status']));
1445
+ $this->filter['status'] = $q['status'];
1446
+ $status = "'" . str_replace(",", "','", implode(",", $q['status'])) . "'";
1447
+ $whichstatus .= " AND {$wpdb->prefix}gmedia.status IN ({$status})";
1448
+ }
1449
+
1450
+ // Author/user stuff for ID
1451
+ if(!empty($q['author']) && $q['author'] != '0'){
1452
+ $q['author'] = addslashes_gpc('' . urldecode($q['author']));
1453
  $authors = array_unique(array_map('intval', preg_split('/[,\s]+/', $q['author'])));
1454
+ foreach($authors as $author){
1455
+ $key = $author > 0? 'author__in' : 'author__not_in';
1456
+ $q[ $key ][] = abs($author);
1457
+ }
1458
+ $q['author'] = implode(',', $authors);
1459
+ }
1460
+
1461
+ if(!empty($q['author__not_in'])){
1462
+ $author__not_in = array_map('absint', array_unique(wp_parse_id_list($q['author__not_in'])));
1463
+ $this->filter['author__not_in'] = $author__not_in;
1464
+ $author__not_in = implode(',', $author__not_in);
1465
+ $whichauthor .= " AND {$wpdb->prefix}gmedia.author NOT IN ($author__not_in) ";
1466
+ } elseif(!empty($q['author__in'])){
1467
+ $author__in = array_map('absint', array_unique(wp_parse_id_list($q['author__in'])));
1468
+ $this->filter['author__in'] = $author__in;
1469
+ $author__in = implode(',', $author__in);
1470
+ $whichauthor .= " AND {$wpdb->prefix}gmedia.author IN ($author__in) ";
1471
+ }
1472
+
1473
+ // Author stuff for name
1474
+ if('' != $q['author_name']){
1475
+ $q['author_name'] = esc_sql($q['author_name']);
1476
+ $author = get_user_by('slug', $q['author_name']);
1477
+ if($author){
1478
+ $q['author'] = $author->ID;
1479
+ $whichauthor .= " AND ({$wpdb->prefix}gmedia.author = " . absint($q['author']) . ')';
1480
+ $this->filter['author__in'] = $q['author'];
1481
+ }
1482
+ }
1483
+
1484
+ // MIME-Type stuff
1485
+ if(isset($q['mime_type']) && !empty($q['mime_type'])){
1486
+ if(is_string($q['mime_type'])){
1487
+ $q['mime_type'] = array_map('trim', explode(',', $q['mime_type']));
1488
+ }
1489
+ $whichmimetype = $this->gmedia_mime_type_where($q['mime_type'], $wpdb->prefix . 'gmedia');
1490
+ $this->filter['mime_type'] = $q['mime_type'];
1491
+ }
1492
+
1493
+ $where .= $whichstatus . $search;
1494
+
1495
+ $empty_order = empty($q['order']);
1496
+ if($empty_order || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))){
1497
+ $q['order'] = 'DESC';
1498
+ }
1499
+
1500
+ // Order by
1501
+ if(empty($q['orderby']) || ('none' == $q['orderby'])){
1502
+ $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
1503
+ } else{
1504
+ // Used to filter values
1505
+ $allowed_keys = array('ID', 'author', 'date', 'title', 'filename', 'gmuid', 'modified', 'mime_type', 'gmedia__in', 'rand', 'comment_count');
1506
+ if($album['order'] && !empty($album['alias'])){
1507
+ $allowed_keys[] = 'custom';
1508
+ }
1509
+ $q['orderby'] = urldecode($q['orderby']);
1510
+ $q['orderby'] = addslashes_gpc($q['orderby']);
1511
+ if(in_array($q['orderby'], array('_created_timestamp', 'views', 'likes', '_size'))){
1512
+ $q['meta_key'] = $q['orderby'];
1513
+ $q['orderby'] = 'meta_value_num';
1514
+ $join .= " LEFT JOIN {$wpdb->prefix}gmedia_meta ON ({$wpdb->prefix}gmedia.ID = {$wpdb->prefix}gmedia_meta.gmedia_id AND " . $wpdb->prepare("{$wpdb->prefix}gmedia_meta.meta_key = %s", $q['meta_key']) . ")";
1515
+ }
1516
+ if(!empty($q['meta_key']) || !empty($q['meta_query'])){
1517
+ if(!empty($q['meta_key'])) {
1518
+ $allowed_keys[] = $q['meta_key'];
1519
+ }
1520
+ $allowed_keys[] = 'meta_value';
1521
+ $allowed_keys[] = 'meta_value_num';
1522
+ }
1523
+ if(in_array($q['orderby'], array('custom', 'title', 'date', 'modified', 'comment_count', 'meta_value', 'meta_value_num'))){
1524
+ $q['orderby'] .= ' ID.DESC';
1525
+ $allowed_keys[] = 'ID.DESC';
1526
+ }
1527
+ $orderby_array = array();
1528
+ foreach(explode(' ', $q['orderby']) as $_orderby){
1529
+ // Only allow certain values for safety
1530
+ if(!in_array($_orderby, $allowed_keys)){
1531
+ continue;
1532
+ }
1533
+
1534
+ switch($_orderby){
1535
+ case 'rand':
1536
+ $orderby = 'RAND()';
1537
+ break;
1538
+ case $q['meta_key']:
1539
+ case 'meta_value':
1540
+ $orderby = "{$wpdb->prefix}gmedia_meta.meta_value";
1541
+ break;
1542
+ case 'meta_value_num':
1543
+ $orderby = "{$wpdb->prefix}gmedia_meta.meta_value+0";
1544
+ break;
1545
+ case 'gmedia__in':
1546
+ if(count($q['gmedia__in']) > 1){
1547
+ $orderby = "FIELD({$wpdb->prefix}gmedia.ID, " . join(', ', $q['gmedia__in']) . ")";
1548
+ } else{
1549
+ $orderby = "{$wpdb->prefix}gmedia.ID";
1550
+ }
1551
+ if($empty_order) {
1552
+ $q['order'] = 'ASC';
1553
+ }
1554
+ break;
1555
+ case 'filename':
1556
+ $orderby = "{$wpdb->prefix}gmedia.gmuid";
1557
+ break;
1558
+ case 'custom':
1559
+ $orderby = "{$album['alias']}.gmedia_order";
1560
+ break;
1561
+ case 'comment_count':
1562
+ $orderby = "wp.comment_count";
1563
+ break;
1564
+ case 'ID.DESC':
1565
+ $orderby = "{$wpdb->prefix}gmedia.ID";
1566
+ break;
1567
+ default:
1568
+ $orderby = "{$wpdb->prefix}gmedia." . $_orderby;
1569
+ }
1570
+
1571
+ if('ID.DESC' !== $_orderby){
1572
+ $orderby .= " {$q['order']}";
1573
+ } else{
1574
+ $orderby .= " DESC";
1575
+ }
1576
+ $orderby_array[] = $orderby;
1577
+ }
1578
+ $orderby = implode(', ', $orderby_array);
1579
+
1580
+ if(empty($orderby)){
1581
+ $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
1582
+ }
1583
+ }
1584
+
1585
+ // Paging
1586
+ $page = $q['page'];
1587
+ if(empty($page)){
1588
+ $page = 1;
1589
+ }
1590
+ if(empty($q['nopaging'])){
1591
+ if($q['limit'] && ($q['per_page'] > $q['limit'])){
1592
+ $q['per_page'] = $q['limit'];
1593
+ }
1594
+ if(empty($q['offset']) && ((0 != $q['offset']) || ('0' != $q['offset']))){
1595
+ $per_page = $q['per_page'];
1596
+ $offset = ($page - 1) * $per_page;
1597
+ if($q['limit'] && (($offset + $per_page) > $q['limit'])){
1598
+ $per_page = $q['limit'] - $offset;
1599
+ if(0 > $per_page){
1600
+ $per_page = 0;
1601
+ }
1602
+ }
1603
+ $pgstrt = $offset . ', ';
1604
+ $limits = 'LIMIT ' . $pgstrt . $per_page;
1605
+ } else{ // we're ignoring $page and using 'offset'
1606
+ $q['offset'] = absint($q['offset']);
1607
+ $pgstrt = $q['offset'] . ', ';
1608
+ $limits = 'LIMIT ' . $pgstrt . $q['per_page'];
1609
+ $this->resultLimited = true;
1610
+ }
1611
+ } elseif($q['limit']){
1612
+ $limits = 'LIMIT ' . $q['limit'];
1613
+ }
1614
+
1615
+ // Announce current selection parameters. For use by caching plugins.
1616
+ do_action('gmedia_selection', $where . $whichauthor . $whichmimetype . $groupby . $orderby . $limits . $join);
1617
+
1618
+ if(!empty($groupby)){
1619
+ $groupby = 'GROUP BY ' . $groupby;
1620
+ }
1621
+ if(!empty($orderby)){
1622
+ $orderby = 'ORDER BY ' . $orderby;
1623
+ }
1624
+
1625
+ $found_rows = '';
1626
+ if(!$q['no_found_rows'] && !empty($limits)){
1627
+ $found_rows = 'SQL_CALC_FOUND_ROWS';
1628
+ }
1629
+
1630
+ $this->sql_query = "SELECT $found_rows $fields FROM {$wpdb->prefix}gmedia $join WHERE 1=1 $where $whichauthor $whichmimetype $groupby $orderby $limits";
1631
+
1632
+ $clauses = compact('join', 'where', 'whichauthor', 'whichmimetype', 'groupby', 'orderby', 'limits');
1633
+ $this->clauses = $clauses;
1634
+
1635
+ if('ids' == $q['fields']){
1636
+ $gmedias = $wpdb->get_col($this->sql_query);
1637
+
1638
+ return $gmedias;
1639
+ }
1640
+
1641
+ $gmedias = $wpdb->get_results($this->sql_query);
1642
+
1643
+ if('post_ids' == $q['fields']){
1644
+
1645
+ return $gmedias;
1646
+ }
1647
+
1648
+ $gmedia_count = count($gmedias);
1649
+
1650
+ if(!$q['no_found_rows'] && !empty($limits)){
1651
+ $this->totalResult = (int)$wpdb->get_var('SELECT FOUND_ROWS()');
1652
+ if($q['limit']){
1653
+ $this->hardlimit = $q['limit'];
1654
+ $this->trueTotalResult = $this->totalResult;
1655
+ if($this->totalResult > $q['limit']){
1656
+ $this->totalResult = $q['limit'];
1657
+ }
1658
+ }
1659
+ } else{
1660
+ $this->totalResult = $gmedia_count;
1661
+ $this->trueTotalResult = $this->totalResult;
1662
+ }
1663
+ if($q['per_page'] && (- 1 != $q['per_page'])){
1664
+ $this->pages = ceil($this->totalResult / $q['per_page']);
1665
+ $this->perPages = (int)$q['per_page'];
1666
+ } else{
1667
+ $this->pages = 1;
1668
+ $this->perPages = $gmedia_count;
1669
+ }
1670
+ $this->openPage = $page;
1671
+ $this->resultPerPage = $gmedia_count;
1672
+
1673
+ if(!isset($q['cache_results'])){
1674
+ if($_wp_using_ext_object_cache){
1675
+ $q['cache_results'] = false;
1676
+ } else{
1677
+ $q['cache_results'] = true;
1678
+ }
1679
+ }
1680
+
1681
+ if(!isset($q['update_gmedia_term_cache'])){
1682
+ $q['update_gmedia_term_cache'] = true;
1683
+ }
1684
+
1685
+ if(!isset($q['update_gmedia_meta_cache'])){
1686
+ $q['update_gmedia_meta_cache'] = true;
1687
+ }
1688
+
1689
+ if($q['cache_results']){
1690
+ $this->update_gmedia_caches($gmedias, $q['update_gmedia_term_cache'], $q['update_gmedia_meta_cache']);
1691
+ }
1692
+
1693
+ if($gmedia_count > 0){
1694
+ $this->gmedia = $gmedias[0];
1695
+ }
1696
+ $this->query = $gmedias;
1697
+
1698
+ return $gmedias;
1699
+ }
1700
+
1701
+ /**
1702
+ * @return array
1703
+ */
1704
+ public function get_duplicates(){
1705
+ global $wpdb;
1706
+
1707
+ // $sql = "SELECT gmedia_id, meta_value, COUNT(*) AS dups FROM {$wpdb->prefix}gmedia_meta GROUP BY meta_value HAVING dups > 1";
1708
+ $sql = "SELECT DISTINCT g.gmedia_id, g.meta_value, g2.dupe_count
1709
+ FROM {$wpdb->prefix}gmedia_meta AS g
1710
+ JOIN (
1711
+ SELECT count(*) AS dupe_count, meta_value
1712
+ FROM {$wpdb->prefix}gmedia_meta
1713
+ WHERE meta_key = '_hash'
1714
+ GROUP BY meta_value
1715
+ HAVING dupe_count > 1
1716
+ ) AS g2 ON g.meta_value = g2.meta_value ORDER BY g.meta_value, g.gmedia_id ASC;";
1717
+
1718
+ $duplicate_ids = array();
1719
+ $duplicate_hashes = array();
1720
+ $duplicate_select = array();
1721
+
1722
+ $duplicates = $wpdb->get_results($sql);
1723
+
1724
+ if($duplicates){
1725
+ foreach($duplicates as $dups){
1726
+ $duplicate_ids[] = $dups->gmedia_id;
1727
+ if(!isset($duplicate_hashes[ $dups->meta_value ])){
1728
+ $duplicate_hashes[ $dups->meta_value ] = $dups->dupe_count;
1729
+ } else{
1730
+ $duplicate_select[] = $dups->gmedia_id;
1731
+ }
1732
+ }
1733
+ $duplicate_ids = array_reverse($duplicate_ids);
1734
+ }
1735
+
1736
+ return compact('duplicate_ids', 'duplicate_select', 'duplicate_hashes');
1737
+ }
1738
+
1739
+ /**
1740
+ * Category stuff for gmedia query.
1741
+ *
1742
+ * @param $q
1743
+ */
1744
+ function gmedias_category_stuff(&$q){
1745
+ global $wpdb;
1746
+
1747
+ if(isset($q['category_name']) && !empty($q['category_name'])){
1748
+ $q['category_name'] = "'" . esc_sql($q['category_name']) . "'";
1749
+ $cat = $wpdb->get_var("
1750
+ SELECT term_id
1751
+ FROM {$wpdb->prefix}gmedia_term
1752
+ WHERE taxonomy = 'gmedia_category'
1753
+ AND name = {$q['category_name']}
1754
+ ");
1755
+ if($cat){
1756
+ unset($q['category_name']);
1757
+ $q['category__in'][] = $cat;
1758
+ }
1759
+ }
1760
+ if(isset($q['cat'])){
1761
+ if(!empty($q['cat']) && ('0' !== $q['cat']) && (0 !== $q['cat'])){
1762
+ $q['cat'] = '' . urldecode($q['cat']) . '';
1763
+ $q['cat'] = addslashes_gpc($q['cat']);
1764
+ $cat_array = preg_split('/[,\s]+/', $q['cat']);
1765
+ $q['cat'] = '';
1766
+ $req_cats = array();
1767
+ foreach((array)$cat_array as $cat){
1768
+ $cat = intval($cat, 10);
1769
+ $req_cats[] = $cat;
1770
+ $in = ($cat >= 0);
1771
+ $cat = abs($cat);
1772
+ if($in){
1773
+ $q['category__in'][] = $cat;
1774
+ } else{
1775
+ $q['category__not_in'][] = $cat;
1776
+ }
1777
+ }
1778
+ $q['cat'] = implode(',', $req_cats);
1779
+ } elseif(('0' === $q['cat']) || (0 === $q['cat'])){
1780
+ $q['category__not_in'] = $this->get_terms('gmedia_category', array('fields' => 'ids'));
1781
+ $q['without_category'] = true;
1782
+ }
1783
+ }
1784
+
1785
+ if(isset($q['category__in']) && (!empty($q['category__in']) || ('0' === $q['category__in']) || (0 === $q['category__in']))){
1786
+ $q['category__in'] = wp_parse_id_list($q['category__in']);
1787
+ if(in_array(0, $q['category__in'])){
1788
+ $q['category__in'] = array_filter($q['category__in']);
1789
+ $q['category__not_in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__in']);
1790
+ $q['without_category'] = true;
1791
+ if(!empty($q['category__in'])){
1792
+ $q['with_category__in'] = $q['category__in'];
1793
+ }
1794
+ $q['category__in'] = array();
1795
+ }
1796
+ }
1797
+ if(isset($q['category__not_in']) && (!empty($q['category__not_in']) || ('0' === $q['category__not_in']) || (0 === $q['category__not_in']))){
1798
+ $q['category__not_in'] = wp_parse_id_list($q['category__not_in']);
1799
+ if(in_array(0, $q['category__not_in'])){
1800
+ $q['category__not_in'] = array_filter($q['category__not_in']);
1801
+ $q['category__in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__not_in']);
1802
+ $q['within_category'] = true;
1803
+ if(!empty($q['category__not_in'])){
1804
+ $q['with_category__not_in'] = $q['category__not_in'];
1805
+ }
1806
+ $q['category__not_in'] = array();
1807
+ }
1808
+ }
1809
+ if(isset($q['category__and']) && !empty($q['category__and'])){
1810
+ $q['category__and'] = wp_parse_id_list($q['category__and']);
1811
+ }
1812
+
1813
+ }
1814
+
1815
+ /**
1816
+ * Album stuff for gmedia query.
1817
+ *
1818
+ * @param $q
1819
+ */
1820
+ function gmedias_album_stuff(&$q){
1821
+ global $wpdb;
1822
+
1823
+ $date_order = false;
1824
+ if ( ! empty( $q['albums_order'] ) ) {
1825
+ $order_by = explode( '_', $q['albums_order'] );
1826
+ $albums_orderby = $order_by[0];
1827
+ if ( 'date' === $albums_orderby ) {
1828
+ $albums_orderby = 'id';
1829
+ $date_order = true;
1830
+ }
1831
+ $albums_order = ( isset( $order_by[1] ) && 'desc' === $order_by[1] ) ? 'DESC' : 'ASC';
1832
+ } else {
1833
+ $albums_orderby = 'include';
1834
+ $albums_order = 'ASC';
1835
+ }
1836
+
1837
+ if(isset($q['album_name']) && !empty($q['album_name'])){
1838
+ $q['album_name'] = "'" . esc_sql($q['album_name']) . "'";
1839
+ $alb = $wpdb->get_var("
1840
+ SELECT term_id
1841
+ FROM {$wpdb->prefix}gmedia_term
1842
+ WHERE taxonomy = 'gmedia_album'
1843
+ AND name = {$q['album_name']}
1844
+ ");
1845
+ if($alb){
1846
+ unset($q['album_name']);
1847
+ $q['album__in'][] = $alb;
1848
+ }
1849
+ }
1850
+ if(isset($q['alb'])){
1851
+ if(!empty($q['alb']) && ('0' !== $q['alb']) && (0 !== $q['alb'])){
1852
+ $q['alb'] = '' . urldecode($q['alb']) . '';
1853
+ $q['alb'] = addslashes_gpc($q['alb']);
1854
+ $alb_array = preg_split('/[,\s]+/', $q['alb']);
1855
+ $q['alb'] = '';
1856
+ $req_albs = array();
1857
+ foreach((array)$alb_array as $alb){
1858
+ if(!($alb = intval($alb, 10))){
1859
+ continue;
1860
+ }
1861
+ $in = ($alb >= 0);
1862
+ $alb = abs($alb);
1863
+ if($in){
1864
+ /*if(isset($q['album__status'])){
1865
+ $alb_obj = $this->get_term($alb, 'gmedia_album');
1866
+ if(empty($alb_obj) || (is_wp_error($alb_obj) || !in_array($alb_obj->status, (array) $q['album__status']))){
1867
+ continue;
1868
+ }
1869
+ }*/
1870
+ $q['album__in'][] = $alb;
1871
+ $req_albs[] = $alb;
1872
+ } else{
1873
+ $q['album__not_in'][] = $alb;
1874
+ $req_albs[] = - $alb;
1875
+ }
1876
+ }
1877
+ $q['alb'] = implode(',', $req_albs);
1878
+ } elseif(('0' === $q['alb']) || (0 === $q['alb'])){
1879
+ $q['album__not_in'] = $this->get_terms('gmedia_album', array('fields' => 'ids'));
1880
+ $q['without_album'] = true;
1881
+ }
1882
+ }
1883
+
1884
+ if(isset($q['album__in']) && (!empty($q['album__in']) || ('0' === $q['album__in']) || (0 === $q['album__in']))){
1885
+ $q['album__in'] = wp_parse_id_list($q['album__in']);
1886
+ $without_album = in_array(0, $q['album__in'])? true : false;
1887
+ if(isset($q['album__status'])){
1888
+ $q['album__in'] = $this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'include' => $q['album__in'], 'status' => $q['album__status']));
1889
+ } elseif('include' !== $albums_orderby && 'id' !== $albums_orderby) {
1890
+ $q['album__in'] = $this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'include' => $q['album__in']));
1891
+ } elseif('id' === $albums_orderby) {
1892
+ if('ASC' === $albums_order) {
1893
+ sort( $q['album__in'] );
1894
+ } else {
1895
+ rsort( $q['album__in'] );
1896
+ }
1897
+ }
1898
+ if($without_album){
1899
+ $q['album__in'] = array_filter($q['album__in']);
1900
+ $q['album__not_in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids')), $q['album__in']);
1901
+ $q['without_album'] = true;
1902
+ if(!empty($q['album__in'])){
1903
+ $q['with_album__in'] = $q['album__in'];
1904
+ }
1905
+ $q['album__in'] = array();
1906
+ }
1907
+ }
1908
+ if(isset($q['album__not_in']) && (!empty($q['album__not_in']) || ('0' === $q['album__not_in']) || (0 === $q['album__not_in']))){
1909
+ $q['album__not_in'] = wp_parse_id_list($q['album__not_in']);
1910
+ if(in_array(0, $q['album__not_in'])){
1911
+ $q['album__not_in'] = array_filter($q['album__not_in']);
1912
+ if(isset($q['album__status'])){
1913
+ $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order, 'status' => $q['album__status'])), $q['album__not_in']);
1914
+ } else{
1915
+ $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => $albums_orderby, 'order' => $albums_order)), $q['album__not_in']);
1916
+ }
1917
+ $q['within_album'] = true;
1918
+ if(!empty($q['album__not_in'])){
1919
+ $q['with_album__not_in'] = $q['album__not_in'];
1920
+ }
1921
+ $q['album__not_in'] = array();
1922
+ }
1923
+ }
1924
+
1925
+ if ( $date_order && ! empty( $q['album__in'] ) ) {
1926
+ $gmedia_albums = get_posts( array(
1927
+ 'posts_per_page' => -1,
1928
+ 'post_type' => 'gmedia_album',
1929
+ 'post_status' => 'any',
1930
+ 'order_by' => 'post_date',
1931
+ 'order' => $albums_order,
1932
+ 'meta_key' => '_gmedia_term_ID',
1933
+ 'meta_compare' => 'IN',
1934
+ 'meta_value' => $q['album__in'],
1935
+ 'suppress_filters' => true,
1936
+ ) );
1937
+ $alb_in_by_date = array();
1938
+ foreach ( $gmedia_albums as $gm_alb ) {
1939
+ $alb_in_by_date[] = (int) get_post_meta( $gm_alb->ID, '_gmedia_term_ID', true );
1940
+ }
1941
+ $q['album__in'] = array_unique( array_merge( $alb_in_by_date, $q['album__in'] ) );
1942
+ }
1943
+ }
1944
+
1945
+ /**
1946
+ * Tag stuff for gmedia query.
1947
+ *
1948
+ * @param $q
1949
+ */
1950
+ function gmedias_tag_stuff(&$q){
1951
+ global $wpdb;
1952
+
1953
+ if(isset($q['tag']) && '' != $q['tag']){
1954
+ if(strpos($q['tag'], ',') !== false){
1955
+ $tags = preg_split('/[,\s]+/', $q['tag']);
1956
+ foreach((array)$tags as $tag){
1957
+ $q['tag_name__in'][] = $tag;
1958
+ }
1959
+ } else if(preg_match('/[+\s]+/', $q['tag']) || !empty($q['alb'])){
1960
+ $tags = preg_split('/[+\s]+/', $q['tag']);
1961
+ foreach((array)$tags as $tag){
1962
+ $q['tag_name__and'][] = $tag;
1963
+ }
1964
+ } else{
1965
+ $q['tag_name__in'][] = $q['tag'];
1966
+ }
1967
+ }
1968
+
1969
+ if(isset($q['tag_name__in']) && !empty($q['tag_name__in'])){
1970
+ $q['tag_name__in'] = "'" . implode("','", array_map('esc_sql', array_unique((array)$q['tag_name__in']))) . "'";
1971
+ $tag__in = $wpdb->get_col("
1972
+ SELECT term_id
1973
+ FROM {$wpdb->prefix}gmedia_term
1974
+ WHERE taxonomy = 'gmedia_tag'
1975
+ AND name IN ({$q['tag_name__in']})
1976
+ ");
1977
+ if(!empty($tag__in)){
1978
+ unset($q['tag_name__in']);
1979
+ $q['tag__in'] = $tag__in;
1980
+ }
1981
+ }
1982
+
1983
+ if(isset($q['tag_name__and']) && !empty($q['tag_name__and'])){
1984
+ $q['tag_name__and'] = "'" . implode("','", array_map('esc_sql', array_unique((array)$q['tag_name__and']))) . "'";
1985
+ $tag__and = $wpdb->get_col("
1986
+ SELECT term_id
1987
+ FROM {$wpdb->prefix}gmedia_term
1988
+ WHERE taxonomy = 'gmedia_tag'
1989
+ AND name IN ({$q['tag_name__and']})
1990
+ ");
1991
+ if(!empty($tag__and)){
1992
+ unset($q['tag_name__and']);
1993
+ $q['tag__and'] = $tag__and;
1994
+ }
1995
+ }
1996
+
1997
+ if(isset($q['tag__in']) && !empty($q['tag__in'])){
1998
+ $q['tag__in'] = wp_parse_id_list($q['tag__in']);
1999
+ } elseif(isset($q['tag_id']) && !empty($q['tag_id'])){
2000
+ $q['tag__in'] = array(absint($q['tag_id']));
2001
+ }
2002
+
2003
+
2004
+ if(isset($q['tag__not_in']) && !empty($q['tag__not_in'])){
2005
+ $q['tag__not_in'] = wp_parse_id_list($q['tag__not_in']);
2006
+ }
2007
+
2008
+ if(isset($q['tag__and']) && !empty($q['tag__and'])){
2009
+ $q['tag__and'] = wp_parse_id_list($q['tag__and']);
2010
+ }
2011
+ }
2012
+
2013
+ /**
2014
+ * Convert MIME types into SQL.
2015
+ * @see wp_post_mime_type_where()
2016
+ *
2017
+ * @param string|array $mime_types List of mime types or comma separated string of mime types.
2018
+ * @param string $table_alias Optional. Specify a table alias, if needed.
2019
+ *
2020
+ * @return string The SQL AND clause for mime searching.
2021
+ */
2022
+ function gmedia_mime_type_where($mime_types, $table_alias = ''){
2023
+ $where = '';
2024
+ $wildcards = array('', '%', '%/%');
2025
+ if(is_string($mime_types)){
2026
+ $mime_types = array_map('trim', explode(',', $mime_types));
2027
+ }
2028
+ foreach((array)$mime_types as $mime_type){
2029
+ $mime_type = preg_replace('/\s/', '', $mime_type);
2030
+ $slashpos = strpos($mime_type, '/');
2031
+ if(false !== $slashpos){
2032
+ $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2033
+ $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2034
+ if(empty($mime_subgroup)){
2035
+ $mime_subgroup = '*';
2036
+ } else{
2037
+ $mime_subgroup = str_replace('/', '', $mime_subgroup);
2038
+ }
2039
+ $mime_pattern = "$mime_group/$mime_subgroup";
2040
+ } else{
2041
+ $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2042
+ if(false === strpos($mime_pattern, '*')){
2043
+ $mime_pattern .= '/*';
2044
+ }
2045
+ }
2046
+
2047
+ $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2048
+
2049
+ if(in_array($mime_type, $wildcards)){
2050
+ return '';
2051
+ }
2052
+
2053
+ if(false !== strpos($mime_pattern, '%')){
2054
+ $wheres[] = empty($table_alias)? "mime_type LIKE '$mime_pattern'" : "$table_alias.mime_type LIKE '$mime_pattern'";
2055
+ } else{
2056
+ $wheres[] = empty($table_alias)? "mime_type = '$mime_pattern'" : "$table_alias.mime_type = '$mime_pattern'";
2057
+ }
2058
+ }
2059
+ if(!empty($wheres)){
2060
+ $where = ' AND (' . join(' OR ', $wheres) . ') ';
2061
+ }
2062
+
2063
+ return $where;
2064
+ }
2065
+
2066
+ /**
2067
+ * Some postmeta stuff.
2068
+ *
2069
+ * @param int $gmedia
2070
+ * @param string $meta_type
2071
+ *
2072
+ * @return mixed
2073
+ */
2074
+ function has_meta($gmedia, $meta_type = 'gmedia'){
2075
+ global $wpdb;
2076
+
2077
+ if(!in_array($meta_type, array('gmedia', 'gmedia_term'))){
2078
+ $meta_type = 'gmedia';
2079
+ }
2080
+
2081
+ return $wpdb->get_results($wpdb->prepare("SELECT *
2082
+ FROM {$wpdb->prefix}{$meta_type}_meta WHERE {$meta_type}_id = %d
2083
+ ORDER BY meta_key,meta_id", $gmedia), ARRAY_A);
2084
+ }
2085
+
2086
+ /**
2087
+ * Add metadata for the specified object.
2088
+ * @see add_metadata()
2089
+ * @uses $wpdb WordPress database object for queries.
2090
+ * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry,
2091
+ * object ID, meta key, and meta value
2092
+ *
2093
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2094
+ * @param int $object_id ID of the object metadata is for
2095
+ * @param string $meta_key Metadata key
2096
+ * @param string $meta_value Metadata value
2097
+ * @param bool $unique Optional, default is false. Whether the specified metadata key should be
2098
+ * unique for the object. If true, and the object already has a value for the specified
2099
+ * metadata key, no change will be made
2100
+ *
2101
+ * @return bool The meta ID on successful update, false on failure.
2102
+ */
2103
+ function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false){
2104
+ if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2105
+ return false;
2106
+ }
2107
+
2108
+ if(!$object_id = absint($object_id)){
2109
+ return false;
2110
+ }
2111
+
2112
+ /** @var $wpdb wpdb */
2113
+ global $wpdb;
2114
+
2115
+ $table = $wpdb->prefix . $meta_type . '_meta';
2116
+
2117
+ $column = esc_sql($meta_type . '_id');
2118
+
2119
+ // expected_slashed ($meta_key)
2120
+ $meta_key = wp_unslash($meta_key);
2121
+ $meta_value = wp_unslash($meta_value);
2122
+ $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2123
+
2124
+ $check = apply_filters("{$meta_type}_add_metadata", null, $object_id, $meta_key, $meta_value, $unique);
2125
+ if(null !== $check){
2126
+ return $check;
2127
+ }
2128
+
2129
+ if($unique && $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id))){
2130
+ return false;
2131
+ }
2132
+
2133
+ $_meta_value = $meta_value;
2134
+ $meta_value = maybe_serialize($meta_value);
2135
+
2136
+ do_action("{$meta_type}_add_meta", $object_id, $meta_key, $_meta_value);
2137
+
2138
+ $result = $wpdb->insert($table, array($column => $object_id,
2139
+ 'meta_key' => $meta_key,
2140
+ 'meta_value' => $meta_value
2141
+ ));
2142
+
2143
+ if(!$result){
2144
+ return false;
2145
+ }
2146
+
2147
+ $mid = (int)$wpdb->insert_id;
2148
+
2149
+ wp_cache_delete($object_id, $meta_type . '_meta');
2150
+
2151
+ do_action("{$meta_type}_added_meta", $mid, $object_id, $meta_key, $_meta_value);
2152
+
2153
+ return $mid;
2154
+ }
2155
+
2156
+ /**
2157
+ * Update metadata for the specified object. If no value already exists for the specified object
2158
+ * ID and metadata key, the metadata will be added.
2159
+ * @see update_metadata()
2160
+ * @uses $wpdb WordPress database object for queries.
2161
+ * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
2162
+ * metadata entry to update, object ID, meta key, and meta value
2163
+ * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
2164
+ * updated metadata entry, object ID, meta key, and meta value
2165
+ *
2166
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2167
+ * @param int $object_id ID of the object metadata is for
2168
+ * @param string $meta_key Metadata key
2169
+ * @param string|array $meta_value Metadata value
2170
+ * @param string $prev_value Optional. If specified, only update existing metadata entries with
2171
+ * the specified value. Otherwise, update all entries.
2172
+ *
2173
+ * @return bool True on successful update, false on failure.
2174
+ */
2175
+ function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = ''){
2176
+ if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2177
+ return false;
2178
+ }
2179
+
2180
+ if(!$object_id = absint($object_id)){
2181
+ return false;
2182
+ }
2183
+
2184
+ /** @var $wpdb wpdb */
2185
+ global $wpdb;
2186
+
2187
+ $table = $wpdb->prefix . $meta_type . '_meta';
2188
+
2189
+ $column = esc_sql($meta_type . '_id');
2190
+ $id_column = 'meta_id';
2191
+
2192
+ // expected_slashed ($meta_key)
2193
+ $meta_key = stripslashes($meta_key);
2194
+ $passed_value = $meta_value;
2195
+ $meta_value = stripslashes_deep($meta_value);
2196
+ $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2197
+
2198
+ $check = apply_filters("{$meta_type}_update_metadata", null, $object_id, $meta_key, $meta_value, $prev_value);
2199
+ if(null !== $check){
2200
+ return (bool)$check;
2201
+ }
2202
+
2203
+ if(!$meta_id = $wpdb->get_var($wpdb->prepare("SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id))){
2204
+ return $this->add_metadata($meta_type, $object_id, $meta_key, $passed_value);
2205
+ }
2206
+
2207
+ // Compare existing value to new value if no prev value given and the key exists only once.
2208
+ if(empty($prev_value)){
2209
+ $old_value = $this->get_metadata($meta_type, $object_id, $meta_key);
2210
+ if(count($old_value) == 1){
2211
+ if($old_value[0] === $meta_value){
2212
+ return false;
2213
+ }
2214
+ }
2215
+ }
2216
+
2217
+ $_meta_value = $meta_value;
2218
+ $meta_value = maybe_serialize($meta_value);
2219
+
2220
+ $data = compact('meta_value');
2221
+ $where = array($column => $object_id, 'meta_key' => $meta_key);
2222
+
2223
+ if(!empty($prev_value)){
2224
+ $prev_value = maybe_serialize($prev_value);
2225
+ $where['meta_value'] = $prev_value;
2226
+ }
2227
+
2228
+ do_action("{$meta_type}_update_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2229
+
2230
+ $wpdb->update($table, $data, $where);
2231
+
2232
+ wp_cache_delete($object_id, $meta_type . '_meta');
2233
+
2234
+ do_action("{$meta_type}_updated_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2235
+
2236
+ return true;
2237
+ }
2238
+
2239
+ /**
2240
+ * Delete metadata for the specified object.
2241
+ * @see delete_metadata()
2242
+ * @uses $wpdb WordPress database object for queries.
2243
+ * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
2244
+ * deleted metadata entries, object ID, meta key, and meta value
2245
+ *
2246
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2247
+ * @param int $object_id ID of the object metadata is for
2248
+ * @param string $meta_key Metadata key
2249
+ * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries
2250
+ * with this value. Otherwise, delete all entries with the specified meta_key.
2251
+ * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
2252
+ * for all objects, ignoring the specified object_id. Otherwise, only delete matching
2253
+ * metadata entries for the specified object_id.
2254
+ *
2255
+ * @return bool True on successful delete, false on failure.
2256
+ */
2257
+ function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false){
2258
+ if(!$meta_type || !$meta_key || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2259
+ return false;
2260
+ }
2261
+
2262
+ if((!$object_id = absint($object_id)) && !$delete_all){
2263
+ return false;
2264
+ }
2265
+
2266
+ /** @var $wpdb wpdb */
2267
+ global $wpdb;
2268
+
2269
+ $table = $wpdb->prefix . $meta_type . '_meta';
2270
+
2271
+ $type_column = esc_sql($meta_type . '_id');
2272
+ $id_column = 'meta_id';
2273
+ // expected_slashed ($meta_key)
2274
+ $meta_key = stripslashes($meta_key);
2275
+ $meta_value = stripslashes_deep($meta_value);
2276
+
2277
+ $check = apply_filters("{$meta_type}_delete_metadata", null, $object_id, $meta_key, $meta_value, $delete_all);
2278
+ if(null !== $check){
2279
+ return (bool)$check;
2280
+ }
2281
+
2282
+ $_meta_value = $meta_value;
2283
+ $meta_value = maybe_serialize($meta_value);
2284
+
2285
+ $query = $wpdb->prepare("SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key);
2286
+
2287
+ if(!$delete_all){
2288
+ $query .= $wpdb->prepare(" AND $type_column = %d", $object_id);
2289
+ }
2290
+
2291
+ if($meta_value){
2292
+ $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value);
2293
+ }
2294
+
2295
+ $meta_ids = $wpdb->get_col($query);
2296
+ if(!count($meta_ids)){
2297
+ return false;
2298
+ }
2299
+
2300
+ /** @var $object_ids */
2301
+ if($delete_all){
2302
+ $object_ids = $wpdb->get_col($wpdb->prepare("SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key));
2303
+ }
2304
+
2305
+ do_action("delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value);
2306
+
2307
+ $query = "DELETE FROM $table WHERE $id_column IN( " . implode(',', $meta_ids) . " )";
2308
+
2309
+ $count = $wpdb->query($query);
2310
+
2311
+ if(!$count){
2312
+ return false;
2313
+ }
2314
+
2315
+ if($delete_all){
2316
+ foreach((array)$object_ids as $o_id){
2317
+ wp_cache_delete($o_id, $meta_type . '_meta');
2318
+ }
2319
+ } else{
2320
+ wp_cache_delete($object_id, $meta_type . '_meta');
2321
+ }
2322
+
2323
+ do_action("{$meta_type}_deleted_meta", $meta_ids, $object_id, $meta_key, $_meta_value);
2324
+
2325
+ return true;
2326
+ }
2327
+
2328
+ /**
2329
+ * Retrieve metadata for the specified object.
2330
+ * @see get_metadata()
2331
+ *
2332
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, or gmedia_term)
2333
+ * @param int $object_id ID of the object metadata is for
2334
+ * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
2335
+ * the specified object.
2336
+ * @param bool $single Optional, default is false. If true, return only the first value of the
2337
+ * specified meta_key. This parameter has no effect if meta_key is not specified.
2338
+ *
2339
+ * @return string|array Single metadata value, or array of values
2340
+ */
2341
+ function get_metadata($meta_type, $object_id, $meta_key = '', $single = false){
2342
+ if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2343
+ return false;
2344
+ }
2345
+
2346
+ if(!$object_id = absint($object_id)){
2347
+ return false;
2348
+ }
2349
+
2350
+ $check = apply_filters("{$meta_type}_get_metadata", null, $object_id, $meta_key, $single);
2351
+ if(null !== $check){
2352
+ if($single && is_array($check)){
2353
+ return $check[0];
2354
+ } else{
2355
+ return $check;
2356
+ }
2357
+ }
2358
+
2359
+ $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
2360
+
2361
+ if(!$meta_cache){
2362
+ $meta_cache = $this->update_meta_cache($meta_type, array($object_id));
2363
+ $meta_cache = $meta_cache[ $object_id ];
2364
+ }
2365
+
2366
+ if(!$meta_key){
2367
+ global $gmCore;
2368
+ $meta_cache = $gmCore->array_map_recursive('maybe_unserialize', $meta_cache);
2369
+
2370
+ return $meta_cache;
2371
+ }
2372
+
2373
+ if(isset($meta_cache[ $meta_key ])){
2374
+ if($single){
2375
+ return maybe_unserialize($meta_cache[ $meta_key ][0]);
2376
+ } else{
2377
+ return array_map('maybe_unserialize', $meta_cache[ $meta_key ]);
2378
+ }
2379
+ }
2380
+
2381
+ if($single){
2382
+ return '';
2383
+ } else{
2384
+ return array();
2385
+ }
2386
+ }
2387
+
2388
+ /**
2389
+ * Get meta data by meta ID
2390
+ * @since 1.6.3
2391
+ *
2392
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2393
+ * @param int $meta_id ID for a specific meta row
2394
+ *
2395
+ * @return object Meta object or false.
2396
+ */
2397
+ function get_metadata_by_mid($meta_type, $meta_id){
2398
+ global $wpdb;
2399
+
2400
+ if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2401
+ return false;
2402
+ }
2403
+
2404
+ $meta_id = absint($meta_id);
2405
+ if(!$meta_id){
2406
+ return false;
2407
+ }
2408
+
2409
+ $table = $wpdb->prefix . $meta_type . '_meta';
2410
+
2411
+ $meta = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE meta_id = %d", $meta_id));
2412
+
2413
+ if(empty($meta)){
2414
+ return false;
2415
+ }
2416
+
2417
+ if(isset($meta->meta_value)){
2418
+ $meta->meta_value = maybe_unserialize($meta->meta_value);
2419
+ }
2420
+
2421
+ return $meta;
2422
+ }
2423
+
2424
+ /**
2425
+ * Update meta data by meta ID
2426
+ * @since 1.6.3
2427
+ *
2428
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2429
+ * @param int $meta_id ID for a specific meta row
2430
+ * @param string $meta_value Metadata value
2431
+ * @param string|bool $meta_key Optional, you can provide a meta key to update it
2432
+ *
2433
+ * @return bool True on successful update, false on failure.
2434
+ */
2435
+ function update_metadata_by_mid($meta_type, $meta_id, $meta_value, $meta_key = false){
2436
+ global $wpdb;
2437
+
2438
+ // Make sure everything is valid.
2439
+ if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2440
+ return false;
2441
+ }
2442
+
2443
+ $meta_id = absint($meta_id);
2444
+ if(!$meta_id){
2445
+ return false;
2446
+ }
2447
+
2448
+ $table = $wpdb->prefix . $meta_type . '_meta';
2449
+
2450
+ $column = sanitize_key($meta_type . '_id');
2451
+ $id_column = 'meta_id';
2452
+
2453
+ // Fetch the meta and go on if it's found.
2454
+ if(($meta = $this->get_metadata_by_mid($meta_type, $meta_id))){
2455
+ $original_key = $meta->meta_key;
2456
+ $object_id = $meta->{$column};
2457
+
2458
+ // If a new meta_key (last parameter) was specified, change the meta key,
2459
+ // otherwise use the original key in the update statement.
2460
+ if(false === $meta_key){
2461
+ $meta_key = $original_key;
2462
+ } elseif(!is_string($meta_key)){
2463
+ return false;
2464
+ }
2465
+
2466
+ // Sanitize the meta
2467
+ $_meta_value = $meta_value;
2468
+ $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);
2469
+ $meta_value = maybe_serialize($meta_value);
2470
+
2471
+ // Format the data query arguments.
2472
+ $data = array('meta_key' => $meta_key,
2473
+ 'meta_value' => $meta_value
2474
+ );
2475
+
2476
+ // Format the where query arguments.
2477
+ $where = array();
2478
+ $where[ $id_column ] = $meta_id;
2479
+
2480
+ do_action("{$meta_type}_update_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2481
+
2482
+ // Run the update query, all fields in $data are %s, $where is a %d.
2483
+ $result = $wpdb->update($table, $data, $where, '%s', '%d');
2484
+ if(!$result){
2485
+ return false;
2486
+ }
2487
+
2488
+ // Clear the caches.
2489
+ wp_cache_delete($object_id, $meta_type . '_meta');
2490
+
2491
+ do_action("{$meta_type}_updated_meta", $meta_id, $object_id, $meta_key, $_meta_value);
2492
+
2493
+ return true;
2494
+ }
2495
+
2496
+ // And if the meta was not found.
2497
+ return false;
2498
+ }
2499
+
2500
+ /**
2501
+ * Delete meta data by meta ID
2502
+ * @since 1.6.3
2503
+ *
2504
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
2505
+ * @param int $meta_id ID for a specific meta row
2506
+ *
2507
+ * @return bool True on successful delete, false on failure.
2508
+ */
2509
+ function delete_metadata_by_mid($meta_type, $meta_id){
2510
+ global $wpdb;
2511
+
2512
+ // Make sure everything is valid.
2513
+ if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($meta_id)){
2514
+ return false;
2515
+ }
2516
+
2517
+ $meta_id = absint($meta_id);
2518
+ if(!$meta_id){
2519
+ return false;
2520
+ }
2521
+
2522
+ $table = $wpdb->prefix . $meta_type . '_meta';
2523
+
2524
+ // object and id columns
2525
+ $column = sanitize_key($meta_type . '_id');
2526
+ $id_column = 'meta_id';
2527
+
2528
+ // Fetch the meta and go on if it's found.
2529
+ if(($meta = $this->get_metadata_by_mid($meta_type, $meta_id))){
2530
+ $object_id = $meta->{$column};
2531
+
2532
+ do_action("{$meta_type}_delete_meta", (array)$meta_id, $object_id, $meta->meta_key, $meta->meta_value);
2533
+
2534
+ // Run the query, will return true if deleted, false otherwise
2535
+ $result = (bool)$wpdb->delete($table, array($id_column => $meta_id));
2536
+
2537
+ // Clear the caches.
2538
+ wp_cache_delete($object_id, $meta_type . '_meta');
2539
+
2540
+ do_action("{$meta_type}_deleted_meta", (array)$meta_id, $object_id, $meta->meta_key, $meta->meta_value);
2541
+
2542
+ return $result;
2543
+ }
2544
+
2545
+ // Meta id was not found.
2546
+ return false;
2547
+ }
2548
+
2549
+ /**
2550
+ * Determine if a meta key is set for a given object
2551
+ * @see metadata_exists()
2552
+ *
2553
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia or gmedia_term)
2554
+ * @param int $object_id ID of the object metadata is for
2555
+ * @param string $meta_key Metadata key.
2556
+ *
2557
+ * @return boolean true of the key is set, false if not.
2558
+ */
2559
+ function metadata_exists($meta_type, $object_id, $meta_key){
2560
+ if(!$meta_type || !in_array($meta_type, array('gmedia', 'gmedia_term')) || !is_numeric($object_id)){
2561
+ return false;
2562
+ }
2563
+
2564
+ if(!$object_id = absint($object_id)){
2565
+ return false;
2566
+ }
2567
+
2568
+ $check = apply_filters("{$meta_type}_get_metadata", null, $object_id, $meta_key, true);
2569
+ if(null !== $check){
2570
+ return true;
2571
+ }
2572
+
2573
+ $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
2574
+
2575
+ if(!$meta_cache){
2576
+ $meta_cache = $this->update_meta_cache($meta_type, array($object_id));
2577
+ $meta_cache = $meta_cache[ $object_id ];
2578
+ }
2579
+
2580
+ if(isset($meta_cache[ $meta_key ])){
2581
+ return true;
2582
+ }
2583
+
2584
+ return false;
2585
+ }
2586
+
2587
+ /**
2588
+ * Get all Term data from database by Term ID.
2589
+ * The usage of the get_term function is to apply filters to a term object. It
2590
+ * is possible to get a term object from the database before applying the
2591
+ * filters.
2592
+ * There are two hooks, one is specifically for each term, named 'get_gmedia_term', and
2593
+ * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
2594
+ * term object, and the taxonomy name as parameters. Both hooks are expected to
2595
+ * return a Term object.
2596
+ * 'get_gmedia_term' hook - Takes two parameters the term Object and the taxonomy name.
2597
+ * Must return term object. Used in get_term() as a catch-all filter for every
2598
+ * $term.
2599
+ * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
2600
+ * name. Must return term object. $taxonomy will be the taxonomy name, so for
2601
+ * example, if 'gmedia_album', it would be 'get_gmedia_album' as the filter name. Useful
2602
+ * for custom taxonomies or plugging into default taxonomies.
2603
+ * @uses $wpdb
2604
+ * @see get_term()
2605
+ *
2606
+ * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
2607
+ * @param string|array $args Taxonomy name that $term is part of or args with user_id and taxonomy.
2608
+ * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
2609
+ *
2610
+ * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty.
2611
+ */
2612
+ function get_term($term, $args = null, $output = OBJECT){
2613
+ /** @var $wpdb wpdb */
2614
+ global $wpdb, $user_ID, $gmCore;
2615
+ $null = null;
2616
+
2617
+ if(empty($term)){
2618
+ $error = new WP_Error('invalid_term', __('Empty Term'));
2619
+
2620
+ return $error;
2621
+ }
2622
+
2623
+ if(is_object($term)){
2624
+ $term = $term->term_id;
2625
+ $taxonomy = $term->taxonomy;
2626
+ }
2627
+
2628
+ if($gmCore->is_digit($term)){
2629
+ $term = (int)$term;
2630
+ if(!$_term = wp_cache_get($term, 'gmedia_term')){
2631
+ $_term = $wpdb->get_row($wpdb->prepare("SELECT t.* FROM {$wpdb->prefix}gmedia_term AS t WHERE t.term_id = %d LIMIT 1", $term));
2632
+ if(!$_term){
2633
+ return $null;
2634
+ }
2635
+ wp_cache_add($term, $_term, 'gmedia_term');
2636
+ }
2637
+ } else{
2638
+ $global = $user_ID;
2639
+ $taxonomy = is_string($args)? $args : false;
2640
+ if(is_array($args)){
2641
+ if(isset($args['global'])){
2642
+ $global = (int)$args['global'];
2643
+ }
2644
+ if(isset($args['taxonomy'])){
2645
+ $taxonomy = $args['taxonomy'];
2646
+ }
2647
+ }
2648
+ if($taxonomy){
2649
+ $_term = $wpdb->get_row($wpdb->prepare("SELECT t.* FROM {$wpdb->prefix}gmedia_term AS t WHERE t.taxonomy = %s AND t.name = %s AND t.global = %d LIMIT 1", $taxonomy, $term, $global));
2650
+ if(!$_term){
2651
+ return $null;
2652
+ }
2653
+ wp_cache_add($_term->term_id, $_term, 'gmedia_term');
2654
+ } else{
2655
+ return $null;
2656
+ }
2657
+ }
2658
+
2659
+ $_term = apply_filters('get_gmedia_term', $_term, $_term->taxonomy);
2660
+ $_term = apply_filters("get_{$_term->taxonomy}", $_term, $_term->taxonomy);
2661
+ //$_term = sanitize_term($_term, $_term->taxonomy, $filter); // TODO sanitize_term after applying filters
2662
+
2663
+ if($output == OBJECT){
2664
+ return $_term;
2665
+ } elseif($output == ARRAY_A){
2666
+ $__term = get_object_vars($_term);
2667
+
2668
+ return $__term;
2669
+ } elseif($output == ARRAY_N){
2670
+ $__term = array_values(get_object_vars($_term));
2671
+
2672
+ return $__term;
2673
+ } else{
2674
+ return $_term;
2675
+ }
2676
+ }
2677
+
2678
+ /**
2679
+ * Updates Terms to Taxonomy in cache.
2680
+ *
2681
+ * @param array $terms List of term objects to change.
2682
+ */
2683
+ function update_term_cache($terms){
2684
+ foreach((array)$terms as $term){
2685
+ // Create a copy in case the array was passed by reference.
2686
+ $_term = clone $term;
2687
+
2688
+ // Object ID should not be cached.
2689
+ unset($_term->object_id);
2690
+
2691
+ wp_cache_add($term->term_id, $_term, 'gmedia_term');
2692
+ }
2693
+ }
2694
+
2695
+ /**
2696
+ * Get Taxonomy by Term ID.
2697
+ * @uses $wpdb
2698
+ *
2699
+ * @param int $term_id
2700
+ *
2701
+ * @return string $taxonomy
2702
+ */
2703
+ function get_tax_by_term_id($term_id){
2704
+ /** @var $wpdb wpdb */
2705
+ global $wpdb, $gmCore;
2706
+ $null = null;
2707
+
2708
+ if(!$gmCore->is_digit($term_id)){
2709
+ return $null;
2710
+ }
2711
+ $taxonomy = $wpdb->get_var($wpdb->prepare("SELECT taxonomy FROM {$wpdb->prefix}gmedia_term WHERE term_id = %d", $term_id));
2712
+
2713
+ return $taxonomy;
2714
+ }
2715
+
2716
+ /**
2717
+ * Retrieve the name of a term.
2718
+ * @see get_cat_name()
2719
+ *
2720
+ * @param object|int $term
2721
+ *
2722
+ * @return string Term name, or an empty string if term doesn't exist.
2723
+ */
2724
+ function get_term_name($term){
2725
+ if(is_object($term)){
2726
+ return $term->name;
2727
+ }
2728
+ $term = $this->get_term((int)$term);
2729
+ if(!$term || is_wp_error($term)){
2730
+ return '';
2731
+ }
2732
+
2733
+ return $term->name;
2734
+ }
2735
+
2736
+ /**
2737
+ * Retrieve the terms in a given taxonomy or list of taxonomies.
2738
+ * You can fully inject any customizations to the query before it is sent, as
2739
+ * well as control the output with a filter.
2740
+ * The 'get_gmedia_terms' filter will be called when the cache has the term and will
2741
+ * pass the found term along with the array of $taxonomies and array of $args.
2742
+ * This filter is also called before the array of terms is passed and will pass
2743
+ * the array of terms, along with the $taxonomies and $args.
2744
+ * The 'get_gmedia_terms_orderby' filter passes the ORDER BY clause for the query
2745
+ * along with the $args array.
2746
+ * The 'get_gmedia_terms_fields' filter passes the fields for the SELECT query
2747
+ * along with the $args array.
2748
+ * The list of arguments that $args can contain, which will overwrite the defaults:
2749
+ * orderby - Default is 'name'. Can be name, count, global, description or nothing
2750
+ * (will use term_id), Passing a custom value other than these will cause it to
2751
+ * order based on the custom value.
2752
+ * order - Default is ASC. Can use DESC.
2753
+ * hide_empty - Default is false. Will return empty terms, which means
2754
+ * terms whose count is 0 according to the given taxonomy.
2755
+ * exclude - Default is an empty array. An array, comma- or space-delimited string
2756
+ * of term ids to exclude from the return array. If 'include' is non-empty,
2757
+ * 'exclude' is ignored.
2758
+ * include - Default is an empty array. An array, comma- or space-delimited string
2759
+ * of term ids to include in the return array.
2760
+ * number - The maximum number of terms to return. Default is to return them all.
2761
+ * offset - The number by which to offset the terms query.
2762
+ * status - can be used generaly for albums. Defaults: 'publish', 'private', 'draft'.
2763
+ * fields - Default is 'all', which returns an array of term objects.
2764
+ * If 'fields' is 'ids' or 'names', returns an array of
2765
+ * integers or strings, respectively.
2766
+ * search - Returned terms' names will contain the value of 'search',
2767
+ * case-insensitive. Default is an empty string.
2768
+ * name__like - Returned terms' names will begin with the value of 'name__like',
2769
+ * case-insensitive. Default is empty string.
2770
+ * The 'get' argument, if set to 'all' instead of its default empty string,
2771
+ * returns terms regardless of ancestry or whether the terms are empty.
2772
+ * The 'global' argument, when used, should be set to the integer of a term ID. Its default is
2773
+ * the empty string '', which has a different meaning from the integer 0.
2774
+ * If set to an integer value, all returned terms will have as an immediate
2775
+ * ancestor the term whose ID is specified by that integer according to the given taxonomy.
2776
+ * The 'global' argument is different from 'child_of' in that a term X is considered a 'global'
2777
+ * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
2778
+ * @uses $wpdb
2779
+ * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
2780
+ * @see get_terms()
2781
+ *
2782
+ * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
2783
+ * @param string|array $args The values of what to search for when returning terms
2784
+ *
2785
+ * @return array|WP_Error List of Term Objects. Will return WP_Error, if any of $taxonomies does not exist.
2786
+ */
2787
+ function get_terms($taxonomies, $args = array()){
2788
+ /** @var $wpdb wpdb */
2789
+ global $wpdb;
2790
+
2791
+ if(!is_array($taxonomies)){
2792
+ $taxonomies = array($taxonomies);
2793
+ }
2794
+
2795
+ $defaults = array('orderby' => 'name',
2796
+ 'order' => 'ASC',
2797
+ 'hide_empty' => false,
2798
+ 'exclude' => array(),
2799
+ 'include' => array(),
2800
+ 'get' => '',
2801
+ 'number' => '',
2802
+ 'fields' => 'all',
2803
+ 'name__like' => '',
2804
+ 'offset' => '',
2805
+ 'search' => '',
2806
+ 'global' => '',
2807
+ 'status' => '',
2808
+ 'page' => 1,
2809
+ 'no_found_rows' => false
2810
+ );
2811
+ // $args can be whatever, only use the args defined in defaults
2812
+ $args = array_intersect_key((array)$args, $defaults);
2813
+ $args = wp_parse_args($args, $defaults);
2814
+ $args['number'] = absint($args['number']);
2815
+ $args['offset'] = absint($args['offset']);
2816
+
2817
+ if('all' == $args['get']){
2818
+ $args['hide_empty'] = false;
2819
+ }
2820
+
2821
+ $args = apply_filters('gmedia_get_terms_args', $args, $taxonomies);
2822
+
2823
+ /** @var $orderby
2824
+ * @var $order
2825
+ * @var $hide_empty
2826
+ * @var $exclude
2827
+ * @var $include
2828
+ * @var $number
2829
+ * @var $fields
2830
+ * @var $get
2831
+ * @var $name_like
2832
+ * @var $offset
2833
+ * @var $search
2834
+ * @var $global
2835
+ * @var $status
2836
+ * @var $page
2837
+ * @var $no_found_rows
2838
+ * */
2839
+ extract($args, EXTR_SKIP);
2840
+
2841
+ $key = md5(serialize(compact(array_keys($defaults))) . serialize($taxonomies));
2842
+ $last_changed = wp_cache_get('last_changed', 'gmedia_terms');
2843
+ if(!$last_changed){
2844
+ $last_changed = time();
2845
+ wp_cache_set('last_changed', $last_changed, 'gmedia_terms');
2846
+ }
2847
+ $cache_key = "gmedia_get_terms:$key:$last_changed";
2848
+ $cache = wp_cache_get($cache_key, 'gmedia_terms');
2849
+ if(false !== $cache){
2850
+ $cache_tax = wp_cache_get($cache_key, 'gmedia_terms_counts');
2851
+ if(false != $cache_tax){
2852
+ $this->openPage = $cache_tax['openPage'];
2853
+ $this->resultPerPage = $cache_tax['resultPerPage'];
2854
+ $this->totalResult = $cache_tax['totalResult'];
2855
+ $this->pages = $cache_tax['pages'];
2856
+ $this->filter_tax = $cache_tax['filter_tax'];
2857
+ }
2858
+ $args['terms_counts'] = $cache_tax;
2859
+
2860
+ $cache = apply_filters('gmedia_get_terms', $cache, $taxonomies, $args);
2861
+
2862
+ return $cache;
2863
+ }
2864
+
2865
+ $order = strtoupper($order);
2866
+ if('' !== $order && !in_array($order, array('ASC', 'DESC'))){
2867
+ $order = 'ASC';
2868
+ }
2869
+
2870
+ $_orderby = strtolower($orderby);
2871
+ if('count' == $_orderby){
2872
+ $orderby = "ORDER BY t.count $order, t.term_id $order";
2873
+ } else if('name' == $_orderby){
2874
+ $orderby = "ORDER BY t.name $order";
2875
+ } else if('description' == $_orderby){
2876
+ $orderby = "ORDER BY t.description $order, t.term_id $order";
2877
+ } else if('include' == $_orderby && !empty($args['include'])){
2878
+ $include = implode(',', array_map('absint', $args['include']));
2879
+ $orderby = "ORDER BY FIELD( t.term_id, $include )";
2880
+ } else if('global' == $_orderby){
2881
+ $orderby = "ORDER BY t.global ASC, t.term_id $order";
2882
+ } else if('global_desc_name' == $_orderby){
2883
+ $orderby = "ORDER BY t.global DESC, t.name $order";
2884
+ } else if('global_asc_name' == $_orderby){
2885
+ $orderby = "ORDER BY t.global ASC, t.name $order";
2886
+ } else if('rand' == $_orderby){
2887
+ $orderby = 'ORDER BY RAND()';
2888
+ } else if('none' == $_orderby){
2889
+ $orderby = '';
2890
+ } elseif(empty($_orderby) || 'id' == $_orderby){
2891
+ $orderby = "ORDER BY t.term_id $order";
2892
+ } else{
2893
+ $orderby = "ORDER BY t.name $order";
2894
+ }
2895
+
2896
+ $orderby = apply_filters('gmedia_get_terms_orderby', $orderby, $args);
2897
+
2898
+ $where_ = "t.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
2899
+ $where = '';
2900
+ $inclusions = '';
2901
+ if(!empty($include)){
2902
+ $exclude = '';
2903
+ $include = wp_parse_id_list($include);
2904
+ $inclusions = implode(',', $include);
2905
+ $this->filter_tax['term__in'] = $include;
2906
+ }
2907
+
2908
+ if(!empty($inclusions)){
2909
+ $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
2910
+ $where .= $inclusions;
2911
+ }
2912
+
2913
+ $exclusions = '';
2914
+ if(!empty($exclude)){
2915
+ $exterms = wp_parse_id_list($exclude);
2916
+ $this->filter_tax['term__not_in'] = $exterms;
2917
+ if(empty($exclusions)){
2918
+ $exclusions = implode(',', $exterms);
2919
+ } else{
2920
+ $exclusions .= ', ' . implode(',', $exterms);
2921
+ }
2922
+ }
2923
+
2924
+ if(!empty($exclusions)){
2925
+ $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
2926
+ }
2927
+
2928
+ $exclusions = apply_filters('list_gmedia_terms_exclusions', $exclusions, $args);
2929
+ if(!empty($exclusions)){
2930
+ $where .= $exclusions;
2931
+ }
2932
+
2933
+ if(!empty($name__like)){
2934
+ $this->filter_tax['name__like'] = $name__like;
2935
+ $name__like = addcslashes($name__like, '_%\\');
2936
+ $where .= $wpdb->prepare(" AND t.name LIKE %s", $name__like . '%');
2937
+ }
2938
+
2939
+ if(!empty($global) || '0' === $global || 0 === $global){
2940
+ $global = wp_parse_id_list($global);
2941
+ $this->filter_tax['global'] = $global;
2942
+ $where .= " AND t.global IN ('" . implode("', '", $global) . "')";
2943
+ }
2944
+
2945
+ if($hide_empty){
2946
+ $where .= ' AND t.count > 0';
2947
+ }
2948
+
2949
+ if(!empty($number)){
2950
+ if(!empty($page)){
2951
+ $page = (int)$page? (int)$page : 1;
2952
+ $offset = ($page - 1) * $number;
2953
+ }
2954
+ if($offset){
2955
+ $limits = 'LIMIT ' . $offset . ',' . $number;
2956
+ } else{
2957
+ $limits = 'LIMIT ' . $number;
2958
+ }
2959
+ } else{
2960
+ $limits = '';
2961
+ }
2962
+
2963
+ if(!empty($search)){
2964
+ $search = addcslashes($search, '_%\\');
2965
+ $where .= $wpdb->prepare(" AND (t.name LIKE %s)", '%' . $search . '%');
2966
+ }
2967
+
2968
+ if(!empty($status)){
2969
+ if(is_array($status)){
2970
+ $arr_status = array();
2971
+ foreach($status as $_status){
2972
+ $arr_status[] = $wpdb->prepare("t.status = %s", $_status);
2973
+ }
2974
+ $where .= ' AND (' . implode(' OR ', $arr_status) . ')';
2975
+ } else{
2976
+ $where .= $wpdb->prepare(" AND t.status = %s", $status);
2977
+ }
2978
+ }
2979
+
2980
+ switch($fields){
2981
+ case 'ids':
2982
+ case 'id=>global':
2983
+ $selects = array('t.term_id', 't.global');
2984
+ break;
2985
+ case 'names':
2986
+ $selects = array('t.name');
2987
+ break;
2988
+ case 'id=>names':
2989
+ $selects = array('t.term_id', 't.name');
2990
+ break;
2991
+ case 'names_count':
2992
+ $selects = array('t.term_id', 't.name', 't.count');
2993
+ break;
2994
+ case 'count':
2995
+ $orderby = '';
2996
+ $selects = array('COUNT(*)');
2997
+ break;
2998
+ case 'all':
2999
+ default:
3000
+ $selects = array('t.*');
3001
+ break;
3002
+ }
3003
+
3004
+ $_fields = $fields;
3005
+
3006
+ $fields = implode(', ', apply_filters('gmedia_get_terms_fields', $selects, $args, $taxonomies));
3007
+
3008
+ $join = "";
3009
+
3010
+ $pieces = array('fields', 'join', 'where', 'orderby', 'order', 'limits');
3011
+ $clauses = apply_filters('gmedia_terms_clauses', compact($pieces), $taxonomies, $args);
3012
+ foreach($pieces as $piece){
3013
+ $$piece = isset($clauses[ $piece ])? $clauses[ $piece ] : '';
3014
+ }
3015
+
3016
+ $found_rows = '';
3017
+ if(!$no_found_rows && !empty($limits)){
3018
+ $found_rows = 'SQL_CALC_FOUND_ROWS';
3019
+ }
3020
+
3021
+ $where_where = $where_ . $where;
3022
+ $this->sql_query = "SELECT $found_rows $fields FROM {$wpdb->prefix}gmedia_term AS t $join WHERE $where_where $orderby $limits";
3023
+
3024
+ $fields = $_fields;
3025
+
3026
+ if('count' == $fields){
3027
+ $term_count = $wpdb->get_var($this->sql_query);
3028
+
3029
+ return $term_count;
3030
+ }
3031
+
3032
+ $terms = $wpdb->get_results($this->sql_query);
3033
+
3034
+ $this->openPage = $page;
3035
+ $this->resultPerPage = count($terms);
3036
+ if(!$no_found_rows){
3037
+ if(!empty($limits)){
3038
+ $this->totalResult = $wpdb->get_var('SELECT FOUND_ROWS()');
3039
+ $this->pages = ceil($this->totalResult / $number);
3040
+ $this->perPages = (int)$number;
3041
+ } else{
3042
+ $this->totalResult = $this->resultPerPage;
3043
+ $this->pages = 1;
3044
+ $this->perPages = $this->resultPerPage;
3045
+ }
3046
+ }
3047
+ $terms_counts = array('openPage' => $this->openPage,
3048
+ 'resultPerPage' => $this->resultPerPage,
3049
+ 'totalResult' => $this->totalResult,
3050
+ 'pages' => $this->pages,
3051
+ 'perPages' => $this->perPages,
3052
+ 'filter_tax' => $this->filter_tax
3053
+ );
3054
+
3055
+ if('all' == $fields){
3056
+ $this->update_term_cache($terms);
3057
+ }
3058
+
3059
+ if(empty($terms)){
3060
+ wp_cache_add($cache_key, array(), 'gmedia_terms', 86400); // one day
3061
+ wp_cache_add($cache_key, array(), 'gmedia_terms_counts', 86400); // one day
3062
+ $terms = apply_filters('gmedia_get_terms', array(), $taxonomies, $args);
3063
+
3064
+ return $terms;
3065
+ }
3066
+
3067
+ reset($terms);
3068
+ $_terms = array();
3069
+ if('id=>global' == $fields){
3070
+ while(($term = array_shift($terms))){
3071
+ $_terms[ $term->term_id ] = $term->global;
3072
+ }
3073
+ $terms = $_terms;
3074
+ } elseif('ids' == $fields){
3075
+ while(($term = array_shift($terms))){
3076
+ $_terms[] = $term->term_id;
3077
+ }
3078
+ $terms = $_terms;
3079
+ } elseif('names' == $fields){
3080
+ while(($term = array_shift($terms))){
3081
+ $_terms[] = $term->name;
3082
+ }
3083
+ $terms = $_terms;
3084
+ } elseif('id=>names' == $fields){
3085
+ while(($term = array_shift($terms))){
3086
+ $_terms[ $term->term_id ] = $term->name;
3087
+ }
3088
+ $terms = $_terms;
3089
+ } elseif('name=>all' == $fields){
3090
+ while(($term = array_shift($terms))){
3091
+ $_terms[ $term->name ] = $term;
3092
+ }
3093
+ $terms = $_terms;
3094
+ } elseif('names_count' == $fields){
3095
+ while(($term = array_shift($terms))){
3096
+ $_terms[ $term->term_id ] = array('name' => $term->name, 'count' => $term->count, 'term_id' => $term->term_id);
3097
+ }
3098
+ $terms = $_terms;
3099
+ }
3100
+
3101
  if(0 < $number && intval(@count($terms)) > $number){
3102
+ $terms = array_slice($terms, $offset, $number);
3103
+ }
3104
+
3105
+ wp_cache_add($cache_key, $terms, 'gmedia_terms', 86400); // one day
3106
+ wp_cache_add($cache_key, $terms_counts, 'gmedia_terms_counts', 86400); // one day
3107
+ $args['terms_counts'] = $terms_counts;
3108
+
3109
+ $terms = apply_filters('gmedia_get_terms', $terms, $taxonomies, $args);
3110
+
3111
+ return $terms;
3112
+ }
3113
+
3114
+ /**
3115
+ * Adds a new term to the database. Optionally marks it as an alias of an existing term.
3116
+ * Error handling is assigned for the nonexistence of the $taxonomy and $term
3117
+ * parameters before inserting. If both the term id and taxonomy exist
3118
+ * previously, then an array will be returned that contains the term id and the
3119
+ * contents of what is returned. The keys of the array are 'term_id' containing numeric values.
3120
+ * It is assumed that the term does not yet exist or the above will apply. The
3121
+ * term will be first added to the term table and related to the taxonomy
3122
+ * if everything is well. If everything is correct, then several actions will be
3123
+ * run prior to a filter and then several actions will be run after the filter
3124
+ * is run.
3125
+ * The arguments decide how the term is handled based on the $args parameter.
3126
+ * The following is a list of the available overrides and the defaults.
3127
+ * 'description'. There is no default. If exists, will be added to the database
3128
+ * along with the term. Expected to be a string.
3129
+ * 'global'. Expected to be numeric and default is 0 (zero). Will assign value
3130
+ * of 'global' to the term.
3131
+ * @see wp_insert_term()
3132
+ * @uses $wpdb
3133
+ * @uses apply_filters() Calls 'pre_insert_gmedia_term' hook with term and taxonomy as parameters.
3134
+ * @uses do_action() Calls 'create_gmedia_term' hook with the term id and taxonomy id as parameters.
3135
+ * @uses do_action() Calls 'created_gmedia_term' hook with the term id and taxonomy id as parameters.
3136
+ *
3137
+ * @param string $term The term to add or update.
3138
+ * @param string $taxonomy The taxonomy to which to add the term
3139
+ * @param array|string $args Change the values of the inserted term
3140
+ *
3141
+ * @return int|WP_Error The Term ID array('term_id'=>$term_id)
3142
+ */
3143
+ function insert_term($term, $taxonomy, $args = array()){
3144
+ /** @var $wpdb wpdb */
3145
+ global $wpdb, $gmGallery, $gmCore, $user_ID;
3146
+
3147
+ $term = apply_filters('pre_insert_gmedia_term', $term, $taxonomy);
3148
+ if(is_wp_error($term)){
3149
+ return $term;
3150
+ }
3151
+
3152
+ if(is_int($term) && 0 == $term){
3153
+ return new WP_Error('gm_invalid_term_id', __('Invalid term ID'));
3154
+ }
3155
+
3156
+ if('' == trim($term)){
3157
+ return new WP_Error('gm_empty_term_name', __('A name is required for this term'));
3158
+ }
3159
+
3160
+ $defaults = array('description' => '', 'global' => intval($user_ID), 'status' => 'publish');
3161
+ $taxterm = str_replace('gmedia_', '', $taxonomy);
3162
+ switch($taxterm){
3163
+ case 'album':
3164
+ $defaults['status'] = $gmGallery->options['in_album_status'];
3165
+ $defaults['meta']['_orderby'] = $gmGallery->options['in_album_orderby'];
3166
+ $defaults['meta']['_order'] = $gmGallery->options['in_album_order'];
3167
+ break;
3168
+ case 'category':
3169
+ $defaults['meta']['_orderby'] = $gmGallery->options['in_category_orderby'];
3170
+ $defaults['meta']['_order'] = $gmGallery->options['in_category_order'];
3171
+ break;
3172
+ }
3173
+ $args = wp_parse_args($args, $defaults);
3174
+ $args['name'] = $term;
3175
+ $args['taxonomy'] = $taxonomy;
3176
+ // TODO $args = sanitize_term($args, $taxonomy, 'db');
3177
+ /** @var $name
3178
+ * @var $description
3179
+ * @var $global
3180
+ * @var $status
3181
+ * @var $comment_status
3182
+ * @var $slug
3183
+ * @var $meta
3184
+ */
3185
+ extract($args, EXTR_SKIP);
3186
+
3187
+ // expected_slashed ($name)
3188
+ $name = stripslashes($name);
3189
+ $name = $gmCore->mb_convert_encoding_utf8($name);
3190
+ if('gmedia_module' == $taxonomy){
3191
+ $description = maybe_serialize($description);
3192
+ } else{
3193
+ $description = stripslashes($description);
3194
+ $description = $gmCore->mb_convert_encoding_utf8($description);
3195
+ if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category'))){
3196
+ $global = 0;
3197
+ }
3198
+ }
3199
+
3200
+ if(($term_id = $this->term_exists($name, $taxonomy, $global))){
3201
+ // Same name, same global.
3202
+ return new WP_Error('gm_term_exists', __('A term with the name provided already exists.'), $term_id);
3203
+ }
3204
+
3205
+ do_action("create_gmedia_term", $term_id, $taxonomy);
3206
+
3207
+ // This term does not exist, Create it.
3208
+ if(false === $wpdb->insert($wpdb->prefix . 'gmedia_term', compact('name', 'taxonomy', 'description', 'global', 'status') + array('count' => 0))){
3209
+ return new WP_Error('gm_db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
3210
+ }
3211
+ $term_id = (int)$wpdb->insert_id;
3212
+
3213
+ if(isset($meta) && is_array($meta) && !empty($meta)){
3214
+ $meta_type = 'gmedia_term';
3215
+ foreach($meta as $key => $value){
3216
+ if(in_array($key, array('_cover', '_orderby', '_order', '_module_preset'))){
3217
+ $value = ltrim($value, '#');
3218
+ $this->add_metadata($meta_type, $term_id, $key, $value);
3219
+ continue;
3220
+ }
3221
+ $key = trim($key);
3222
+ if(!empty($key) && !$gmCore->is_digit($key) && !empty($value) && !$gmCore->is_protected_meta($key, $meta_type)){
3223
+ $this->add_metadata($meta_type, $term_id, $key, $value);
3224
+ }
3225
+ }
3226
+ }
3227
+
3228
+ if(in_array($taxonomy, array('gmedia_album', 'gmedia_gallery'))){
3229
+ $post_data = array('post_author' => $global,
3230
+ 'post_content' => $description,
3231
+ 'post_title' => $name,
3232
+ 'post_status' => $status,
3233
+ 'post_type' => $taxonomy
3234
+ );
3235
+ if(isset($slug) && !empty($slug)){
3236
+ $post_data['post_name'] = $slug;
3237
+ }
3238
+ if(!empty($comment_status)){
3239
+ $post_data['comment_status'] = $comment_status;
3240
+ } else{
3241
+ $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
3242
+ }
3243
+ $_post_ID = wp_insert_post($post_data);
3244
+ if($_post_ID){
3245
+ add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3246
+ $this->add_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3247
+ }
3248
+
3249
+ }
3250
+
3251
+ $this->clean_term_cache($term_id);
3252
+
3253
+ do_action("created_gmedia_term", $term_id, $taxonomy);
3254
+
3255
+ return $term_id;
3256
+ }
3257
+
3258
+ /**
3259
+ * Update term based on arguments provided.
3260
+ * The $args will indiscriminately override all values with the same field name.
3261
+ * Care must be taken to not override important information need to update or
3262
+ * update will fail (or perhaps create a new term, neither would be acceptable).
3263
+ * @see wp_update_term()
3264
+ * @uses $wpdb
3265
+ * @uses do_action() Will call both 'edit_gmedia_term' and 'edit_$taxonomy'.
3266
+ *
3267
+ * @param int $term_id The ID of the term
3268
+ * @param array|string $args Overwrite term field values
3269
+ *
3270
+ * @return int|WP_Error Returns Term ID
3271
+ */
3272
+ function update_term($term_id, $args = array()){
3273
+ /** @var $wpdb wpdb */
3274
+ global $wpdb, $gmCore, $gmGallery;
3275
+
3276
+ $term_id = (int)$term_id;
3277
+
3278
+ // First, get all of the original args
3279
+ $term = $this->get_term($term_id, null, ARRAY_A);
3280
+
3281
+ if(is_wp_error($term) || empty($term)){
3282
+ return $term;
3283
+ }
3284
+
3285
+ // Escape data pulled from DB.
3286
+ $term = add_magic_quotes($term);
3287
+ $taxonomy = $term['taxonomy'];
3288
+
3289
+ // Merge old and new args with new args overwriting old ones.
3290
+ $args = array_merge($term, $args);
3291
+
3292
+ $defaults = array('global' => $term['global'], 'name' => $term['name'], 'description' => '', 'status' => 'publish', 'meta' => array());
3293
+ $args = wp_parse_args($args, $defaults);
3294
+
3295
+ /** @var $name
3296
+ * @var $description
3297
+ * @var $status
3298
+ * @var $global
3299
+ * @var $meta
3300
+ */
3301
+ extract($args, EXTR_SKIP);
3302
+
3303
+ // expected_slashed ($name)
3304
+ $name = stripslashes($name);
3305
+ $name = $gmCore->mb_convert_encoding_utf8($name);
3306
+ if('' == trim($name)){
3307
+ return new WP_Error('gm_empty_term_name', __('A name is required for term'));
3308
+ }
3309
+
3310
+ if(current_user_can('gmedia_edit_others_media')){
3311
+ $global = (int)$global;
3312
+ } else{
3313
+ $global = $term['global'];
3314
+ }
3315
+
3316
+ if('gmedia_module' == $taxonomy){
3317
+ $description = maybe_serialize($description);
3318
+ } else{
3319
+ $description = stripslashes($description);
3320
+ $description = $gmCore->mb_convert_encoding_utf8($description);
3321
+ if(in_array($taxonomy, array('gmedia_tag', 'gmedia_category'))){
3322
+ $global = 0;
3323
+ }
3324
+ }
3325
+
3326
+ $term_id = $wpdb->get_var($wpdb->prepare("SELECT t.term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE t.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id));
3327
+ do_action("edit_gmedia_term", $term_id, $taxonomy);
3328
+ $wpdb->update($wpdb->prefix . 'gmedia_term', compact('term_id', 'name', 'taxonomy', 'description', 'global', 'status'), array('term_id' => $term_id));
3329
+
3330
+ if(('gmedia_album' == $taxonomy)){
3331
+ $default_meta = array('_orderby' => 'ID',
3332
+ '_order' => 'DESC'
3333
+ );
3334
+ $meta = array_merge($default_meta, $meta);
3335
+ if(isset($status_global)){
3336
+ $db_gmedia_ids = $this->get_gmedias(array('no_found_rows' => true, 'album__in' => $term_id, 'fields' => 'post_ids'));
3337
+ if(!empty($db_gmedia_ids)){
3338
+ $values = array('gm' => array(), 'wp' => array());
3339
+ foreach($db_gmedia_ids as $gmids){
3340
+ $values['gm'][] = $wpdb->prepare("%d", $gmids->ID);
3341
+ wp_cache_delete($gmids->ID, 'gmedias');
3342
+ if(!empty($gmids->post_id)){
3343
+ $values['wp'][] = $wpdb->prepare("%d", $gmids->post_id);
3344
+ wp_cache_delete($gmids->post_id, 'wpgmedias');
3345
+ wp_cache_delete($gmids->post_id, 'posts');
3346
+ }
3347
+ }
3348
+ if(!empty($values['gm'])){
3349
+ $status = esc_sql($status);
3350
+ if(false === $wpdb->query("UPDATE {$wpdb->prefix}gmedia SET status = '{$status}' WHERE ID IN (" . join(',', $values['gm']) . ")")){
3351
+ return new WP_Error('db_insert_error', __('Could not update statuses for gmedia items in the database'), $wpdb->last_error);
3352
+ }
3353
+ if(!empty($values['wp'])){
3354
+ $wpdb->query("UPDATE $wpdb->posts SET post_status = '{$status}' WHERE ID IN (" . join(',', $values['wp']) . ")");
3355
+ }
3356
+ }
3357
+ }
3358
+ }
3359
+ }
3360
+
3361
+ if(!empty($meta) && is_array($meta)){
3362
+ $meta_type = 'gmedia_term';
3363
+ foreach($meta as $key => $value){
3364
+ if(in_array($key, array('_cover', '_orderby', '_order', '_module_preset'))){
3365
+ $value = ltrim($value, '#');
3366
+ $this->update_metadata($meta_type, $term_id, $key, $value);
3367
+ } elseif($gmCore->is_digit($key)){
3368
+ $mid = (int)$key;
3369
+ //$value = wp_unslash( $value );
3370
+ if(!($meta = $this->get_metadata_by_mid('gmedia_term', $mid))){
3371
+ continue;
3372
+ }
3373
+ if('' == trim($value)){
3374
+ $this->delete_metadata_by_mid($meta_type, $key);
3375
+ continue;
3376
+ }
3377
+ if($meta->meta_value != $value){
3378
+ $this->update_metadata_by_mid($meta_type, $mid, $value);
3379
+ }
3380
+ }
3381
+ }
3382
+ }
3383
+
3384
+ if(in_array($taxonomy, array('gmedia_album', 'gmedia_gallery'))){
3385
+ $post_data = array('post_author' => $global,
3386
+ 'post_content' => $description,
3387
+ 'post_title' => $name,
3388
+ 'post_status' => $status,
3389
+ 'post_type' => $taxonomy
3390
+ );
3391
+ if(!empty($slug)){
3392
+ $post_data['post_name'] = $slug;
3393
+ }
3394
+ if(!empty($comment_status)){
3395
+ $post_data['comment_status'] = $comment_status;
3396
+ } else{
3397
+ $post_data['comment_status'] = $gmGallery->options['default_gmedia_comment_status'];
3398
+ }
3399
+ $_post_ID = $this->get_metadata('gmedia_term', $term_id, '_post_ID', true);
3400
+ if($_post_ID){
3401
+ $post_data['ID'] = $_post_ID;
3402
+
3403
+ if ( ! empty( $post_date ) ) {
3404
+ $post_data['post_date'] = $post_date;
3405
+ $post_data['post_date_gmt'] = get_gmt_from_date( $post_date );
3406
+ }
3407
+
3408
+ if(!wp_update_post($post_data)){
3409
+ unset($post_data['ID']);
3410
+ $_post_ID = wp_insert_post($post_data);
3411
+ if($_post_ID){
3412
+ add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3413
+ $this->update_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3414
+ }
3415
+ }
3416
+ } else{
3417
+ $_post_ID = wp_insert_post($post_data);
3418
+ if($_post_ID){
3419
+ add_metadata('post', $_post_ID, '_gmedia_term_ID', $term_id);
3420
+ $this->update_metadata('gmedia_term', $term_id, '_post_ID', $_post_ID);
3421
+ }
3422
+ }
3423
+ }
3424
+
3425
+ do_action("edit_$taxonomy", $term_id);
3426
+
3427
+ $term_id = apply_filters('gmedia_term_id_filter', $term_id);
3428
+
3429
+ $this->clean_term_cache($term_id);
3430
+
3431
+ do_action("edited_gmedia_term", $term_id, $taxonomy);
3432
+ do_action("edited_$taxonomy", $term_id);
3433
+
3434
+ return $term_id;
3435
+ }
3436
+
3437
+ /**
3438
+ * Update term's items sort order based on arguments provided.
3439
+ * @uses $wpdb
3440
+ * @uses do_action() Will call both 'sort_gmedia_term' and 'sort_$taxonomy'.
3441
+ *
3442
+ * @param int $term_id The ID of the term
3443
+ * @param array $gm_ids_order
3444
+ *
3445
+ * @return int|WP_Error Returns Term ID
3446
+ */
3447
+ function update_term_sortorder($term_id, $gm_ids_order = array()){
3448
+ /** @var $wpdb wpdb */
3449
+ global $wpdb;
3450
+
3451
+ $term_id = $this->term_exists($term_id);
3452
+ if(!$term_id){
3453
+ return new WP_Error('gm_invalid_term_id', __('Invalid term ID'));
3454
+ }
3455
+
3456
+ do_action("sort_gmedia_term", $term_id);
3457
+
3458
+ if(empty($gm_ids_order)){
3459
+ $term_meta = $this->get_metadata('gmedia_term', $term_id);
3460
+ $_orderby = isset($term_meta['_orderby'][0])? $term_meta['_orderby'][0] : 'ID';
3461
+ $_order = isset($term_meta['_order'][0])? $term_meta['_order'][0] : 'DESC';
3462
+ if($_orderby == 'custom'){
3463
+ $_orderby = 'ID';
3464
+ $_order = 'DESC';
3465
+ }
3466
+ $gm_ids_order = $this->get_gmedias(array('no_found_rows' => true,
3467
+ 'album__in' => $term_id,
3468
+ 'orderby' => $_orderby,
3469
+ 'order' => $_order,
3470
+ 'fields' => 'ids'
3471
+ ));
3472
+ $gm_ids_order = array_merge(array(0), $gm_ids_order);
3473
+ unset($gm_ids_order[0]);
3474
+ $gm_ids_order = array_flip($gm_ids_order);
3475
+ }
3476
+
3477
+ $final_gmedia_ids = array();
3478
+ if(!empty($gm_ids_order)){
3479
+ $_db_gmedia_ids = $this->get_gmedias(array('no_found_rows' => true, 'album__in' => $term_id, 'orderby' => 'custom', 'order' => 'ASC', 'fields' => 'ids'));
3480
+ $db_gmedia_ids = array_merge(array(0), $_db_gmedia_ids);
3481
+ unset($db_gmedia_ids[0]);
3482
+ $db_gmedia_ids = array_flip($db_gmedia_ids);
3483
+
3484
+ if($gm_ids_order != $db_gmedia_ids){
3485
+ $final_gmedia_ids = array_intersect_key($gm_ids_order, $db_gmedia_ids) + $db_gmedia_ids;
3486
+ asort($final_gmedia_ids, SORT_NUMERIC);
3487
+ $final_gmedia_ids = array_keys($final_gmedia_ids);
3488
+ $final_gmedia_ids = array_diff_assoc($final_gmedia_ids, $_db_gmedia_ids);
3489
+
3490
+ $values = array();
3491
+ foreach($final_gmedia_ids as $gmedia_order => $gmedia_id){
3492
+ $values[] = $wpdb->prepare("(%d, %d, %d)", $gmedia_id, $term_id, ($gmedia_order + 1));
3493
+ }
3494
+ if($values){
3495
+ if(false === $wpdb->query("INSERT INTO {$wpdb->prefix}gmedia_term_relationships (gmedia_id, gmedia_term_id, gmedia_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE gmedia_order = VALUES(gmedia_order)")){
3496
+ return new WP_Error('db_insert_error', __('Could not insert gmedia term relationship into the database'), $wpdb->last_error);
3497
+ }
3498
+ }
3499
+ $this->clean_object_term_cache($final_gmedia_ids);
3500
+ }
3501
+ }
3502
+
3503
+ $this->clean_term_cache($term_id);
3504
+
3505
+ do_action("sorted_gmedia_term", $term_id);
3506
+
3507
+ return $final_gmedia_ids;
3508
+ }
3509
+
3510
+ /**
3511
+ * Check if Term exists.
3512
+ * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
3513
+ * @see term_exists()
3514
+ * @uses $wpdb
3515
+ *
3516
+ * @param int|string $term The term to check
3517
+ * @param string $taxonomy The taxonomy name to use
3518
+ * @param bool|int $global global parameter under which to confine the exists search.
3519
+ *
3520
+ * @return int Get the term id or Term Object, if exists.
3521
+ */
3522
+ function term_exists($term, $taxonomy = '', $global = false){
3523
+ /** @var $wpdb wpdb */
3524
+ global $wpdb, $gmCore;
3525
+
3526
+ $select = "SELECT term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE ";
3527
+
3528
+ if($gmCore->is_digit($term)){
3529
+ if(0 == $term){
3530
+ return 0;
3531
+ }
3532
+ $where = 't.term_id = %d';
3533
+ if(!empty($taxonomy)){
3534
+ return $wpdb->get_var($wpdb->prepare($select . $where . " AND t.taxonomy = %s", $term, $taxonomy));
3535
+ } else{
3536
+ return $wpdb->get_var($wpdb->prepare($select . $where, $term));
3537
+ }
3538
+ }
3539
+
3540
+ if('' === $term = trim(stripslashes($term))){
3541
+ return 0;
3542
+ }
3543
+
3544
+ $where = 't.name = %s';
3545
+ $where_fields = array($term);
3546
+ if(!empty($taxonomy)){
3547
+ if(false !== $global){
3548
+ $global = (int)$global;
3549
+ $where_fields[] = $global;
3550
+ $where .= ' AND t.global = %d';
3551
+ }
3552
+
3553
+ $where_fields[] = $taxonomy;
3554
+
3555
+ return $wpdb->get_var($wpdb->prepare("SELECT t.term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE $where AND t.taxonomy = %s", $where_fields));
3556
+ }
3557
+
3558
+ return $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->prefix}gmedia_term AS t WHERE $where", $where_fields));
3559
+ }
3560
+
3561
+ /**
3562
+ * Create Term and Taxonomy Relationships.
3563
+ * Relates an object to a term and taxonomy type. Creates the
3564
+ * term and taxonomy relationship if it doesn't already exist. Creates a term if
3565
+ * it doesn't exist.
3566
+ * A relationship means that the term is grouped in or belongs to the taxonomy.
3567
+ * A term has no meaning until it is given context by defining which taxonomy it
3568
+ * exists under.
3569
+ * @see wp_set_object_terms()
3570
+ * @uses $wpdb
3571
+ *
3572
+ * @param int $object_id The object to relate to.
3573
+ * @param array|int|string $terms The slug or id of the term, will replace all existing
3574
+ * related terms in this taxonomy.
3575
+ * @param array|string $taxonomy The context in which to relate the term to the object.
3576
+ * @param int $append If 1, don't delete existing tags, just add on. If 0, replace the tags with the new tags. If -1, remove given tags.
3577
+ *
3578
+ * @return array|WP_Error Affected Term IDs
3579
+ */
3580
+ function set_gmedia_terms($object_id, $terms, $taxonomy, $append = 0){
3581
+ /** @var $wpdb wpdb */
3582
+ global $wpdb, $gmCore;
3583
+
3584
+ $object_id = (int)$object_id;
3585
+
3586
+ if(!is_array($terms)){
3587
+ $terms = array($terms);
3588
+ }
3589
+ $terms = array_filter(array_map('trim', (array)$terms));
3590
+
3591
+ if($append == 0){
3592
+ if(empty($terms)){
3593
+ $this->delete_gmedia_term_relationships($object_id, $taxonomy);
3594
+
3595
+ return 0;
3596
+ }
3597
+ $old_term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
3598
+ } else{
3599
+ $old_term_ids = array();
3600
+ }
3601
+
3602
+ $term_ids = array();
3603
+ $new_term_ids = array();
3604
+ if(!empty($terms)){
3605
+ foreach($terms as $term){
3606
+ if(!strlen(trim($term))){
3607
+ continue;
3608
+ }
3609
+ if(('gmedia_album' == $taxonomy) && !$gmCore->is_digit($term)){
3610
+ $global = get_current_user_id();
3611
+ } else{
3612
+ $global = false;
3613
+ }
3614
+ if(!$term_id = $this->term_exists($term, $taxonomy, $global)){
3615
+ // Skip if a non-existent term ID is passed or if taxonomy is category or if user is not allowed to add new terms.
3616
+ if($gmCore->is_digit($term) || ($append < 0) || !current_user_can($taxonomy . '_manage')){
3617
+ continue;
3618
+ }
3619
+ if($global){
3620
+ $args = array('global' => $global);
3621
+ } else{
3622
+ $args = array();
3623
+ }
3624
+ $term_id = $this->insert_term($term, $taxonomy, $args);
3625
+ if(is_wp_error($term_id)){
3626
+ return $term_id;
3627
+ }
3628
+ } else{
3629
+ if(in_array($taxonomy, array('gmedia_album')) && !current_user_can('gmedia_edit_others_media')){
3630
+ $alb = $this->get_term($term_id);
3631
+ if($alb->global && ($alb->global != get_current_user_id())){
3632
+ continue;
3633
+ }
3634
+ }
3635
+ }
3636
+ $term_ids[] = $term_id;
3637
+
3638
+ if($append < 0){
3639
+ continue;
3640
+ }
3641
+
3642
+ if($wpdb->get_var($wpdb->prepare("SELECT gmedia_term_id FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id = %d", $object_id, $term_id))){
3643
+ continue;
3644
+ }
3645
+ do_action('add_gmedia_term_relationships', $object_id, $term_id);
3646
+ $wpdb->insert($wpdb->prefix . 'gmedia_term_relationships', array('gmedia_id' => $object_id, 'gmedia_term_id' => $term_id));
3647
+ do_action('added_gmedia_term_relationships', $object_id, $term_id);
3648
+ $new_term_ids[] = $term_id;
3649
+ }
3650
+ }
3651
+
3652
+ if(!empty($new_term_ids)){
3653
+ $this->update_term_count($term_ids);
3654
+ }
3655
+
3656
+ if($append < 1){
3657
+ if($append == 0){
3658
+ $delete_terms = array_diff($old_term_ids, $term_ids);
3659
+ } else{
3660
+ $delete_terms = $term_ids;
3661
+ }
3662
+ if(!empty($delete_terms)){
3663
+ $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
3664
+ do_action('delete_gmedia_term_relationships', $object_id, $delete_terms);
3665
+ $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_id = %d AND gmedia_term_id IN ($in_delete_terms)", $object_id));
3666
+ do_action('deleted_gmedia_term_relationships', $object_id, $delete_terms);
3667
+ $this->update_term_count($delete_terms);
3668
+ }
3669
+ }
3670
+
3671
+ // TODO sort terms (albums)
3672
+ $sort = ('gmedia_tag' == $taxonomy)? true : false;
3673
+ if(!$append && $sort){
3674
+ $values = array();
3675
+ $term_order = 0;
3676
+ $final_term_ids = $this->get_gmedia_terms($object_id, $taxonomy, array('fields' => 'ids'));
3677
+ foreach($term_ids as $term_id){
3678
+ if(in_array($term_id, $final_term_ids)){
3679
+ $values[] = $wpdb->prepare("(%d, %d, %d)", $object_id, $term_id, ++ $term_order);
3680
+ }
3681
+ }
3682
+ if($values){
3683
+ if(false === $wpdb->query("INSERT INTO {$wpdb->prefix}gmedia_term_relationships (gmedia_id, gmedia_term_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)")){
3684
+ return new WP_Error('db_insert_error', __('Could not insert gmedia term relationship into the database'), $wpdb->last_error);
3685
+ }
3686
+ }
3687
+ }
3688
+
3689
+ wp_cache_delete($object_id, $taxonomy . '_relationships');
3690
+
3691
+ do_action('set_gmedia_terms', $object_id, $terms, $term_ids, $taxonomy, $append, $old_term_ids);
3692
+
3693
+ return $term_ids;
3694
+ }
3695
+
3696
+ /**
3697
+ * Retrieve the terms of the taxonomy that are attached to the gmedia.
3698
+ * @see get_the_terms()
3699
+ *
3700
+ * @param int $id gmedia ID
3701
+ * @param string $taxonomy Taxonomy name.
3702
+ *
3703
+ * @return array|bool False on failure. Array of term objects on success.
3704
+ */
3705
+ function get_the_gmedia_terms($id, $taxonomy){
3706
+ $id = (int)$id;
3707
+
3708
+ if(!$id){
3709
+ return false;
3710
+ }
3711
+
3712
+ $terms = wp_cache_get($id, "{$taxonomy}_relationships");
3713
+ if(false === $terms){
3714
+ $terms = $this->get_gmedia_terms($id, $taxonomy);
3715
+ wp_cache_add($id, $terms, $taxonomy . '_relationships');
3716
+ }
3717
+
3718
+ $terms = apply_filters('get_the_gmedia_terms', $terms, $id, $taxonomy);
3719
+
3720
+ if(empty($terms)){
3721
+ return false;
3722
+ }
3723
+
3724
+ return $terms;
3725
+ }
3726
+
3727
+ /**
3728
+ * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
3729
+ * The following information has to do the $args parameter and for what can be
3730
+ * contained in the string or array of that parameter, if it exists.
3731
+ * The first argument is called, 'orderby' and has the default value of 'name'.
3732
+ * The other value that is supported is 'count'.
3733
+ * The second argument is called, 'order' and has the default value of 'ASC'.
3734
+ * The only other value that will be acceptable is 'DESC'.
3735
+ * The final argument supported is called, 'fields' and has the default value of
3736
+ * 'all'. There are multiple other options that can be used instead. Supported
3737
+ * values are as follows: 'all', 'ids', 'names', and finally
3738
+ * 'all_with_object_id'.
3739
+ * The fields argument also decides what will be returned. If 'all' or
3740
+ * 'all_with_object_id' is chosen or the default kept intact, then all matching
3741
+ * terms objects will be returned. If either 'ids' or 'names' is used, then an
3742
+ * array of all matching term ids or term names will be returned respectively.
3743
+ * @see wp_get_object_terms()
3744
+ * @uses $wpdb
3745
+ *
3746
+ * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
3747
+ * @param string|array $taxonomies The taxonomies to retrieve terms from.
3748
+ * @param array|string $args Change what is returned
3749
+ *
3750
+ * @return array The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
3751
+ */
3752
+ function get_gmedia_terms($object_ids, $taxonomies, $args = array()){
3753
+ /** @var $wpdb wpdb */
3754
+ global $wpdb;
3755
+
3756
+ if(!is_array($taxonomies)){
3757
+ $taxonomies = array($taxonomies);
3758
+ }
3759
+
3760
+ if(!is_array($object_ids)){
3761
+ $object_ids = array($object_ids);
3762
+ }
3763
+ $object_ids = array_map('intval', $object_ids);
3764
+
3765
+ $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all', 'unique' => true);
3766
+ $args = wp_parse_args($args, $defaults);
3767
+
3768
+ $terms = array();
3769
+
3770
+ /** @var $orderby
3771
+ * @var $order
3772
+ * @var $fields
3773
+ * @var $unique
3774
+ */
3775
+ extract($args, EXTR_SKIP);
3776
+
3777
+ if($unique){
3778
+ $groupby = 'GROUP BY t.term_id';
3779
+ } else{
3780
+ $groupby = '';
3781
+ }
3782
+
3783
+ if('count' == $orderby){
3784
+ $orderby = 't.count';
3785
+ } else if('name' == $orderby){
3786
+ $orderby = 't.name';
3787
+ } else if('global' == $orderby){
3788
+ $orderby = 't.global';
3789
+ } else if('term_order' == $orderby){
3790
+ $orderby = 'tr.term_order';
3791
+ } else if('none' == $orderby){
3792
+ $orderby = '';
3793
+ $order = '';
3794
+ } else{
3795
+ $orderby = 't.term_id';
3796
+ }
3797
+
3798
+ if(!empty($orderby)){
3799
+ $orderby = "ORDER BY $orderby";
3800
+ }
3801
+
3802
+ $taxonomies = "'" . implode("', '", $taxonomies) . "'";
3803
+ $object_ids = implode(', ', $object_ids);
3804
+
3805
+ $select_this = '';
3806
+ if('all' == $fields){
3807
+ $select_this = 't.*, tr.term_order, tr.gmedia_order';
3808
+ } else if('ids' == $fields){
3809
+ $select_this = 't.term_id';
3810
+ } else if('names' == $fields){
3811
+ $select_this = 't.name';
3812
+ } else if('all_with_object_id' == $fields){
3813
+ $select_this = 't.*, tr.gmedia_id, tr.term_order, tr.gmedia_order';
3814
+ $groupby = '';
3815
+ }
3816
+
3817
+ $query = "SELECT $select_this FROM {$wpdb->prefix}gmedia_term AS t INNER JOIN {$wpdb->prefix}gmedia_term_relationships AS tr ON tr.gmedia_term_id = t.term_id WHERE t.taxonomy IN ($taxonomies) AND tr.gmedia_id IN ($object_ids) $groupby $orderby $order";
3818
+
3819
+ if('all' == $fields || 'all_with_object_id' == $fields){
3820
+ $terms = array_merge($terms, $wpdb->get_results($query));
3821
+ $this->update_term_cache($terms);
3822
+ } else if('ids' == $fields || 'names' == $fields){
3823
+ $terms = array_merge($terms, $wpdb->get_col($query));
3824
+ }
3825
+
3826
+ if(!$terms){
3827
+ $terms = array();
3828
+ }
3829
+
3830
+ return apply_filters('get_gmedia_terms', $terms, $object_ids, $taxonomies, $args);
3831
+ }
3832
+
3833
+ /**
3834
+ * Removes a term from the database.
3835
+ * If the term is a parent of other terms, then the children will be updated to
3836
+ * that term's parent.
3837
+ * The $args 'default' will only override the terms found, if there is only one
3838
+ * term found. Any other and the found terms are used.
3839
+ * The $args 'force_default' will force the term supplied as default to be
3840
+ * assigned even if the object was not going to be termless
3841
+ * @see wp_delete_term()
3842
+ * @uses $wpdb
3843
+ * @uses do_action() Calls both 'delete_gmedia_term' and 'gm_delete_$taxonomy' action
3844
+ * hooks, passing term object, term id. 'gm_delete_term' gets an additional
3845
+ * parameter with the $taxonomy parameter.
3846
+ *
3847
+ * @param int $term_id Term ID
3848
+ * @param array|string $args Optional. Change 'default' term id and override found term ids.
3849
+ *
3850
+ * @return bool|WP_Error Returns false if not term; term_id if completes delete action.
3851
+ */
3852
+ function delete_term($term_id, $args = array()){
3853
+ /** @var $wpdb wpdb */
3854
+ global $wpdb;
3855
+
3856
+ $term_id = (int)$term_id;
3857
+
3858
+ if(!$term_id = $this->term_exists($term_id)){
3859
+ return false;
3860
+ }
3861
+ if(is_wp_error($term_id)){
3862
+ return $term_id;
3863
+ }
3864
+
3865
+ extract($args, EXTR_SKIP);
3866
+
3867
+ if(!isset($taxonomy)){
3868
+ $taxonomy = $this->get_tax_by_term_id($term_id);
3869
+ }
3870
+
3871
+ $objects = $wpdb->get_col($wpdb->prepare("SELECT gmedia_id FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_term_id = %d", $term_id));
3872
+
3873
+ foreach((array)$objects as $object){
3874
+ $terms = $this->get_gmedia_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
3875
+ $terms = array_diff($terms, array($term_id));
3876
+ $terms = array_map('intval', $terms);
3877
+ $this->set_gmedia_terms($object, $terms, $taxonomy);
3878
+ }
3879
+
3880
+ $_post_ID = $this->get_metadata('gmedia_term', $term_id, '_post_ID', true);
3881
+ $gmedia_term_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->prefix}gmedia_term_meta WHERE gmedia_term_id = %d ", $term_id));
3882
+ if(!empty($gmedia_term_meta_ids)){
3883
+ do_action('delete_gmedia_term_meta', $gmedia_term_meta_ids);
3884
+ $in_gmedia_term_meta_ids = "'" . implode("', '", $gmedia_term_meta_ids) . "'";
3885
+ $wpdb->query("DELETE FROM {$wpdb->prefix}gmedia_term_meta WHERE meta_id IN($in_gmedia_term_meta_ids)");
3886
+ do_action('deleted_gmedia_term_meta', $gmedia_term_meta_ids);
3887
+ }
3888
+
3889
+ do_action('delete_gmedia_term', $term_id);
3890
+ $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}gmedia_term WHERE term_id = %d", $term_id));
3891
+ if($_post_ID){
3892
+ wp_delete_post($_post_ID, true);
3893
+ }
3894
+ do_action('deleted_gmedia_term', $term_id);
3895
+
3896
+ $this->clean_term_cache($term_id);
3897
+
3898
+ do_action("delete_$taxonomy", $term_id);
3899
+
3900
+ return $term_id;
3901
+ }
3902
+
3903
+ /**
3904
+ * Will remove all of the term ids from the cache.
3905
+ * @uses $wpdb
3906
+ * @see clean_term_cache()
3907
+ *
3908
+ * @param int|array $ids Single or list of Term IDs
3909
+ */
3910
+ function clean_term_cache($ids){
3911
+ if(!is_array($ids)){
3912
+ $ids = array($ids);
3913
+ }
3914
+
3915
+ foreach($ids as $id){
3916
+ wp_cache_delete($id, 'gmedia_term');
3917
+ }
3918
+
3919
+ do_action('gmedia_clean_term_cache', $ids);
3920
+
3921
+ wp_cache_set('last_changed', time(), 'gmedia_terms');
3922
+ }
3923
+
3924
+
3925
+ /**
3926
+ * Call major cache updating functions for list of Post objects.
3927
+ * @see update_post_caches()
3928
+ *
3929
+ * @param array $gmedias Array of gmedia objects
3930
+ * @param bool $update_term_cache Whether to update the term cache. Default is true.
3931
+ * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
3932
+ *
3933
+ * @return null if we didn't match any gmedia objects
3934
+ */
3935
+ function update_gmedia_caches(&$gmedias, $update_term_cache = true, $update_meta_cache = true){
3936
+ // No point in doing all this work if we didn't match any gmedia objects.
3937
+ if(!$gmedias){
3938
+ return null;
3939
+ }
3940
+
3941
+ foreach($gmedias as $gmedia){
3942
+ wp_cache_add($gmedia->ID, $gmedia, 'gmedias');
3943
+ if(!empty($gmedia->post_id)){
3944
+ wp_cache_add($gmedia->post_id, $gmedia, 'wpgmedias');
3945
+ }
3946
+ }
3947
+
3948
+ $gmedia_ids = array();
3949
+ foreach($gmedias as $gmedia){
3950
+ $gmedia_ids[] = $gmedia->ID;
3951
+ }
3952
+
3953
+ if($update_term_cache){
3954
+ $gmedia_ids = array_map('intval', $gmedia_ids);
3955
+ $taxonomies = array('gmedia_album', 'gmedia_category', 'gmedia_tag');
3956
+
3957
+ $ids = array();
3958
+ foreach((array)$gmedia_ids as $id){
3959
+ foreach($taxonomies as $taxonomy){
3960
+ if(false === wp_cache_get($id, "{$taxonomy}_relationships")){
3961
+ $ids[] = $id;
3962
+ break;
3963
+ }
3964
+ }
3965
+ }
3966
+
3967
+ if(!empty($ids)){
3968
+ $terms = $this->get_gmedia_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
3969
+
3970
+ $object_terms = array();
3971
+ foreach((array)$terms as $term){
3972
+ $object_terms[ $term->gmedia_id ][ $term->taxonomy ][ $term->term_id ] = $term;
3973
+ }
3974
+
3975
+ foreach($ids as $id){
3976
+ foreach($taxonomies as $taxonomy){
3977
+ if(!isset($object_terms[ $id ][ $taxonomy ])){
3978
+ if(!isset($object_terms[ $id ])){
3979
+ $object_terms[ $id ] = array();
3980
+ }
3981
+ $object_terms[ $id ][ $taxonomy ] = array();
3982
+ }
3983
+ }
3984
+ }
3985
+
3986
+ foreach($object_terms as $id => $value){
3987
+ foreach($value as $taxonomy => $terms){
3988
+ wp_cache_set($id, $terms, "{$taxonomy}_relationships");
3989
+ }
3990
+ }
3991
+ }
3992
+ }
3993
+
3994
+ if($update_meta_cache){
3995
+ $this->update_meta_cache('gmedia', $gmedia_ids);
3996
+ }
3997
+
3998
+ }
3999
+
4000
+ /**
4001
+ * Update the metadata cache for the specified objects.
4002
+ * @see update_meta_cache()
4003
+ * @uses $wpdb WordPress database object for queries.
4004
+ *
4005
+ * @param string $meta_type Type of object metadata is for (e.g., gmedia, gmedia_term)
4006
+ * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
4007
+ *
4008
+ * @return mixed Metadata cache for the specified objects, or false on failure.
4009
+ */
4010
+ function update_meta_cache($meta_type, $object_ids){
4011
+ /** @var $wpdb wpdb */
4012
+ global $wpdb;
4013
+
4014
+ if(empty($meta_type) || empty($object_ids) || !in_array($meta_type, array('gmedia', 'gmedia_term'))){
4015
+ return false;
4016
+ }
4017
+
4018
+ $table = $wpdb->prefix . $meta_type . '_meta';
4019
+
4020
+ $column = esc_sql($meta_type . '_id');
4021
+
4022
+ if(!is_array($object_ids)){
4023
+ $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
4024
+ $object_ids = explode(',', $object_ids);
4025
+ }
4026
+
4027
+ $object_ids = array_map('intval', $object_ids);
4028
+
4029
+ $cache_key = $meta_type . '_meta';
4030
+ $ids = array();
4031
+ $cache = array();
4032
+ foreach($object_ids as $id){
4033
+ $cached_object = wp_cache_get($id, $cache_key);
4034
+ if(false === $cached_object){
4035
+ $ids[] = $id;
4036
+ } else{
4037
+ $cache[ $id ] = $cached_object;
4038
+ }
4039
+ }
4040
+
4041
+ if(empty($ids)){
4042
+ return $cache;
4043
+ }
4044
+
4045
+ // Get meta info
4046
+ $id_list = join(',', $ids);
4047
+ $meta_list = $wpdb->get_results("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)", ARRAY_A);
4048
+
4049
+ if(!empty($meta_list)){
4050
+ foreach($meta_list as $metarow){
4051
+ $mpid = intval($metarow[ $column ]);
4052
+ $mkey = $metarow['meta_key'];
4053
+ $mval = $metarow['meta_value'];
4054
+
4055
+ // Force subkeys to be array type:
4056
+ if(!isset($cache[ $mpid ]) || !is_array($cache[ $mpid ])){
4057
+ $cache[ $mpid ] = array();
4058
+ }
4059
+ if(!isset($cache[ $mpid ][ $mkey ]) || !is_array($cache[ $mpid ][ $mkey ])){
4060
+ $cache[ $mpid ][ $mkey ] = array();
4061
+ }
4062
+
4063
+ // Add a value to the current pid/key:
4064
+ $cache[ $mpid ][ $mkey ][] = $mval;
4065
+ }
4066
+ }
4067
+
4068
+ foreach($ids as $id){
4069
+ if(!isset($cache[ $id ])){
4070
+ $cache[ $id ] = array();
4071
+ }
4072
+ wp_cache_add($id, $cache[ $id ], $cache_key);
4073
+ }
4074
+
4075
+ return $cache;
4076
+ }
4077
+
4078
+ /**
4079
+ * Removes the taxonomy relationship to terms from the cache.
4080
+ * Will remove the entire taxonomy relationship containing term $object_id.
4081
+ * @see clean_object_term_cache()
4082
+ * @see get_object_taxonomies() for more on $object_type
4083
+ * @uses do_action() Will call action hook named, 'gmedia_clean_object_term_cache' after completion.
4084
+ * Passes, function params in same order.
4085
+ *
4086
+ * @param int|array $object_ids Single or list of term object ID(s)
4087
+ * @param array $taxonomies
4088
+ */
4089
+ function clean_object_term_cache($object_ids, $taxonomies = array()){
4090
+ if(!is_array($object_ids)){
4091
+ $object_ids = array($object_ids);
4092
+ }
4093
+ if(empty($taxonomies)){
4094
+ $taxonomies = array('gmedia_album', 'gmedia_category', 'gmedia_tag');
4095
+ }
4096
+
4097
+ foreach($object_ids as $id){
4098
+ foreach($taxonomies as $taxonomy){
4099
+ wp_cache_delete($id, "{$taxonomy}_relationships");
4100
+ }
4101
+ }
4102
+
4103
+ do_action('gmedia_clean_object_term_cache', $object_ids, $taxonomies);
4104
+ }
4105
+
4106
+ /**
4107
+ * Will update term count based on number of objects.
4108
+ * @see wp_update_term_count()
4109
+ * @uses $wpdb
4110
+ *
4111
+ * @param array $terms List of Term taxonomy IDs
4112
+ *
4113
+ * @return bool Always true when complete.
4114
+ */
4115
+ function update_term_count($terms){
4116
+ /** @var $wpdb wpdb */
4117
+ global $wpdb;
4118
+
4119
+ if(!is_array($terms)){
4120
+ $terms = array($terms);
4121
+ }
4122
+
4123
+ foreach((array)$terms as $term_id){
4124
+ $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}gmedia_term_relationships WHERE gmedia_term_id = %d", $term_id));
4125
+
4126
+ do_action('update_gmedia_term_count', $term_id);
4127
+ $wpdb->update($wpdb->prefix . 'gmedia_term', compact('count'), array('term_id' => $term_id));
4128
+ do_action('updated_gmedia_term_count', $term_id);
4129
+ }
4130
+
4131
+ $this->clean_term_cache($terms);
4132
+
4133
+ return true;
4134
+ }
4135
+
4136
+ /**
4137
+ * This function returns all roles, sorted by user level (lowest to highest)
4138
+ * @return array
4139
+ */
4140
+ function get_sorted_roles(){
4141
+ global $wp_roles;
4142
+ $roles = $wp_roles->role_objects;
4143
+ $sorted = array();
4144
+
4145
+ if(class_exists('RoleManager')){
4146
+ foreach($roles as $role_key => $role_name){
4147
+ $role = get_role($role_key);
4148
+ if(empty($role)){
4149
+ continue;
4150
+ }
4151
+ $role_user_level = array_reduce(array_keys($role->capabilities), array('WP_User', 'level_reduction'), 0);
4152
+ $sorted[ $role_user_level ] = $role;
4153
+ }
4154
+ $sorted = array_values($sorted);
4155
+ } else{
4156
+ $role_order = array("subscriber", "contributor", "author", "editor", "administrator");
4157
+ foreach($role_order as $role_key){
4158
+ $sorted[ $role_key ] = get_role($role_key);
4159
+ }
4160
+ }
4161
+
4162
+ return $sorted;
4163
+ }
4164
+
4165
+ /**
4166
+ * This function return the lowest roles which has the capabilities
4167
+ *
4168
+ * @param $capability
4169
+ *
4170
+ * @return bool
4171
+ */
4172
+ function get_role($capability){
4173
+ $check_order = $this->get_sorted_roles();
4174
+
4175
+ $args = array_slice(func_get_args(), 1);
4176
+ $args = array_merge(array($capability), $args);
4177
+
4178
+ foreach($check_order as $check_role){
4179
+ if(empty($check_role)){
4180
+ return false;
4181
+ }
4182
+
4183
+ if(call_user_func_array(array(&$check_role, 'has_cap'), $args)){
4184
+ return $check_role->name;
4185
+ }
4186
+ }
4187
+
4188
+ return false;
4189
+ }
4190
+
4191
+ /**
4192
+ * This function set or remove the $capability
4193
+ *
4194
+ * @param $lowest_role
4195
+ * @param $capability
4196
+ */
4197
+ function set_capability($lowest_role, $capability){
4198
+ $check_order = $this->get_sorted_roles();
4199
+
4200
+ $add_capability = false;
4201
+
4202
+ foreach($check_order as $the_role){
4203
+ $role = $the_role->name;
4204
+
4205
+ if($lowest_role == $role){
4206
+ $add_capability = true;
4207
+ }
4208
+
4209
+ // If you rename the roles, the please use the role manager plugin
4210
+ if(empty($the_role)){
4211
+ continue;
4212
+ }
4213
+
4214
+ /** @noinspection PhpUndefinedMethodInspection */
4215
+ $add_capability? $the_role->add_cap($capability) : $the_role->remove_cap($capability);
4216
+ }
4217
+
4218
+ }
4219
+
4220
+ /**
4221
+ * Reassign media to other blog user
4222
+ *
4223
+ * @param $user_id
4224
+ * @param $reassign
4225
+ */
4226
+ function reassign_media($user_id, $reassign){
4227
+ $gmedias = $this->get_gmedias(array('nopaging' => true, 'author' => $user_id));
4228
+ $taxonomies = $this->get_terms(array('gmedia_album', 'gmedia_gallery', 'gmedia_module'), array('global' => $user_id));
4229
+ if(empty($reassign)){
4230
+ $reassign = get_current_user_id();
4231
+ }
4232
+ if(!empty($gmedias)){
4233
+ $modified = current_time('mysql');
4234
+ foreach($gmedias as $item){
4235
+ $item->author = $reassign;
4236
+ $item->modified = $modified;
4237
+ $this->insert_gmedia($item);
4238
+ }
4239
+ }
4240
+ if(!empty($taxonomies)){
4241
+ foreach($taxonomies as $item){
4242
+ $this->update_term($item->term_id, array('global' => $reassign));
4243
+ }
4244
+ }
4245
+ }
4246
+
4247
+ }
4248
+
4249
+ global $gmDB;
4250
+ $gmDB = new GmediaDB;
inc/frontend.filters.php CHANGED
@@ -443,7 +443,7 @@ function gmedia_post_type__the_content( $content ) {
443
 
444
  <div class="gmsingle_location_info">
445
  <a href='https://www.google.com/maps/place/<?php echo $loc; ?>'
446
- target='_blank'><img
447
  src='//maps.googleapis.com/maps/api/staticmap?key=<?php esc_attr_e( $gmGallery->options['google_api_key'] ); ?>&size=320x240&zoom=10&scale=2&maptype=roadmap&markers=<?php echo $loc; ?>'
448
  alt='' width='320' height='240'/></a>
449
  </div>
@@ -995,4 +995,4 @@ function gmedia_widget_comments_args( $args ) {
995
  }
996
 
997
  return $args;
998
- }
443
 
444
  <div class="gmsingle_location_info">
445
  <a href='https://www.google.com/maps/place/<?php echo $loc; ?>'
446
+ target='_blank'><img class="noLazy"
447
  src='//maps.googleapis.com/maps/api/staticmap?key=<?php esc_attr_e( $gmGallery->options['google_api_key'] ); ?>&size=320x240&zoom=10&scale=2&maptype=roadmap&markers=<?php echo $loc; ?>'
448
  alt='' width='320' height='240'/></a>
449
  </div>
995
  }
996
 
997
  return $args;
998
+ }
inc/shortcodes.php CHANGED
@@ -1,550 +1,555 @@
1
- <?php
2
- if ( preg_match( '#' . basename( dirname( __FILE__ ) ) . '/' . basename( __FILE__ ) . '#', $_SERVER['PHP_SELF'] ) ) {
3
- die( 'You are not allowed to call this page directly.' );
4
- }
5
-
6
- /** *********************** **/
7
- /** Shortcodes Declarations **/
8
- /** *********************** **/
9
- add_shortcode( 'gmedia', 'gmedia_shortcode' );
10
- add_shortcode( 'gm', 'gmedia_shortcode' );
11
-
12
- //add_filter('the_content', 'do_shortcode');
13
- add_filter( 'the_content', 'get_gmedia_unformatted_shortcode_blocks', 4 );
14
-
15
- /** ******************************* **/
16
- /** Shortcodes Functions and Markup **/
17
- /** ******************************* **/
18
- $gmedia_shortcode_instance = array();
19
-
20
- /**
21
- * @param $atts
22
- * @param string $shortcode_post_content
23
- *
24
- * @return string
25
- */
26
- function gmedia_shortcode( $atts, $shortcode_post_content = '' ) {
27
- global $gmDB, $gmGallery, $gmCore;
28
- global $gmedia_shortcode_instance, $gmedia_shortcode_ids;
29
-
30
- $shortcode_raw = ( isset( $atts['_raw'] ) && '1' === $atts['_raw'] );
31
- $shortcode_copy = isset( $atts['_copy'] ) ? (int) $atts['_copy'] : null;
32
- unset( $atts['_raw'], $atts['_copy'] );
33
-
34
- $atts_hash = md5( build_query( $atts ) );
35
- if ( ! isset( $atts['id'] ) ) {
36
- if ( ! empty( $atts['album'] ) ) {
37
- $atts['id'] = $atts['album'];
38
- unset( $atts['album'] );
39
- } elseif ( ! empty( $atts['category'] ) ) {
40
- $atts['id'] = $atts['category'];
41
- unset( $atts['category'] );
42
- } elseif ( ! empty( $atts['tag'] ) ) {
43
- $atts['id'] = $atts['tag'];
44
- unset( $atts['tag'] );
45
- }
46
- }
47
-
48
- if ( isset( $gmedia_shortcode_instance[ $atts_hash ] ) ) {
49
- $out = $gmedia_shortcode_instance[ $atts_hash ]['shortcode'];
50
- ++ $gmedia_shortcode_instance[ $atts_hash ]['copy'];
51
- if ( ! $shortcode_raw ) {
52
- $sc_id = $gmedia_shortcode_instance[ $atts_hash ]['id'];
53
- $sc_copy = ( null === $shortcode_copy ) ? $gmedia_shortcode_instance[ $atts_hash ]['copy'] : $shortcode_copy;
54
- if ( $sc_copy ) {
55
- $out = str_replace( $sc_id, "{$sc_id}_{$sc_copy}", $out );
56
- }
57
- }
58
-
59
- return $out;
60
- } else {
61
- $gmedia_shortcode_instance[ $atts_hash ] = array(
62
- 'shortcode' => '',
63
- 'id' => '',
64
- 'copy' => 0,
65
- );
66
- }
67
- $shortcode_raw = ( isset( $gmGallery->options['shortcode_raw'] ) && '1' === $gmGallery->options['shortcode_raw'] );
68
- $cache_expiration = isset( $gmGallery->options['cache_expiration'] ) ? (int) $gmGallery->options['cache_expiration'] * HOUR_IN_SECONDS : 24 * HOUR_IN_SECONDS;
69
-
70
- $query = array();
71
- if ( ! empty( $atts['query'] ) ) {
72
- if ( is_string( $atts['query'] ) ) {
73
- $atts['query'] = html_entity_decode( $atts['query'] );
74
- }
75
- $query = wp_parse_args( $atts['query'], array() );
76
- }
77
-
78
- $atts_module = ! empty( $atts['module'] );
79
- $_module = $atts_module ? $atts['module'] : $gmGallery->options['default_gmedia_module'];
80
- $preset = $gmCore->getModulePreset( $_module );
81
- $_module = $preset['module'];
82
- $settings = $preset['settings'];
83
-
84
- $id = isset( $atts['id'] ) ? (int) $atts['id'] : 0;
85
- $userid = get_current_user_id();
86
- if ( $id && ( $term = gmedia_shortcode_id_data( $id ) ) ) {
87
- $is_gallery_visible = ( 'publish' !== $term->status && ! $userid ) || ( 'draft' === $term->status && $userid != $term->global && ! is_super_admin() );
88
- if ( apply_filters( 'is_gmedia_gallery_visible', $is_gallery_visible ) ) {
89
- return '';
90
- }
91
-
92
- $taxterm = str_replace( 'gmedia_', '', $term->taxonomy );
93
- if ( $taxterm === 'gallery' ) {
94
- if ( ! empty( $term->meta['_query'] ) ) {
95
- $query = array_merge( $query, $term->meta['_query'] );
96
- }
97
- } else {
98
- $query = array_merge( $query, array( "{$taxterm}__in" => $term->term_id ) );
99
- }
100
-
101
- if ( ! empty( $term->meta['_module'] ) ) {
102
- $_module = $term->meta['_module'];
103
- } elseif ( ! $atts_module && ! empty( $term->meta['_module_preset'] ) ) {
104
- $preset = $gmCore->getModulePreset( $term->meta['_module_preset'] );
105
- $_module = $preset['module'];
106
- $settings = $preset['settings'];
107
-
108
- $term->meta['_module'] = $_module;
109
- $term->meta['_settings'][ $_module ] = (array) $settings[ $_module ];
110
- }
111
- if ( isset( $term->meta['_settings'][ $_module ] ) ) {
112
- $settings = (array) $term->meta['_settings'];
113
- }
114
- } elseif ( isset( $atts['library'] ) && ( $quick_gallery = wp_parse_id_list( $atts['library'] ) ) ) {
115
- $query = array_merge( $query, array( 'gmedia__in' => $quick_gallery ) );
116
- if ( ! isset( $query['orderby'] ) ) {
117
- $query['orderby'] = 'gmedia__in';
118
- }
119
- }
120
- if ( empty( $term ) ) {
121
- $term = (object) array(
122
- 'name' => '',
123
- 'description' => '',
124
- );
125
- }
126
- if ( isset( $atts['orderby'] ) ) {
127
- $query['orderby'] = $atts['orderby'];
128
- }
129
- if ( isset( $atts['order'] ) ) {
130
- $query['order'] = $atts['order'];
131
- }
132
-
133
- if ( $userid && current_user_can( 'gmedia_gallery_manage' ) && ( $preview_module = $gmCore->_get( 'gmedia_module' ) ) ) {
134
- if ( $preview_module != $_module ) {
135
- $_module = $preview_module;
136
- $preset = $gmCore->getModulePreset( $_module );
137
- if ( $preset['module'] == $_module ) {
138
- $settings = $preset['settings'];
139
- } else {
140
- $settings = array( $_module => array() );
141
- }
142
- }
143
- }
144
-
145
- $gallery = array();
146
- if ( ! $id ) {
147
- $id = $atts_hash;
148
- // Backward compatibility
149
- $gallery = array(
150
- 'term_id' => $id,
151
- 'name' => __( 'Gallery', 'grand-media' ),
152
- 'description' => '',
153
- );
154
- }
155
-
156
- $module = $gmCore->get_module_path( $_module );
157
- if ( ! $module || ! is_file( $module['path'] . '/index.php' ) || ! is_file( $module['path'] . '/settings.php' ) ) {
158
- return '<div class="gmedia_gallery gmediaShortcodeError" data-gmid="' . $id . '" data-error="' . $_module . ': folder missed or module broken">' . $shortcode_post_content . '</div>';
159
- }
160
-
161
- if ( $_module !== $module['name'] ) {
162
- $_module = $module['name'];
163
- $settings = array( $_module => array() );
164
- }
165
-
166
- if ( ! empty( $atts['preset'] ) ) {
167
- $preset = $gmDB->get_term( $atts['preset'], 'gmedia_module' );
168
- if ( ! empty( $preset ) && ! is_wp_error( $preset ) && ( $module['name'] == $preset->status ) ) {
169
- $settings = array( $module['name'] => (array) maybe_unserialize( $preset->description ) );
170
- }
171
- }
172
-
173
- $protected_query_args = array( 'status' => array( 'publish' ) );
174
- if ( $userid ) {
175
- $protected_query_args['status'][] = 'private';
176
- }
177
- $query = array_merge( apply_filters( 'gmedia_shortcode_query', $query, $id ), $protected_query_args );
178
-
179
- include( $module['path'] . '/index.php' );
180
- include( $module['path'] . '/settings.php' );
181
- $module['info'] = isset( $module_info ) ? $module_info : array( 'dependencies' => '' );
182
- $module['options'] = isset( $default_options ) ? $default_options : array();
183
-
184
- $settings = apply_filters( 'gmedia_shortcode_settings', $gmCore->array_diff_keyval_recursive( (array) $settings[ $module['name'] ], $module['options'], false ) );
185
-
186
- $moduleCSS = isset( $gmGallery->do_module[ $_module ] ) ? '' : $gmGallery->load_module_styles( $module );
187
- $customCSS = ( isset( $settings['customCSS'] ) && ( '' !== trim( $settings['customCSS'] ) ) ) ? $settings['customCSS'] : '';
188
-
189
- $gmGallery->do_module[ $_module ] = $module;
190
- $gmGallery->shortcode[ $id ] = compact( 'id', 'query', 'module', 'settings', 'term' );
191
-
192
- $is_bot = false;
193
- if ( ! ( $is_mob = wp_is_mobile() ) ) {
194
- $is_bot = $gmCore->is_bot();
195
- }
196
- $mob_cache_key = $is_mob ? '_mob' : '';
197
-
198
- if ( $cache_expiration ) {
199
- $cache_key = md5( json_encode( $gmGallery->shortcode[ $id ] ) );
200
- $cache_value = get_transient( 'gm_cache_' . $cache_key );
201
- if ( ! $is_bot ) {
202
- $cache_value_m = get_transient( 'gm_cache_m_' . $cache_key . $mob_cache_key );
203
- } else {
204
- $cache_value_m = false;
205
- }
206
- }
207
-
208
- unset( $settings['customCSS'] );
209
-
210
- if ( empty( $module['info']['branch'] ) ) {
211
- $gmedia = array();
212
- if ( ! empty( $cache_value ) && is_array( $cache_value ) ) {
213
- extract( $cache_value, EXTR_OVERWRITE );
214
- } else {
215
- $query = array( $id => $query );
216
- if ( ! empty( $term ) ) {
217
- if ( in_array( $_module, array( 'afflux', 'afflux-mod', 'cube', 'flatwall', 'green-style', 'minima', 'optima', 'photo-blog', 'photo-pro', 'slider', 'sphere' ) ) ) {
218
- add_filter( 'jetpack_photon_skip_image', 'jetpack_photon_skip_gmedia', 10, 3 );
219
- $_query = array_merge( $query[ $id ], array( 'album__status' => $protected_query_args['status'] ) );
220
- $gmDB->gmedias_album_stuff( $_query );
221
- if ( ! empty( $_query['album__in'] ) && empty( $_query['album__not_in'] ) ) {
222
- $album__in = wp_parse_id_list( $_query['album__in'] );
223
- foreach ( $_query as $key => $q ) {
224
- if ( 'alb' === substr( $key, 0, 3 ) ) {
225
- unset( $_query[ $key ] );
226
- }
227
- }
228
- foreach ( $album__in as $alb ) {
229
- $album = $gmDB->get_term( $alb );
230
- if ( empty( $album ) || is_wp_error( $album ) || $album->count == 0 ) {
231
- continue;
232
- }
233
- $terms[ $alb ] = $album;
234
- $new_query[ $alb ] = array_merge( $_query, array( 'album__in' => $alb ) );
235
- }
236
- if ( ! empty( $new_query ) ) {
237
- $query = $new_query;
238
- }
239
- }
240
- }
241
- if ( empty( $terms ) ) {
242
- $terms = array( $id => $term );
243
- }
244
- $gallery = (array) $term;
245
- } else {
246
- $terms = array( $id => (object) $gallery );
247
- }
248
-
249
- foreach ( $query as $term_id => $args ) {
250
- if ( empty( $args['orderby'] ) || empty( $args['order'] ) ) {
251
- $term_query_order = null;
252
- if ( isset( $args['tag__in'] ) && ( ! isset( $args['category__in'] ) && ! isset( $args['album__in'] ) ) ) {
253
- $term_query_order = array(
254
- 'orderby' => $gmGallery->options['in_tag_orderby'],
255
- 'order' => $gmGallery->options['in_tag_order'],
256
- );
257
- }
258
- if ( isset( $args['category__in'] ) && ! isset( $args['album__in'] ) ) {
259
- $cat_ids = wp_parse_id_list( $args['category__in'] );
260
- if ( 1 === count( $cat_ids ) ) {
261
- $cat_meta = $gmDB->get_metadata( 'gmedia_term', $cat_ids[0] );
262
- $term_query_order = array(
263
- 'orderby' => ! empty( $cat_meta['_orderby'][0] ) ? $cat_meta['_orderby'][0] : $gmGallery->options['in_category_orderby'],
264
- 'order' => ! empty( $cat_meta['_order'][0] ) ? $cat_meta['_order'][0] : $gmGallery->options['in_category_order'],
265
- );
266
- }
267
- }
268
- if ( isset( $args['album__in'] ) ) {
269
- $alb_ids = wp_parse_id_list( $args['album__in'] );
270
- if ( 1 === count( $alb_ids ) ) {
271
- $album_meta = $gmDB->get_metadata( 'gmedia_term', $alb_ids[0] );
272
- $term_query_order = array(
273
- 'orderby' => ! empty( $album_meta['_orderby'][0] ) ? $album_meta['_orderby'][0] : $gmGallery->options['in_album_orderby'],
274
- 'order' => ! empty( $album_meta['_order'][0] ) ? $album_meta['_order'][0] : $gmGallery->options['in_album_order'],
275
- );
276
- }
277
- }
278
- if ( $term_query_order ) {
279
- $args = array_merge( $term_query_order, $args );
280
- }
281
- }
282
- $gmedia[ $term_id ] = $gmDB->get_gmedias( $args );
283
- }
284
-
285
- if ( $cache_expiration ) {
286
- set_transient( 'gm_cache_' . $cache_key, array( 'gallery' => $gallery, 'gmedia' => $gmedia, 'terms' => $terms, 'query' => $query ), $cache_expiration );
287
- }
288
- }
289
-
290
- if ( 0 === count( $gmedia ) ) {
291
- return '<div class="gmedia_gallery gmedia_gallery_empty" data-gmid="' . esc_attr( $id ) . '" data-module="' . $_module . '">' . __( 'Gallery is empty' ) . '<br />' . $shortcode_post_content . '</div>';
292
- }
293
- } else {
294
- if ( ! empty( $cache_value ) && is_array( $cache_value ) ) {
295
- $query = $cache_value;
296
- } else {
297
- $gmDB->gmedias_album_stuff( $query );
298
- $gmDB->gmedias_category_stuff( $query );
299
- $gmDB->gmedias_tag_stuff( $query );
300
- if ( isset( $query['album__in'] ) ) {
301
- $query['album__in'] = join( ',', $query['album__in'] );
302
- }
303
- if ( isset( $query['category__in'] ) ) {
304
- $query['category__in'] = join( ',', $query['category__in'] );
305
- }
306
- if ( isset( $query['tag__in'] ) ) {
307
- $query['tag__in'] = join( ',', $query['tag__in'] );
308
- }
309
-
310
- if ( $cache_expiration ) {
311
- set_transient( 'gm_cache_' . $cache_key, $query, $cache_expiration );
312
- }
313
- }
314
- }
315
-
316
- $sc_id = str_replace( ' ', '_', "GmediaGallery_{$id}" );
317
-
318
- $sc_classes = "gmedia_gallery {$_module}_module";
319
- if ( $is_bot ) {
320
- $sc_classes .= " is_bot";
321
- }
322
- if ( $is_mob ) {
323
- $sc_classes .= " is_mobile";
324
- }
325
- if ( ! empty( $atts['class'] ) ) {
326
- $sc_classes .= ' ' . esc_attr( $atts['class'] );
327
- }
328
-
329
- $sc_styles = '';
330
- if ( ! empty( $atts['style'] ) ) {
331
- $sc_styles = ' style="' . esc_attr( $atts['style'] ) . '"';
332
- }
333
-
334
- do_action( 'pre_gmedia_shortcode' );
335
-
336
- if ( ! empty( $cache_value_m ) ) {
337
- $out = $cache_value_m;
338
- } else {
339
- $out = '<div class="' . $sc_classes . '" id="' . esc_attr( $sc_id ) . '" data-gmid="' . esc_attr( $id ) . '" data-module="' . esc_attr( $_module ) . '"' . $sc_styles . '>';
340
-
341
- if (
342
- in_array( $_module, array( 'albums-switcher', 'photocluster', 'albumsview' ) )
343
- && empty( $query['album__in'] ) && empty( $query['category__in'] ) && empty( $query['tag__in'] )
344
- ) {
345
- $out = __( 'This Gmedia gallery module require at least one term (album, category or tag) to be chosen in Query Builder.', 'grand-media' );
346
- $module_content = '';
347
- } else {
348
- ob_start();
349
- /** @noinspection PhpIncludeInspection */
350
- include( $module['path'] . '/init.php' );
351
- $module_content = ob_get_contents();
352
- ob_end_clean();
353
-
354
- $matches = array();
355
- preg_match_all( '/<img[\s\r\n]+.*?>/is', $module_content, $matches );
356
- $search = array();
357
- $replace = array();
358
- foreach ( $matches[0] as $img_html ) {
359
- // add the noLazy class to the img element.
360
- if ( preg_match( '/class=["\']/i', $img_html ) ) {
361
- $replace_html = preg_replace( '/class=(["\'])(.*?)["\']/is', 'class=$1noLazy $2$1', $img_html );
362
- } else {
363
- $replace_html = preg_replace( '/<img/is', '<img class="noLazy"', $img_html );
364
- }
365
- array_push( $search, $img_html );
366
- array_push( $replace, $replace_html );
367
- }
368
- $search = array_unique( $search );
369
- $replace = array_unique( $replace );
370
- $module_content = str_replace( $search, $replace, $module_content );
371
- }
372
-
373
- if ( $moduleCSS || $customCSS ) {
374
- $out .= "<style type='text/css' class='gmedia_module_style_import'>{$moduleCSS}";
375
- if ( $customCSS ) {
376
- $out .= "/**** .{$_module}_module #{$sc_id} ****/{$customCSS}";
377
- }
378
- $out .= '</style>';
379
- }
380
- $out .= $shortcode_post_content;
381
- $out .= $module_content;
382
- $out .= '</div>';
383
-
384
- if ( $cache_expiration && ! $is_bot ) {
385
- set_transient( 'gm_cache_m_' . $cache_key . $mob_cache_key, $out, $cache_expiration );
386
- }
387
- }
388
-
389
- $id_duplicount = 0;
390
- if ( empty( $gmedia_shortcode_ids ) ) {
391
- $gmedia_shortcode_ids[] = (string) $id;
392
- } else {
393
- if ( in_array( $id, $gmedia_shortcode_ids ) ) {
394
- $id_duplicount = 1;
395
- while ( true ) {
396
- if ( in_array( "{$id}_{$id_duplicount}", $gmedia_shortcode_ids ) ) {
397
- $id_duplicount ++;
398
- } else {
399
- $gmedia_shortcode_ids[] = "{$id}_{$id_duplicount}";
400
- break;
401
- }
402
- }
403
- } else {
404
- $gmedia_shortcode_ids[] = (string) $id;
405
- }
406
- }
407
-
408
- if ( $id_duplicount ) {
409
- $_sc_id = "{$sc_id}_{$id_duplicount}";
410
- $out = str_replace( $sc_id, $_sc_id, $out );
411
-
412
- $gmedia_shortcode_instance[ $atts_hash ]['_id'] = $_sc_id;
413
- }
414
- $gmedia_shortcode_instance[ $atts_hash ]['id'] = $sc_id;
415
- $gmedia_shortcode_instance[ $atts_hash ]['shortcode'] = $out;
416
-
417
- do_action( 'gmedia_shortcode' );
418
-
419
- if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) {
420
- do_action( 'gmedia_enqueue_scripts' );
421
- }
422
-
423
- return $out;
424
-
425
- }
426
-
427
- /**
428
- * Process the [gmedia _raw] shortcode in priority 4.
429
- * Since the gmedia raw shortcode needs to be run earlier than other shortcodes,
430
- * this function removes all existing shortcodes, uses the shortcode parser to grab all [gmedia blocks],
431
- * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
432
- *
433
- * @uses $shortcode_tags
434
- * @uses remove_all_shortcodes()
435
- * @uses add_shortcode()
436
- * @uses do_shortcode()
437
- *
438
- * @param string $content Content to parse
439
- *
440
- * @return string Content with shortcode parsed
441
- */
442
- function get_gmedia_unformatted_shortcode_blocks( $content ) {
443
- global $gmGallery;
444
-
445
- if ( ! (int) $gmGallery->options['shortcode_raw'] ) {
446
- return $content;
447
- }
448
-
449
- global $shortcode_tags;
450
-
451
- // Back up current registered shortcodes and clear them all out
452
- $orig_shortcode_tags = $shortcode_tags;
453
- remove_all_shortcodes();
454
-
455
- // gmedia_raw_shortcode(), below, saves the rawr blocks into $this->unformatted_shortcode_blocks[]
456
- add_shortcode( 'gmedia', 'gmedia_raw_shortcode' );
457
- add_shortcode( 'gm', 'gmedia_raw_shortcode' );
458
-
459
- // Do the shortcode (only the [gmedia] shortcodes are now registered)
460
- $content = do_shortcode( $content );
461
-
462
- // Put the original shortcodes back for normal processing at priority 11
463
- $shortcode_tags = $orig_shortcode_tags;
464
-
465
- return $content;
466
- }
467
-
468
- /**
469
- * @param $atts
470
- * @param string $shortcode_post_content
471
- *
472
- * @return string
473
- */
474
- function gmedia_raw_shortcode( $atts, $shortcode_post_content = '' ) {
475
- global $wp_filter, $merged_filters, $wp_current_filter;
476
- $wp_filter_ = $wp_filter;
477
- $merged_filters_ = $merged_filters;
478
- $wp_current_filter_ = $wp_current_filter;
479
- $noraw = do_shortcode( apply_filters( 'the_content', '[raw][/raw]' ) );
480
- $wp_filter = $wp_filter_;
481
- $merged_filters = $merged_filters_;
482
- $wp_current_filter = $wp_current_filter_;
483
-
484
- global $gmedia_shortcode_instance;
485
-
486
- unset( $atts['_raw'], $atts['_copy'] );
487
- $atts_hash = md5( build_query( $atts ) );
488
- $atts['_raw'] = '1';
489
- gmedia_shortcode( $atts, $shortcode_post_content );
490
- unset( $atts['_raw'] );
491
-
492
- $atts['_copy'] = $gmedia_shortcode_instance[ $atts_hash ]['copy'];
493
- $shortcode_atts = '';
494
- // Put the shortcode tag back with raw index, so it gets processed again below.
495
- foreach ( $atts as $key => $value ) {
496
- $shortcode_atts .= " {$key}='{$value}'";
497
- }
498
- if ( ! $noraw ) {
499
- return "[raw][gmedia{$shortcode_atts}]{$shortcode_post_content}[/gmedia][/raw]";
500
- } else {
501
- return "[gmedia{$shortcode_atts}]{$shortcode_post_content}[/gmedia]";
502
- }
503
- }
504
-
505
- /**
506
- * @param $id
507
- *
508
- * @return object
509
- */
510
- function gmedia_shortcode_id_data( $id ) {
511
- global $gmDB, $gmCore;
512
-
513
- $item = $gmDB->get_term( $id );
514
-
515
- if ( empty( $item ) || is_wp_error( $item ) ) {
516
- return false;
517
- }
518
-
519
- $meta = $gmDB->get_metadata( 'gmedia_term', $item->term_id );
520
-
521
- if ( $item->global ) {
522
- $item->author_name = get_the_author_meta( 'display_name', $item->global );
523
- } else {
524
- $item->author_name = '';
525
- }
526
-
527
- $post_id = isset( $meta['_post_ID'][0] ) ? (int) $meta['_post_ID'][0] : 0;
528
- $item->post_id = $post_id;
529
- if ( $post_id ) {
530
- $post_item = get_post( $post_id );
531
- if ( $post_item ) {
532
- $item->slug = $post_item->post_name;
533
- $item->post_password = $post_item->post_password;
534
- $item->comment_count = $post_item->comment_count;
535
- $item->comment_status = $post_item->comment_status;
536
- }
537
- }
538
-
539
- $item->custom_meta = array();
540
- $item->meta = array();
541
- foreach ( $meta as $key => $value ) {
542
- if ( $gmCore->is_protected_meta( $key, 'gmedia_term' ) ) {
543
- $item->meta[ $key ] = $value[0];
544
- } else {
545
- $item->custom_meta[ $key ] = $value;
546
- }
547
- }
548
-
549
- return apply_filters( 'gmedia_shortcode_id_data', $item );
550
- }
 
 
 
 
 
1
+ <?php
2
+ if ( preg_match( '#' . basename( dirname( __FILE__ ) ) . '/' . basename( __FILE__ ) . '#', $_SERVER['PHP_SELF'] ) ) {
3
+ die( 'You are not allowed to call this page directly.' );
4
+ }
5
+
6
+ /** *********************** **/
7
+ /** Shortcodes Declarations **/
8
+ /** *********************** **/
9
+ add_shortcode( 'gmedia', 'gmedia_shortcode' );
10
+ add_shortcode( 'gm', 'gmedia_shortcode' );
11
+
12
+ //add_filter('the_content', 'do_shortcode');
13
+ add_filter( 'the_content', 'get_gmedia_unformatted_shortcode_blocks', 4 );
14
+
15
+ /** ******************************* **/
16
+ /** Shortcodes Functions and Markup **/
17
+ /** ******************************* **/
18
+ $gmedia_shortcode_instance = array();
19
+
20
+ /**
21
+ * @param $atts
22
+ * @param string $shortcode_post_content
23
+ *
24
+ * @return string
25
+ */
26
+ function gmedia_shortcode( $atts, $shortcode_post_content = '' ) {
27
+ global $wp, $gmDB, $gmGallery, $gmCore;
28
+ global $gmedia_shortcode_instance, $gmedia_shortcode_ids;
29
+
30
+ $shortcode_raw = ( isset( $atts['_raw'] ) && '1' === $atts['_raw'] );
31
+ $shortcode_copy = isset( $atts['_copy'] ) ? (int) $atts['_copy'] : null;
32
+ unset( $atts['_raw'], $atts['_copy'] );
33
+
34
+ $atts_hash = md5( build_query( $atts ) );
35
+ if ( ! isset( $atts['id'] ) ) {
36
+ if ( ! empty( $atts['album'] ) ) {
37
+ $atts['id'] = $atts['album'];
38
+ unset( $atts['album'] );
39
+ } elseif ( ! empty( $atts['category'] ) ) {
40
+ $atts['id'] = $atts['category'];
41
+ unset( $atts['category'] );
42
+ } elseif ( ! empty( $atts['tag'] ) ) {
43
+ $atts['id'] = $atts['tag'];
44
+ unset( $atts['tag'] );
45
+ }
46
+ }
47
+
48
+ if ( isset( $gmedia_shortcode_instance[ $atts_hash ] ) ) {
49
+ $out = $gmedia_shortcode_instance[ $atts_hash ]['shortcode'];
50
+ ++ $gmedia_shortcode_instance[ $atts_hash ]['copy'];
51
+ if ( ! $shortcode_raw ) {
52
+ $sc_id = $gmedia_shortcode_instance[ $atts_hash ]['id'];
53
+ $sc_copy = ( null === $shortcode_copy ) ? $gmedia_shortcode_instance[ $atts_hash ]['copy'] : $shortcode_copy;
54
+ if ( $sc_copy ) {
55
+ $out = str_replace( $sc_id, "{$sc_id}_{$sc_copy}", $out );
56
+ }
57
+ }
58
+
59
+ return $out;
60
+ } else {
61
+ $gmedia_shortcode_instance[ $atts_hash ] = array(
62
+ 'shortcode' => '',
63
+ 'id' => '',
64
+ 'copy' => 0,
65
+ );
66
+ }
67
+ $shortcode_raw = ( isset( $gmGallery->options['shortcode_raw'] ) && '1' === $gmGallery->options['shortcode_raw'] );
68
+ if ( ! isset( $_GET['is_admin_preview'] ) ) {
69
+ $cache_expiration = isset( $gmGallery->options['cache_expiration'] ) ? (int) $gmGallery->options['cache_expiration'] * HOUR_IN_SECONDS : HOUR_IN_SECONDS;
70
+ } else {
71
+ $cache_expiration = 0;
72
+ }
73
+
74
+ $query = array();
75
+ if ( ! empty( $atts['query'] ) ) {
76
+ if ( is_string( $atts['query'] ) ) {
77
+ $atts['query'] = html_entity_decode( $atts['query'] );
78
+ }
79
+ $query = wp_parse_args( $atts['query'], array() );
80
+ }
81
+
82
+ $atts_module = ! empty( $atts['module'] );
83
+ $_module = $atts_module ? $atts['module'] : $gmGallery->options['default_gmedia_module'];
84
+ $preset = $gmCore->getModulePreset( $_module );
85
+ $_module = $preset['module'];
86
+ $settings = $preset['settings'];
87
+
88
+ $id = isset( $atts['id'] ) ? (int) $atts['id'] : 0;
89
+ $userid = get_current_user_id();
90
+ if ( $id && ( $term = gmedia_shortcode_id_data( $id ) ) ) {
91
+ $is_gallery_visible = ( 'publish' !== $term->status && ! $userid ) || ( 'draft' === $term->status && $userid != $term->global && ! is_super_admin() );
92
+ if ( apply_filters( 'is_gmedia_gallery_visible', $is_gallery_visible ) ) {
93
+ return '';
94
+ }
95
+
96
+ $taxterm = str_replace( 'gmedia_', '', $term->taxonomy );
97
+ if ( $taxterm === 'gallery' ) {
98
+ if ( ! empty( $term->meta['_query'] ) ) {
99
+ $query = array_merge( $query, $term->meta['_query'] );
100
+ }
101
+ } else {
102
+ $query = array_merge( $query, array( "{$taxterm}__in" => $term->term_id ) );
103
+ }
104
+
105
+ if ( ! empty( $term->meta['_module'] ) ) {
106
+ $_module = $term->meta['_module'];
107
+ } elseif ( ! $atts_module && ! empty( $term->meta['_module_preset'] ) ) {
108
+ $preset = $gmCore->getModulePreset( $term->meta['_module_preset'] );
109
+ $_module = $preset['module'];
110
+ $settings = $preset['settings'];
111
+
112
+ $term->meta['_module'] = $_module;
113
+ $term->meta['_settings'][ $_module ] = (array) $settings[ $_module ];
114
+ }
115
+ if ( isset( $term->meta['_settings'][ $_module ] ) ) {
116
+ $settings = (array) $term->meta['_settings'];
117
+ }
118
+ } elseif ( isset( $atts['library'] ) && ( $quick_gallery = wp_parse_id_list( $atts['library'] ) ) ) {
119
+ $query = array_merge( $query, array( 'gmedia__in' => $quick_gallery ) );
120
+ if ( ! isset( $query['orderby'] ) ) {
121
+ $query['orderby'] = 'gmedia__in';
122
+ }
123
+ }
124
+ if ( empty( $term ) ) {
125
+ $term = (object) array(
126
+ 'name' => '',
127
+ 'description' => '',
128
+ );
129
+ }
130
+ if ( isset( $atts['orderby'] ) ) {
131
+ $query['orderby'] = $atts['orderby'];
132
+ }
133
+ if ( isset( $atts['order'] ) ) {
134
+ $query['order'] = $atts['order'];
135
+ }
136
+
137
+ if ( $userid && current_user_can( 'gmedia_gallery_manage' ) && ( $preview_module = $gmCore->_get( 'gmedia_module' ) ) ) {
138
+ if ( $preview_module != $_module ) {
139
+ $_module = $preview_module;
140
+ $preset = $gmCore->getModulePreset( $_module );
141
+ if ( $preset['module'] == $_module ) {
142
+ $settings = $preset['settings'];
143
+ } else {
144
+ $settings = array( $_module => array() );
145
+ }
146
+ }
147
+ }
148
+
149
+ $gallery = array();
150
+ if ( ! $id ) {
151
+ $id = $atts_hash;
152
+ // Backward compatibility
153
+ $gallery = array(
154
+ 'term_id' => $id,
155
+ 'name' => __( 'Gallery', 'grand-media' ),
156
+ 'description' => '',
157
+ );
158
+ }
159
+
160
+ $module = $gmCore->get_module_path( $_module );
161
+ if ( ! $module || ! is_file( $module['path'] . '/index.php' ) || ! is_file( $module['path'] . '/settings.php' ) ) {
162
+ return '<div class="gmedia_gallery gmediaShortcodeError" data-gmid="' . $id . '" data-error="' . $_module . ': folder missed or module broken">' . $shortcode_post_content . '</div>';
163
+ }
164
+
165
+ if ( $_module !== $module['name'] ) {
166
+ $_module = $module['name'];
167
+ $settings = array( $_module => array() );
168
+ }
169
+
170
+ if ( ! empty( $atts['preset'] ) ) {
171
+ $preset = $gmDB->get_term( $atts['preset'], 'gmedia_module' );
172
+ if ( ! empty( $preset ) && ! is_wp_error( $preset ) && ( $module['name'] == $preset->status ) ) {
173
+ $settings = array( $module['name'] => (array) maybe_unserialize( $preset->description ) );
174
+ }
175
+ }
176
+
177
+ $protected_query_args = array( 'status' => array( 'publish' ) );
178
+ if ( $userid ) {
179
+ $protected_query_args['status'][] = 'private';
180
+ }
181
+ $query = array_merge( apply_filters( 'gmedia_shortcode_query', $query, $id ), $protected_query_args );
182
+
183
+ include( $module['path'] . '/index.php' );
184
+ include( $module['path'] . '/settings.php' );
185
+ $module['info'] = isset( $module_info ) ? $module_info : array( 'dependencies' => '' );
186
+ $module['options'] = isset( $default_options ) ? $default_options : array();
187
+
188
+ $settings = apply_filters( 'gmedia_shortcode_settings', $gmCore->array_diff_keyval_recursive( (array) $settings[ $module['name'] ], $module['options'], false ) );
189
+
190
+ $moduleCSS = isset( $gmGallery->do_module[ $_module ] ) ? '' : $gmGallery->load_module_styles( $module );
191
+ $customCSS = ( isset( $settings['customCSS'] ) && ( '' !== trim( $settings['customCSS'] ) ) ) ? $settings['customCSS'] : '';
192
+ $current_url = home_url($wp->request);
193
+
194
+ $gmGallery->do_module[ $_module ] = $module;
195
+ $gmGallery->shortcode[ $id ] = compact( 'id', 'query', 'module', 'settings', 'term', 'current_url' );
196
+
197
+ $is_bot = false;
198
+ if ( ! ( $is_mob = wp_is_mobile() ) ) {
199
+ $is_bot = $gmCore->is_bot();
200
+ }
201
+ $mob_cache_key = $is_mob ? '_mob' : '';
202
+
203
+ if ( $cache_expiration ) {
204
+ $cache_key = md5( json_encode( $gmGallery->shortcode[ $id ] ) );
205
+ $cache_value = get_transient( 'gm_cache_' . $cache_key );
206
+ if ( ! $is_bot ) {
207
+ $cache_value_m = get_transient( 'gm_cache_m_' . $cache_key . $mob_cache_key );
208
+ } else {
209
+ $cache_value_m = false;
210
+ }
211
+ }
212
+
213
+ unset( $settings['customCSS'] );
214
+
215
+ if ( empty( $module['info']['branch'] ) ) {
216
+ $gmedia = array();
217
+ if ( ! empty( $cache_value ) && is_array( $cache_value ) ) {
218
+ extract( $cache_value, EXTR_OVERWRITE );
219
+ } else {
220
+ $query = array( $id => $query );
221
+ if ( ! empty( $term ) ) {
222
+ if ( in_array( $_module, array( 'afflux', 'afflux-mod', 'cube', 'flatwall', 'green-style', 'minima', 'optima', 'photo-blog', 'photo-pro', 'slider', 'sphere' ) ) ) {
223
+ add_filter( 'jetpack_photon_skip_image', 'jetpack_photon_skip_gmedia', 10, 3 );
224
+ $_query = array_merge( $query[ $id ], array( 'album__status' => $protected_query_args['status'] ) );
225
+ $gmDB->gmedias_album_stuff( $_query );
226
+ if ( ! empty( $_query['album__in'] ) && empty( $_query['album__not_in'] ) ) {
227
+ $album__in = wp_parse_id_list( $_query['album__in'] );
228
+ foreach ( $_query as $key => $q ) {
229
+ if ( 'alb' === substr( $key, 0, 3 ) ) {
230
+ unset( $_query[ $key ] );
231
+ }
232
+ }
233
+ foreach ( $album__in as $alb ) {
234
+ $album = $gmDB->get_term( $alb );
235
+ if ( empty( $album ) || is_wp_error( $album ) || $album->count == 0 ) {
236
+ continue;
237
+ }
238
+ $terms[ $alb ] = $album;
239
+ $new_query[ $alb ] = array_merge( $_query, array( 'album__in' => $alb ) );
240
+ }
241
+ if ( ! empty( $new_query ) ) {
242
+ $query = $new_query;
243
+ }
244
+ }
245
+ }
246
+ if ( empty( $terms ) ) {
247
+ $terms = array( $id => $term );
248
+ }
249
+ $gallery = (array) $term;
250
+ } else {
251
+ $terms = array( $id => (object) $gallery );
252
+ }
253
+
254
+ foreach ( $query as $term_id => $args ) {
255
+ if ( empty( $args['orderby'] ) || empty( $args['order'] ) ) {
256
+ $term_query_order = null;
257
+ if ( isset( $args['tag__in'] ) && ( ! isset( $args['category__in'] ) && ! isset( $args['album__in'] ) ) ) {
258
+ $term_query_order = array(
259
+ 'orderby' => $gmGallery->options['in_tag_orderby'],
260
+ 'order' => $gmGallery->options['in_tag_order'],
261
+ );
262
+ }
263
+ if ( isset( $args['category__in'] ) && ! isset( $args['album__in'] ) ) {
264
+ $cat_ids = wp_parse_id_list( $args['category__in'] );
265
+ if ( 1 === count( $cat_ids ) ) {
266
+ $cat_meta = $gmDB->get_metadata( 'gmedia_term', $cat_ids[0] );
267
+ $term_query_order = array(
268
+ 'orderby' => ! empty( $cat_meta['_orderby'][0] ) ? $cat_meta['_orderby'][0] : $gmGallery->options['in_category_orderby'],
269
+ 'order' => ! empty( $cat_meta['_order'][0] ) ? $cat_meta['_order'][0] : $gmGallery->options['in_category_order'],
270
+ );
271
+ }
272
+ }
273
+ if ( isset( $args['album__in'] ) ) {
274
+ $alb_ids = wp_parse_id_list( $args['album__in'] );
275
+ if ( 1 === count( $alb_ids ) ) {
276
+ $album_meta = $gmDB->get_metadata( 'gmedia_term', $alb_ids[0] );
277
+ $term_query_order = array(
278
+ 'orderby' => ! empty( $album_meta['_orderby'][0] ) ? $album_meta['_orderby'][0] : $gmGallery->options['in_album_orderby'],
279
+ 'order' => ! empty( $album_meta['_order'][0] ) ? $album_meta['_order'][0] : $gmGallery->options['in_album_order'],
280
+ );
281
+ }
282
+ }
283
+ if ( $term_query_order ) {
284
+ $args = array_merge( $term_query_order, $args );
285
+ }
286
+ }
287
+ $gmedia[ $term_id ] = $gmDB->get_gmedias( $args );
288
+ }
289
+
290
+ if ( $cache_expiration ) {
291
+ set_transient( 'gm_cache_' . $cache_key, array( 'gallery' => $gallery, 'gmedia' => $gmedia, 'terms' => $terms, 'query' => $query ), $cache_expiration );
292
+ }
293
+ }
294
+
295
+ if ( 0 === count( $gmedia ) ) {
296
+ return '<div class="gmedia_gallery gmedia_gallery_empty" data-gmid="' . esc_attr( $id ) . '" data-module="' . $_module . '">' . __( 'Gallery is empty' ) . '<br />' . $shortcode_post_content . '</div>';
297
+ }
298
+ } else {
299
+ if ( ! empty( $cache_value ) && is_array( $cache_value ) ) {
300
+ $query = $cache_value;
301
+ } else {
302
+ $gmDB->gmedias_album_stuff( $query );
303
+ $gmDB->gmedias_category_stuff( $query );
304
+ $gmDB->gmedias_tag_stuff( $query );
305
+ if ( isset( $query['album__in'] ) ) {
306
+ $query['album__in'] = join( ',', $query['album__in'] );
307
+ }
308
+ if ( isset( $query['category__in'] ) ) {
309
+ $query['category__in'] = join( ',', $query['category__in'] );
310
+ }
311
+ if ( isset( $query['tag__in'] ) ) {
312
+ $query['tag__in'] = join( ',', $query['tag__in'] );
313
+ }
314
+
315
+ if ( $cache_expiration ) {
316
+ set_transient( 'gm_cache_' . $cache_key, $query, $cache_expiration );
317
+ }
318
+ }
319
+ }
320
+
321
+ $sc_id = str_replace( ' ', '_', "GmediaGallery_{$id}" );
322
+
323
+ $sc_classes = "gmedia_gallery {$_module}_module";
324
+ if ( $is_bot ) {
325
+ $sc_classes .= " is_bot";
326
+ }
327
+ if ( $is_mob ) {
328
+ $sc_classes .= " is_mobile";
329
+ }
330
+ if ( ! empty( $atts['class'] ) ) {
331
+ $sc_classes .= ' ' . esc_attr( $atts['class'] );
332
+ }
333
+
334
+ $sc_styles = '';
335
+ if ( ! empty( $atts['style'] ) ) {
336
+ $sc_styles = ' style="' . esc_attr( $atts['style'] ) . '"';
337
+ }
338
+
339
+ do_action( 'pre_gmedia_shortcode' );
340
+
341
+ if ( ! empty( $cache_value_m ) ) {
342
+ $out = $cache_value_m;
343
+ } else {
344
+ $out = '<div class="' . $sc_classes . '" id="' . esc_attr( $sc_id ) . '" data-gmid="' . esc_attr( $id ) . '" data-module="' . esc_attr( $_module ) . '"' . $sc_styles . '>';
345
+
346
+ if (
347
+ in_array( $_module, array( 'albums-switcher', 'photocluster', 'albumsview' ) )
348
+ && empty( $query['album__in'] ) && empty( $query['category__in'] ) && empty( $query['tag__in'] )
349
+ ) {
350
+ $out = __( 'This Gmedia gallery module require at least one term (album, category or tag) to be chosen in Query Builder.', 'grand-media' );
351
+ $module_content = '';
352
+ } else {
353
+ ob_start();
354
+ /** @noinspection PhpIncludeInspection */
355
+ include( $module['path'] . '/init.php' );
356
+ $module_content = ob_get_contents();
357
+ ob_end_clean();
358
+
359
+ $matches = array();
360
+ preg_match_all( '/<img[\s\r\n]+.*?>/is', $module_content, $matches );
361
+ $search = array();
362
+ $replace = array();
363
+ foreach ( $matches[0] as $img_html ) {
364
+ // add the noLazy class to the img element.
365
+ if ( preg_match( '/class=["\']/i', $img_html ) ) {
366
+ $replace_html = preg_replace( '/class=(["\'])(.*?)["\']/is', 'class=$1noLazy $2$1', $img_html );
367
+ } else {
368
+ $replace_html = preg_replace( '/<img/is', '<img class="noLazy"', $img_html );
369
+ }
370
+ array_push( $search, $img_html );
371
+ array_push( $replace, $replace_html );
372
+ }
373
+ $search = array_unique( $search );
374
+ $replace = array_unique( $replace );
375
+ $module_content = str_replace( $search, $replace, $module_content );
376
+ }
377
+
378
+ if ( $moduleCSS || $customCSS ) {
379
+ $out .= "<style type='text/css' class='gmedia_module_style_import'>{$moduleCSS}";
380
+ if ( $customCSS ) {
381
+ $out .= "/**** .{$_module}_module #{$sc_id} ****/{$customCSS}";
382
+ }
383
+ $out .= '</style>';
384
+ }
385
+ $out .= $shortcode_post_content;
386
+ $out .= $module_content;
387
+ $out .= '</div>';
388
+
389
+ if ( $cache_expiration && ! $is_bot ) {
390
+ set_transient( 'gm_cache_m_' . $cache_key . $mob_cache_key, $out, $cache_expiration );
391
+ }
392
+ }
393
+
394
+ $id_duplicount = 0;
395
+ if ( empty( $gmedia_shortcode_ids ) ) {
396
+ $gmedia_shortcode_ids[] = (string) $id;
397
+ } else {
398
+ if ( in_array( $id, $gmedia_shortcode_ids ) ) {
399
+ $id_duplicount = 1;
400
+ while ( true ) {
401
+ if ( in_array( "{$id}_{$id_duplicount}", $gmedia_shortcode_ids ) ) {
402
+ $id_duplicount ++;
403
+ } else {
404
+ $gmedia_shortcode_ids[] = "{$id}_{$id_duplicount}";
405
+ break;
406
+ }
407
+ }
408
+ } else {
409
+ $gmedia_shortcode_ids[] = (string) $id;
410
+ }
411
+ }
412
+
413
+ if ( $id_duplicount ) {
414
+ $_sc_id = "{$sc_id}_{$id_duplicount}";
415
+ $out = str_replace( $sc_id, $_sc_id, $out );
416
+
417
+ $gmedia_shortcode_instance[ $atts_hash ]['_id'] = $_sc_id;
418
+ }
419
+ $gmedia_shortcode_instance[ $atts_hash ]['id'] = $sc_id;
420
+ $gmedia_shortcode_instance[ $atts_hash ]['shortcode'] = $out;
421
+
422
+ do_action( 'gmedia_shortcode' );
423
+
424
+ if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) {
425
+ do_action( 'gmedia_enqueue_scripts' );
426
+ }
427
+
428
+ return $out;
429
+
430
+ }
431
+
432
+ /**
433
+ * Process the [gmedia _raw] shortcode in priority 4.
434
+ * Since the gmedia raw shortcode needs to be run earlier than other shortcodes,
435
+ * this function removes all existing shortcodes, uses the shortcode parser to grab all [gmedia blocks],
436
+ * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
437
+ *
438
+ * @uses $shortcode_tags
439
+ * @uses remove_all_shortcodes()
440
+ * @uses add_shortcode()
441
+ * @uses do_shortcode()
442
+ *
443
+ * @param string $content Content to parse
444
+ *
445
+ * @return string Content with shortcode parsed
446
+ */
447
+ function get_gmedia_unformatted_shortcode_blocks( $content ) {
448
+ global $gmGallery;
449
+
450
+ if ( ! (int) $gmGallery->options['shortcode_raw'] ) {
451
+ return $content;
452
+ }
453
+
454
+ global $shortcode_tags;
455
+
456
+ // Back up current registered shortcodes and clear them all out
457
+ $orig_shortcode_tags = $shortcode_tags;
458
+ remove_all_shortcodes();
459
+
460
+ // gmedia_raw_shortcode(), below, saves the rawr blocks into $this->unformatted_shortcode_blocks[]
461
+ add_shortcode( 'gmedia', 'gmedia_raw_shortcode' );
462
+ add_shortcode( 'gm', 'gmedia_raw_shortcode' );
463
+
464
+ // Do the shortcode (only the [gmedia] shortcodes are now registered)
465
+ $content = do_shortcode( $content );
466
+
467
+ // Put the original shortcodes back for normal processing at priority 11
468
+ $shortcode_tags = $orig_shortcode_tags;
469
+
470
+ return $content;
471
+ }
472
+
473
+ /**
474
+ * @param $atts
475
+ * @param string $shortcode_post_content
476
+ *
477
+ * @return string
478
+ */
479
+ function gmedia_raw_shortcode( $atts, $shortcode_post_content = '' ) {
480
+ global $wp_filter, $merged_filters, $wp_current_filter;
481
+ $wp_filter_ = $wp_filter;
482
+ $merged_filters_ = $merged_filters;
483
+ $wp_current_filter_ = $wp_current_filter;
484
+ $noraw = do_shortcode( apply_filters( 'the_content', '[raw][/raw]' ) );
485
+ $wp_filter = $wp_filter_;
486
+ $merged_filters = $merged_filters_;
487
+ $wp_current_filter = $wp_current_filter_;
488
+
489
+ global $gmedia_shortcode_instance;
490
+
491
+ unset( $atts['_raw'], $atts['_copy'] );
492
+ $atts_hash = md5( build_query( $atts ) );
493
+ $atts['_raw'] = '1';
494
+ gmedia_shortcode( $atts, $shortcode_post_content );
495
+ unset( $atts['_raw'] );
496
+
497
+ $atts['_copy'] = $gmedia_shortcode_instance[ $atts_hash ]['copy'];
498
+ $shortcode_atts = '';
499
+ // Put the shortcode tag back with raw index, so it gets processed again below.
500
+ foreach ( $atts as $key => $value ) {
501
+ $shortcode_atts .= " {$key}='{$value}'";
502
+ }
503
+ if ( ! $noraw ) {
504
+ return "[raw][gmedia{$shortcode_atts}]{$shortcode_post_content}[/gmedia][/raw]";
505
+ } else {
506
+ return "[gmedia{$shortcode_atts}]{$shortcode_post_content}[/gmedia]";
507
+ }
508
+ }
509
+
510
+ /**
511
+ * @param $id
512
+ *
513
+ * @return object
514
+ */
515
+ function gmedia_shortcode_id_data( $id ) {
516
+ global $gmDB, $gmCore;
517
+
518
+ $item = $gmDB->get_term( $id );
519
+
520
+ if ( empty( $item ) || is_wp_error( $item ) ) {
521
+ return false;
522
+ }
523
+
524
+ $meta = $gmDB->get_metadata( 'gmedia_term', $item->term_id );
525
+
526
+ if ( $item->global ) {
527
+ $item->author_name = get_the_author_meta( 'display_name', $item->global );
528
+ } else {
529
+ $item->author_name = '';
530
+ }
531
+
532
+ $post_id = isset( $meta['_post_ID'][0] ) ? (int) $meta['_post_ID'][0] : 0;
533
+ $item->post_id = $post_id;
534
+ if ( $post_id ) {
535
+ $post_item = get_post( $post_id );
536
+ if ( $post_item ) {
537
+ $item->slug = $post_item->post_name;
538
+ $item->post_password = $post_item->post_password;
539
+ $item->comment_count = $post_item->comment_count;
540
+ $item->comment_status = $post_item->comment_status;
541
+ }
542
+ }
543
+
544
+ $item->custom_meta = array();
545
+ $item->meta = array();
546
+ foreach ( $meta as $key => $value ) {
547
+ if ( $gmCore->is_protected_meta( $key, 'gmedia_term' ) ) {
548
+ $item->meta[ $key ] = $value[0];
549
+ } else {
550
+ $item->custom_meta[ $key ] = $value;
551
+ }
552
+ }
553
+
554
+ return apply_filters( 'gmedia_shortcode_id_data', $item );
555
+ }
module/amron/index.php CHANGED
@@ -3,7 +3,7 @@ $module_info = array(
3
  'base' => 'amron',
4
  'name' => 'amron',
5
  'title' => 'Amron',
6
- 'version' => '3.1',
7
  'author' => 'GalleryCreator',
8
  'description' => 'Responsive AJAX Gallery with Masonry layout. The gallery is completely customisable, resizable and is compatible with all browsers and devices (iPhone, iPad and Android smartphones). Required Gmedia Gallery plugin v1.14+',
9
  'type' => 'gallery',
3
  'base' => 'amron',
4
  'name' => 'amron',
5
  'title' => 'Amron',
6
+ 'version' => '4.5',
7
  'author' => 'GalleryCreator',
8
  'description' => 'Responsive AJAX Gallery with Masonry layout. The gallery is completely customisable, resizable and is compatible with all browsers and devices (iPhone, iPad and Android smartphones). Required Gmedia Gallery plugin v1.14+',
9
  'type' => 'gallery',
module/amron/js/script.js CHANGED
@@ -1 +1 @@
1
- !function(e){var t={};function i(o){if(t[o])return t[o].exports;var a=t[o]={i:o,l:!1,exports:{}};return e[o].call(a.exports,a,a.exports,i),a.l=!0,a.exports}i.m=e,i.c=t,i.d=function(e,t,o){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(i.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)i.d(o,a,function(t){return e[t]}.bind(null,a));return o},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=17)}([function(e,t,i){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var i=function(e,t){var i=e[1]||"",o=e[3];if(!o)return i;if(t&&"function"==typeof btoa){var a=(s=o,r=btoa(unescape(encodeURIComponent(JSON.stringify(s)))),l="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(r),"/*# ".concat(l," */")),n=o.sources.map((function(e){return"/*# sourceURL=".concat(o.sourceRoot).concat(e," */")}));return[i].concat(n).concat([a]).join("\n")}var s,r,l;return[i].join("\n")}(t,e);return t[2]?"@media ".concat(t[2],"{").concat(i,"}"):i})).join("")},t.i=function(e,i){"string"==typeof e&&(e=[[null,e,""]]);for(var o={},a=0;a<this.length;a++){var n=this[a][0];null!=n&&(o[n]=!0)}for(var s=0;s<e.length;s++){var r=e[s];null!=r[0]&&o[r[0]]||(i&&!r[2]?r[2]=i:i&&(r[2]="(".concat(r[2],") and (").concat(i,")")),t.push(r))}},t}},function(e,t,i){var o,a,n={},s=(o=function(){return window&&document&&document.all&&!window.atob},function(){return void 0===a&&(a=o.apply(this,arguments)),a}),r=function(e,t){return t?t.querySelector(e):document.querySelector(e)},l=function(e){var t={};return function(e,i){if("function"==typeof e)return e();if(void 0===t[e]){var o=r.call(this,e,i);if(window.HTMLIFrameElement&&o instanceof window.HTMLIFrameElement)try{o=o.contentDocument.head}catch(e){o=null}t[e]=o}return t[e]}}(),c=null,d=0,h=[],m=i(4);function u(e,t){for(var i=0;i<e.length;i++){var o=e[i],a=n[o.id];if(a){a.refs++;for(var s=0;s<a.parts.length;s++)a.parts[s](o.parts[s]);for(;s<o.parts.length;s++)a.parts.push(y(o.parts[s],t))}else{var r=[];for(s=0;s<o.parts.length;s++)r.push(y(o.parts[s],t));n[o.id]={id:o.id,refs:1,parts:r}}}}function p(e,t){for(var i=[],o={},a=0;a<e.length;a++){var n=e[a],s=t.base?n[0]+t.base:n[0],r={css:n[1],media:n[2],sourceMap:n[3]};o[s]?o[s].parts.push(r):i.push(o[s]={id:s,parts:[r]})}return i}function g(e,t){var i=l(e.insertInto);if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var o=h[h.length-1];if("top"===e.insertAt)o?o.nextSibling?i.insertBefore(t,o.nextSibling):i.appendChild(t):i.insertBefore(t,i.firstChild),h.push(t);else if("bottom"===e.insertAt)i.appendChild(t);else{if("object"!=typeof e.insertAt||!e.insertAt.before)throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");var a=l(e.insertAt.before,i);i.insertBefore(t,a)}}function v(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e);var t=h.indexOf(e);t>=0&&h.splice(t,1)}function f(e){var t=document.createElement("style");if(void 0===e.attrs.type&&(e.attrs.type="text/css"),void 0===e.attrs.nonce){var o=function(){0;return i.nc}();o&&(e.attrs.nonce=o)}return w(t,e.attrs),g(e,t),t}function w(e,t){Object.keys(t).forEach((function(i){e.setAttribute(i,t[i])}))}function y(e,t){var i,o,a,n;if(t.transform&&e.css){if(!(n="function"==typeof t.transform?t.transform(e.css):t.transform.default(e.css)))return function(){};e.css=n}if(t.singleton){var s=d++;i=c||(c=f(t)),o=C.bind(null,i,s,!1),a=C.bind(null,i,s,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(i=function(e){var t=document.createElement("link");return void 0===e.attrs.type&&(e.attrs.type="text/css"),e.attrs.rel="stylesheet",w(t,e.attrs),g(e,t),t}(t),o=T.bind(null,i,t),a=function(){v(i),i.href&&URL.revokeObjectURL(i.href)}):(i=f(t),o=k.bind(null,i),a=function(){v(i)});return o(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;o(e=t)}else a()}}e.exports=function(e,t){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(t=t||{}).attrs="object"==typeof t.attrs?t.attrs:{},t.singleton||"boolean"==typeof t.singleton||(t.singleton=s()),t.insertInto||(t.insertInto="head"),t.insertAt||(t.insertAt="bottom");var i=p(e,t);return u(i,t),function(e){for(var o=[],a=0;a<i.length;a++){var s=i[a];(r=n[s.id]).refs--,o.push(r)}e&&u(p(e,t),t);for(a=0;a<o.length;a++){var r;if(0===(r=o[a]).refs){for(var l=0;l<r.parts.length;l++)r.parts[l]();delete n[r.id]}}}};var b,x=(b=[],function(e,t){return b[e]=t,b.filter(Boolean).join("\n")});function C(e,t,i,o){var a=i?"":o.css;if(e.styleSheet)e.styleSheet.cssText=x(t,a);else{var n=document.createTextNode(a),s=e.childNodes;s[t]&&e.removeChild(s[t]),s.length?e.insertBefore(n,s[t]):e.appendChild(n)}}function k(e,t){var i=t.css,o=t.media;if(o&&e.setAttribute("media",o),e.styleSheet)e.styleSheet.cssText=i;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(i))}}function T(e,t,i){var o=i.css,a=i.sourceMap,n=void 0===t.convertToAbsoluteUrls&&a;(t.convertToAbsoluteUrls||n)&&(o=m(o)),a&&(o+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */");var s=new Blob([o],{type:"text/css"}),r=e.href;e.href=URL.createObjectURL(s),r&&URL.revokeObjectURL(r)}},function(e,t,i){var o=i(3);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".amron_module *{box-sizing:border-box !important}.gmedia-amron-collection-tags-cloud{position:relative;display:block;margin-top:10px;margin-bottom:2px;text-align:center}.gmedia-amron-collection-tags-cloud ul{margin:0 !important;padding:0 !important;list-style:none}.gmedia-amron-collection-tags-cloud ul li::before{display:none}.gmedia-amron-collection-tags-cloud ul li{display:inline-block;max-width:200px;padding:5px 8px !important;margin:3px !important;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;font-size:15px !important;border-radius:2px;text-decoration:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;transition:0.3s}.gmedia-amron-masonry-collection{position:relative;width:100%;min-height:200px;overflow:hidden;transition:transform 0.5s;z-index:2}.gmedia-amron-masonry-collection .gmedia-amron-content{position:relative;width:100%}.gmedia-amron-masonry-collection .gmedia-amron-content .gmedia-amron-collection-column{position:relative;float:left}.gmedia-amron-masonry-collection .gmedia-amron-header{position:relative;width:100%}.gmedia-amron-masonry-collection .gmedia-amron-header .gmedia-amron-navi{position:relative;width:100%;overflow:hidden}.gmedia-amron-masonry-collection .gmedia-amron-header .gmedia-amron-term-title{position:relative;display:inline-block;font-size:28px;line-height:34px}.gmedia-amron-masonry-collection .gmedia-amron-header .gmedia-amron-back-button{position:relative;float:left;margin:0 10px 0 0;width:54px;height:34px;border-radius:2px;cursor:pointer}.gmedia-amron-masonry-collection .gmedia-amron-header .gmedia-amron-back-button svg{width:100%;height:100%;vertical-align:baseline !important}.gmedia-amron-masonry-thumb-pint{position:relative;width:100%;opacity:0;transition:opacity 0.45s;float:left;box-sizing:border-box !important}.gmedia-amron-masonry-thumb-pint .gmedia-amron-image-holder{position:relative;width:100%;overflow:hidden}.gmedia-amron-masonry-thumb-pint .gmedia-amron-image-holder.gmedia-hover .gmedia-amron-zoom{transform:translateX(-10%)}.gmedia-amron-masonry-thumb-pint .gmedia-amron-image-holder.gmedia-hover img{transform:scale(1.1)}.gmedia-amron-masonry-thumb-pint .gmedia-amron-image-over{position:absolute;top:0;width:100%;height:100%;transition:opacity 0.5s;opacity:0}.gmedia-amron-masonry-thumb-pint .gmedia-amron-image-over.gmedia-hover{opacity:1}.gmedia-amron-masonry-thumb-pint .gmedia-amron-zoom{position:absolute;width:50px;height:50px;padding:15px !important;right:0;bottom:4px;transform:translateX(100%);margin:auto;cursor:pointer;transition:transform 0.2s}.gmedia-amron-masonry-thumb-pint .gmedia-amron-zoom.media{width:40px;height:40px;background-color:rgba(255,255,255,0.5);border-radius:50%;padding:5px !important;transform:translateX(-10%)}.gmedia-amron-masonry-thumb-pint .gmedia-amron-zoom.media svg{stroke:none}.gmedia-amron-masonry-thumb-pint .gmedia-amron-zoom svg{width:100%;height:100%;stroke:white;vertical-align:baseline !important}.gmedia-amron-masonry-thumb-pint img{display:block;border:0 !important;margin:0 !important;padding:0 !important;max-height:none !important;max-width:none !important;min-height:0 !important;min-width:0 !important;width:100% !important;height:auto !important;-webkit-backface-visibility:hidden;backface-visibility:hidden;transition:0.5s ease-out 0s;opacity:0}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-content{position:relative;display:block;padding:7px 20px !important;text-align:left;background-color:white;overflow:hidden;width:100%;z-index:1;box-sizing:border-box}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-title{position:relative;margin:10px 0 5px;display:block;font-size:18px;line-height:1.1;letter-spacing:1px;font-weight:600}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-description{position:relative;display:block;margin:10px 0;padding:0;font-size:13px}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-read-more{text-decoration:none;box-shadow:none;position:relative;cursor:pointer;font-size:10px;border-radius:2px;text-transform:uppercase;line-height:38px;padding:0 15px;font-weight:700;letter-spacing:1px;color:white;display:inline-block;background-color:rgba(0,0,0,0.59);transition:0.5s}.gmedia-amron-masonry-thumb-pint a:hover,.gmedia-amron-masonry-thumb-pint a:visited,.gmedia-amron-masonry-thumb-pint a:link,.gmedia-amron-masonry-thumb-pint a:active{text-decoration:none;box-shadow:none}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-menu-holder{position:relative;display:block;width:100%;margin:15px 0;overflow:hidden;text-align:right}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-menu-holder .gmedia-amron-items-buttons{position:relative;padding:9px;width:36px;height:36px;cursor:pointer;float:right;transition:.5s;box-sizing:border-box;margin:0 1px;border-radius:2px}.gmedia-amron-masonry-thumb-pint .gmedia-amron-item-menu-holder .gmedia-amron-items-buttons svg{width:100%;height:100%;transition:fill .2s;vertical-align:baseline !important}\n",""])},function(e,t){e.exports=function(e){var t="undefined"!=typeof window&&window.location;if(!t)throw new Error("fixUrls requires window.location");if(!e||"string"!=typeof e)return e;var i=t.protocol+"//"+t.host,o=i+t.pathname.replace(/\/[^\/]*$/,"/");return e.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(e,t){var a,n=t.trim().replace(/^"(.*)"$/,(function(e,t){return t})).replace(/^'(.*)'$/,(function(e,t){return t}));return/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(n)?e:(a=0===n.indexOf("//")?n:0===n.indexOf("/")?i+n:o+n.replace(/^\.\//,""),"url("+JSON.stringify(a)+")")}))}},function(e,t,i){var o=i(6);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-preloader{min-height:inherit;position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;z-index:100}.gmedia-preloader .c-spinner{animation:1s spinner linear infinite}@keyframes spinner{0%{transform:rotate(-360deg)}100%{transform:rotate(0deg)}}@keyframes _spinner{to{transform:rotate(-1440deg)}}@keyframes gmFadeIn{from{opacity:0}to{opacity:1}}\n",""])},function(e,t,i){var o=i(8);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-slider-view{position:absolute;overflow:hidden;left:0;right:0;top:0;bottom:0}.gmedia-slider-view *{box-sizing:border-box !important;line-height:1.4}.gmedia-slider-view .gmedia-slider-hints{position:absolute;display:inline-block;padding:5px 10px;font-size:12px;line-height:normal;background-color:rgba(0,0,0,0.8);color:white;transform:translateY(-100%);border-radius:2px;transition:.4s}.gmedia-slider-view.gmedia-slider-activate{pointer-events:auto;visibility:visible;opacity:1}.gmedia-slider-view .gmedia-slider-bg{width:100%;height:100%;transform:translateZ(0)}.gmedia-slider-view .gmedia-slider-wrap{position:absolute;user-select:none;width:100%;top:0;bottom:0}.gmedia-slider-view .miniScreen{margin-top:0;margin-bottom:0}.gmedia-slider-view .gmedia-slider-next-prev-button{position:absolute;width:45px;height:40px;top:50%;margin:0 10px;padding:0;cursor:pointer;transition:transform .5s ease-out;border-radius:2px}.gmedia-slider-view .gmedia-slider-next-prev-button.next-prev-button-mini-screen{display:none}.gmedia-slider-view .gmedia-slider-next-prev-button svg{width:100%;height:100%;vertical-align:baseline !important}.gmedia-slider-page-view{position:absolute;display:block;transform:translate3d(0px, 0px, 0px);width:100%;top:0;bottom:0;left:0;-webkit-backface-visibility:hidden;backface-visibility:hidden;overflow:hidden;-moz-user-select:none;-ms-user-select:none}.gmedia-slider-page-view .gmedia-slider-page-inner{position:absolute;display:block;left:0;top:0;bottom:0;width:100%;overflow:hidden;transform:translate3d(0, 0, 0);backface-visibility:hidden;-webkit-backface-visibility:hidden;-webkit-transform-origin:left top;transform-origin:left top;user-select:none}.gmedia-slider-page-view .gmedia-slider-page-inner img{-webkit-backface-visibility:hidden;backface-visibility:hidden;position:absolute !important;display:block !important;border:none !important;max-width:none !important;opacity:0;padding:0 !important;margin:0 !important;transition:.35s ease-out;user-select:none}.gmedia-slider-page-view .gmedia-slider-page-inner img.onLoad{opacity:1}.gmedia-slider-page-view .gmedia-slider-page-inner.video-play img{visibility:hidden}.gmedia-slider-page-view .gmedia-slider-page-inner .video-wrap{position:absolute;display:block;border:none}.gmedia-slider-page-view .gmedia-slider-page-inner .video-wrap iframe{width:100% !important;height:100% !important;top:0;left:0}.gmedia-slider-page-view .gmedia-slider-page-icon-holder{position:absolute;width:140px;height:140px;border-radius:50%;background-color:rgba(255,255,255,0.6);transform:translateY(-50%) translateX(-50%);left:50%;top:50%;padding:30px;visibility:hidden;will-change:transform;cursor:pointer}.gmedia-slider-page-view .gmedia-slider-page-icon-holder svg{width:100%;height:100%;fill:rgba(0,0,0,0.4)}.gmedia-slider-page-view.info-icon .gmedia-slider-page-icon-holder{visibility:visible}@keyframes rotate{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.gmWrapRotate{animation-name:rotate;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear}\n",""])},function(e,t,i){var o=i(10);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-item-menu-view{position:relative;overflow:hidden;float:left}.gmedia-item-menu-view.gmedia-item-menu-type-ultrabox{display:flex;flex-direction:row;flex-wrap:wrap;margin-right:5px}.gmedia-item-menu-view.gmedia-item-menu-type-ultrabox .gmedia-item-menu-button{padding:3px;width:43px;height:43px;margin:0 5px;border-radius:2px}.gmedia-item-menu-view.gmedia-item-menu-type-lightbox .gmedia-item-menu-button{margin:2px}.gmedia-item-menu-view.gmedia-item-menu-type-thumb .gmedia-item-menu-button{margin:1px}.gmedia-item-menu-view .gmedia-item-menu-button{position:relative;padding:9px;width:38px;height:38px;cursor:pointer;float:left;transition:background-color .2s, transform .4s ease-out;border-radius:2px}.gmedia-item-menu-view .gmedia-item-menu-button svg{width:100%;height:100%;fill:inherit;transition:fill .2s, transform .4s ease-out;vertical-align:baseline !important}\n",""])},function(e,t,i){var o=i(12);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-scroll-bar-wrap{position:relative;flex:none;width:490px;height:50px;margin:5px 0;overflow:hidden}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view{position:absolute}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item{position:absolute;height:50px;width:70px;overflow:hidden}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item .gmedia-scroll-bar-item-bg{position:absolute;left:3px;right:3px;top:3px;bottom:3px;background-position:center;-webkit-background-size:cover;background-size:cover;background-repeat:no-repeat;-webkit-backface-visibility:hidden;backface-visibility:hidden}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item .gmedia-scroll-bar-item-hover{position:absolute;opacity:0;transition:opacity .2s;pointer-events:none;top:0;left:0;right:0;bottom:0;border-style:solid;border-width:3px;border-color:#fff}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item .gmedia-scroll-bar-item-link{position:absolute;width:34px;height:34px;padding:6px;border-radius:50%;left:50%;top:50%;transform:translateY(-50%) translateX(-50%)}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item .gmedia-scroll-bar-item-link svg{width:100%;height:100%;fill:rgba(0,0,0,0.58);vertical-align:baseline !important}.gmedia-scroll-bar-wrap .gmedia-scroll-bar-view .gmedia-scroll-bar-item .gmedia-scroll-bar-item-link.rotate svg{animation:1s spinner linear infinite}.gm_grabbable{cursor:move;cursor:grab;cursor:-moz-grab;cursor:-webkit-grab}.gm_grabbable:active{cursor:grabbing;cursor:-moz-grabbing;cursor:-webkit-grabbing}\n",""])},function(e,t,i){var o=i(14);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-lightbox-b-view{position:fixed;z-index:99999;left:0;right:0;top:0;bottom:0;visibility:hidden;opacity:0;-ms-touch-action:none;touch-action:none;-webkit-text-size-adjust:100%;font-family:Arial, Helvetica, sans-serif;-webkit-transition:opacity .4s ease;transition:opacity .4s ease, visibility .4s ease}.gmedia-lightbox-b-view *{box-sizing:border-box !important;line-height:1.4}.gmedia-lightbox-b-view.gmedia-lightbox-b-activate{pointer-events:auto;visibility:visible;opacity:1}.gmedia-lightbox-b-view .gmedia-lightbox-b-bg{width:100%;height:100%;transform:translateZ(0)}.gmedia-lightbox-b-view .gmedia-lightbox-b-content{position:absolute;top:0;left:0;width:100%;height:100%}.gmedia-lightbox-b-view .gmedia-lightbox-b-header{position:absolute;padding:5px;left:0;top:0;width:100%;display:flex;flex-wrap:wrap;transform:translateY(-100%);transition:transform .4s ease-out}.gmedia-lightbox-b-view .gmedia-lightbox-b-header *{user-select:none;-moz-user-select:none;-webkit-user-select:none}.gmedia-lightbox-b-view .gmedia-lightbox-b-header.gmedia-show{transform:translateY(0%)}.gmedia-lightbox-b-view .gmedia-lightbox-b-footer{user-select:none;position:absolute;display:flex;justify-content:center;align-items:center;flex-wrap:wrap;padding:0 10px;left:0;bottom:0;width:100%;transform:translateY(100%);transition:transform .4s ease-out}.gmedia-lightbox-b-view .gmedia-lightbox-b-footer.gmedia-show{transform:translateY(0%)}.gmedia-lightbox-b-view .gmedia-lightbox-b-footer.gmedia-lightbox-b-touch-device .gmedia-lightbox-b-caption-wrap{border-radius:2px;padding:0;margin:0}.gmedia-lightbox-b-view .gmedia-lightbox-b-footer .gmedia-lightbox-b-caption-wrap{border-radius:2px;padding:3px 10px;margin:2px}.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap{flex:none;width:400px;max-width:100%;padding:0 5px;height:100%}.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap a{cursor:pointer}.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap a:hover,.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap a:visited,.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap a:link,.gmedia-lightbox-b-view .gmedia-lightbox-b-description-wrap a:active{text-decoration:none;box-shadow:none}.gmedia-lightbox-b-view .gmedia-lightbox-b-item-title{text-rendering:auto;color:#fff;font-size:18px;width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;line-height:1.3;box-sizing:content-box;letter-spacing:0;margin-top:1px;margin-bottom:3px;text-decoration:none !important;box-shadow:none !important}.gmedia-lightbox-b-view .gmedia-lightbox-b-item-description{color:#969696;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.3}.gmedia-lightbox-b-view .gmedia-lightbox-b-free-space{flex:auto}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-play-wrap{display:flex;align-items:center}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-play-wrap .gmedia-lightbox-b-autoplay-wrap{margin-left:15px}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-wrap{position:relative;flex:none;font-size:13px;line-height:22px;font-weight:400;color:white;display:inline-block}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-current{position:relative;display:inline-block}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-delimiter{position:relative;display:inline-block;padding:0 3px}.gmedia-lightbox-b-view .gmedia-lightbox-b-caption-all{position:relative;display:inline-block}.gmedia-lightbox-b-view .gmedia-lightbox-b-autoplay-wrap{position:relative;opacity:0;height:22px;transition:opacity .4s}.gmedia-lightbox-b-view .gmedia-lightbox-b-info-wrap{position:relative;flex:none;min-height:30px;padding:0 10px}.gmedia-lightbox-b-view .gmedia-lightbox-b-item-menu-wrap{position:relative;flex:none;min-width:40px;overflow:hidden}\n",""])},function(e,t,i){var o=i(16);"string"==typeof o&&(o=[[e.i,o,""]]);var a={hmr:!0,transform:void 0,insertInto:void 0};i(1)(o,a);o.locals&&(e.exports=o.locals)},function(e,t,i){(e.exports=i(0)(!1)).push([e.i,".gmedia-modal-window{position:fixed;-webkit-backface-visibility:hidden;backface-visibility:hidden;top:0;left:0;right:0;bottom:0;overflow:hidden;opacity:0;will-change:opacity;transition:opacity .4s;text-align:center}.gmedia-modal-window *{box-sizing:border-box}.gmedia-modal-window .gmedia-modal-flex{display:inline-block;width:0;height:100%;vertical-align:middle}.gmedia-modal-window .gmedia-modal-close-button{position:absolute;width:100%;height:100%;z-index:-100;will-change:opacity}.gmedia-item-info-bar{font-size:14px;line-height:1.3;margin:0 10px;padding-bottom:10px;max-width:720px;min-width:260px;background-color:white;border-radius:2px;box-shadow:0 8px 16px rgba(0,0,0,0.15);vertical-align:middle;display:inline-block;will-change:transform}.gmedia-item-info-bar .gmedia-item-info-close-button{position:absolute;margin:10px;width:24px;height:24px;cursor:pointer;right:0}.gmedia-item-info-bar .gmedia-item-info-close-button svg{width:100%;height:100%;vertical-align:baseline !important}.gmedia-item-info-bar .gmedia-item-info-description-wrap{min-width:200px;min-height:44px;padding:10px 20px 0 20px;float:left;text-align:left;font-size:1em}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-item-title{font-size:130%;font-weight:600}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-item-description{font-size:80%;font-weight:400}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-terms-list{list-style:none;margin:0;overflow:hidden;padding:0}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-terms-list.gmedia-item-info-tags-ul{font-size:1rem !important;line-height:1.4 !important;margin-bottom:0 !important;margin-left:0 !important}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-terms-list.gmedia-item-info-tags-ul li{border-radius:3px;display:inline-block;height:26px;line-height:26px;padding:0 20px 0 23px;position:relative;margin:0 7px 10px 0;text-decoration:none;cursor:pointer;transition:.3s}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-meta-exif-value{line-height:1.9;display:inline-block}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-meta-exif-separator{display:inline-block;font-size:100%;margin:0 2px;opacity:.4}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-item-date{font-size:100%;line-height:1.9}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-item-date .gmedia-item-info-item-meta-key{float:left;width:40%;min-width:80px}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-item-date .gmedia-item-info-item-meta-value{float:left;white-space:nowrap;text-transform:capitalize}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-likes-view-com{position:relative;min-width:60px;min-height:40px;border:1px solid;border-color:rgba(0,0,0,0.18);border-radius:2px;background-color:#fafafa;padding:4px;margin:0 1%;text-align:center;display:inline-block}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-likes-view-com svg{display:inline-block;width:24px;height:24px;vertical-align:baseline !important}.gmedia-item-info-bar .gmedia-item-info-description-wrap .gmedia-item-info-likes-view-com .gmedia-item-info-counter-text{font-size:15px;line-height:1}.gmedia-item-info-bar .gmedia-item-info-terms-title{display:inline-block;line-height:26px;padding:0 20px 0 3px;position:relative;text-decoration:none}.gmedia-item-share-bar{font-size:14px;line-height:1.3;margin:0 10px;padding-bottom:10px;max-width:480px;min-width:260px;background-color:white;border-radius:2px;box-shadow:0 8px 16px rgba(0,0,0,0.15);vertical-align:middle;display:inline-block;will-change:transform}.gmedia-item-share-bar .gmedia-item-share-close-button{position:absolute;margin:10px;width:24px;height:24px;cursor:pointer;right:0}.gmedia-item-share-bar .gmedia-item-share-close-button svg{width:100%;height:100%;vertical-align:baseline !important}.gmedia-item-share-bar .gmedia-item-share-description-wrap{min-width:270px;min-height:44px;padding:10px 20px 0 20px;float:left;text-align:left}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-title{display:block;font-size:130%;font-weight:600;line-height:1.3}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap{position:relative;display:inline-block;padding:0 4px;min-width:130px;width:50%;height:42px}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-button{border:1px solid;border-color:rgba(0,0,0,0.18);cursor:pointer;width:100%;height:100%;border-radius:2px;background-color:#fafafa;transition:.4s}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-button svg{width:40px;height:40px;float:left;vertical-align:baseline !important}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-button .gmedia-item-share-button-title{white-space:nowrap;position:absolute;left:30px;right:0;font-size:15px;font-weight:400;line-height:41px;text-align:center;opacity:0.7;transition:opacity .4s}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-button:hover{box-shadow:0 1px 4px rgba(0,0,0,0.2)}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-button:hover .gmedia-item-share-button-title{opacity:1}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-copy-link{background-color:#fafafa;border:solid 1px rgba(0,0,0,0.17);width:100%;height:100%;border-radius:2px;overflow:hidden;position:relative;cursor:pointer;transition:.4s}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-copy-link .gmedia-item-share-button-title{position:absolute;white-space:nowrap;line-height:41px;left:41px;right:10px;overflow:hidden;opacity:.7;transition:.4s}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-copy-link svg{width:40px;height:40px;padding:4px;float:left;transition:fill .4s;vertical-align:baseline !important}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-copy-link:hover{box-shadow:0 1px 4px rgba(0,0,0,0.2)}.gmedia-item-share-bar .gmedia-item-share-description-wrap .gmedia-item-share-item-button-wrap .gmedia-item-share-item-copy-link:hover .gmedia-item-share-button-title{opacity:1}\n",""])},function(e,t,i){"use strict";i.r(t);i(2),i(5);function o(e,t){for(var i=0;i<t.length;i++){var o=t[i];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function a(e,t,i){return t&&o(e.prototype,t),i&&o(e,i),e}var n=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var t=this;this.mouseDetected=!1,this.mouseMoveHandler=function(){return function(e){window.removeEventListener("mousedown",t.mouseMoveHandler,!1),window.removeEventListener("touchstart",t.mouseMoveHandler,!1),"touchstart"===e.type?(e.stopPropagation(),t.mouseDetected=!1):t.mouseDetected=!0}},window.addEventListener("mousedown",this.mouseMoveHandler,!1),window.addEventListener("touchstart",this.mouseMoveHandler,!1)}return a(e,null,[{key:"ICONS",get:function(){return{MAXIMIZE_SVG:'<svg fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" x2="14" y1="3" y2="10"/><line x1="3" x2="10" y1="21" y2="14"/></svg>',NOTE_SVG:'<svg version="1.1" viewBox="0 0 58 94" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M37.992,0h-8.021v65.358c-4.435-1.706-10.174-1.73-15.835,0.328C3.994,69.377-2.049,78.355,0.638,85.736 c2.688,7.383,13.088,10.374,23.229,6.683c8.614-3.134,14.249-10.082,14.111-16.626l0.014-53.451 c13.986,2.204,14.943,19.884,13.268,24.842c-0.636,1.879,0.484,3.286,2.598,0C68.938,23.726,37.992,13.376,37.992,0z"/></g><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/></svg>',VIMEO_SVG:'<svg enable-background="new 0 0 56.693 56.693" height="56.693px" id="Layer_1" version="1.1" viewBox="-5 -5 66.693 66.693" width="56.693px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M3.602,22.974l2.01,2.636c0,0,4.146-3.267,5.528-1.634c1.382,1.634,6.656,21.357,8.417,24.997 c1.537,3.192,5.777,7.413,10.426,4.397c4.646-3.014,20.098-16.205,22.863-31.781c2.764-15.574-18.594-12.313-20.854,1.256 c5.652-3.395,8.671,1.38,5.778,6.784c-2.889,5.399-5.527,8.921-6.908,8.921c-1.379,0-2.441-3.612-4.021-9.928 c-1.635-6.53-1.624-18.291-8.416-16.958C12.019,12.921,3.602,22.974,3.602,22.974z"/></svg>',YOU_TUBE_SVG:'<svg data-name="Layer 21" height="24" id="Layer_21" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><title/><path d="M21.80731,7.805a2.79915,2.79915,0,0,0-2.54907-2.53906C17.69061,5.13586,15.36707,5,12.50012,5c-3.45251,0-6.05865.14105-7.74353.27332A2.79932,2.79932,0,0,0,2.1925,7.815C2.08936,8.90021,2,10.33344,2,12.0423c0,1.66632.08862,3.07422.19128,4.14594a2.79852,2.79852,0,0,0,2.56384,2.53833C6.43994,18.85883,9.04657,19,12.50012,19c2.86694,0,5.19049-.13586,6.75812-.266a2.799,2.799,0,0,0,2.54907-2.539C21.91052,15.11548,22,13.69189,22,12S21.91052,8.88452,21.80731,7.805ZM9.77594,14.93878V9.06122L15.574,12Z"/></svg>',BOOKMARK_SVG:'<svg height="1792" viewBox="0 0 1792 1792" width="1792" xmlns="http://www.w3.org/2000/svg"><path d="M1420 128q23 0 44 9 33 13 52.5 41t19.5 62v1289q0 34-19.5 62t-52.5 41q-19 8-44 8-48 0-83-32l-441-424-441 424q-36 33-83 33-23 0-44-9-33-13-52.5-41t-19.5-62v-1289q0-34 19.5-62t52.5-41q21-9 44-9h1048z"/></svg>',HEART_SVG:'<svg enable-background="new 0 0 51 46" height="46px" id="Layer_1" version="1.1" viewBox="0 0 51 46" width="51px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M46.188,4.101c-5.529-5.53-14.495-5.53-20.023,0L25.39,4.875l-0.996-0.774c-5.529-5.53-14.715-5.53-20.245,0 C-1.38,9.63-1.27,18.595,4.26,24.125l18.753,18.643c0.671,0.671,1.4,1.258,2.376,1.766c0.76-0.508,1.483-1.095,2.155-1.766 l18.643-18.643C51.717,18.595,51.717,9.63,46.188,4.101z""/></svg>',HEART_2_SVG:'<svg enable-background="new 0 0 24 24" id="Layer_1" version="1.0" viewBox="0 0 24 24" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M16.4,6c2,0,3.6,1.6,3.6,3.6c0,2-3.9,6.4-8,9.8c-4.1-3.5-8-7.9-8-9.8C4,7.6,5.6,6,7.6,6C10,6,12,9,12,9S13.9,6,16.4,6 M16.4,4C14.6,4,13,4.9,12,6.3C11,4.9,9.4,4,7.6,4C4.5,4,2,6.5,2,9.6C2,14,12,22,12,22s10-8,10-12.4C22,6.5,19.5,4,16.4,4L16.4,4z"/></svg>',COMENTS_SVG:'<svg style="enable-background:new 0 0 24 24;" version="1.1" viewBox="0 0 24 24" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="info"/><g id="icons"><path d="M20,1H4C1.8,1,0,2.8,0,5v10c0,2.2,1.8,4,4,4v3c0,0.9,1.1,1.3,1.7,0.7L9.4,19H20c2.2,0,4-1.8,4-4V5 C24,2.8,22.2,1,20,1z M14,13H8c-0.6,0-1-0.4-1-1c0-0.6,0.4-1,1-1h6c0.6,0,1,0.4,1,1C15,12.6,14.6,13,14,13z M16,9H8 C7.4,9,7,8.6,7,8c0-0.6,0.4-1,1-1h8c0.6,0,1,0.4,1,1C17,8.6,16.6,9,16,9z" id="message"/></g></svg>',COMENTS_2_SVG:'<svg enable-background="new 0 0 64 64" height="64px" id="Layer_1" version="1.1" viewBox="0 0 64 64" width="64px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M47.964,8.127H16.036c-4.4,0-8,3.6-8,8v20.977c0,4.4,3.6,8,8,8h7.397v10.768l13.333-10.768h11.197c4.4,0,8-3.6,8-8V16.127 C55.964,11.727,52.364,8.127,47.964,8.127z M50.964,37.104c0,1.626-1.374,3-3,3H36.767H35l-1.375,1.11l-5.191,4.193v-0.303v-5h-5 h-7.397c-1.626,0-3-1.374-3-3V16.127c0-1.626,1.374-3,3-3h31.928c1.626,0,3,1.374,3,3V37.104z"/><circle cx="21.743" cy="26.617" r="2.913"/><circle cx="32" cy="26.617" r="2.913"/><circle cx="42.256" cy="26.617" r="2.913"/></g></svg>',INFO_SVG:'<svg height="100px" id="Capa_1" style="enable-background:new 0 0 46 100;" version="1.1" viewBox="0 0 46 100" width="46px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M35.162,0c6.696,0,10.043,4.567,10.043,9.789c0,6.522-5.814,12.555-13.391,12.555c-6.344,0-10.045-3.752-9.869-9.947 C21.945,7.176,26.35,0,35.162,0z M14.543,100c-5.287,0-9.164-3.262-5.463-17.615l6.07-25.457c1.057-4.077,1.23-5.707,0-5.707 c-1.588,0-8.451,2.816-12.51,5.59L0,52.406C12.863,41.48,27.662,35.072,34.004,35.072c5.285,0,6.168,6.361,3.525,16.148 L30.58,77.98c-1.234,4.729-0.703,6.359,0.527,6.359c1.586,0,6.787-1.963,11.896-6.041L46,82.377C33.488,95.1,19.83,100,14.543,100z "/></g><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/><g/></svg>',DOWNLOAD_SVG:'<svg version="1.1" viewBox="0 0 24 24" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="info"/><g id="icons"><g id="save"><path d="M11.2,16.6c0.4,0.5,1.2,0.5,1.6,0l6-6.3C19.3,9.8,18.8,9,18,9h-4c0,0,0.2-4.6,0-7c-0.1-1.1-0.9-2-2-2c-1.1,0-1.9,0.9-2,2 c-0.2,2.3,0,7,0,7H6c-0.8,0-1.3,0.8-0.8,1.4L11.2,16.6z"/><path d="M19,19H5c-1.1,0-2,0.9-2,2v0c0,0.6,0.4,1,1,1h16c0.6,0,1-0.4,1-1v0C21,19.9,20.1,19,19,19z"/></g></g></svg>',DOWNLOAD_2_SVG:'<svg enable-background="new 0 0 64 64" height="64px" id="Layer_1" version="1.1" viewBox="0 0 64 64" width="64px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M40.001,36.254c0,3.299-2.673,5.971-5.97,5.971H29.97c-3.297,0-5.97-2.672-5.97-5.971H8v17c0,2.209,1.791,4,4,4h40 c2.209,0,4-1.791,4-4v-17H40.001z"/><path d="M31.916,33.246l7.608-7.452c0.747-0.733,0.506-1.327-0.543-1.327h-4.565V9.246c0-1.381-1.119-2.5-2.5-2.5 s-2.5,1.119-2.5,2.5v15.221h-4.565c-1.05,0-1.291,0.595-0.542,1.327L31.916,33.246z"/></g></svg>',LINK_SVG:'<svg height="1792" viewBox="0 0 1792 1792" width="1792" xmlns="http://www.w3.org/2000/svg"><path d="M1520 1216q0-40-28-68l-208-208q-28-28-68-28-42 0-72 32 3 3 19 18.5t21.5 21.5 15 19 13 25.5 3.5 27.5q0 40-28 68t-68 28q-15 0-27.5-3.5t-25.5-13-19-15-21.5-21.5-18.5-19q-33 31-33 73 0 40 28 68l206 207q27 27 68 27 40 0 68-26l147-146q28-28 28-67zm-703-705q0-40-28-68l-206-207q-28-28-68-28-39 0-68 27l-147 146q-28 28-28 67 0 40 28 68l208 208q27 27 68 27 42 0 72-31-3-3-19-18.5t-21.5-21.5-15-19-13-25.5-3.5-27.5q0-40 28-68t68-28q15 0 27.5 3.5t25.5 13 19 15 21.5 21.5 18.5 19q33-31 33-73zm895 705q0 120-85 203l-147 146q-83 83-203 83-121 0-204-85l-206-207q-83-83-83-203 0-123 88-209l-88-88q-86 88-208 88-120 0-204-84l-208-208q-84-84-84-204t85-203l147-146q83-83 203-83 121 0 204 85l206 207q83 83 83 203 0 123-88 209l88 88q86-88 208-88 120 0 204 84l208 208q84 84 84 204z"/></svg>',LINK_2_SVG:'<svg data-name="Layer 21" height="24" id="Layer_21" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><title/><path d="M9.87012,5.541l4.26953,4.26953a2.02108,2.02108,0,0,1,0,2.855l-1.42383,1.42285,1.41406,1.415,1.42383-1.42334a4.02449,4.02449,0,0,0,0-5.68359L11.28418,4.127a4.01858,4.01858,0,0,0-5.68359,0L4.17676,5.55029a4.02212,4.02212,0,0,0,0,5.68311L5.59082,9.81934a2.02108,2.02108,0,0,1,0-2.855L7.01465,5.541A2.06778,2.06778,0,0,1,9.87012,5.541Z"/><path d="M19.82324,12.666l-1.41406,1.41406a2.02108,2.02108,0,0,1,0,2.855L16.98535,18.3584a2.06778,2.06778,0,0,1-2.85547,0L9.86035,14.08887a2.02108,2.02108,0,0,1,0-2.855L11.28418,9.811,9.87012,8.396,8.44629,9.81934a4.02449,4.02449,0,0,0,0,5.68359l4.26953,4.26953a4.01917,4.01917,0,0,0,5.68359.00049l1.42383-1.42334A4.02449,4.02449,0,0,0,19.82324,12.666Z"/></svg>',SHARE_SVG:'<svg height="1792" viewBox="0 0 1792 1792" width="1792" xmlns="http://www.w3.org/2000/svg"><path d="M1344 1024q133 0 226.5 93.5t93.5 226.5-93.5 226.5-226.5 93.5-226.5-93.5-93.5-226.5q0-12 2-34l-360-180q-92 86-218 86-133 0-226.5-93.5t-93.5-226.5 93.5-226.5 226.5-93.5q126 0 218 86l360-180q-2-22-2-34 0-133 93.5-226.5t226.5-93.5 226.5 93.5 93.5 226.5-93.5 226.5-226.5 93.5q-126 0-218-86l-360 180q2 22 2 34t-2 34l360 180q92-86 218-86z"/></svg>',SHARE_2_SVG:'<svg enable-background="new 0 0 64 64" height="64px" id="Layer_1" version="1.1" viewBox="0 0 64 64" width="64px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M48,39.26c-2.377,0-4.515,1-6.033,2.596L24.23,33.172c0.061-0.408,0.103-0.821,0.103-1.246c0-0.414-0.04-0.818-0.098-1.215 l17.711-8.589c1.519,1.609,3.667,2.619,6.054,2.619c4.602,0,8.333-3.731,8.333-8.333c0-4.603-3.731-8.333-8.333-8.333 s-8.333,3.73-8.333,8.333c0,0.414,0.04,0.817,0.098,1.215l-17.711,8.589c-1.519-1.609-3.666-2.619-6.054-2.619 c-4.603,0-8.333,3.731-8.333,8.333c0,4.603,3.73,8.333,8.333,8.333c2.377,0,4.515-1,6.033-2.596l17.737,8.684 c-0.061,0.407-0.103,0.821-0.103,1.246c0,4.603,3.731,8.333,8.333,8.333s8.333-3.73,8.333-8.333C56.333,42.99,52.602,39.26,48,39.26 z"/></svg>',FULL_SCREEN_SVG:'<svg height="14px" version="1.1" viewBox="0 0 14 14" width="14px" xmlns="http://www.w3.org/2000/svg" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns" xmlns:xlink="http://www.w3.org/1999/xlink"><title/><desc/><defs/><g fill-rule="evenodd" id="Page-1" stroke="none" stroke-width="1"><g transform="translate(-215.000000, -257.000000)"><g id="fullscreen" transform="translate(215.000000, 257.000000)"><path d="M2,9 L0,9 L0,14 L5,14 L5,12 L2,12 L2,9 L2,9 Z M0,5 L2,5 L2,2 L5,2 L5,0 L0,0 L0,5 L0,5 Z M12,12 L9,12 L9,14 L14,14 L14,9 L12,9 L12,12 L12,12 Z M9,0 L9,2 L12,2 L12,5 L14,5 L14,0 L9,0 L9,0 Z" id="Shape"/></g></g></g></svg>',NORMAL_SCREEN_SVG:'<svg height="14px" version="1.1" viewBox="0 0 14 14" width="14px" xmlns="http://www.w3.org/2000/svg" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns" xmlns:xlink="http://www.w3.org/1999/xlink"><g fill-rule="evenodd" stroke="none" stroke-width="1"><g id="Core" transform="translate(-257.000000, -257.000000)"><g id="fullscreen-exit" transform="translate(257.000000, 257.000000)"><path d="M0,11 L3,11 L3,14 L5,14 L5,9 L0,9 L0,11 L0,11 Z M3,3 L0,3 L0,5 L5,5 L5,0 L3,0 L3,3 L3,3 Z M9,14 L11,14 L11,11 L14,11 L14,9 L9,9 L9,14 L9,14 Z M11,3 L11,0 L9,0 L9,5 L14,5 L14,3 L11,3 L11,3 Z" id="Shape"/></g></g></g></svg>',CLOSE_SVG:'<svg height="512px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M437.5,386.6L306.9,256l130.6-130.6c14.1-14.1,14.1-36.8,0-50.9c-14.1-14.1-36.8-14.1-50.9,0L256,205.1L125.4,74.5 c-14.1-14.1-36.8-14.1-50.9,0c-14.1,14.1-14.1,36.8,0,50.9L205.1,256L74.5,386.6c-14.1,14.1-14.1,36.8,0,50.9 c14.1,14.1,36.8,14.1,50.9,0L256,306.9l130.6,130.6c14.1,14.1,36.8,14.1,50.9,0C451.5,423.4,451.5,400.6,437.5,386.6z"/></svg>',VIEW_SVG:'<svg enable-background="new 0 0 167 93" height="93px" id="Layer_1" version="1.1" viewBox="0 0 167 93" width="167px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M83.25,29.25c-9.649,0-17.5,7.851-17.5,17.5s7.851,17.5,17.5,17.5s17.5-7.851,17.5-17.5 S92.899,29.25,83.25,29.25z"/><path d="M83.25,0.75c-45.84,0-83,46-83,46s37.16,46,83,46s83-46,83-46S129.09,0.75,83.25,0.75z M83.25,81.25 c-19.054,0-34.5-15.445-34.5-34.5c0-19.054,15.446-34.5,34.5-34.5s34.5,15.446,34.5,34.5C117.75,65.805,102.304,81.25,83.25,81.25z "/></g></svg>',FB_SVG_COLOR:'<svg version="1.1" viewBox="0 0 32 32" width="32" height="32" aria-hidden="false"><path d="M27.6 3h-23.2c-.8 0-1.4.6-1.4 1.4v23.1c0 .9.6 1.5 1.4 1.5h12.5v-10.1h-3.4v-3.9h3.4v-2.9c0-3.4 2.1-5.2 5-5.2 1.4 0 2.7.1 3 .2v3.5h-2.1c-1.6 0-1.9.8-1.9 1.9v2.5h3.9l-.5 3.9h-3.4v10.1h6.6c.8 0 1.4-.6 1.4-1.4v-23.2c.1-.8-.5-1.4-1.3-1.4z"></path></svg>',FB_SVG:'<svg enable-background="new 0 0 32 32" version="1.1" viewBox="0 0 32 32" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="Flat_copy"><path d="M11.848,32h6.612V15.998h4.411l0.584-5.514H18.46l0.007-2.761c0-1.437,0.137-2.209,2.2-2.209h2.757V0h-4.412 c-5.299,0-7.164,2.675-7.164,7.174v3.311H8.545v5.515h3.303V32z"/></g></svg>',TW_SVG:'<svg version="1.1" viewBox="0 0 32 32" width="32" height="32" aria-hidden="false"><path d="M30 7.3c-1 .5-2.1.8-3.3.9 1.2-.7 2.1-1.8 2.5-3.2-1.1.7-2.3 1.1-3.6 1.4-1-1.1-2.5-1.8-4.2-1.8-3.2 0-5.7 2.6-5.7 5.7 0 .5.1.9.1 1.3-4.8-.2-9-2.5-11.8-6-.5.9-.8 1.9-.8 3 0 2 1 3.8 2.6 4.8-.9 0-1.8-.3-2.6-.7v.1c0 2.8 2 5.1 4.6 5.6-.5.1-1 .2-1.5.2-.4 0-.7 0-1.1-.1.7 2.3 2.9 3.9 5.4 4-2 1.5-4.4 2.5-7.1 2.5-.5 0-.9 0-1.4-.1 2.5 1.6 5.6 2.6 8.8 2.6 10.6 0 16.3-8.8 16.3-16.3v-.7c1.1-1 2-2 2.8-3.2z"></path></svg>',PIN_SVG:'<svg version="1.1" viewBox="0 0 32 32" width="32" height="32" aria-hidden="false"><path d="M16 3c-7.2 0-13 5.8-13 13 0 5.5 3.4 10.2 8.3 12.1-.1-1-.2-2.6 0-3.7.2-1 1.5-6.5 1.5-6.5s-.4-.8-.4-1.9c0-1.8 1-3.2 2.4-3.2 1.1 0 1.6.8 1.6 1.8 0 1.1-.7 2.8-1.1 4.3-.3 1.3.6 2.3 1.9 2.3 2.3 0 4.1-2.4 4.1-6 0-3.1-2.2-5.3-5.4-5.3-3.7 0-5.9 2.8-5.9 5.6 0 1.1.4 2.3 1 3 .1.1.1.2.1.4-.1.4-.3 1.3-.4 1.5-.1.2-.2.3-.4.2-1.6-.8-2.6-3.1-2.6-5 0-4.1 3-7.9 8.6-7.9 4.5 0 8 3.2 8 7.5 0 4.5-2.8 8.1-6.7 8.1-1.3 0-2.6-.7-3-1.5 0 0-.7 2.5-.8 3.1-.3 1.1-1.1 2.5-1.6 3.4 1.2.4 2.5.6 3.8.6 7.2 0 13-5.8 13-13 0-7.1-5.8-12.9-13-12.9z"></path></svg>',ZOOM_IN_SVG:'<svg enable-background="new 0 0 512 512" height="512px" id="Layer_1" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M497.913,497.914c-18.782,18.781-49.226,18.781-68.008,0l-84.862-84.864c-34.89,22.366-76.131,35.718-120.66,35.718 C100.468,448.768,0,348.314,0,224.384C0,100.454,100.468,0,224.383,0c123.931,0,224.384,100.453,224.384,224.384 c0,44.529-13.353,85.771-35.718,120.675l84.863,84.849C516.695,448.689,516.695,479.131,497.913,497.914z M224.383,64.11 c-88.511,0-160.274,71.763-160.274,160.274c0,88.526,71.764,160.274,160.274,160.274c88.526,0,160.273-71.748,160.273-160.274 C384.656,135.873,312.909,64.11,224.383,64.11z M256.438,320.548h-64.108v-64.109H128.22V192.33h64.109v-64.11h64.108v64.11h64.11 v64.109h-64.11V320.548z"/></svg>',ZOOM_OUT_SVG:'<svg enable-background="new 0 0 512 512" height="512px" id="Layer_1" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><g><path d="M497.913,429.906l-84.863-84.848c22.365-34.903,35.718-76.146,35.718-120.676C448.768,100.453,348.314,0,224.383,0 C100.468,0,0,100.453,0,224.384s100.468,224.384,224.383,224.384c44.529,0,85.771-13.352,120.66-35.718l84.862,84.864 c18.782,18.781,49.226,18.781,68.008,0C516.695,479.131,516.695,448.689,497.913,429.906z M224.383,384.658 c-88.511,0-160.274-71.748-160.274-160.274c0-88.511,71.764-160.274,160.274-160.274c88.526,0,160.273,71.763,160.273,160.274 C384.656,312.91,312.909,384.658,224.383,384.658z M128.219,256.438h192.329v-64.109H128.219V256.438z"/></g></g></svg>',PLAY_SVG:'<svg height="512px" id="Layer_1" enable-background:new 0 0 512 512 version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M405.2,232.9L126.8,67.2c-3.4-2-6.9-3.2-10.9-3.2c-10.9,0-19.8,9-19.8,20H96v344h0.1c0,11,8.9,20,19.8,20 c4.1,0,7.5-1.4,11.2-3.4l278.1-165.5c6.6-5.5,10.8-13.8,10.8-23.1C416,246.7,411.8,238.5,405.2,232.9z"/></svg>',PAUSE_SVG:'<svg height="512px" id="Layer_1" enable-background:new 0 0 512 512 version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M224,435.8V76.1c0-6.7-5.4-12.1-12.2-12.1h-71.6c-6.8,0-12.2,5.4-12.2,12.1v359.7c0,6.7,5.4,12.2,12.2,12.2h71.6 C218.6,448,224,442.6,224,435.8z"/><path d="M371.8,64h-71.6c-6.7,0-12.2,5.4-12.2,12.1v359.7c0,6.7,5.4,12.2,12.2,12.2h71.6c6.7,0,12.2-5.4,12.2-12.2V76.1 C384,69.4,378.6,64,371.8,64z"/></g></svg>'}}}]),a(e,null,[{key:"moduleSettings",value:function(e){return window[e]&&window[e].settings?window[e].settings:null}},{key:"requestAnimationFrame",value:function(e){return(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame)(e)}},{key:"cancelAnimationFrame",value:function(e){(window.cancelAnimationFrame||window.mozCancelAnimationFrame)(e)}},{key:"whichTransitionEventEnd",value:function(){var e=document.createElement("fakeelement"),t={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"},i=Object.keys(t);for(var o in i)if(void 0!==e.style[o])return t[o]}},{key:"copyProperties",value:function(e,t){for(var i=Object.keys(e),o=0;o<i.length;o+=1){var a=i[o];t[a]=e[a]}}},{key:"shuffle",value:function(e){for(var t,i,o=e.length;0!==o;)i=Math.floor(Math.random()*o),t=e[o-=1],e[o]=e[i],e[i]=t;return e}},{key:"Rect",value:function(e,t,i,o){return{x:e,y:t,width:i,height:o}}},{key:"Size",value:function(e,t){return{width:e,height:t}}},{key:"Point",value:function(e,t){return{x:e,y:t}}},{key:"findHighestZIndex",value:function(e){for(var t,i=99999,o=0;o<e.childNodes.length;o+=1){var a=e.childNodes[o];1===a.nodeType&&"SCRIPT"!==a.nodeName&&(t=document.defaultView.getComputedStyle(a,null).getPropertyValue("z-index")),t>i&&"auto"!==t&&(i=parseInt(t,10))}return i}},{key:"timeConverter",value:function(e){var t=new Date(1e3*e),i=new Date,o=new Date(Date.now()-864e5),a=t.getFullYear(),n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],s=t.getDate(),r=t.getHours(),l=t.getMinutes();return t.setHours(0,0,0,0)===i.setHours(0,0,0,0)?"Today, ".concat(r,":").concat(l):t.setHours(0,0,0,0)===o.setHours(0,0,0,0)?"Yesterday, ".concat(r,":").concat(l):a===(new Date).getFullYear()?"".concat(s," ").concat(n,", ").concat(a):"".concat(s," ").concat(n," ").concat(a)}},{key:"createPreloaderView",value:function(e){var t=0,i=document.createElement("div");i.className="gmedia-preloader";var o=document.createElement("div");o.style.position="absolute",o.style.width="".concat(8,"px"),o.style.height="".concat(8,"px"),o.style.margin="".concat(-4,"px"),o.style.left="50%",o.style.top="50%",o.style.borderRadius="50%",o.style.backgroundColor=e,i.appendChild(o);var a=document.createElement("div");a.className="c-spinner",a.style.position="absolute",a.style.width="".concat(36,"px"),a.style.height="".concat(36,"px"),a.style.margin="".concat(-18,"px"),a.style.left="50%",a.style.top="50%";for(var n=0;n<8;n+=1){var s=document.createElement("div");s.style.position="absolute",s.style.top="50%",s.style.left="50%",s.style.marginTop="".concat(-4,"px"),s.style.marginLeft="".concat(-4,"px"),s.style.width="".concat(8,"px"),s.style.height="".concat(8,"px"),s.style.backgroundColor=e,s.style.borderRadius="100%",s.style.transform="rotate(".concat(t,"deg) translate(").concat(18,"px)"),t+=45,a.appendChild(s)}return i.appendChild(a),i}},{key:"trace",value:function(e){if(1!==arguments.length){for(var t="",i=0;i<arguments.length;i++){var o=arguments[i];t+="".concat(o," , ")}t=t.slice(0,-2),console.log(t)}else console.log(e)}},{key:"preventDefaultForScrollKeys",value:function(e){return!{37:1,38:1,39:1,40:1}[e.keyCode]||(e.preventDefault(),!1)}},{key:"preventDefault",value:function(e){(e=e||window.event).preventDefault&&e.preventDefault(),e.returnValue=!1}},{key:"disableBodyScroll",value:function(){document.getElementsByTagName("html")[0].classList.add("gmedia_PopUpActive")}},{key:"enableBodyScroll",value:function(){document.getElementsByTagName("html")[0].classList.remove("gmedia_PopUpActive")}},{key:"disableBodyScrollSlider",value:function(){if(window.addEventListener){var t=e.passiveListener,i=e.preventDefault;window.addEventListener("wheel",i,t),window.addEventListener("mousewheel",i,t),window.addEventListener("touchmove",i,t)}document.onkeydown=e.preventDefaultForScrollKeys}},{key:"enableBodyScrollSlider",value:function(){if(window.removeEventListener){var t=e.passiveListener,i=e.preventDefault;window.removeEventListener("wheel",i,t),window.removeEventListener("mousewheel",i,t),window.removeEventListener("touchmove",i,t)}document.onkeydown=null}},{key:"collapseElementsInElemt",value:function(e,t){for(var i=[],o=0;o<e.childNodes.length;o+=1){var a={},n=e.childNodes[o];1===n.nodeType&&"SCRIPT"!==n.nodeName&&n!==t&&(a.element=n,a.height=null,a.overflow=null,""!==n.style.height&&(a.height=n.style.height),""!==n.style.overflow&&(a.overflow=n.style.overflow),i.push(a),n.style.overflow="hidden",n.style.height="0")}return i}},{key:"recoverElements",value:function(e){if(0!==e.length)for(var t=0;t<e.length;t+=1){var i=e[t].element;i&&(e[t].overflow?i.style.overflow=e[t].overflow:i.style.removeProperty("overflow"),e[t].height?i.style.height=e[t].height:i.style.removeProperty("height"))}}},{key:"hexToRgbaStrin",value:function(e,t){e=e.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(function(e,t,i,o){return t+t+i+i+o+o}));var i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return i?"rgba(".concat(parseInt(i[1],16),",").concat(parseInt(i[2],16),",").concat(parseInt(i[3],16),",").concat(t,")"):null}},{key:"getFrameForBoxWithMode",value:function(e,t,i){var o=e.width,a=e.height,n=t.width,s=t.height,r=1,l=1,c=1;i?(r=n/o,l=s/a,c=Math.max(r,l)):(r=n/o,l=s/a,c=(c=Math.min(r,l))>1?1:c);var d=Math.round(o*c),h=Math.round(a*c),m=Math.round((n-d)/2),u=Math.round((s-h)/2);return this.Rect(m,u,d,h)}},{key:"getItemFrameByIndexForBox",value:function(e,t,i,o,a,n){var s=1;n&&(s=n);var r=a=Math.min(t,a),l=Math.floor(t/a),c=(r=l>1?(t-(l-1)*i)/l:t)*s,d=Math.ceil((e+1)/l)-1,h=d*(c+o),m=(e-d*l)*(r+i);return this.Rect(m,h,r,c)}},{key:"fadeOut",value:function(e,t,i){i||(i=500);var o=Math.sqrt,a=(new Date).getTime();!function n(){var s=(new Date).getTime()-a,r=s/i;if(r<1){var l=1-o(r);e.style.opacity=String(l),setTimeout(n,Math.min(25,i-s))}else e.style.opacity="0",t&&t()}()}},{key:"ellipsizeTextBoxToLine",value:function(e,t){e.innerHTML=e.textContent||e.innerText||"";var i=e.innerHTML,o=e.innerHTML.split(" ");e.innerHTML=o[0].substring(0,3);var a=e.clientHeight*t;for(e.innerHTML=i;e.clientHeight>a;)o.pop(),e.innerHTML="".concat(o.join(" ")," ...")}},{key:"ellipsizeTextBox",value:function(e){e.innerHTML=e.textContent||e.innerText||"";for(var t=e.innerHTML.split(" ");e.scrollHeight>e.offsetHeight;)t.pop(),e.innerHTML="".concat(t.join(" ")," ...")}},{key:"scrollToY",value:function(e,t){var i,o=window.pageYOffset,a=Math.PI/(t/15),n=o/2,s=0,r=setInterval((function(){window.pageYOffset>e?(s+=1,i=n-n*Math.cos(s*a),window.scrollTo(0,o-i)):clearInterval(r)}),15)}},{key:"toggleFullScreen",value:function(e){var t=document.webkitIsFullScreen||document.mozFullScreen||!1;e.requestFullScreen=e.requestFullScreen||e.webkitRequestFullScreen||e.mozRequestFullScreen||function(){return!1},document.cancelFullScreen=document.cancelFullScreen||document.webkitCancelFullScreen||document.mozCancelFullScreen||function(){return!1},t?document.cancelFullScreen():e.requestFullScreen()}},{key:"CacheItemsList",value:function(){var e={};function t(o){!e.itemsList||e.cached===e.itemsList.length&&!e.amount||e.amount&&e.cached>=e.amount||(e.amount&&(e.amount=Math.min(e.amount,e.itemsList.length)),e.currentItem=e.itemsList[o].webView,e.lastIndex=o,e.currentItem.complete?(e.cached+=1,t(e.lastIndex+1>=e.itemsList.length?0:e.lastIndex+1)):e.currentItem.addEventListener("load",i,!1))}function i(){e.cached+=1,t(e.lastIndex+1>=e.itemsList.length?0:e.lastIndex+1)}return e.cached=0,e.itemsList=void 0,e.currentItem=void 0,e.amount=void 0,e.lastIndex=void 0,e.init=function(o,a,n){e.currentItem&&e.currentItem.removeEventListener("load",i,!1),e.amount=n,e.cached=0,e.currentItem=void 0,e.lastIndex=a,e.itemsList=o,void 0===a&&(a=0),t(a)},e.status=function(){return{list:e.itemsList,index:e.lastIndex}},e}},{key:"GMEventsManager",value:function(){return{listenerSet:{},addGMEventListener:function(e,t,i){this.listenerSet[e]||(this.listenerSet[e]=[]);var o={};o.listener=t,o.handler=i,this.listenerSet[e].push(o)},removeGMEventListener:function(e,t,i){if(this.listenerSet[e])for(var o=0;o<this.listenerSet[e].length;o+=1)this.listenerSet[e][o].listener===t&&this.listenerSet[e][o].handler===i&&(this.listenerSet[e].splice(o,1),o=this.listenerSet[e].length)},dispatchGMEvent:function(e){if(this.listenerSet[e.type])for(var t=this.listenerSet[e.type],i=0;i<t.length;i+=1){var o=t[i];o&&o.listener&&"function"==typeof o.listener[o.handler]&&o.listener[o.handler](e)}}}}},{key:"GMEvent",value:function(e,t,i){var o={};return o.type=e,o.params=i,o.target=t,o}},{key:"request",value:function(t,i,o,a){var n=new XMLHttpRequest;n.open("POST",this.moduleSettings(i.appName).appApi,!0),n.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),n.setRequestHeader("X-Requested-With","XMLHttpRequest"),n.setRequestHeader("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"),n.onreadystatechange=function(){4===this.readyState&&(200!==this.status?o&&e.moduleSettings(i.appName).appEventManager.dispatchGMEvent(e.GMEvent(o,i,{error:this.statusText,params:a})):o&&e.moduleSettings(i.appName).appEventManager.dispatchGMEvent(e.GMEvent(o,i,{data:this.responseText,params:a})))},n.onerror=function(){!0===confirm("Failed to load resource: The network connection was lost. Let's try again?")&&e.request(t,i,o,a)};try{n.send(t),e.moduleSettings(i.appName).appEventManager.dispatchGMEvent(e.GMEvent("REQUEST_START",i,null))}catch(t){e.trace(t)}}},{key:"Item",value:function(t,i){var o={get webView(){return this.webImg.src?o.webImg:(this.webImg.src=this.itemViewSrc,this.webImg)}};if(e.copyProperties(t,o),o.appName=i,o.idPrefix=void 0,o.webImg=new Image,o.webImgFrame=e.Rect(0,0,0,0),o.webImg.addEventListener("load",(function(){this.classList.add("onLoad")}),!1),o.link&&""!==o.link){var a,n,s,r=o.link;r.match(/youtu\.be/i)||r.match(/youtube\.com/i)?(n=/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/,(s=r.match(n))&&11===s[7].length&&(a=s[7]),void 0!==a&&(o.mime_type="video/youtube",o.videoId=a,o.link=void 0)):r.match(/vimeo\.com/i)&&(n=/(www\.)?vimeo.com\/(\d+)($|\/)/,(s=r.match(n))&&(a=s[2]),void 0!==a&&(o.mime_type="video/vimeo",o.videoId=a,o.link=void 0))}return"audio/mpeg"===o.mime_type&&(o.type="audio"),"image"===o.mime_type.split("/")[0]&&(o.type="image"),"video"===o.mime_type.split("/")[0]&&(o.type="video"),o.hasTag=function(e){if("all"===e)return!0;if(!o.tags||0===o.tags.length)return!1;for(var t=0;t<o.tags.length;t+=1){if(o.tags[t].term_id===e)return!0}return!1},o.itemViewSrc=o.meta?o.meta.web?o.meta.web.link:o.meta.original?o.meta.original.link:o.meta.thumb?o.meta.thumb.link:null:null,o.itemViewThumbSrc=o.meta?o.meta.thumb?o.meta.thumb.link:o.meta.web?o.meta.web.link:null:null,o.itemViewSize=o.meta?o.meta.web?e.Size(o.meta.web.width,o.meta.web.height):o.meta.original?e.Size(o.meta.original.width,o.meta.original.height):e.Size(300,300):e.Size(300,300),o.itemViewThumbSize=o.meta?o.meta.thumb?e.Size(o.meta.thumb.width,o.meta.thumb.height):o.meta.web?e.Size(o.meta.web.width,o.meta.web.height):e.Size(300,300):e.Size(300,300),o}},{key:"Term",value:function(t,i){var o={set gmedia__in(e){this.query_Pr&&(this.query_Pr.gmedia__in=e.toString(),this.gmedia_in_Pr=e,this.count=e.length,"myCollection"===this.taxonomy&&this.query_Pr&&(this.sharelink="".concat(self.moduleSettings(i).post_url,"/?").concat(self.moduleSettings(i).galleryID,"[gmedia__in]=").concat(this.query_Pr.gmedia__in)))},get gmedia__in(){return this.gmedia_in_Pr},get taxony_type(){var e;switch(this.taxonomy){case"gmedia_album":e="albums";break;case"gmedia_category":e="categories";break;case"gmedia_tag":e="tags";break;case"myCollection":e="gmedia__in";break;default:e=null}return e},get term_id(){return"myCollection"===this.taxonomy?"".concat(this.taxony_type,"-").concat(this.gmedia__in.toString()):this.term_id_Pr},set term_id(e){this.term_id_Pr=e},get query(){var e,t;if("myCollection"===this.taxonomy)return t={orderby:"gmedia__in",order:"ASC",gmedia__in:this.gmedia_in_Pr.toString()};switch(this.taxonomy){case"gmedia_album":e="album__in";break;case"gmedia_category":e="category__in";break;case"gmedia_tag":e="tag__in"}return(t={per_page:0,admin:!1,page:1})[e]=[this.term_id],t}};if(e.copyProperties(t,o),t.term_id&&(o.term_id_Pr=t.term_id),o.appName=i,o.key=void 0,o.gmedia_in_Pr=[],o.meta){var a=e.Meta(o.meta,o.appName);o.meta=a}return"gmedia_tag"===o.taxonomy&&(o.name="#".concat(o.name)),"myCollection"===o.taxonomy&&o.query_Pr&&(o.gmedia__in=o.query_Pr.gmedia__in.split(",")),o}},{key:"termDataByQueryNameId",value:function(e,t,i){if(!e.gmedia__in)return null;var o=e.gmedia__in.split(",").length,a=e.orderby,n=e.order;return{count:o,name:t,meta:{_order:n,_orderby:a,order:n,orderby:a},taxonomy:"myCollection",term_id:i,_query:e}}},{key:"termsListFromAppQuery",value:function(e){var t,i=[];if(e.album__in){var o=e.album__in.split(",");for(t in o)Object.prototype.hasOwnProperty.call(o,t)&&i.push({taxonomy_type:"albums",term_id:o[t]})}if(e.category__in){var a=e.category__in.split(",");for(t in a)Object.prototype.hasOwnProperty.call(a,t)&&i.push({taxonomy_type:"categories",term_id:a[t]})}if(e.tag__in){var n=e.tag__in.split(",");for(t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.push({taxonomy_type:"tags",term_id:n[t]})}return i.length>0?i:void 0}},{key:"Meta",value:function(t,i){var o={};return e.copyProperties(t,o),o.appName=i,o._cover&&(o._cover=e.Item(t._cover,o.appName)),o.cover=o._cover?o._cover:null,o}},{key:"passiveListener",get:function(){var e=!1;try{var t={get:function(){e=!0}},i=Object.defineProperty({},"passive",t);window.addEventListener("testPassive",null,i),window.removeEventListener("testPassive",null,i)}catch(e){}return!!e&&{passive:!1,capture:!1}}},{key:"Device",get:function(){var e=window,t=e.navigator.userAgent,i={ios:!1,android:!1,androidChrome:!1,desktop:!1,windows:!1,iphone:!1,ipod:!1,ipad:!1,cordova:e.cordova||e.phonegap,phonegap:e.cordova||e.phonegap,browser:{ie11:!1}},o=t.match(/(Windows Phone);?[\s\/]+([\d.]+)?/),a=t.match(/(Android);?[\s\/]+([\d.]+)?/),n=t.match(/(iPad).*OS\s([\d_]+)/),s=t.match(/(iPod)(.*OS\s([\d_]+))?/),r=!n&&t.match(/(iPhone\sOS|iOS)\s([\d_]+)/);if(o&&(i.os="windows",i.osVersion=o[2],i.windows=!0),a&&!o&&(i.os="android",i.osVersion=a[2],i.android=!0,i.androidChrome=t.toLowerCase().indexOf("chrome")>=0),(n||r||s)&&(i.os="ios",i.ios=!0),r&&!s&&(i.osVersion=r[2].replace(/_/g,"."),i.iphone=!0),n&&(i.osVersion=n[2].replace(/_/g,"."),i.ipad=!0),s&&(i.osVersion=s[3]?s[3].replace(/_/g,"."):null,i.iphone=!0),i.ios&&i.osVersion&&t.indexOf("Version/")>=0&&"10"===i.osVersion.split(".")[0]&&(i.osVersion=t.toLowerCase().split("version/")[1].split(" ")[0]),i.desktop=!(i.os||i.android||i.webView),i.webView=(r||n||s)&&t.match(/.*AppleWebKit(?!.*Safari)/i),i.os&&"ios"===i.os){var l=i.osVersion.split("."),c=document.querySelector('meta[name="viewport"]');i.minimalUi=!i.webView&&(s||r)&&(1*l[0]==7?1*l[1]>=1:1*l[0]>7)&&c&&c.getAttribute("content").indexOf("minimal-ui")>=0}return i.pixelRatio=e.devicePixelRatio||1,window.navigator.userAgent.indexOf("Trident/7.0")>-1&&(i.browser.ie11=!0),i}},{key:"isTouchDevice",get:function(){return navigator.maxTouchPoints||"ontouchstart"in window}},{key:"getScrollbarWidth",get:function(){var e=document.createElement("div");e.style.visibility="hidden",e.style.width="100px",e.style.msOverflowStyle="scrollbar",document.body.appendChild(e);var t=e.offsetWidth;e.style.overflow="scroll";var i=document.createElement("div");i.style.width="100%",e.appendChild(i);var o=i.offsetWidth;return e.parentNode.removeChild(e),t-o}},{key:"hasScrollbar",get:function(){if("number"==typeof window.innerWidth)return window.innerWidth>document.documentElement.clientWidth;var e,t,i=document.documentElement||document.body;void 0!==i.currentStyle&&(e=i.currentStyle.overflow),e=e||window.getComputedStyle(i,"").overflow,void 0!==i.currentStyle&&(t=i.currentStyle.overflowY),t=t||window.getComputedStyle(i,"").overflowY;var o=i.scrollHeight>i.clientHeight,a=/^(visible|auto)$/.test(e)||/^(visible|auto)$/.test(t);return o&&a||("scroll"===e||"scroll"===t)}},{key:"miniScreen",get:function(){return window.screen.height<500||window.screen.width<500}},{key:"youTubeCode",get:function(){return'<iframe src="https://www.youtube.com/embed/%id%?autoplay=1&rel=0&showinfo=0&wmode=transparent" allow="autoplay" frameborder="0" allowfullscreen></iframe>'}},{key:"vimeoCode",get:function(){return'<iframe src="https://player.vimeo.com/video/%id%?autoplay=1&byline=0&portrait=0&transparent=0" frameborder=“0” allowfullscreen allow=autoplay></iframe>'}},{key:"isFullscreen",get:function(){return document.webkitIsFullScreen||document.mozFullScreen||!1}}]),e}();i(7);function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){for(var i=0;i<t.length;i++){var o=t[i];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function l(e,t,i){return t&&r(e.prototype,t),i&&r(e,i),e}var c=function(){function e(t){s(this,e),this.delegate=t,this.item=void 0,this.id=void 0,this.appName=t.appName,this.itemIndex=void 0,this.iconSet=t.iconSet,this.positionIndex=0,this.view=document.createElement("div"),this.view.className="".concat(e.classPref,"view"),this.itemInner=document.createElement("div"),this.itemInner.className="".concat(e.classPref,"inner"),this.view.appendChild(this.itemInner),this.iconHolder=document.createElement("div"),this.iconHolder.className="".concat(e.classPref,"icon-holder"),this.preloader=n.createPreloaderView(this.delegate.params.preloaderColor),this.preloader.style.display="none",this.view.appendChild(this.preloader),this.view.appendChild(this.iconHolder),this.size=n.Size(0,0),this.imgSize=n.Size(0,0),this.imageFramePr=n.Rect(0,0,0,0),this.imageFrameFF=n.Rect(0,0,0,0),this.imageScaledFF=!1,this.width=0,this.height=0,this.maxXoffset=0,this.maxYoffset=0,this.MaxScale=4,this.imgScale=1,this.imgScaleFF=1,this.scale=1,this.newScale=1,this.newScaleMW=1,this.viewTranslatePr=n.Point(0,0),this.origin=n.Point(0,0),this.boundingBox=void 0,this.boundingBoxScale=void 0,this.animaSliderRender=void 0,this.speedX=0,this.speedY=0,this.oldX=0,this.newX=0,this.oldY=0,this.newY=0,this.draging=!1,this.isBlockDraging=!1,this.isBlockDragingMem=!1,this.startScale=void 0,this.startGlobalPoint=void 0,this.startDistForZoom=void 0}return l(e,null,[{key:"classPref",get:function(){return"gmedia-slider-page-"}}]),l(e,[{key:"initByItem",value:function(e){if(this.id!==e.ID){var t=this;switch(this.item=e,this.id=e.ID,1!==this.scale&&(this.scale=1,this.viewTranslate=n.Point(0,0)),this.itemInner.firstChild&&this.itemInner.removeChild(this.itemInner.firstChild),this.itemInner.appendChild(e.webView),this.itemImg=e.webView,e.webView.complete?(this.imgSize.width=this.itemImg.naturalWidth,this.imgSize.height=this.itemImg.naturalHeight,this.isInScale&&this.normalize(),this.fit(!1)):(this.preloader.style.display="block",e.webView.addEventListener("load",(function(){t.preloader.style.display="none",t.imgSize.width=this.naturalWidth,t.imgSize.height=this.naturalHeight,t.isInScale&&t.normalize(),t.fit(!1)}),!1)),e.type){case"audio":this.iconHolder.innerHTML=this.iconSet.NOTE_SVG,this.view.classList.add("info-icon");break;case"video":this.view.classList.add("info-icon"),this.iconHolder.innerHTML=this.iconSet.PLAY_SVG,this.iconHolder.firstChild.style.marginLeft="7px";break;default:this.view.classList.remove("info-icon")}}}},{key:"resize",value:function(e){this.size=e,this.posX=this.positionIndex,this.isInScale&&this.normalize(),this.fit(!0)}},{key:"fit",value:function(){if(this.itemImg){var e=this.delegate.params.xOffset,t=0,i=n.getFrameForBoxWithMode(this.imgSize,n.Size(this.size.width-2*e,this.size.height-2*t),!1,!1);i.x+=e,i.y+=t,this.imageFrameFF=i,t=this.delegate.params.yOffset,(i=n.getFrameForBoxWithMode(this.imgSize,n.Size(this.size.width-2*e,this.size.height-2*t),!1,!1)).x+=e,i.y+=t,this.imageFrameNF=i,this.imgScale=Math.min(this.imgSize.width/i.width,this.MaxScale),this.imgScaleFF=this.imageFrameFF.height/i.height,"video"!==this.item.type&&(this.delegate.FF_Mode?(this.imageFrame=this.imageFrameFF,i=this.imageFrameFF,this.imageScaledFF=!0):(this.imageFrame=this.imageFrameNF,i=this.imageFrameNF,this.imageScaledFF=!1)),this.item.webImgFrame.x!==i.x||this.item.webImgFrame.y!==i.y||this.item.webImgFrame.width!==i.width||this.item.webImgFrame.height!==i.height?(this.imageFrame=i,this.item.webImgFrame=i):this.imageFramePr=i,this.videoWrap&&(this.videoWrapFrame=i)}}},{key:"checkOffset",value:function(e,t){var i=this.imageScaledFF?this.imageFrameFF:this.imageFrame;if(t!==this.boundingBoxScale){var o=i.width*(t||1),a=i.height*(t||1),s=i.x*(t||1),r=i.y*(t||1);this.boundingBox={left:o>this.size.width?-s:(this.size.width-this.size.width*t)/2,top:a>this.size.height?-r:(this.size.height-this.size.height*t)/2,right:o>this.size.width?this.size.width-(s+o):(this.size.width-this.size.width*t)/2,bottom:a>this.size.height?this.size.height-(r+a):(this.size.height-this.size.height*t)/2},this.boundingBoxScale=t}var l=e.x>this.boundingBox.left?this.boundingBox.left:e.x;l=l<this.boundingBox.right?this.boundingBox.right:l;var c=e.y>this.boundingBox.top?this.boundingBox.top:e.y;return c=c<this.boundingBox.bottom?this.boundingBox.bottom:c,n.Point(l,c)}},{key:"isPointInItem",value:function(e){var t=this.viewTranslate.x+this.size.width/2*this.newScale-this.imageFrame.width/2*this.newScale,i=t+this.imageFrame.width*this.newScale,o=this.size.height/2*this.newScale+this.viewTranslate.y-this.imageFrame.height/2*this.newScale*this.newScale,a=o+this.imageFrame.height*this.scale*this.newScale;return e.x>t&&e.x<i&&e.y>o&&e.y<a}},{key:"normalize",value:function(e){n.cancelAnimationFrame(this.animaSliderRender),e?this.renderTransformTo(n.Point(0,0),1):(this.scale=1,this.newScale=1,this.newScaleMW=1,this.viewTranslate=n.Point(0,0),this.origin=n.Point(0,0))}},{key:"zoomIn",value:function(e,t){if("audio"!==this.item.type&&"video"!==this.item.type){n.cancelAnimationFrame(this.animaSliderRender);var i=t.x-this.viewTranslate.x,o=t.y-this.viewTranslate.y,a=i/this.scale,s=o/this.scale,r=t.x-a*e,l=t.y-s*e,c=n.Point(r,l);this.renderTransformTo(this.checkOffset(c,e),e)}}},{key:"zoomByScaleIter",value:function(e,t){if("audio"!==this.item.type&&"video"!==this.item.type){var i=e<0?1.065:.935;n.cancelAnimationFrame(this.animaSliderRender),this.newScale*i>this.MaxScale&&(i=this.MaxScale/this.newScale),this.newScale*i<1&&(i=1/this.newScale),this.newScale*=i,this.origin=n.Point(t.x-i*(t.x-this.origin.x),t.y-i*(t.y-this.origin.y)),this.renderTransformTo(this.checkOffset(this.origin,this.newScale),this.newScale)}}},{key:"zoomByScaleDeltaToPoint",value:function(e,t){if("audio"!==this.item.type&&"video"!==this.item.type){var i;n.cancelAnimationFrame(this.animaSliderRender);var o=e/this.startDistForZoom,a=0;(i=this.startDistForZoom/this.startScale*o/(this.startDistForZoom/this.startScale)*this.startScale)>this.MaxScale&&(a=.8*-(i-this.MaxScale)),i+=a;var s=this.startGlobalPoint.x-this.startTranslate.x,r=this.startGlobalPoint.y-this.startTranslate.y,l=s/this.newScale,c=r/this.newScale,d=this.startGlobalPoint.x-l*i,h=this.startGlobalPoint.y-c*i,m=n.Point(d-t.x,h-t.y);this.scale=i,this.newScale=i,this.viewTranslate=m,this.startTranslate=n.Point(d,h)}}},{key:"renderTransformTo",value:function(e,t){var i=this;n.cancelAnimationFrame(i.animaSliderRender),this.origin=e,this.newScale=t;var o=0,a=0,s=0,r=.05,l=.1;i.animaSliderRender=n.requestAnimationFrame((function c(){o=o*r+(e.x-i.viewTranslate.x)*l,a=a*r+(e.y-i.viewTranslate.y)*l,t&&(s=s*r+.1*(t-i.scale));var d=i.viewTranslate.x;d+=o;var h=i.viewTranslate.y;h+=a,t&&(i.scale+=s),i.viewTranslate=n.Point(d,h),Math.abs(o)<.02&&Math.abs(a)<.02&&Math.abs(s)<.02?(n.cancelAnimationFrame(i.animaSliderRender),t&&(i.scale=t),i.viewTranslate=n.Point(e.x,e.y)):i.animaSliderRender=n.requestAnimationFrame(c)}))}},{key:"renderGlidingTransform",value:function(){var e=this;n.cancelAnimationFrame(e.animaSliderRender);var t=.95,i=.95;e.animaSliderRender=n.requestAnimationFrame((function o(){e.speedX*=t,e.speedY*=i;var a=e.viewTranslate.x;a+=e.speedX;var s=e.viewTranslate.y;if(s+=e.speedY,a>e.boundingBox.left||a<e.boundingBox.right){e.speedX*=-1;var r=a<e.boundingBox.right?e.boundingBox.right:a;a=a>e.boundingBox.left?e.boundingBox.left:r,a+=e.speedX,t=.75}if(s>e.boundingBox.top||s<e.boundingBox.bottom){e.speedY*=-1;var l=s<e.boundingBox.bottom?e.boundingBox.bottom:s;s=s>e.boundingBox.top?e.boundingBox.top:l,s+=e.speedY,i=.75}e.origin=n.Point(a,s),e.viewTranslate=n.Point(a,s),Math.abs(e.speedX)<.02&&Math.abs(e.speedY)<.02?(n.cancelAnimationFrame(e.animaSliderRender),e.speedX=0,e.speedY=0):e.animaSliderRender=n.requestAnimationFrame(o)}))}},{key:"renderStretchstretchTransform",value:function(){var e=this;n.cancelAnimationFrame(e.animaSliderRender);var t=this.checkOffset(n.Point(e.viewTranslate.x+e.speedX,e.viewTranslate.y+e.speedY),e.scale),i=.2,o=.15,a=0,s=0;e.animaSliderRender=n.requestAnimationFrame((function r(){a=a*i+(t.x-e.viewTranslate.x)*o,s=s*i+(t.y-e.viewTranslate.y)*o;var l=e.viewTranslate.x+a,c=e.viewTranslate.y+s;e.viewTranslate=n.Point(l,c),Math.abs(a)<.02&&Math.abs(s)<.02?(n.cancelAnimationFrame(e.animaSliderRender),e.viewTranslate=t):e.animaSliderRender=n.requestAnimationFrame(r)}))}},{key:"startDrag",value:function(e,t){n.cancelAnimationFrame(this.animaSliderRender),"audio"!==this.item.type&&"video"!==this.item.type&&(this.startDistForZoom=t,this.startGlobalPoint=e,this.startTranslate=this.viewTranslate,this.speedX=0,this.speedY=0,this.newX=this.viewTranslate.x,this.newY=this.viewTranslate.y,this.startScale=this.scale)}},{key:"stopDrag",value:function(){if("audio"!==this.item.type&&"video"!==this.item.type){if(this.isInScale)if(this.scale<1)this.normalize(!0);else if(this.scale>this.MaxScale)this.zoomIn(this.MaxScale,this.startGlobalPoint);else{var e=this.checkOffset(this.origin,this.newScale);this.isBlockDraging=e.x!==this.origin.x||e.y!==this.origin.y,this.isBlockDraging&&this.renderStretchstretchTransform()}this.draging&&(this.isBlockDraging?this.renderStretchstretchTransform():this.renderGlidingTransform(),this.draging=!1)}}},{key:"dragin",value:function(e){if("audio"===this.item.type||"video"===this.item.type)return!1;var t=this.startTranslate.x-e.x,i=this.startTranslate.y-e.y,o=this.checkOffset(n.Point(t,i),this.newScale);this.isBlockDraging=o.x!==t||o.y!==i,t-=.7*(t-o.x),i-=.7*(i-o.y);return this.oldX=this.newX,this.newX=t,this.speedX=.7*(this.newX-this.oldX),this.oldY=this.newY,this.newY=i,this.speedY=.7*(this.newY-this.oldY),this.origin=n.Point(t,i),this.viewTranslate=n.Point(t,i),this.draging=!0,!0}},{key:"action",value:function(e){if(this.item)switch(e){case"click":if("video"===this.item.type)return this.videoWrap?(this.removeVideoContent(),"videoStop"):(this.view.classList.add("video-play"),this.view.classList.remove("info-icon"),this.addVideoContent(),"videoPlay");if("audio"===this.item.type)return this.tryPlayOrPauseMp3(),"audioPlay";break;case"removeSubContent":if("video"===this.item.type)return this.removeVideoContent(),"videoStop";"audio"===this.item.type&&this.audioPlayer&&!this.audioPlayer.paused&&(this.audioPlayer.pause(),this.iconHolder.firstChild.classList.remove("gmWrapRotate"));break;default:return}}},{key:"addVideoContent",value:function(){var e=this.item.mime_type.split("/")[1];if(e)switch(this.videoWrap||(this.videoWrap=document.createElement("div"),this.videoWrap.className="video-wrap",this.videoWrapFrame=this.imageFrame,this.itemInner.appendChild(this.videoWrap)),e){case"youtube":this.videoWrap.innerHTML=n.youTubeCode.replace("%id%",this.item.videoId);break;case"vimeo":this.videoWrap.innerHTML=n.vimeoCode.replace("%id%",this.item.videoId)}}},{key:"removeVideoContent",value:function(){this.videoWrap&&(this.view.classList.remove("video-play"),this.videoWrap.parentNode&&this.videoWrap.parentNode.removeChild(this.videoWrap),this.videoWrap=void 0,this.view.classList.remove("video-play"),"image"!==this.item.type&&this.view.classList.add("info-icon"))}},{key:"tryPlayOrPauseMp3",value:function(){if("audio"===this.item.type){if(!this.audioPlayer){if(!document.getElementById("gmAudioPlayer"))return;this.audioPlayer=document.getElementById("gmAudioPlayer")}this.audioPlayer.src===this.item.url?this.audioPlayer.paused?(this.audioPlayer.play(),this.iconHolder.firstChild.classList.add("gmWrapRotate")):(this.audioPlayer.pause(),this.iconHolder.firstChild.classList.remove("gmWrapRotate")):(this.audioPlayer.src=this.item.url,this.audioPlayer.play(),this.iconHolder.firstChild.classList.add("gmWrapRotate"))}}},{key:"posX",set:function(e){this.view.style.left="".concat(this.size.width*e,"px"),this.positionIndex=e}},{key:"imageFrame",set:function(e){this.itemImg.style.left="".concat(e.x,"px