· 9 years ago · Feb 14, 2017, 06:24 PM
1<?php
2/**
3 * Plugin Name: WP-ClanWars
4 * Author URI: http://www.codeispoetry.ru/
5 * Plugin URI: https://bitbucket.org/and/wp-clanwars
6 * Description: ClanWars plugin for a cyber-sport team website
7 * Author: Andrej Mihajlov
8 * Version: 1.7.1
9 *
10 * Tags: cybersport, clanwar, team, clan, cyber, sport, match
11 **/
12
13/*
14 WP-Clanwars plugin
15 (c) 2011 Andrej Mihajlov
16
17 This file is part of WP-Clanwars.
18
19 WP-Clanwars is free software: you can redistribute it and/or modify
20 it under the terms of the GNU General Public License as published by
21 the Free Software Foundation, either version 3 of the License, or
22 (at your option) any later version.
23
24 WP-Clanwars 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 WP-Clanwars. If not, see <http://www.gnu.org/licenses/>.
31*/
32
33// Exit if accessed directly
34defined( 'ABSPATH' ) || exit;
35
36global $wpClanWars;
37
38define('WP_CLANWARS_VERSION', '1.7.1');
39
40define('WP_CLANWARS_TEXTDOMAIN', 'wp-clanwars');
41define('WP_CLANWARS_COUNTRIES_TEXTDOMAIN', 'wp-clanwars-countries');
42
43define('WP_CLANWARS_CATEGORY', '_wp_clanwars_category');
44define('WP_CLANWARS_DEFAULTCSS', '_wp_clanwars_defaultcss');
45
46define('WP_CLANWARS_URL', WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)));
47
48// this folder is created in wp-content/
49define('WP_CLANWARS_EXPORTDIR', 'wp-clanwars');
50define('WP_CLANWARS_ZIPINDEX', 'index.json');
51
52require_once (dirname(__FILE__) . '/classes/view.class.php');
53require_once (dirname(__FILE__) . '/classes/flash.class.php');
54require_once (dirname(__FILE__) . '/classes/utils.class.php');
55require_once (dirname(__FILE__) . '/classes/games.class.php');
56require_once (dirname(__FILE__) . '/classes/teams.class.php');
57require_once (dirname(__FILE__) . '/classes/maps.class.php');
58require_once (dirname(__FILE__) . '/classes/rounds.class.php');
59require_once (dirname(__FILE__) . '/classes/matches.class.php');
60require_once (dirname(__FILE__) . '/classes/api.class.php');
61require_once (dirname(__FILE__) . '/classes/acl.class.php');
62
63require_once(dirname(__FILE__) . '/classes/match_table.class.php');
64require_once(dirname(__FILE__) . '/classes/teams_table.class.php');
65require_once(dirname(__FILE__) . '/classes/games_table.class.php');
66require_once(dirname(__FILE__) . '/classes/maps_table.class.php');
67
68require_once (dirname(__FILE__) . '/wp-clanwars-widget.php');
69require_once (dirname(__FILE__) . '/wp-livematch-widget.php');
70require_once (dirname(__FILE__) . '/wp-topmatch-widget.php');
71require_once (ABSPATH . 'wp-admin/includes/class-pclzip.php');
72
73// namespace import
74use \WP_Clanwars\Flash;
75use \WP_Clanwars\Utils;
76use \WP_Clanwars\View;
77use \WP_Clanwars\API as CloudAPI;
78
79class WP_ClanWars {
80
81 var $match_status = array();
82 var $page_hooks = array();
83
84 const ErrorOK = 0;
85 const ErrorDatabase = -199;
86 const ErrorUploadMaxFileSize = 1; // UPLOAD_ERR_INI_SIZE
87 const ErrorUploadHTMLMaxFileSize = 2; // UPLOAD_ERR_FORM_SIZE
88 const ErrorUploadPartially = 3; // UPLOAD_ERR_PARTIAL
89 const ErrorUploadNoFile = 4; // UPLOAD_ERR_NO_FILE
90 const ErrorUploadMissingTemp = 6; // UPLOAD_ERR_NO_TMP_DIR
91 const ErrorUploadDiskWrite = 7; // UPLOAD_ERR_CANT_WRITE
92 const ErrorUploadStoppedByExt = 8; // UPLOAD_ERR_EXTENSION
93 const ErrorUploadFileTypeNotAllowed = -215;
94
95 function __construct() {
96 load_plugin_textdomain(WP_CLANWARS_TEXTDOMAIN, PLUGINDIR . '/' . dirname(plugin_basename(__FILE__)) . '/langs/', //2.5 Compatibility
97 dirname(plugin_basename(__FILE__)) . '/langs/'); //2.6+, Works with custom wp-content dirs.
98
99 add_action('widgets_init', array($this, 'on_widgets_init'));
100 add_action('init', array($this, 'on_init'));
101 }
102
103 /**
104 * Check if plugin runs within jumpstarter instance
105 *
106 * @return bool true if plugin runs within jumpstarter instance, otherwise false
107 */
108 function is_jumpstarter() {
109 // JS_WP_User is defined in wp-jumpstarter:
110 // see: https://github.com/jumpstarter-io/wp-jumpstarter/blob/master/jumpstarter.php
111 return class_exists('JS_WP_User');
112 }
113
114 /**
115 * Plugin activation hook
116 *
117 * Creates tables if needed
118 *
119 * @return void
120 */
121
122 public function on_activate()
123 {
124 global $wpdb;
125
126 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
127
128 $charset_collate = $wpdb->get_charset_collate();
129
130 $dbstruct = array();
131 $dbstruct[] = \WP_Clanwars\Games::schema();
132 $dbstruct[] = \WP_Clanwars\Maps::schema();
133 $dbstruct[] = \WP_Clanwars\Matches::schema();
134 $dbstruct[] = \WP_Clanwars\Rounds::schema();
135 $dbstruct[] = \WP_Clanwars\Teams::schema();
136
137 add_option(WP_CLANWARS_CATEGORY, -1);
138 add_option(WP_CLANWARS_DEFAULTCSS, true);
139
140 $dbstruct = implode("\n", $dbstruct);
141
142 // update database
143 dbDelta($dbstruct);
144 }
145
146 /**
147 * Plugin deactivation hook
148 *
149 * @return void
150 */
151
152 public function on_deactivate()
153 {
154 }
155
156 public function on_uninstall()
157 {
158 global $wpdb;
159
160 delete_option(WP_CLANWARS_CATEGORY);
161 delete_option(WP_CLANWARS_DEFAULTCSS);
162 \WP_Clanwars\ACL::destroy();
163
164 $tables = array();
165
166 array_push( \WP_Clanwars\Games::table() );
167 array_push( \WP_Clanwars\Maps::table() );
168 array_push( \WP_Clanwars\Rounds::table() );
169 array_push( \WP_Clanwars\Matches::table() );
170 array_push( \WP_Clanwars\Teams::table() );
171
172 foreach($tables as $table) {
173 $wpdb->query( "DROP TABLE `$table`" );
174 }
175 }
176
177 /**
178 * WP init hook
179 *
180 * Plugin initialization method used to load textdomain,
181 * register hooks, scripts and styles.
182 *
183 * @return void
184 */
185
186 function on_init()
187 {
188 $this->match_status = array(
189 __('99DAMAGE', WP_CLANWARS_TEXTDOMAIN),
190 __('ESL', WP_CLANWARS_TEXTDOMAIN),
191 __('PCW', WP_CLANWARS_TEXTDOMAIN),
192 __('Official', WP_CLANWARS_TEXTDOMAIN)
193 );
194
195 add_action('admin_print_styles', array($this, 'on_admin_print_styles'));
196 add_action('admin_init', array($this, 'on_admin_init'));
197 add_action('admin_menu', array($this, 'on_admin_menu'));
198 add_action('template_redirect', array($this, 'on_template_redirect'));
199 add_action('wp_footer', array($this, 'on_wp_footer'));
200
201 add_action('admin_post_wp-clanwars-deleteteams', array($this, 'on_admin_post_deleteteams'));
202 add_action('admin_post_wp-clanwars-sethometeam', array($this, 'on_admin_post_sethometeam'));
203 add_action('admin_post_wp-clanwars-gamesop', array($this, 'on_admin_post_gamesop'));
204 add_action('admin_post_wp-clanwars-deletemaps', array($this, 'on_admin_post_deletemaps'));
205 add_action('admin_post_wp-clanwars-delete-match', array($this, 'on_admin_post_delete_match'));
206
207 add_action('admin_post_wp-clanwars-settings', array($this, 'on_admin_post_settings'));
208 add_action('admin_post_wp-clanwars-acl', array($this, 'on_admin_post_acl'));
209 add_action('admin_post_wp-clanwars-deleteacl', array($this, 'on_admin_post_deleteacl'));
210 add_action('admin_post_wp-clanwars-import', array($this, 'on_admin_post_import'));
211 add_action('admin_post_wp-clanwars-publish', array($this, 'on_admin_post_publish'));
212 add_action('admin_post_wp-clanwars-login', array($this, 'on_admin_post_login'));
213 add_action('admin_post_wp-clanwars-logout', array($this, 'on_admin_post_logout'));
214
215 add_action('admin_post_wp-clanwars-setupteam', array($this, 'on_admin_post_setup_team'));
216 add_action('admin_post_wp-clanwars-setupgames', array($this, 'on_admin_post_setup_games'));
217
218 add_action('wp_ajax_get_maps', array($this, 'on_ajax_get_maps'));
219 add_shortcode('wp-clanwars', array($this, 'on_shortcode'));
220
221 $this->register_cssjs();
222 }
223
224 function on_admin_print_styles() {
225echo <<<EOT
226<style type="text/css">
227#toplevel_page_wp-clanwars-matches .wp-menu-image {
228 background-size: 16px 16px !important;
229}
230</style>
231EOT;
232 }
233
234 function on_admin_init() {
235 Flash::setup();
236 }
237
238 /**
239 * WP admin_menu hook
240 *
241 * Page, Assets registration, load-* action hooks
242 *
243 * @return void
244 */
245 function on_admin_menu()
246 {
247 global $current_user;
248
249 $acl_table = array(
250 'manage_matches' => 'manage_options',
251 'manage_teams' => 'manage_options',
252 'manage_games' => 'manage_options',
253 );
254
255 $routes = array(
256 'manage_matches' => 'wp-clanwars-matches',
257 'manage_teams' => 'wp-clanwars-teams',
258 'manage_games' => 'wp-clanwars-games'
259 );
260
261 $user_role = $current_user->roles[0];
262 $top_level_slug = '';
263
264 foreach( $acl_table as $custom_cap => $wordpress_cap ) {
265 $has_permissions = \WP_Clanwars\ACL::user_can( $custom_cap );
266 if(!$has_permissions) {
267 continue;
268 }
269
270 $acl_table[$custom_cap] = $user_role;
271
272 // point top level slug to first menu user has access to
273 if($top_level_slug === '') {
274 $top_level_slug = $routes[$custom_cap];
275 }
276 }
277
278 // do not register admin menu becuase user doesn't have any permissions
279 if($top_level_slug === '') {
280 return;
281 }
282
283 // place plugin below dashboard on jumpstarter
284 $menu_position = $this->is_jumpstarter() ? 3 : null;
285
286 // prepare SVG data URI image for menu
287 $iconData = file_get_contents( dirname(__FILE__) . '/images/plugin-icon.svg' );
288 $iconDataURI = 'data:image/svg+xml;base64,' . base64_encode($iconData);
289
290 $top = add_menu_page(
291 __('ClanWars', WP_CLANWARS_TEXTDOMAIN),
292 __('ClanWars', WP_CLANWARS_TEXTDOMAIN),
293 $user_role,
294 $top_level_slug,
295 null,
296 $iconDataURI,
297 $menu_position
298 );
299
300 $this->page_hooks['matches'] = add_submenu_page(
301 $top_level_slug,
302 __('Matches', WP_CLANWARS_TEXTDOMAIN),
303 __('Matches', WP_CLANWARS_TEXTDOMAIN),
304 $acl_table['manage_matches'],
305 $routes['manage_matches'],
306 $this->onboarding_or_page( 'on_manage_matches' )
307 );
308
309 $this->page_hooks['teams'] = add_submenu_page(
310 $top_level_slug,
311 __('Teams', WP_CLANWARS_TEXTDOMAIN),
312 __('Teams', WP_CLANWARS_TEXTDOMAIN),
313 $acl_table['manage_teams'],
314 $routes['manage_teams'],
315 $this->onboarding_or_page( 'on_manage_teams' )
316 );
317
318 $this->page_hooks['games'] = add_submenu_page(
319 $top_level_slug,
320 __('Games', WP_CLANWARS_TEXTDOMAIN),
321 __('Games', WP_CLANWARS_TEXTDOMAIN),
322 $acl_table['manage_games'],
323 $routes['manage_games'],
324 $this->onboarding_or_page( 'on_manage_games' )
325 );
326
327 $this->page_hooks['import'] = add_submenu_page(
328 $top_level_slug,
329 __('Clanwars Cloud', WP_CLANWARS_TEXTDOMAIN),
330 __('Clanwars Cloud', WP_CLANWARS_TEXTDOMAIN),
331 'manage_options',
332 'wp-clanwars-cloud',
333 $this->onboarding_or_page( 'on_import' )
334 );
335
336 $this->page_hooks['settings'] = add_submenu_page(
337 $top_level_slug,
338 __('Settings', WP_CLANWARS_TEXTDOMAIN),
339 __('Settings', WP_CLANWARS_TEXTDOMAIN),
340 'manage_options',
341 'wp-clanwars-settings',
342 $this->onboarding_or_page( 'on_settings' )
343 );
344
345 if(!$this->should_onboard_user()) {
346 add_action('load-' . $this->page_hooks['matches'], array($this, 'on_load_manage_matches'));
347 add_action('load-' . $this->page_hooks['teams'], array($this, 'on_load_manage_teams'));
348 add_action('load-' . $this->page_hooks['games'], array($this, 'on_load_manage_games'));
349 }
350
351 foreach($this->page_hooks as $page_hook) {
352 add_action('load-' . $page_hook, array($this, 'on_load_any'));
353 }
354 }
355
356 function register_cssjs()
357 {
358 wp_register_script('wp-clanwars-matches', WP_CLANWARS_URL . '/js/matches.js', array( 'jquery', 'select2' ), WP_CLANWARS_VERSION);
359 wp_register_script('wp-clanwars-gallery', WP_CLANWARS_URL . '/js/gallery.js', array('jquery', 'jquery-ui-sortable', 'media-upload'), WP_CLANWARS_VERSION);
360
361 wp_register_script('wp-clanwars-admin', WP_CLANWARS_URL . '/js/admin.js', array('jquery', 'select2'), WP_CLANWARS_VERSION);
362 wp_localize_script('wp-clanwars-admin',
363 'wpCWAdminL10n',
364 array(
365 'confirmDeleteMap' => __('Are you sure you want to delete this map?', WP_CLANWARS_TEXTDOMAIN),
366 'confirmDeleteGame' => __('Are you sure you want to delete this game?', WP_CLANWARS_TEXTDOMAIN),
367 'confirmDeleteTeam' => __('Are you sure you want to delete this team?', WP_CLANWARS_TEXTDOMAIN),
368 'confirmDeleteMatch' => __('Are you sure you want to delete this match?', WP_CLANWARS_TEXTDOMAIN)
369 )
370 );
371
372 wp_register_script('wp-clanwars-game-browser', WP_CLANWARS_URL . '/js/game-browser.js', array('jquery'), WP_CLANWARS_VERSION);
373 wp_register_script('wp-clanwars-login', WP_CLANWARS_URL . '/js/login.js', array('jquery', 'jquery-tipsy'), WP_CLANWARS_VERSION);
374
375 wp_register_style('wp-clanwars-admin', WP_CLANWARS_URL . '/css/admin.css', array( 'select2', 'jquery-tipsy', 'font-awesome', 'wp-admin' ), WP_CLANWARS_VERSION);
376 wp_register_style('wp-clanwars-flags', WP_CLANWARS_URL . '/css/flags.css', array(), '1.01');
377
378 wp_register_script('jquery-tipsy', WP_CLANWARS_URL . '/components/tipsy/src/javascripts/jquery.tipsy.js', array('jquery'));
379 wp_register_style('jquery-tipsy', WP_CLANWARS_URL . '/components/tipsy/src/stylesheets/tipsy.css', array());
380
381 wp_register_script('select2', WP_CLANWARS_URL . '/components/select2/dist/js/select2.full.min.js', array('jquery'));
382 wp_register_style('select2', WP_CLANWARS_URL . '/components/select2/dist/css/select2.min.css');
383 wp_register_style('font-awesome', WP_CLANWARS_URL . '/components/font-awesome/css/font-awesome.min.css');
384
385 wp_register_script('wp-clanwars-public', WP_CLANWARS_URL . '/js/public.js', array('jquery-tipsy'), WP_CLANWARS_VERSION);
386
387 wp_register_style('wp-clanwars-sitecss', WP_CLANWARS_URL . '/css/site.css', array(), WP_CLANWARS_VERSION);
388 wp_register_style('wp-clanwars-widgetcss', WP_CLANWARS_URL . '/css/widget.css', array(), WP_CLANWARS_VERSION);
389
390 $callbackURL = admin_url( 'admin-post.php?action=wp-clanwars-login' );
391 $facebook_login_url = CloudAPI::get_login_url('facebook', $callbackURL);
392 $steam_login_url = CloudAPI::get_login_url('steam', $callbackURL);
393 wp_localize_script('wp-clanwars-login',
394 'wpClanwarsLoginSettings',
395 compact('facebook_login_url', 'steam_login_url')
396 );
397 }
398
399 function onboarding_or_page($page_method) {
400 if($this->should_onboard_user()) {
401 return array( $this, 'onboarding_page');
402 }
403 return array( $this, $page_method );
404 }
405
406 function should_onboard_user() {
407 static $flag = null;
408
409 if($flag === null) {
410 $has_hometeam = is_object( \WP_Clanwars\Teams::get_hometeam() );
411 $games = \WP_Clanwars\Games::get_game(array(), true);
412
413 $flag = ($games->count() === 0 || !$has_hometeam) && current_user_can('manage_options');
414 }
415
416 return $flag;
417 }
418
419 function onboarding_page() {
420 $games = \WP_Clanwars\Games::get_game(array(), true);
421
422 $has_hometeam = is_object( \WP_Clanwars\Teams::get_hometeam() );
423 $has_games = ($games->count() > 0);
424
425 if(!$has_hometeam && !$has_games) {
426 $page_submit = __( 'Continue', WP_CLANWARS_TEXTDOMAIN );
427 }
428 else {
429 $page_submit = __( 'Get started', WP_CLANWARS_TEXTDOMAIN );
430 }
431
432 if(!$has_hometeam) {
433 $this->onboarding_setup_team_page($page_submit);
434 }
435 else if(!$has_games) {
436 $this->onboarding_setup_games_page($page_submit);
437 }
438 }
439
440 function onboarding_setup_team_page($page_submit) {
441 $view = new View( 'setup_team' );
442 $view->add_helper('html_country_select_helper', array('\\WP_Clanwars\\Utils', 'html_country_select_helper'));
443 $context = compact('page_submit');
444
445 $view->render( $context );
446 }
447
448 function onboarding_setup_games_page($page_submit) {
449 $query_args = Utils::extract_args( $_GET, array( 'q' => '' ) );
450
451 $search_query = trim( (string) $query_args['q'] );
452 $installed_games = \WP_Clanwars\Games::get_game('');
453 $store_ids = array_filter(
454 array_map( function ($game) {
455 return $game->store_id;
456 }, $installed_games)
457 );
458 $active_tab = '';
459 $install_action = 'wp-clanwars-import';
460
461 if( empty($search_query) ) {
462 $api_response = CloudAPI::get_popular();
463
464 $active_tab = 'popular';
465 }
466 else {
467 $api_response = CloudAPI::search( $search_query );
468
469 $active_tab = 'search';
470 }
471
472 $api_games = array();
473
474 if( !is_wp_error( $api_response ) ) {
475 array_walk($api_response, function (&$game) use ($store_ids) {
476 $game->is_installed = in_array($game->_id, $store_ids);
477 });
478 $api_games = $api_response;
479 }
480 else {
481 $api_error_message = $api_response->get_error_message();
482 }
483
484 $view = new View( 'setup_games' );
485 $context = compact( 'page_submit', 'api_games', 'api_error_message', 'search_query', 'active_tab', 'install_action' );
486
487 wp_enqueue_script( 'wp-clanwars-game-browser' );
488
489 $view->render( $context );
490 }
491
492 function on_admin_post_setup_team() {
493 if( !current_user_can('manage_options') ) {
494 wp_die(__('Cheatin’ uh?'));
495 }
496
497 check_admin_referer('wp-clanwars-setupteam');
498
499 $data = Utils::extract_args( $_POST, array(
500 'title' => '',
501 'country' => ''
502 ) );
503
504 $data['home_team'] = 1;
505
506 if( !empty( $data['title'] ) && !empty( $data['country'] ) ) {
507 \WP_Clanwars\Teams::add_team( $data );
508 }
509 else {
510 Flash::error( __( 'Please fill in all required fields.', WP_CLANWARS_TEXTDOMAIN ) );
511 }
512
513 wp_redirect( $_REQUEST['_wp_http_referer'] );
514 }
515
516 function on_admin_post_setup_games() {
517 if(!current_user_can('manage_options')) {
518 wp_die(__('Cheatin’ uh?'));
519 }
520
521 check_admin_referer('wp-clanwars-setupgames');
522
523 extract(Utils::extract_args($_POST, array(
524 'import' => '',
525 'new_game_name' => ''
526 )
527 ));
528
529 $redirect_url = $_POST['_wp_http_referer'];
530
531 if( $import === 'upload') {
532 if(isset($_FILES['userfile'])) {
533 $file = $_FILES['userfile'];
534
535 if($file['error'] === 0) {
536 $err = $this->import_game( $file['tmp_name'] );
537
538 if( is_wp_error( $err ) ) {
539 Flash::error( $err->get_error_message() );
540 }
541 else {
542 Flash::success( __( 'Imported game.', WP_CLANWARS_TEXTDOMAIN ) );
543 }
544 }
545 else {
546 Flash::error( __( 'Failed to upload file.', WP_CLANWARS_TEXTDOMAIN ) );
547 }
548 }
549 }
550 else if( $import === 'create' ) {
551
552 $new_game_name = trim($new_game_name);
553
554 if( !empty ( $new_game_name ) ) {
555 $new_game_id = \WP_Clanwars\Games::add_game(array(
556 'title' => $new_game_name,
557 'abbr' => strtoupper($new_game_name)
558 ));
559
560 if($new_game_id === false) {
561 Flash::error( __( 'Failed to create a game.', WP_CLANWARS_TEXTDOMAIN ) );
562 } else {
563 Flash::success( __( 'Created a game.', WP_CLANWARS_TEXTDOMAIN ) );
564
565 // take user to maps management
566 $redirect_url = admin_url('admin.php?page=wp-clanwars-games&act=maps&game_id=' . $new_game_id);
567 }
568 }
569 else {
570 Flash::error( __( 'Please fill in the game name.', WP_CLANWARS_TEXTDOMAIN ) );
571 }
572 }
573
574 wp_redirect( $redirect_url );
575 }
576
577 function on_template_redirect() {
578 wp_enqueue_script('wp-clanwars-public');
579 wp_enqueue_style('jquery-tipsy');
580 wp_enqueue_style('wp-clanwars-flags');
581 }
582
583 function on_wp_footer() {
584 if(get_option(WP_CLANWARS_DEFAULTCSS)) {
585 wp_enqueue_style('wp-clanwars-sitecss');
586 wp_enqueue_style('wp-clanwars-widgetcss');
587 }
588 }
589
590 function on_load_any() {
591 wp_enqueue_style('wp-clanwars-admin');
592 wp_enqueue_style('wp-clanwars-flags');
593 wp_enqueue_script('wp-clanwars-admin');
594
595 add_filter( 'admin_body_class', array($this, 'on_admin_body_class') );
596
597 // override page title during onboarding
598 if($this->should_onboard_user()) {
599 $this->set_page_title( __( 'Get started with WP-Clanwars', WP_CLANWARS_TEXTDOMAIN ) );
600 }
601 }
602
603 /**
604 * It's like 'admin_title' hook but less trashy.
605 * Use wisely and on time.
606 * @param string $page_title
607 */
608 function set_page_title( $page_title ) {
609 global $title;
610 $title = $page_title;
611 }
612
613 function on_admin_body_class($classes) {
614 return trim("$classes wp-clanwars");
615 }
616
617 function on_widgets_init()
618 {
619 register_widget('WP_TopMatch_Widget');
620 register_widget('WP_LiveMatch_Widget');
621 register_widget('WP_ClanWars_Widget');
622 return;
623 }
624
625 function html_notice_helper($message, $type = 'updated', $echo = true) {
626
627 $text = '<div class="' . $type . ' fade"><p>' . $message . '</p></div>';
628
629 if($echo) echo $text;
630
631 return $text;
632 }
633
634 function print_table_header($columns, $id = true)
635 {
636 foreach ( $columns as $column_key => $column_display_name ) {
637 $class = ' class="manage-column';
638
639 $class .= " column-$column_key";
640
641 if ( 'cb' == $column_key )
642 $class .= ' check-column';
643 elseif ( in_array($column_key, array('posts', 'comments', 'links')) )
644 $class .= ' num';
645
646 $class .= '"';
647 ?>
648 <th scope="col" <?php echo $id ? "id=\"$column_key\"" : ""; echo $class; ?>><?php echo $column_display_name; ?></th>
649 <?php }
650 }
651
652 /**
653 * Image uploading handling, used internally by plugin
654 *
655 * @param string $name $_FILES array key for a file which should be uploaded
656 *
657 * @return int|WP_Error attachment_id or WP_Error
658 */
659
660 function handle_upload($name)
661 {
662 $mimes = apply_filters('upload_mimes', array(
663 'jpg|jpeg|jpe' => 'image/jpeg',
664 'gif' => 'image/gif',
665 'png' => 'image/png')
666 );
667
668 $upload = isset($_FILES[$name]) ? $_FILES[$name] : false;
669 $upload_errors = array(
670 self::ErrorUploadMaxFileSize => __('The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>.', WP_CLANWARS_TEXTDOMAIN),
671 self::ErrorUploadHTMLMaxFileSize => __('The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form.', WP_CLANWARS_TEXTDOMAIN),
672 self::ErrorUploadPartially => __('The uploaded file was only partially uploaded.', WP_CLANWARS_TEXTDOMAIN),
673 self::ErrorUploadNoFile => __('No file was uploaded.', WP_CLANWARS_TEXTDOMAIN),
674 self::ErrorUploadMissingTemp => __('Missing a temporary folder.', WP_CLANWARS_TEXTDOMAIN),
675 self::ErrorUploadDiskWrite => __('Failed to write file to disk.', WP_CLANWARS_TEXTDOMAIN),
676 self::ErrorUploadStoppedByExt => __('File upload stopped by extension.', WP_CLANWARS_TEXTDOMAIN),
677 self::ErrorUploadFileTypeNotAllowed => __('File type does not meet security guidelines. Try another.', WP_CLANWARS_TEXTDOMAIN)
678 );
679
680 if( empty($upload) ) {
681 return new WP_Error( self::ErrorUploadNoFile, $upload_errors[self::ErrorUploadNoFile] );
682 }
683
684 if($upload['error'] > 0) {
685 $code = $upload['error'];
686
687 if(isset($upload_errors[$code])) {
688 return new WP_Error( $code, $upload_errors[$code] );
689 }
690
691 return new WP_Error( $code, sprintf(__( 'Unknown upload error: %d', WP_CLANWARS_TEXTDOMAIN ), $code ) );
692 }
693
694 extract( wp_check_filetype($upload['name'], $mimes) );
695
696 if(!$type || !$ext) {
697 return new WP_Error( self::ErrorUploadFileTypeNotAllowed, $upload_errors[self::ErrorUploadFileTypeNotAllowed] );
698 }
699
700 $options = array(
701 'test_type' => false,
702 'test_form' => false,
703 'upload_error_handler' => function ( $file, $message ) use ($upload_errors) {
704 $code = $file['error'];
705 return new WP_Error( $code, $upload_errors[$code] );
706 }
707 );
708
709 $file_data = wp_handle_upload($upload, $options);
710
711 if( empty($file_data) || !is_array($file_data) ) {
712 return false;
713 }
714
715 $file_data['type'] = $type;
716 if( isset($file_data['error']) ) {
717 $code = $file_data['error'];
718 return new WP_Error( $code, $upload_errors[$code] );
719 }
720
721 $fileinfo = pathinfo($file_data['file']);
722 $attach_title = basename($fileinfo['basename'], '.' . $fileinfo['extension']);
723 $attach_options = array('guid' => $file_data['url'],
724 'post_title' => $attach_title,
725 'post_content' => '',
726 'post_status' => 'publish',
727 'post_mime_type' => $file_data['type']
728 );
729 $attach_id = wp_insert_attachment($attach_options, $file_data['file']);
730
731 if( empty($attach_id) || !is_int($attach_id) ) {
732 return new WP_Error( self::ErrorDatabase, __( 'Failed to save attachment in database.', WP_CLANWARS_TEXTDOMAIN ) );
733 }
734
735 $metadata = wp_generate_attachment_metadata($attach_id, $file_data['file']);
736 if( !empty($metadata) ) {
737 wp_update_attachment_metadata($attach_id, $metadata);
738 }
739
740 return $attach_id;
741 }
742
743 function on_admin_post_deleteteams()
744 {
745 if( !\WP_Clanwars\ACL::user_can('manage_teams') ) {
746 wp_die( __('Cheatin’ uh?') );
747 }
748
749 check_admin_referer('wp-clanwars-deleteteams');
750
751 $redirect_url = $_REQUEST['_wp_http_referer'];
752
753 $args = Utils::extract_args( $_REQUEST, array(
754 'do_action' => '',
755 'do_action2' => '',
756 'delete' => array()
757 )
758 );
759 extract( $args );
760
761 if( $do_action == 'delete' || $do_action2 == 'delete' ) {
762 $result = \WP_Clanwars\Teams::delete_team( $delete );
763
764 if( is_wp_error( $result ) ) {
765 Flash::error( sprintf( __( 'Failed to delete a team. Error: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() ) );
766 }
767 else {
768 Flash::success( sprintf( _n( 'Deleted %d team.', 'Deleted %d teams.', $result, WP_CLANWARS_TEXTDOMAIN), $result ) );
769 }
770 }
771
772 wp_redirect( $redirect_url );
773 }
774
775 function on_admin_post_sethometeam()
776 {
777 if(!\WP_Clanwars\ACL::user_can('manage_teams')) {
778 wp_die( __('Cheatin’ uh?') );
779 }
780
781 check_admin_referer('wp-clanwars-sethometeam');
782
783 $referer = $_REQUEST['_wp_http_referer'];
784
785 extract(Utils::extract_args($_REQUEST, array('id' => array())));
786
787 $error = \WP_Clanwars\Teams::set_hometeam($id);
788
789 wp_redirect($referer);
790 }
791
792 function on_add_team()
793 {
794 return $this->team_editor(__('New Team', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-addteam', __('Add Team', WP_CLANWARS_TEXTDOMAIN));
795 }
796
797 function on_edit_team()
798 {
799 $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
800
801 return $this->team_editor(__('Edit Team', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-editteam', __('Update Team', WP_CLANWARS_TEXTDOMAIN), $id);
802 }
803
804 function team_editor($page_title, $page_action, $page_submit, $team_id = 0)
805 {
806 $defaults = array('title' => '', 'logo' => 0, 'country' => '', 'home_team' => 0, 'action' => '');
807 $team = new stdClass();
808
809 if($team_id > 0) {
810 $teams = \WP_Clanwars\Teams::get_team( array('id' => $team_id) );
811 if(!empty($teams)) {
812 $team = reset($teams);
813 }
814 }
815
816 extract(Utils::extract_args(stripslashes_deep($_POST), Utils::extract_args($team, $defaults)));
817
818 $country_select = Utils::html_country_select_helper('name=country&id=country&show_popular=1&class=select2&select=' . $country, false);
819
820 $view = new View( 'edit_team' );
821 $context = compact('page_title', 'page_action', 'page_submit',
822 'team_id', 'title', 'logo', 'country', 'home_team', 'action',
823 'country_select');
824 $context['attach'] = isset($team->logo) ? wp_get_attachment_image($team->logo, 'thumbnail') : '';
825 $view->render( $context );
826 }
827
828 function on_load_manage_teams()
829 {
830 $args = Utils::extract_args( $_GET, array(
831 'act' => '',
832 'id' => 0
833 ) );
834 extract($args);
835
836 // ACL checks on edit
837 if($act == 'edit') {
838 $team = \WP_Clanwars\Teams::get_team( compact('id') );
839
840 if( $id != 0 && empty( $team ) ) {
841 wp_die( __('Cheatin’ uh?') );
842 }
843 }
844 else {
845 // setup teams table only when displaying all teams
846 $this->teams_table = new \WP_Clanwars\TeamsTable();
847 $this->teams_table->prepare_items();
848 }
849
850 // check if POST
851 if( !Utils::is_post() ) {
852 return;
853 }
854
855 // add team?
856 if( $act == 'add' ) {
857 $this->handle_add_team();
858 }
859 else if( $act == 'edit' ) { // update team?
860 $this->handle_edit_team();
861 }
862 else {
863 $this->handle_teams_bulk_actions();
864 }
865 }
866
867 function handle_add_team() {
868 $redirect_url = admin_url( 'admin.php?page=wp-clanwars-teams' );
869 $defaults = array( 'title' => '', 'country' => '', 'delete_image' => false );
870 $data = Utils::extract_args( stripslashes_deep( $_POST ), $defaults );
871 extract($data);
872
873 unset($data['delete_image']);
874
875 if( empty( $title ) ) {
876 Flash::error( __( 'Team title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
877 return;
878 }
879
880 if( !empty($delete_image) ) {
881 $data['logo'] = 0;
882 }
883
884 $upload_id = $this->handle_upload( 'logo_file' );
885
886 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
887 Flash::error( $upload_id->get_error_message() );
888 return;
889 }
890 else if( is_int($upload_id) ) {
891 $data['logo'] = $upload_id;
892 }
893
894 if( \WP_Clanwars\Teams::add_team( $data ) ) {
895 Flash::success( __( 'Added a new team.', WP_CLANWARS_TEXTDOMAIN ) );
896 wp_redirect( $redirect_url );
897 exit();
898 }
899 else {
900 Flash::error( __( 'Failed to add a team.', WP_CLANWARS_TEXTDOMAIN ) );
901 }
902 }
903
904 function handle_edit_team() {
905 $id = isset($_GET['id']) ? $_GET['id'] : 0;
906 $redirect_url = admin_url( 'admin.php?page=wp-clanwars-teams' );
907 $defaults = array( 'title' => '', 'country' => '', 'delete_image' => false );
908 $data = Utils::extract_args( stripslashes_deep( $_POST ), $defaults );
909 extract($data);
910
911 unset($data['delete_image']);
912
913 if( empty( $title ) ) {
914 Flash::error( __( 'Team title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
915 return;
916 }
917
918 if( !empty($delete_image) ) {
919 $data['logo'] = 0;
920 }
921
922 $upload_id = $this->handle_upload( 'logo_file' );
923
924 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
925 Flash::error( $upload_id->get_error_message() );
926 return;
927 }
928 else if( is_int($upload_id) ) {
929 $data['logo'] = $upload_id;
930 }
931
932 if(\WP_Clanwars\Teams::update_team( $id, $data ) !== false) {
933 Flash::success( __( 'Updated a team.', WP_CLANWARS_TEXTDOMAIN ) );
934 $redirect_url = add_query_arg( compact( 'act', 'id' ), $redirect_url );
935 wp_redirect( $redirect_url );
936 exit();
937 }
938 else {
939 Flash::error( __('Failed to update a team.', WP_CLANWARS_TEXTDOMAIN) );
940 }
941 }
942
943 function handle_teams_bulk_actions() {
944 check_admin_referer( 'bulk-teams' );
945
946 if( !\WP_Clanwars\ACL::user_can('manage_teams') ) {
947 wp_die( __('Cheatin’ uh?') );
948 }
949
950 $table_action = Utils::get_list_table_action();
951
952 if($table_action === 'delete' && isset($_POST['id'])) {
953 $result = \WP_Clanwars\Teams::delete_team( $_POST['id'] );
954
955 if( is_wp_error( $result ) ) {
956 Flash::error( sprintf( __( 'Failed to delete a team. Error: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() ) );
957 }
958 else {
959 Flash::success( sprintf( _n( 'Deleted %d team.', 'Deleted %d teams.', $result, WP_CLANWARS_TEXTDOMAIN), $result ) );
960 }
961 }
962
963 wp_redirect( admin_url( 'admin.php?page=wp-clanwars-teams' ) );
964 die();
965 }
966
967 function on_manage_teams()
968 {
969 $act = isset($_GET['act']) ? $_GET['act'] : '';
970 $current_page = isset($_GET['paged']) ? $_GET['paged'] : 1;
971 $limit = 10;
972
973 switch($act) {
974 case 'add':
975 return $this->on_add_team();
976 break;
977 case 'edit':
978 return $this->on_edit_team();
979 break;
980 }
981
982 $teams = \WP_Clanwars\Teams::get_team('id=all&order=asc&orderby=title&limit=' . $limit . '&offset=' . ($limit * ($current_page-1)));
983 $pagination = $teams->get_pagination();
984
985 $page_links = paginate_links( array(
986 'base' => add_query_arg('paged', '%#%'),
987 'format' => '',
988 'prev_text' => __('«'),
989 'next_text' => __('»'),
990 'total' => $pagination->get_num_pages(),
991 'current' => $current_page
992 ));
993
994 $page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s–%s of %s' ) . '</span>%s',
995 number_format_i18n( (($current_page - 1) * $limit) + 1 ),
996 number_format_i18n( min( $current_page * $limit, $pagination->get_num_rows() ) ),
997 '<span class="total-type-count">' . number_format_i18n( $pagination->get_num_rows() ) . '</span>',
998 $page_links
999 );
1000
1001 $table_columns = array(
1002 'cb' => '<input type="checkbox" />',
1003 'logo' => __('Logo', WP_CLANWARS_TEXTDOMAIN),
1004 'title' => __('Title', WP_CLANWARS_TEXTDOMAIN),
1005 'country' => __('Country', WP_CLANWARS_TEXTDOMAIN)
1006 );
1007
1008 foreach($teams as $team) {
1009 $team->attach = wp_get_attachment_image($team->logo, 'thumbnail');
1010 }
1011
1012 $view = new View( 'team_table' );
1013
1014 $wp_list_table = $this->teams_table;
1015 $context = compact('teams', 'page_links_text', 'table_columns', 'wp_list_table');
1016
1017 $view->render( $context );
1018 }
1019
1020 /*
1021 * Games Managment
1022 */
1023
1024 function on_admin_post_gamesop()
1025 {
1026 if(!\WP_Clanwars\ACL::user_can('manage_games')) {
1027 wp_die( __('Cheatin’ uh?') );
1028 }
1029
1030 check_admin_referer('wp-clanwars-gamesop');
1031
1032 $referer = remove_query_arg(array('add', 'update', 'export'), $_REQUEST['_wp_http_referer']);
1033
1034 $args = Utils::extract_args( $_REQUEST, array(
1035 'do_action' => '',
1036 'do_action2' => '',
1037 'items' => array()
1038 )
1039 );
1040 extract($args);
1041
1042 $action = !empty($do_action) ? $do_action : (!empty($do_action2) ? $do_action2 : '');
1043
1044 if(!empty($items)) {
1045
1046 switch($action) {
1047 case 'delete':
1048 $result = \WP_Clanwars\Games::delete_game($items);
1049
1050 if( is_wp_error( $result ) ) {
1051 Flash::error( sprintf( __( 'Failed to delete games. Error: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() ) );
1052 }
1053 else {
1054 Flash::success( sprintf( _n( 'Deleted %d game.', 'Deleted %d games.', $result, WP_CLANWARS_TEXTDOMAIN ), $result ) );
1055 }
1056 break;
1057 case 'export':
1058 $game_id = current($items);
1059 $zip_archive = $this->export_game($game_id);
1060
1061 if(is_wp_error($zip_archive)) {
1062 var_dump($zip_archive);
1063 die();
1064 }
1065
1066 $zip_url = trailingslashit(site_url()) . str_replace(ABSPATH, '', $zip_archive);
1067
1068 wp_redirect($zip_url);
1069 die();
1070 break;
1071 }
1072
1073 }
1074
1075 wp_redirect($referer);
1076 }
1077
1078 function export_game($id)
1079 {
1080 global $wp_filesystem;
1081 WP_Filesystem();
1082
1083 $id = (int)$id;
1084 $games = \WP_Clanwars\Games::get_game(array('id' => $id));
1085 $game = current($games);
1086
1087 if(!$game) {
1088 return new WP_Error('plugin-error', 'Unable to find game.');
1089 }
1090
1091 $upload_dir = wp_upload_dir();
1092 $export_dir = trailingslashit($upload_dir['basedir']) . WP_CLANWARS_EXPORTDIR;
1093
1094 $game_data = Utils::extract_args($game, array(
1095 'title' => '', 'abbr' => '',
1096 'icon' => '', 'maplist' => array()
1097 ));
1098 $zip_files = array();
1099
1100 $maplist = \WP_Clanwars\Maps::get_map(array('game_id' => $game->id));
1101
1102 if($game->icon != 0) {
1103 $attach = get_attached_file($game->icon);
1104 $mimetype = get_post_mime_type($game->icon);
1105
1106 if(!empty($attach)) {
1107 $game_data['icon'] = array(
1108 'filename' => trim(str_replace($upload_dir['basedir'], '', $attach), '/\\'),
1109 'mimetype' => $mimetype
1110 );
1111 $zip_files[] = $attach;
1112 }
1113 }
1114
1115 foreach($maplist as $map) {
1116 $map_data = array('title' => $map->title, 'screenshot' => '');
1117
1118 if($map->screenshot != 0) {
1119 $attach = get_attached_file($map->screenshot);
1120 $mimetype = get_post_mime_type($map->screenshot);
1121
1122 if(!empty($attach)) {
1123 $map_data['screenshot'] = array(
1124 'filename' => trim(str_replace($upload_dir['basedir'], '', $attach), '/\\'),
1125 'mimetype' => $mimetype
1126 );
1127 $zip_files[] = $attach;
1128 }
1129 }
1130
1131 $game_data['maplist'][] = $map_data;
1132 }
1133
1134 // define a folder for temporary index.json that we need to add into zip archive
1135 $index_file_dir = sprintf('%s/zip-' . md5(microtime(true)), $export_dir);
1136
1137 // create folders for zip file
1138 $wp_filesystem->mkdir($export_dir);
1139
1140 // create zip file
1141 $zip_path = sprintf('%s/gamepack-%s.zip', $export_dir, (strlen($game->abbr) ? $game->abbr : $game->id));
1142
1143 // encode game data as JSON
1144 $index_json = json_encode($game_data);
1145
1146 // clean up existing file first
1147 $wp_filesystem->delete($zip_path);
1148
1149 // Zip can use a lot of memory, but not this much hopefully
1150 /** This filter is documented in wp-admin/admin.php */
1151 @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
1152
1153 // use pecl ZipArchive if available
1154 if(class_exists('ZipArchive')) {
1155 $zip_acrhive = new ZipArchive();
1156
1157 // open archive
1158 if($zip_acrhive->open($zip_path, ZIPARCHIVE::CREATE) !== true) {
1159 return new WP_Error('plugin-error', 'Failed to open ZIP file. Reason: ' . $zip_acrhive->getStatusString());
1160 }
1161
1162 // zip index.json first
1163 $zip_acrhive->addFromString(WP_CLANWARS_ZIPINDEX, $index_json);
1164
1165 // zip all images
1166 foreach($zip_files as $file) {
1167 $localname = trim(str_replace($upload_dir['basedir'], '', $file), '/\\');
1168 $zip_acrhive->addFile($file, $localname);
1169 }
1170
1171 // close archive
1172 $zip_acrhive->close();
1173 } else {
1174 // fallback to PclZip
1175 $zip_acrhive = new PclZip($zip_path);
1176
1177 // PclZip does not support adding files from memory
1178 $index_file_json = trailingslashit($index_file_dir) . WP_CLANWARS_ZIPINDEX;
1179 $wp_filesystem->mkdir($index_file_dir);
1180 $wp_filesystem->put_contents($index_file_json, $index_json);
1181
1182 // zip index.json first
1183 $zip_status = $zip_acrhive->create($index_file_json, PCLZIP_OPT_REMOVE_PATH, $index_file_dir);
1184
1185 // zip all images
1186 $zip_status = $zip_acrhive->add($zip_files, PCLZIP_OPT_REMOVE_PATH, $upload_dir['basedir']);
1187
1188 // remove temp folder
1189 $wp_filesystem->rmdir($index_file_dir, true);
1190
1191 if($zip_status === 0) {
1192 return new WP_Error('zip-error', 'Failed to ZIP files. Reason: ' . $zip_acrhive->errorInfo(true));
1193 }
1194 }
1195
1196 return $zip_path;
1197 }
1198
1199 function _import_image($p, $zip_dir) {
1200 global $wp_filesystem;
1201
1202 if(empty($p)) return 0;
1203
1204 $upload_dir = wp_upload_dir();
1205 $pathinfo = pathinfo($p['filename']);
1206 $file_name = $pathinfo['basename'];
1207
1208 $zip_file_path = trailingslashit($zip_dir) . $p['filename'];
1209 $save_file_path = trailingslashit($upload_dir['path']) . wp_unique_filename($upload_dir['path'], $file_name);
1210 $file_url = trailingslashit(site_url()) . str_replace(ABSPATH, '', $save_file_path);
1211
1212 if(!$wp_filesystem->move( $zip_file_path, $save_file_path )) {
1213 return 0;
1214 }
1215
1216 $title = basename($file_name, $pathinfo['extension']);
1217 $attach = array('guid' => $file_url,
1218 'post_title' => sanitize_title($title),
1219 'post_status' => 'publish',
1220 'post_content' => '',
1221 'post_mime_type' => $p['mimetype']);
1222 $attach_id = wp_insert_attachment($attach, $save_file_path);
1223
1224 if(!empty($attach_id)) {
1225 $metadata = wp_generate_attachment_metadata($attach_id, $save_file_path);
1226
1227 if(!empty($metadata))
1228 wp_update_attachment_metadata($attach_id, $metadata);
1229
1230 return $attach_id;
1231 }
1232 return 0;
1233 }
1234
1235 function import_remote_game($zip_url) {
1236 $filename = tempnam( get_temp_dir(), 'wp-clanwars-' );
1237 $response = wp_remote_get( $zip_url, array(
1238 'timeout' => 15,
1239 'stream' => true,
1240 'filename' => $filename
1241 ) );
1242
1243 if( is_wp_error( $response ) ) {
1244 return $response;
1245 }
1246
1247 if( wp_remote_retrieve_response_code($response) !== 200 ) {
1248 return new WP_Error( 'import-error', __('File is not found on server.', WP_CLANWARS_TEXTDOMAIN) );
1249 }
1250
1251 $result = $this->import_game( $filename );
1252
1253 @unlink( $filename );
1254
1255 return $result;
1256 }
1257
1258 function import_game($zip_file) {
1259 global $wp_filesystem;
1260 WP_Filesystem();
1261
1262 $upload_dir = wp_upload_dir();
1263 $export_dir = trailingslashit($upload_dir['basedir']) . WP_CLANWARS_EXPORTDIR;
1264 $unzip_dir = $export_dir . '/unzip-' . md5(microtime(true));
1265
1266 $clean_unzip_dir = function () use ($wp_filesystem, $unzip_dir) {
1267 $wp_filesystem->rmdir($unzip_dir, true);
1268 };
1269
1270 $wp_filesystem->mkdir($export_dir);
1271 $wp_filesystem->mkdir($unzip_dir);
1272
1273 // make sure wp-content/uploads/wp-clanwars is not availabe from outside
1274 $stub_files = array(
1275 '.htaccess' => 'deny from all',
1276 'index.php' => "<?php\n// Silence is golden.\n"
1277 );
1278 foreach($stub_files as $file => $content) {
1279 $path = $unzip_dir . '/' . $file;
1280 if( !file_exists($path) ) {
1281 @file_put_contents($path, $content);
1282 }
1283 }
1284
1285 $result = unzip_file($zip_file, $unzip_dir);
1286
1287 if(is_wp_error($result)) {
1288 $clean_unzip_dir();
1289
1290 $message = sprintf( __( 'Unable to unzip file: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() );
1291 return new WP_Error('plugin-error', $message );
1292 }
1293
1294 $index_file = trailingslashit($unzip_dir) . WP_CLANWARS_ZIPINDEX;
1295 if(!file_exists($index_file)) {
1296 $clean_unzip_dir();
1297 return new WP_Error('plugin-error', __( 'Index file is not found in ZIP.', WP_CLANWARS_TEXTDOMAIN ) );
1298 }
1299
1300 $game_data = @json_decode( $wp_filesystem->get_contents($index_file) );
1301
1302 if(!is_object($game_data)) {
1303 $clean_unzip_dir();
1304 return new WP_Error('plugin-error', __( 'Corrupted or missing contents from ZIP file.', WP_CLANWARS_TEXTDOMAIN ) );
1305 }
1306
1307 $game_data = Utils::extract_args($game_data, array(
1308 'title' => '', 'abbr' => '',
1309 'icon' => '', 'maplist' => array(),
1310 'store' => array()
1311 ));
1312
1313 if(empty($game_data['title'])) {
1314 $clean_unzip_dir();
1315 return new WP_Error('plugin-error', __( 'Corrupted or missing contents from ZIP file.', WP_CLANWARS_TEXTDOMAIN ) );
1316 }
1317
1318 $p = $game_data;
1319 $p['icon'] = $this->_import_image((array)$p['icon'], $unzip_dir);
1320
1321 $maplist = $p['maplist'];
1322 unset($p['maplist']);
1323
1324 $store_info = $p['store'];
1325 unset($p['store']);
1326
1327 if(is_object($store_info) && isset($store_info->_id)) {
1328 $p['store_id'] = (string) $store_info->_id;
1329 }
1330
1331 $game_id = \WP_Clanwars\Games::add_game($p);
1332
1333 if(empty($game_id)) {
1334 $clean_unzip_dir();
1335 return new WP_Error('plugin-error', __( 'Failed to add game.', WP_CLANWARS_TEXTDOMAIN ) );
1336 }
1337
1338 foreach($maplist as $map) {
1339 $p = (array)$map;
1340 $p['screenshot'] = $this->_import_image((array)$p['screenshot'], $unzip_dir);
1341 $p['game_id'] = $game_id;
1342
1343 if(!empty($p['title'])) {
1344 \WP_Clanwars\Maps::add_map($p);
1345 }
1346 }
1347
1348 $clean_unzip_dir();
1349
1350 return $game_id;
1351 }
1352
1353 function on_add_game()
1354 {
1355 return $this->game_editor(__('New Game', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-addgame', __('Add Game', WP_CLANWARS_TEXTDOMAIN));
1356 }
1357
1358 function on_edit_game()
1359 {
1360 $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
1361
1362 return $this->game_editor(__('Edit Game', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-editgame', __('Update Game', WP_CLANWARS_TEXTDOMAIN), $id);
1363 }
1364
1365 function on_load_manage_games()
1366 {
1367 $act = isset($_GET['act']) ? $_GET['act'] : '';
1368 $id = isset($_GET['id']) ? $_GET['id'] : 0;
1369 $game_id = isset($_GET['game_id']) ? $_GET['game_id'] : 0;
1370 $die = false;
1371
1372 // Check game or map is really exists
1373 if( $act === 'add' && !\WP_Clanwars\ACL::user_can('manage_game', 'all') ) {
1374 $die = true;
1375 }
1376 else if( $act === 'edit' || $act === 'maps' || $act === 'addmap' ) {
1377
1378 $g = \WP_Clanwars\Games::get_game(array(
1379 'id' => ($act === 'maps' || $act === 'addmap' ? $game_id : $id)
1380 ));
1381
1382 $die = empty($g) || !\WP_Clanwars\ACL::user_can('manage_game', $g[0]->id);
1383
1384 }
1385 else if( $act === 'editmap' ) {
1386 $m = \WP_Clanwars\Maps::get_map( compact('id') );
1387 $die = empty($m) || !\WP_Clanwars\ACL::user_can('manage_game', $m[0]->game_id);
1388 }
1389 else {
1390 // setup games table only when displaying all games
1391 $this->games_table = new \WP_Clanwars\GamesTable();
1392 $this->games_table->prepare_items();
1393 }
1394
1395 if($die) {
1396 wp_die( __('Cheatin’ uh?') );
1397 }
1398
1399 if( $act === 'maps' ) {
1400 // setup maps table only when displaying all maps
1401 $this->maps_table = new \WP_Clanwars\MapsTable();
1402 $this->maps_table->prepare_items();
1403 }
1404
1405 if( !Utils::is_post() ) {
1406 return;
1407 }
1408
1409 if( $act === 'add' ) {
1410 $this->handle_add_game();
1411 }
1412 else if( $act === 'edit' ) {
1413 $this->handle_edit_game();
1414 }
1415 else if($act === 'addmap') {
1416 $this->handle_add_map();
1417 }
1418 else if( $act === 'editmap' ) {
1419 $this->handle_edit_map();
1420 }
1421 else if( $act === 'maps' ) {
1422 $this->handle_maps_bulk_actions();
1423 }
1424 }
1425
1426 function handle_add_game() {
1427 $defaults = array( 'title' => '', 'abbr' => '' );
1428 $data = Utils::extract_args( stripslashes_deep( $_POST ), $defaults );
1429 extract( $data );
1430
1431 if( empty($title) ) {
1432 Flash::error( __( 'Game title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
1433 return;
1434 }
1435
1436 $upload_id = $this->handle_upload( 'icon_file' );
1437
1438 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
1439 Flash::error( $upload_id->get_error_message() );
1440 return;
1441 }
1442 else if( is_int($upload_id) ) {
1443 $data['icon'] = $upload_id;
1444 }
1445
1446 if( \WP_Clanwars\Games::add_game( $data ) ) {
1447 Flash::success( __( 'Added a new game.', WP_CLANWARS_TEXTDOMAIN ) );
1448 wp_redirect( admin_url( 'admin.php?page=wp-clanwars-games' ) );
1449 exit();
1450 }
1451 else {
1452 Flash::error( __( 'Failed to add a game.', WP_CLANWARS_TEXTDOMAIN ) );
1453 }
1454 }
1455
1456 function handle_edit_game() {
1457 $id = isset($_GET['id']) ? $_GET['id'] : 0;
1458 $defaults = array('title' => '', 'abbr' => '', 'delete_image' => false);
1459 $data = Utils::extract_args(stripslashes_deep($_POST), $defaults);
1460 extract($data);
1461
1462 $update_data = compact('title', 'abbr');
1463
1464 if( empty($title) ) {
1465 Flash::error( __( 'Game title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
1466 return;
1467 }
1468
1469 if( !empty($delete_image) ) {
1470 $update_data['icon'] = 0;
1471 }
1472
1473 $upload_id = $this->handle_upload( 'icon_file' );
1474
1475 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
1476 Flash::error( $upload_id->get_error_message() );
1477 return;
1478 }
1479 else if( is_int($upload_id) ) {
1480 $update_data['icon'] = $upload_id;
1481 }
1482
1483 if( \WP_Clanwars\Games::update_game($id, $update_data) !== false ) {
1484 Flash::success( __( 'Updated a game.', WP_CLANWARS_TEXTDOMAIN ) );
1485 wp_redirect( admin_url( sprintf('admin.php?page=wp-clanwars-games&act=edit&id=%d', $id) ) );
1486 exit();
1487 }
1488 else {
1489 Flash::error( __( 'Failed to update a game.', WP_CLANWARS_TEXTDOMAIN ) );
1490 }
1491 }
1492
1493 function handle_add_map() {
1494 $defaults = array('title' => '', 'game_id' => 0, 'id' => 0);
1495 $data = Utils::extract_args(stripslashes_deep($_POST), $defaults);
1496 extract($data);
1497
1498 if( empty($title) ) {
1499 Flash::error( __( 'Map title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
1500 return;
1501 }
1502
1503 $upload_id = $this->handle_upload( 'screenshot_file' );
1504
1505 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
1506 Flash::error( $upload_id->get_error_message() );
1507 return;
1508 }
1509 else if( is_int($upload_id) ) {
1510 $data['screenshot'] = $upload_id;
1511 }
1512
1513 if( \WP_Clanwars\Maps::add_map($data) !== false ) {
1514 Flash::success( __( 'Added a map.', WP_CLANWARS_TEXTDOMAIN ) );
1515 wp_redirect( admin_url( sprintf( 'admin.php?page=wp-clanwars-games&act=maps&game_id=%d', $game_id ) ) );
1516 exit();
1517 }
1518 else {
1519 Flash::error( __( 'Failed to add a map.', WP_CLANWARS_TEXTDOMAIN ) );
1520 }
1521 }
1522
1523 function handle_edit_map() {
1524 $defaults = array('title' => '', 'game_id' => 0, 'id' => 0, 'delete_image' => false);
1525 $data = Utils::extract_args(stripslashes_deep($_POST), $defaults);
1526 extract($data);
1527
1528 $update_data = compact('title');
1529
1530 if( empty($title) ) {
1531 Flash::error( __( 'Map title is a required field.', WP_CLANWARS_TEXTDOMAIN ) );
1532 return;
1533 }
1534
1535 if( !empty($delete_image) ) {
1536 $update_data['screenshot'] = 0;
1537 }
1538
1539 $upload_id = $this->handle_upload( 'screenshot_file' );
1540
1541 if( is_wp_error($upload_id) && $upload_id->get_error_code() !== self::ErrorUploadNoFile ) {
1542 Flash::error( $upload_id->get_error_message() );
1543 return;
1544 }
1545 else if( is_int($upload_id) ) {
1546 $update_data['screenshot'] = $upload_id;
1547 }
1548
1549 if( \WP_Clanwars\Maps::update_map($id, $update_data) !== false ) {
1550 Flash::success( __( 'Updated a map.', WP_CLANWARS_TEXTDOMAIN ) );
1551 wp_redirect( admin_url( sprintf( 'admin.php?page=wp-clanwars-games&act=editmap&id=%d', $id ) ) );
1552 exit();
1553 } else {
1554 Flash::error( __( 'Failed to update a map.', WP_CLANWARS_TEXTDOMAIN ) );
1555 }
1556 }
1557
1558 function handle_maps_bulk_actions() {
1559 check_admin_referer( 'bulk-maps' );
1560
1561 if(!\WP_Clanwars\ACL::user_can('manage_games')) {
1562 wp_die( __('Cheatin’ uh?') );
1563 }
1564
1565 $table_action = Utils::get_list_table_action();
1566
1567 if($table_action === 'delete' && isset($_POST['id'])) {
1568 $result = \WP_Clanwars\Maps::delete_map( $_POST['id'] );
1569
1570 if( is_wp_error( $result ) ) {
1571 Flash::error( sprintf( __( 'Failed to delete maps. Error: %s' ), $result->get_error_message() ) );
1572 }
1573 else {
1574 Flash::success( sprintf( _n( 'Deleted %d map.', 'Deleted %d maps.', $result, WP_CLANWARS_TEXTDOMAIN ), $result ) );
1575 }
1576 }
1577
1578 wp_redirect( $_REQUEST['_wp_http_referer'] );
1579 exit();
1580 }
1581
1582 function on_manage_games()
1583 {
1584 $act = isset($_GET['act']) ? $_GET['act'] : '';
1585 $current_page = isset($_GET['paged']) ? $_GET['paged'] : 1;
1586 $filter_games = \WP_Clanwars\ACL::user_can('which_games');
1587 $limit = 10;
1588
1589 switch($act) {
1590 case 'add':
1591 return $this->on_add_game();
1592 break;
1593 case 'edit':
1594 return $this->on_edit_game();
1595 break;
1596 case 'maps':
1597 return $this->on_edit_maps();
1598 break;
1599 case 'addmap':
1600 return $this->on_add_map();
1601 break;
1602 case 'editmap':
1603 return $this->on_edit_map();
1604 break;
1605 }
1606
1607 $show_add_button = \WP_Clanwars\ACL::user_can('manage_game', 'all');
1608
1609 $view = new View( 'game_table' );
1610 $wp_list_table = $this->games_table;
1611
1612 $context = compact( 'show_add_button', 'games', 'table_columns', 'page_links_text', 'wp_list_table' );
1613
1614 $view->render( $context );
1615 }
1616
1617 function game_editor($page_title, $page_action, $page_submit, $game_id = 0)
1618 {
1619 $defaults = array('title' => '', 'icon' => 0, 'abbr' => '', 'action' => '');
1620 $game = new stdClass();
1621
1622 if($game_id > 0) {
1623 $result = \WP_Clanwars\Games::get_game(array('id' => $game_id));
1624 if(!empty($result)) {
1625 $game = reset($result);
1626 }
1627 }
1628
1629 $view = new View( 'edit_game' );
1630
1631 $context = Utils::extract_args(stripslashes_deep($_POST), Utils::extract_args($game, $defaults));
1632 $context['attach'] = isset($game->icon) ? wp_get_attachment_image($game->icon, 'thumbnail') : '';
1633 $context += compact( 'page_title', 'page_action', 'page_submit', 'game_id' );
1634
1635 $view->render( $context );
1636 }
1637
1638 /*
1639 * Maps managment
1640 */
1641
1642 function on_admin_post_deletemaps()
1643 {
1644 if(!\WP_Clanwars\ACL::user_can('manage_games')) {
1645 wp_die( __('Cheatin’ uh?') );
1646 }
1647
1648 check_admin_referer('wp-clanwars-deletemaps');
1649
1650 $redirect_url = $_REQUEST['_wp_http_referer'];
1651
1652 $args = Utils::extract_args( $_REQUEST, array(
1653 'do_action' => '',
1654 'do_action2' => '',
1655 'delete' => array()
1656 ) );
1657 extract( $args );
1658
1659 if($do_action == 'delete' || $do_action2 == 'delete') {;
1660 $result = \WP_Clanwars\Maps::delete_map( $delete );
1661
1662 if( is_wp_error( $result ) ) {
1663 Flash::error( sprintf( __( 'Failed to delete maps. Error: %s' ), $result->get_error_message() ) );
1664 }
1665 else {
1666 Flash::success( sprintf( _n( 'Deleted %d map.', 'Deleted %d maps.', $result, WP_CLANWARS_TEXTDOMAIN ), $result ) );
1667 }
1668 }
1669
1670 wp_redirect( $redirect_url );
1671 }
1672
1673 function on_edit_maps()
1674 {
1675 $game_id = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
1676 $game = current(\WP_Clanwars\Games::get_game(array('id' => $game_id)));
1677 $game_title = $game->title;
1678
1679 $view = new View( 'map_table' );
1680
1681 $wp_list_table = $this->maps_table;
1682
1683 $context = compact( 'game_title', 'game_id', 'wp_list_table' );
1684
1685 $view->render( $context );
1686 }
1687
1688 function on_add_map()
1689 {
1690 $game_id = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
1691
1692 $this->map_editor(__('Add Map', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-addmap', __('Add Map', WP_CLANWARS_TEXTDOMAIN), $game_id);
1693 }
1694
1695 function on_edit_map()
1696 {
1697 $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
1698
1699 $this->map_editor(__('Edit Map', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-editmap', __('Update Map', WP_CLANWARS_TEXTDOMAIN), 0, $id);
1700 }
1701
1702 function map_editor($page_title, $page_action, $page_submit, $game_id, $id = 0)
1703 {
1704 $defaults = array('title' => '', 'screenshot' => 0, 'abbr' => '', 'action' => '');
1705 $data = array();
1706
1707 if($id > 0) {
1708 $t = \WP_Clanwars\Maps::get_map(array('id' => $id, 'game_id' => $game_id));
1709
1710 if(!empty($t)){
1711 $data = (array)$t[0];
1712 $game_id = $data['game_id'];
1713 }
1714 }
1715
1716 extract(Utils::extract_args(stripslashes_deep($_POST), Utils::extract_args($data, $defaults)));
1717
1718 $attach = wp_get_attachment_image($screenshot, 'thumbnail');
1719
1720 $view = new View( 'edit_map' );
1721
1722 $context = compact('page_title', 'page_action', 'page_submit', 'game_id', 'id',
1723 'attach', 'title', 'screenshot', 'abbr', 'action');
1724
1725 $view->render( $context );
1726 }
1727
1728 /*
1729 * Matches managment
1730 */
1731
1732 function on_admin_post_delete_match() {
1733 if( ! \WP_Clanwars\ACL::user_can('manage_matches') ) {
1734 wp_die( __('Cheatin’ uh?') );
1735 }
1736
1737 check_admin_referer('wp-clanwars-delete-match');
1738
1739 if( isset($_REQUEST['id'] ) ) {
1740 $id = (int) $_REQUEST['id'];
1741 $result = \WP_Clanwars\Matches::delete_match( $id );
1742
1743 if( is_wp_error( $result ) ) {
1744 Flash::error( sprintf( __( 'Failed to delete matches. Error: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() ) );
1745 }
1746 else {
1747 Flash::success( sprintf( _n( 'Deleted %d match.', 'Deleted %d matches.', $result, WP_CLANWARS_TEXTDOMAIN ), $result ) );
1748 }
1749 }
1750
1751 wp_redirect( $_REQUEST['_wp_http_referer'] );
1752 }
1753
1754 function on_add_match()
1755 {
1756 return $this->match_editor(__('Add Match', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-matches', __('Add Match', WP_CLANWARS_TEXTDOMAIN));
1757 }
1758
1759 function on_edit_match()
1760 {
1761 $id = isset($_GET['id']) ? $_GET['id'] : 0;
1762
1763 return $this->match_editor(__('Edit Match', WP_CLANWARS_TEXTDOMAIN), 'wp-clanwars-matches', __('Update Match', WP_CLANWARS_TEXTDOMAIN), $id);
1764 }
1765
1766 function on_ajax_get_maps()
1767 {
1768 if(!\WP_Clanwars\ACL::user_can('manage_games') && !\WP_Clanwars\ACL::user_can('manage_matches')) {
1769 wp_die( __('Cheatin’ uh?') );
1770 }
1771
1772 $game_id = isset($_POST['game_id']) ? (int)$_POST['game_id'] : 0;
1773
1774 if($game_id > 0) {
1775 $maps = \WP_Clanwars\Maps::get_map(array('game_id' => $game_id, 'order' => 'asc', 'orderby' => 'title'));
1776
1777 for($i = 0; $i < sizeof($maps); $i++) {
1778 $url = wp_get_attachment_thumb_url($maps[$i]->screenshot);
1779
1780 $maps[$i]->screenshot_url = !empty($url) ? $url : '';
1781 }
1782
1783 echo json_encode($maps); die();
1784 }
1785 }
1786
1787 function match_editor($page_title, $page_action, $page_submit, $id = 0)
1788 {
1789 $match = new stdClass();
1790 $current_time = Utils::current_time_fixed('timestamp', 0);
1791
1792 $defaults = array(
1793 'game_id' => 0,
1794 'title' => '',
1795 'post_id' => 0,
1796 'team1' => 0,
1797 'team2' => 0,
1798 'scores' => array(),
1799 'match_status' => 0,
1800 'action' => '',
1801 'description' => '',
1802 'external_url' => '',
1803 'date' => array('mm' => date('m', $current_time),
1804 'yy' => date('Y', $current_time),
1805 'jj' => date('j', $current_time),
1806 'hh' => date('H', $current_time),
1807 'mn' => date('i', $current_time)),
1808 'gallery' => array()
1809 );
1810
1811 if($id > 0) {
1812 $matchResult = \WP_Clanwars\Matches::get_match( array('id' => $id) );
1813
1814 if( $matchResult->count() > 0 ) {
1815 $match = $matchResult[0];
1816 $match->date = mysql2date('U', $match->date);
1817 $match->scores = array();
1818
1819 $rounds = \WP_Clanwars\Rounds::get_rounds($match->id);
1820
1821 foreach($rounds as $round) {
1822 $match->scores[$round->group_n]['map_id'] = $round->map_id;
1823 $match->scores[$round->group_n]['round_id'][] = $round->id;
1824 $match->scores[$round->group_n]['team1'][] = $round->tickets1;
1825 $match->scores[$round->group_n]['team2'][] = $round->tickets2;
1826 }
1827
1828 // get gallery
1829 $gallery = get_post_gallery($match->post_id, false);
1830 if(!is_array($gallery)) {
1831 $gallery = array();
1832 }
1833 }
1834 }
1835
1836 $num_comments = isset($match->post_id) ? get_comments_number($match->post_id) : 0;
1837 $match_statuses = $this->match_status;
1838
1839 $games = \WP_Clanwars\Games::get_game(array('id' => \WP_Clanwars\ACL::user_can('which_games'), 'orderby' => 'title', 'order' => 'asc'));
1840 $teams = \WP_Clanwars\Teams::get_team('id=all&orderby=title&order=asc');
1841
1842 $merged_data = Utils::extract_args(stripslashes_deep($_POST), Utils::extract_args($match, $defaults));
1843 $merged_data['date'] = Utils::date_array2time_helper($merged_data['date']);
1844
1845 $view = new View( 'edit_match' );
1846
1847 $view->add_helper('html_date_helper', array('\WP_Clanwars\Utils', 'html_date_helper'));
1848 $view->add_helper('html_country_select_helper', array('\WP_Clanwars\Utils', 'html_country_select_helper'));
1849
1850 $context = compact('page_title', 'page_action', 'page_submit', 'num_comments', 'match_statuses', 'id', 'games', 'teams', 'gallery');
1851 $context += $merged_data;
1852
1853 $view->render( $context );
1854 }
1855
1856 function quick_pick_team($title, $country) {
1857 $team = \WP_Clanwars\Teams::get_team(array('title' => $title, 'limit' => 1));
1858 $team_id = 0;
1859 if(empty($team)) {
1860 $new_team_id = \WP_Clanwars\Teams::add_team(array('title' => $title, 'country' => $country));
1861 if($new_team_id !== false)
1862 $team_id = $new_team_id;
1863 } else {
1864 $team_id = $team[0]->id;
1865 }
1866
1867 return $team_id;
1868 }
1869
1870 function on_load_manage_matches()
1871 {
1872 $id = isset($_GET['id']) ? $_GET['id'] : 0;
1873 $act = isset($_GET['act']) ? $_GET['act'] : '';
1874 $media_options = array();
1875
1876 if($act === 'add') {
1877 $this->set_page_title( __( 'Add match', WP_CLANWARS_TEXTDOMAIN ) );
1878 }
1879 else if($act === 'edit') {
1880 $this->set_page_title( __( 'Edit match', WP_CLANWARS_TEXTDOMAIN ) );
1881
1882 // Check if match really exists
1883 $matchResult = \WP_Clanwars\Matches::get_match(array( 'id' => $id ));
1884
1885 if( !$matchResult->count() ) {
1886 wp_die( __('Cheatin’ uh?') );
1887 }
1888
1889 if( !\WP_Clanwars\ACL::user_can('manage_game', $matchResult[0]->game_id) ) {
1890 wp_die( __('Cheatin’ uh?') );
1891 }
1892
1893 }
1894 else {
1895 // setup match table only when displaying all matches
1896 $this->match_table = new \WP_Clanwars\MatchTable();
1897 $this->match_table->prepare_items();
1898 }
1899
1900 wp_enqueue_media($media_options);
1901 wp_enqueue_script('wp-clanwars-matches');
1902 wp_enqueue_script('wp-clanwars-gallery');
1903 wp_localize_script('wp-clanwars-matches',
1904 'wpCWL10n',
1905 array(
1906 'plugin_url' => WP_CLANWARS_URL,
1907 'addRound' => __('Add Round', WP_CLANWARS_TEXTDOMAIN),
1908 'excludeMap' => __('Exclude map from match', WP_CLANWARS_TEXTDOMAIN),
1909 'removeRound' => __('Remove round', WP_CLANWARS_TEXTDOMAIN),
1910 'addGallery' => __('Add images', WP_CLANWARS_TEXTDOMAIN),
1911 'confirmDeleteScreenshot' => __('Are you sure you want to delete this screenshot?', WP_CLANWARS_TEXTDOMAIN)
1912 )
1913 );
1914
1915 if( !Utils::is_post() ) {
1916 return;
1917 }
1918
1919
1920
1921 if($act === 'add') {
1922 $this->handle_add_match();
1923 }
1924 else if($act === 'edit') {
1925 $this->handle_edit_match();
1926 }
1927 else {
1928 $this->handle_matches_bulk_actions();
1929 }
1930 }
1931
1932 function handle_add_match() {
1933 $defaults = array(
1934 'game_id' => 0,
1935 'title' => '',
1936 'description' => '',
1937 'external_url' => '',
1938 'date' => Utils::current_time_fixed('timestamp', 0),
1939 'team1' => 0,
1940 'team2' => 0,
1941 'scores' => array(),
1942 'new_team_title' => '',
1943 'new_team_country' => '',
1944 'match_status' => 0,
1945 'gallery' => array()
1946 );
1947
1948 extract( Utils::extract_args( stripslashes_deep($_POST), $defaults ) );
1949
1950 $date = Utils::date_array2time_helper($date);
1951
1952 if(!empty($new_team_title) && !empty($new_team_country)) {
1953 $pickteam = $this->quick_pick_team($new_team_title, $new_team_country);
1954
1955 if($pickteam > 0) {
1956 $team2 = $pickteam;
1957 }
1958 }
1959
1960 $model = array(
1961 'title' => $title,
1962 'description' => $description,
1963 'external_url' => $external_url,
1964 'date' => date('Y-m-d H:i:s', $date),
1965 'post_id' => 0,
1966 'team1' => $team1,
1967 'team2' => $team2,
1968 'game_id' => $game_id,
1969 'match_status' => $match_status,
1970 'description' => $description
1971 );
1972
1973 $match_id = \WP_Clanwars\Matches::add_match( $model );
1974
1975 if(!$match_id) {
1976 Flash::error( __( 'Failed to add a match.', WP_CLANWARS_TEXTDOMAIN ) );
1977 return;
1978 }
1979
1980 foreach($scores as $round_group => $r) {
1981 $num_rounds = sizeof($r['team1']);
1982
1983 for($i = 0; $i < $num_rounds; $i++) {
1984 $model = array(
1985 'match_id' => $match_id,
1986 'group_n' => abs($round_group),
1987 'map_id' => $r['map_id'],
1988 'tickets1' => $r['team1'][$i],
1989 'tickets2' => $r['team2'][$i]
1990 );
1991
1992 \WP_Clanwars\Rounds::add_round( $model );
1993 }
1994 }
1995
1996 \WP_Clanwars\Matches::update_match_post( $match_id, $gallery );
1997
1998 Flash::success( __( 'Added a match.', WP_CLANWARS_TEXTDOMAIN ) );
1999
2000 wp_redirect( admin_url( 'admin.php?page=wp-clanwars-matches' ) );
2001 exit();
2002 }
2003
2004 function handle_edit_match() {
2005 $defaults = array(
2006 'id' => 0,
2007 'game_id' => 0,
2008 'title' => '',
2009 'description' => '',
2010 'external_url' => '',
2011 'date' => Utils::current_time_fixed('timestamp', 0),
2012 'team1' => 0,
2013 'team2' => 0,
2014 'new_team_title' => '',
2015 'new_team_country' => '',
2016 'match_status' => 0,
2017 'scores' => array(),
2018 'gallery' => array()
2019 );
2020
2021 extract( Utils::extract_args( stripslashes_deep($_POST), $defaults ) );
2022
2023 $date = Utils::date_array2time_helper($date);
2024
2025 if(!empty($new_team_title) && !empty($new_team_country)) {
2026 $pickteam = $this->quick_pick_team($new_team_title, $new_team_country);
2027
2028 if($pickteam > 0) {
2029 $team2 = $pickteam;
2030 }
2031 }
2032
2033 $model = array(
2034 'title' => $title,
2035 'date' => date('Y-m-d H:i:s', $date),
2036 'team1' => $team1,
2037 'team2' => $team2,
2038 'game_id' => $game_id,
2039 'match_status' => $match_status,
2040 'description' => $description,
2041 'external_url' => $external_url
2042 );
2043
2044 \WP_Clanwars\Matches::update_match( $id, $model );
2045
2046 $rounds_not_in = array();
2047
2048 foreach($scores as $round_group => $r) {
2049 $num_rounds = sizeof($r['team1']);
2050
2051 for($i = 0; $i < $num_rounds; $i++) {
2052 $round_id = $r['round_id'][$i];
2053 $model = array(
2054 'match_id' => $id,
2055 'group_n' => abs($round_group),
2056 'map_id' => $r['map_id'],
2057 'tickets1' => $r['team1'][$i],
2058 'tickets2' => $r['team2'][$i]
2059 );
2060
2061 if($round_id > 0) {
2062 \WP_Clanwars\Rounds::update_round($round_id, $model);
2063
2064 $rounds_not_in[] = $round_id;
2065 }
2066 else {
2067 $new_round = \WP_Clanwars\Rounds::add_round($model);
2068
2069 if($new_round !== false) {
2070 $rounds_not_in[] = $new_round;
2071 }
2072 }
2073 }
2074 }
2075
2076 \WP_Clanwars\Rounds::delete_rounds_not_in($id, $rounds_not_in);
2077
2078 \WP_Clanwars\Matches::update_match_post($id, $gallery);
2079
2080 Flash::success( __('Updated a match.', WP_CLANWARS_TEXTDOMAIN) );
2081
2082 wp_redirect( admin_url( 'admin.php?page=wp-clanwars-matches&act=edit&id=' . $id ) );
2083 exit();
2084 }
2085
2086 function handle_matches_bulk_actions() {
2087 check_admin_referer( 'bulk-matches' );
2088
2089 if( ! \WP_Clanwars\ACL::user_can('manage_matches') ) {
2090 wp_die( __('Cheatin’ uh?') );
2091 }
2092
2093 $table_action = Utils::get_list_table_action();
2094
2095 if($table_action === 'delete' && isset($_POST['id'])) {
2096 $result = \WP_Clanwars\Matches::delete_match( $_POST['id'] );
2097
2098 if( is_wp_error( $result ) ) {
2099 Flash::error( sprintf( __( 'Failed to delete matches. Error: %s', WP_CLANWARS_TEXTDOMAIN ), $result->get_error_message() ) );
2100 }
2101 else {
2102 Flash::success( sprintf( _n( 'Deleted %d match.', 'Deleted %d matches.', $result, WP_CLANWARS_TEXTDOMAIN ), $result ) );
2103 }
2104 }
2105
2106 wp_redirect( admin_url( 'admin.php?page=wp-clanwars-matches' ) );
2107 exit();
2108 }
2109
2110 function on_shortcode($atts) {
2111 extract(shortcode_atts(array('match_id' => 0), $atts));
2112
2113 $match_id = (int)$match_id;
2114 if($match_id > 0) {
2115 return $this->on_match_shortcode($match_id);
2116 }
2117
2118 return $this->on_browser_shortcode($atts);
2119 }
2120
2121 function on_match_shortcode($match_id) {
2122 $matchResult = \WP_Clanwars\Matches::get_match(array('id' => $match_id, 'sum_tickets' => true));
2123
2124 if( !$matchResult->count() ) {
2125 return __("<p>Match with id = $match_id has been removed.</p>", WP_CLANWARS_TEXTDOMAIN);
2126 }
2127
2128 $match = $matchResult[0];
2129 $r = \WP_Clanwars\Rounds::get_rounds($match->id);
2130 $rounds = array();
2131
2132 // group rounds by map
2133 foreach($r as $v) {
2134 if(!isset($rounds[$v->group_n])) {
2135 $rounds[$v->group_n] = array();
2136 }
2137 array_push($rounds[$v->group_n], $v);
2138 }
2139
2140 $match_status_text = $this->match_status[$match->match_status];
2141 $team1_flag = Utils::get_country_flag($match->team1_country);
2142 $team2_flag = Utils::get_country_flag($match->team2_country);
2143
2144 $view = new View( 'match_view' );
2145
2146 $context = compact('match', 'rounds', 'match_status_text', 'team1_flag', 'team2_flag');
2147
2148 return $view->render( $context, false );
2149 }
2150
2151 function on_browser_shortcode($atts) {
2152 $output = '';
2153
2154 extract(shortcode_atts(array('per_page' => 4), $atts));
2155
2156 $per_page = abs($per_page);
2157 $current_page = max( 1, get_query_var('paged') );
2158 $now = Utils::current_time_fixed('timestamp');
2159 $current_game = isset($_GET['game']) ? $_GET['game'] : false;
2160
2161 $games = \WP_Clanwars\Games::get_game('id=all&orderby=title&order=asc');
2162
2163 $p = array(
2164 'limit' => $per_page,
2165 'order' => 'desc',
2166 'orderby' => 'date',
2167 'sum_tickets' => true,
2168 'game_id' => $current_game,
2169 'offset' => ($current_page-1) * $per_page
2170 );
2171
2172 $matches = \WP_Clanwars\Matches::get_match($p);
2173 $pagination = $matches->get_pagination();
2174
2175 $page_links = paginate_links(array(
2176 'prev_text' => __('←'),
2177 'next_text' => __('→'),
2178 'total' => $pagination->get_num_pages(),
2179 'current' => $current_page
2180 ));
2181
2182 $page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s–%s of %s' ) . '</span>%s',
2183 number_format_i18n( (($current_page - 1) * $per_page) + 1 ),
2184 number_format_i18n( min( $current_page * $per_page, $pagination->get_num_rows() ) ),
2185 '<span class="total-type-count">' . number_format_i18n( $pagination->get_num_rows() ) . '</span>',
2186 $page_links
2187 );
2188
2189 $output_btn = '<ul class="wp-clanwars-filter">';
2190
2191 $obj = new stdClass();
2192 $obj->id = 0;
2193 $obj->title = __('All', WP_CLANWARS_TEXTDOMAIN);
2194 $obj->abbr = __('All');
2195 $obj->icon = 0;
2196
2197 array_unshift($games, $obj);
2198
2199 $this_url = remove_query_arg(array('paged', 'game'));
2200 for($i = 0; $i < sizeof($games); $i++) :
2201 $game = $games[$i];
2202 $link = ($game->id == 0) ? $this_url : add_query_arg('game', $game->id, $this_url);
2203
2204 $output_btn .= '<li' . ($game->id == $current_game ? ' class="selected"' : '') . '><a href="' . $link . '" title="' . esc_attr($game->title) . '">' . esc_html($game->abbr) . '</a></li>';
2205 endfor;
2206
2207 $output_btn .= '</ul>';
2208
2209 $output .= '<ul class="wp-clanwars-list">';
2210
2211 // generate table content
2212 foreach($matches as $index => $match) {
2213
2214 $output .= '<li class="match ' . ($index % 2 == 0 ? 'even' : 'odd') . '">';
2215
2216 // output match status
2217 $is_upcoming = false;
2218 $t1 = $match->team1_tickets;
2219 $t2 = $match->team2_tickets;
2220 $wld_class = $t1 == $t2 ? 'draw' : ($t1 > $t2 ? 'win' : 'loss');
2221 $date = mysql2date(get_option('date_format') . ', ' . get_option('time_format'), $match->date);
2222 $timestamp = mysql2date('U', $match->date);
2223
2224 $is_upcoming = $timestamp > $now;
2225 $is_playing = ($now > $timestamp && $now < $timestamp + 3600) && ($t1 == 0 && $t2 == 0);
2226
2227 if($is_upcoming) :
2228 $output .= '<div class="upcoming">' . __('Upcoming', WP_CLANWARS_TEXTDOMAIN) . '</div>';
2229 elseif($is_playing) :
2230 $output .= '<div class="playing">' . __('Playing', WP_CLANWARS_TEXTDOMAIN) . '</div>';
2231 else :
2232 $output .= '<div class="scores ' . $wld_class . '">' . sprintf(__('%d:%d', WP_CLANWARS_TEXTDOMAIN), $t1, $t2) . '</div>';
2233 endif;
2234
2235 // teams
2236 $output .= '<div class="wrap">';
2237
2238 // output game icon
2239 $game_icon = wp_get_attachment_url($match->game_icon);
2240
2241 if($game_icon !== false) {
2242 $output .= '<img src="' . $game_icon . '" alt="' . esc_attr($match->game_title) . '" class="icon" /> ';
2243 }
2244
2245 $team2_title = esc_html($match->team2_title);
2246
2247 if($match->post_id != 0)
2248 $team2_title = '<a href="' . get_permalink($match->post_id) . '" title="' . esc_attr($match->title) . '">' . $team2_title . '</a>';
2249
2250 $output .= '<div class="lmatches">' . esc_html($match->team1_title) .' vs. '. $team2_title .'</div>';
2251
2252 $output .= '<div class="date">' . esc_html($date) . '</div>';
2253
2254 $rounds = array();
2255 $r = \WP_Clanwars\Rounds::get_rounds($match->id);
2256 foreach($r as $v) {
2257 if(isset($rounds[$v->group_n]))
2258 continue;
2259
2260 $image = wp_get_attachment_image_src($v->screenshot);
2261
2262 if(!empty($image)) {
2263 $rounds[$v->group_n] = '<a href="' . esc_attr($image[0]) . '#' . $image[1] . 'x' . $image[2] . '" title="' . esc_attr($v->title) . '">' . esc_html($v->title) . '</a>';
2264 } else
2265 $rounds[$v->group_n] = $v->title;
2266 }
2267
2268 if(!empty($rounds)) {
2269 $maplist = implode(', ', array_values($rounds));
2270 $output .= '<div class="maplist">' . $maplist . '</div>';
2271 }
2272
2273 $output .= '</div>';
2274
2275 $output .= '</li>';
2276
2277 }
2278
2279 $output .= '</ul>';
2280
2281 $output .= '<div class="wp-clanwars-pagination">' .$page_links_text . '</div>';
2282
2283 //return $output;
2284
2285
2286 $output_ext = '<div class="switch">';
2287 $output_ext .= $output_btn;
2288 $output_ext .= '</div><div class="latestmatch">';
2289 $output_ext .= $output; unset($output,$output_btn);
2290 $output_ext .= '</div>';
2291
2292 return $output_ext;
2293 }
2294
2295 function on_manage_matches()
2296 {
2297 $act = isset($_GET['act']) ? $_GET['act'] : '';
2298 $current_page = isset($_GET['paged']) ? $_GET['paged'] : 1;
2299 $limit = 10;
2300 $game_filter = \WP_Clanwars\ACL::user_can('which_games');
2301
2302 if( $act === 'add' ) {
2303 return $this->on_add_match();
2304 }
2305 else if( $act === 'edit' ) {
2306 return $this->on_edit_match();
2307 }
2308
2309 $condition = array(
2310 'id' => 'all',
2311 'game_id' => $game_filter,
2312 'sum_tickets' => true,
2313 'orderby' => 'date',
2314 'order' => 'desc',
2315 'limit' => $limit,
2316 'offset' => ($limit * ($current_page-1))
2317 );
2318
2319 $matches = \WP_Clanwars\Matches::get_match($condition);
2320 $pagination = $matches->get_pagination();
2321 $match_statuses = $this->match_status;
2322
2323 // populate games with urls for icons
2324 foreach ($matches as $match) {
2325 $match->game_icon_url = wp_get_attachment_url($match->game_icon);
2326 }
2327
2328 $page_links = paginate_links( array(
2329 'base' => add_query_arg('paged', '%#%'),
2330 'format' => '',
2331 'prev_text' => __('«'),
2332 'next_text' => __('»'),
2333 'total' => $pagination->get_num_pages(),
2334 'current' => $current_page
2335 ));
2336
2337 $wp_list_table = $this->match_table;
2338
2339 $view = new View( 'match_table' );
2340
2341 $view->add_helper( 'print_table_header', array($this, 'print_table_header') );
2342 $view->add_helper( 'get_country_flag', array('\WP_Clanwars\Utils', 'get_country_flag') );
2343
2344 $context = compact('table_columns', 'page_links_text', 'matches', 'match_statuses', 'wp_list_table');
2345 $view->render($context);
2346 }
2347
2348 function on_admin_post_settings() {
2349 if( !current_user_can('manage_options') ) {
2350 wp_die(__('Cheatin’ uh?'));
2351 }
2352
2353 check_admin_referer('wp-clanwars-settings');
2354
2355 if( isset($_POST['category']) ) {
2356 update_option( WP_CLANWARS_CATEGORY, (int) $_POST['category'] );
2357 }
2358
2359 // keep default styles always enabled on jumpstarter
2360 $enable_default_styles = isset( $_POST['enable_default_styles'] ) || $this->is_jumpstarter();
2361
2362 update_option( WP_CLANWARS_DEFAULTCSS, $enable_default_styles );
2363
2364 Flash::success( __('Settings saved.', WP_CLANWARS_TEXTDOMAIN) );
2365
2366 wp_redirect( $_POST['_wp_http_referer'] );
2367 }
2368
2369 function on_admin_post_acl() {
2370 if(!current_user_can('manage_options')) {
2371 wp_die(__('Cheatin’ uh?'));
2372 }
2373
2374 check_admin_referer('wp-clanwars-acl');
2375
2376 if( isset( $_POST['user'] ) ) {
2377 $user_id = (int) $_POST['user'];
2378 $data = array();
2379
2380 if( isset( $_POST['permissions'] ) ) {
2381 $data['permissions'] = $_POST['permissions'];
2382 }
2383
2384 if( isset( $_POST['games'] ) ) {
2385 $data['games'] = $_POST['games'];
2386 }
2387
2388 \WP_Clanwars\ACL::update( $user_id, $data );
2389 }
2390
2391 Flash::success( __( 'Settings saved.', WP_CLANWARS_TEXTDOMAIN ) );
2392
2393 wp_redirect( $_POST['_wp_http_referer'] );
2394 }
2395
2396 function on_admin_post_deleteacl() {
2397 if( !current_user_can('manage_options') ) {
2398 wp_die(__('Cheatin’ uh?'));
2399 }
2400
2401 check_admin_referer('wp-clanwars-deleteacl');
2402
2403 $args = Utils::extract_args( $_POST, array(
2404 'do_action' => '',
2405 'do_action2' => '',
2406 'users' => array()
2407 ) );
2408 extract($args);
2409
2410 if($do_action == 'delete' || $do_action2 == 'delete') {
2411 $users = array_unique( array_values( $users ) );
2412
2413 foreach( $users as $key => $user_id ) {
2414 \WP_Clanwars\ACL::delete( $user_id );
2415 }
2416 }
2417
2418 Flash::success( __( 'Settings saved.', WP_CLANWARS_TEXTDOMAIN ) );
2419
2420 wp_redirect( $_POST['_wp_http_referer'] );
2421 }
2422
2423 function on_admin_post_import() {
2424 if( !current_user_can('manage_options') ) {
2425 wp_die(__('Cheatin’ uh?'));
2426 }
2427
2428 check_admin_referer('wp-clanwars-import');
2429
2430 if( isset( $_FILES['userfile'] ) ) {
2431 $file = $_FILES['userfile'];
2432
2433 if($file['error'] === 0) {
2434 $err = $this->import_game( $file['tmp_name'] );
2435
2436 if( is_wp_error( $err ) ) {
2437 Flash::error( $err->get_error_message() );
2438 }
2439 else {
2440 Flash::success( __( 'Imported game.', WP_CLANWARS_TEXTDOMAIN ) );
2441 }
2442 }
2443 else {
2444 Flash::error( __( 'Failed to upload file.', WP_CLANWARS_TEXTDOMAIN ) );
2445 }
2446 }
2447 else if( isset( $_POST['remote_id'] ) ) {
2448 $remote_id = (string) $_POST['remote_id'];
2449 $err = $this->import_remote_game( CloudAPI::get_download_url( $remote_id ) );
2450
2451 if( is_wp_error( $err ) ) {
2452 Flash::error( $err->get_error_message() );
2453 }
2454 else {
2455 Flash::success( __( 'Imported game.', WP_CLANWARS_TEXTDOMAIN ) );
2456 }
2457 }
2458
2459 wp_redirect( $_POST['_wp_http_referer'] );
2460 }
2461
2462 function on_admin_post_publish() {
2463 if( !current_user_can('manage_options') ) {
2464 wp_die(__('Cheatin’ uh?'));
2465 }
2466
2467 check_admin_referer('wp-clanwars-publish');
2468
2469 if( isset( $_FILES['userfile'] ) ) {
2470 $file = $_FILES['userfile'];
2471
2472 if($file['error'] === 0) {
2473 // agree to licensing terms?
2474 if( isset( $_POST['terms_confirm'] ) ) {
2475 $err = CloudAPI::publish( $file['tmp_name'] );
2476
2477 if( is_wp_error( $err ) ) {
2478 Flash::error( $err->get_error_message() );
2479 }
2480 else {
2481 Flash::success( __( 'The game has been published and will be publicly available after moderation. You will be notified via e-mail.', WP_CLANWARS_TEXTDOMAIN ) );
2482 }
2483 }
2484 else {
2485 Flash::error( __( 'You must agree to the licensing terms.', WP_CLANWARS_TEXTDOMAIN ) );
2486 }
2487 }
2488 else {
2489 Flash::error( __( 'Failed to upload file.', WP_CLANWARS_TEXTDOMAIN ) );
2490 }
2491 }
2492
2493 wp_redirect( $_POST['_wp_http_referer'] );
2494 }
2495
2496 function on_admin_post_login() {
2497 if(!isset($_POST['token'])) {
2498 $view = new View( 'login_redirect' );
2499 $view->render();
2500 die();
2501 }
2502
2503 if(CloudAPI::update_access_token($_POST['token'])) {
2504 $cloudUser = CloudAPI::get_user_info();
2505 Flash::success( sprintf( __( 'Logged in as %s.', WP_CLANWARS_TEXTDOMAIN ), $cloudUser->fullname ) );
2506 }
2507 else {
2508 Flash::error( __( 'Failed to log in.', WP_CLANWARS_TEXTDOMAIN ) );
2509 }
2510
2511 $view = new View( 'login_complete' );
2512 $view->render();
2513 die();
2514 }
2515
2516 function on_admin_post_logout() {
2517 check_admin_referer('wp-clanwars-logout');
2518
2519 CloudAPI::logout();
2520
2521 wp_redirect( $_REQUEST['_wp_http_referer'] );
2522 exit();
2523 }
2524
2525 // Settings page hook
2526 function on_settings() {
2527 $table_columns = array(
2528 'cb' => '<input type="checkbox" />',
2529 'user_login' => __('User Login', WP_CLANWARS_TEXTDOMAIN),
2530 'user_permissions' => __('Permissions', WP_CLANWARS_TEXTDOMAIN)
2531 );
2532
2533 $categories_dropdown = wp_dropdown_categories(array(
2534 'name' => 'category',
2535 'hierarchical' => true,
2536 'show_option_none' => __('None'),
2537 'hide_empty' => 0,
2538 'hide_if_empty' => 0,
2539 'selected' => get_option(WP_CLANWARS_CATEGORY, -1),
2540 'echo' => false
2541 ));
2542
2543 $enable_default_styles = get_option(WP_CLANWARS_DEFAULTCSS);
2544
2545 // hide default styles checkbox on jumpstarter
2546 $hide_default_styles = $this->is_jumpstarter();
2547
2548 $games = \WP_Clanwars\Games::get_game('id=all');
2549 $acl = \WP_Clanwars\ACL::get();
2550 $acl_keys = \WP_Clanwars\ACL::all_caps();
2551
2552 $obj = new stdClass();
2553 $obj->id = 0;
2554 $obj->title = __('All', WP_CLANWARS_TEXTDOMAIN);
2555 $obj->abbr = __('All');
2556 $obj->icon = 0;
2557
2558 array_unshift($games, $obj);
2559
2560 $user_acl_info = array();
2561
2562 foreach($acl as $user_id => $user_acl) {
2563 $user = get_userdata($user_id);
2564 $allowed_games = \WP_Clanwars\ACL::user_can('which_games', false, $user_id);
2565 $user_games = \WP_Clanwars\Games::get_game(array('id' => $allowed_games, 'orderby' => 'title', 'order' => 'asc'));
2566
2567 // populate games with urls for icons
2568 foreach ($user_games as $game) {
2569 $game->icon_url = wp_get_attachment_url($game->icon);
2570 }
2571
2572 $item = new stdClass();
2573 $item->user = $user;
2574 $item->user_acl = $user_acl;
2575 $item->user_games = $user_games;
2576 $item->allowed_games = $allowed_games;
2577
2578 array_push($user_acl_info, $item);
2579 }
2580
2581 $view = new View( 'settings' );
2582 $view->add_helper( 'print_table_header', array($this, 'print_table_header') );
2583
2584 $context = compact('table_columns', 'games', 'acl_keys', 'user_acl_info',
2585 'categories_dropdown', 'enable_default_styles', 'hide_default_styles');
2586
2587 $view->render( $context );
2588 }
2589
2590 // Import page hook
2591 function on_import() {
2592 add_thickbox();
2593
2594 $tab = isset($_GET['tab']) ? $_GET['tab'] : 'browse';
2595
2596 if($tab === 'upload') {
2597 $this->on_import_upload();
2598 }
2599 else if($tab === 'publish') {
2600 $this->on_import_publish();
2601 }
2602 else {
2603 $this->on_import_browse();
2604 }
2605 }
2606
2607 function on_import_publish() {
2608 $publish_action = 'wp-clanwars-publish';
2609 $active_tab = 'publish';
2610 $logged_into_cloud = CloudAPI::is_logged_in();
2611 $cloud_account = CloudAPI::get_user_info();
2612
2613 $view = new View( 'import_publish' );
2614 $context = compact( 'publish_action', 'active_tab', 'logged_into_cloud', 'cloud_account' );
2615
2616 wp_enqueue_script('wp-clanwars-login');
2617
2618 $view->render( $context );
2619 }
2620
2621 function on_import_upload() {
2622 $install_action = 'wp-clanwars-import';
2623 $view = new View( 'import_upload' );
2624 $context = compact( 'install_action' );
2625 $view->render( $context );
2626 }
2627
2628 function on_import_browse() {
2629 $query_args = Utils::extract_args( stripslashes_deep($_GET), array( 'q' => '' ) );
2630
2631 $logged_into_cloud = CloudAPI::is_logged_in();
2632 $cloud_account = CloudAPI::get_user_info();
2633
2634 $search_query = trim( (string) $query_args['q'] );
2635 $installed_games = \WP_Clanwars\Games::get_game('')->getArrayCopy();
2636
2637 $store_ids = array_filter(
2638 array_map( function ($game) {
2639 return $game->store_id;
2640 }, $installed_games)
2641 );
2642
2643 $active_tab = '';
2644 $install_action = 'wp-clanwars-import';
2645
2646 if( empty($search_query) ) {
2647 $api_response = CloudAPI::get_popular();
2648
2649 $active_tab = 'popular';
2650 }
2651 else {
2652 $api_response = CloudAPI::search( $search_query );
2653
2654 $active_tab = 'search';
2655 }
2656
2657 $api_games = array();
2658
2659 if( !is_wp_error( $api_response ) ) {
2660 array_walk($api_response, function (&$game) use ($store_ids) {
2661 $game->is_installed = in_array($game->_id, $store_ids);
2662 });
2663 $api_games = $api_response;
2664 }
2665 else {
2666 $api_error_message = $api_response->get_error_message();
2667 }
2668
2669 $view = new View( 'import_browse' );
2670 $context = compact( 'api_games', 'api_error_message', 'search_query', 'active_tab', 'install_action', 'logged_into_cloud', 'cloud_account' );
2671
2672 wp_enqueue_script( 'wp-clanwars-game-browser' );
2673 wp_enqueue_script( 'wp-clanwars-login' );
2674
2675 $view->render( $context );
2676 }
2677
2678}
2679
2680/*
2681 * Initialization
2682 */
2683
2684$wpClanWars = new WP_ClanWars();
2685
2686register_activation_hook( __FILE__, array(&$wpClanWars, 'on_activate'));
2687register_deactivation_hook( __FILE__, array(&$wpClanWars, 'on_deactivate'));
2688
2689/**
2690 * Uninstall function
2691 *
2692 * Proxing on_uninstall call of wpClanWars class
2693 * to prevent 'The script tried to execute a method or access a property of an
2694 * incomplete object.' error in the case of direct call to the class
2695 */
2696
2697function wp_clanwars_uninstall()
2698{
2699 global $wpClanWars;
2700
2701 $wpClanWars->on_uninstall();
2702}
2703
2704register_uninstall_hook(__FILE__, 'wp_clanwars_uninstall');
2705?>