Passed
Push — master ( b6c62e...3fdbae )
by Michael
07:59
created

chess_accept_challenge()   F

Complexity

Conditions 18
Paths 576

Size

Total Lines 96
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 18
eloc 64
nc 576
nop 3
dl 0
loc 96
rs 1.2888
c 2
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
// $Id$
4
//  ------------------------------------------------------------------------ //
5
//                XOOPS - PHP Content Management System                      //
6
//                    Copyright (c) 2000 XOOPS.org                           //
7
//                       <https://xoops.org>                             //
8
// ------------------------------------------------------------------------- //
9
//  This program is free software; you can redistribute it and/or modify     //
10
//  it under the terms of the GNU General Public License as published by     //
11
//  the Free Software Foundation; either version 2 of the License, or        //
12
//  (at your option) any later version.                                      //
13
//                                                                           //
14
//  You may not change or alter any portion of this comment or credits       //
15
//  of supporting developers from this source code or any supporting         //
16
//  source code which is considered copyrighted (c) material of the          //
17
//  original comment or credit authors.                                      //
18
//                                                                           //
19
//  This program is distributed in the hope that it will be useful,          //
20
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
21
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
22
//  GNU General Public License for more details.                             //
23
//                                                                           //
24
//  You should have received a copy of the GNU General Public License        //
25
//  along with this program; if not, write to the Free Software              //
26
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
27
//  ------------------------------------------------------------------------ //
28
29
/**
30
 * This module handles chess game creation.
31
 *
32
 * The following forms are generated and processed:
33
 *
34
 *  - Create-form 1 - Specify game type (open challenge, individual challenge or self-play).
35
 *  - Create-form 2 - Specify opponent (for individual challenge), and color and rating options (for open challenge and individual challenge).
36
 *  - Create-form 3 - Confirm entries from forms 1 and 2.
37
 *  - Accept-form   - Accept challenge.
38
 *  - Delete-form   - Delete challenge.
39
 *
40
 * @package    chess
41
 * @subpackage challenge
42
 */
43
44
use XoopsModules\Chess;
45
use \Xmf\Request;
46
47
/**#@+
48
 */
49
require_once dirname(__DIR__, 2) . '/mainfile.php';
50
$xoopsConfig['module_cache'][$xoopsModule->getVar('mid')] = 0; // disable caching
51
require_once XOOPS_ROOT_PATH . '/header.php';
52
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
53
require_once XOOPS_ROOT_PATH . '/modules/chess/include/constants.inc.php';
54
require_once XOOPS_ROOT_PATH . '/modules/chess/include/functions.php';
55
56
#var_dump($_REQUEST);#*#DEBUG#
57
58
if (!chess_can_play()) {
59
    redirect_header(XOOPS_URL . '/index.php', _CHESS_REDIRECT_DELAY_FAILURE, _NOPERM);
60
}
61
62
// user input
63
//$gametype          = chess_sanitize(@$_POST['gametype']);
64
//$opponent          = chess_sanitize(trim(@$_POST['opponent']), _CHESS_USERNAME_ALLOWED_CHARACTERS);
65
$gametype     = Request::getCmd('gametype', '', 'POST');
66
$opponent     = preg_replace('/[^' . _CHESS_USERNAME_ALLOWED_CHARACTERS . ']/i', '', Request::getString('opponent', '', 'POST'));
67
$opponent     = trim($opponent);
68
$opponent_uid      = !empty($opponent) ? chess_opponent_uid($opponent) : 0;
69
//$fen               = chess_moduleConfig('allow_setup') ? chess_sanitize(trim(@$_POST['fen']), 'A-Za-z0-9 /-') : '';
70
$fen               = chess_moduleConfig('allow_setup') ? preg_replace('/[^a-z0-9 \/\-]/i', '', Request::getString('fen', '', 'POST')) : '';
71
$coloroption       = chess_sanitize(@$_POST['coloroption']);
72
$rated             = Request::getInt('rated', 0);
73
$notify_accept     = Request::hasVar('notify_accept', 'POST');
74
$notify_move       = Request::hasVar('notify_move', 'POST');
75
$challenge_id      = Request::getInt('challenge_id', 0);
76
$show_arbiter_ctrl = Request::hasVar('show_arbiter_ctrl', 'POST');
77
$submit_challenge1 = Request::hasVar('submit_challenge1', 'POST');
78
$submit_challenge2 = Request::hasVar('submit_challenge2', 'POST');
79
$submit_challenge3 = Request::hasVar('submit_challenge3', 'POST');
80
$cancel_challenge1 = Request::hasVar('cancel_challenge1', 'POST');
81
$cancel_challenge2 = Request::hasVar('cancel_challenge2', 'POST');
82
$cancel_challenge3 = Request::hasVar('cancel_challenge3', 'POST');
83
$submit_accept     = Request::hasVar('submit_accept', 'POST');
84
$cancel_accept     = Request::hasVar('cancel_accept', 'POST');
85
$submit_delete     = Request::hasVar('submit_delete', 'POST');
86
$confirm_delete    = Request::getInt('confirm_delete', 0, 'POST');
87
88
// If form-submit, check security token.
89
if (($submit_challenge1 || $submit_challenge2 || $submit_challenge3 || $submit_accept || $submit_delete || $show_arbiter_ctrl) && is_object($GLOBALS['xoopsSecurity']) && !$GLOBALS['xoopsSecurity']->check()) {
90
    redirect_header(
91
        XOOPS_URL . '/modules/chess/',
92
        _CHESS_REDIRECT_DELAY_FAILURE,
93
        _MD_CHESS_TOKEN_ERROR . '<br>' . implode('<br>', $GLOBALS['xoopsSecurity']->getErrors())
94
    );
95
}
96
97
// If rating feature disabled, force ratings to off.
98
if ('none' == chess_moduleConfig('rating_system')) {
99
    $rated = 0;
100
}
101
102
$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
103
104
// Determine if user is a valid arbiter.
105
$is_arbiter = is_object($xoopsUser) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'));
106
107
if ($cancel_challenge1) {
108
    redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_SUCCESS, _TAKINGBACK);
109
} elseif ($cancel_challenge2) {
110
    chess_show_create_form1($gametype);
111
} elseif ($cancel_challenge3) {
112
    if (_CHESS_GAMETYPE_OPEN == $gametype || _CHESS_GAMETYPE_USER == $gametype) {
113
        chess_show_create_form2($gametype, $fen);
114
    } else {
115
        chess_show_create_form1($gametype, $fen);
116
    }
117
} elseif ($cancel_accept) {
118
    redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_SUCCESS, _TAKINGBACK);
119
} elseif ($submit_challenge1) {
120
    $fen_error = chess_fen_error($fen);
121
122
    if (!empty($fen_error)) {
123
        chess_show_create_form1($gametype, $fen, _MD_CHESS_FEN_INVALID . ': ' . $fen_error);
124
    } elseif (_CHESS_GAMETYPE_OPEN == $gametype || _CHESS_GAMETYPE_USER == $gametype) {
125
        chess_show_create_form2($gametype, $fen);
126
    } else {
127
        chess_show_create_form3($gametype, $fen, $coloroption, $opponent_uid, $rated);
128
    }
129
} elseif ($submit_challenge2) {
130
    if (_CHESS_GAMETYPE_USER == $gametype) {
131
        if (empty($opponent)) {
132
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_MISSING);
133
        } elseif (!$opponent_uid) {
134
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_INVALID);
135
        } elseif ($opponent_uid == $uid) {
136
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_SELF);
137
        } else {
138
            chess_show_create_form3($gametype, $fen, $coloroption, $opponent_uid, $rated);
139
        }
140
    } else {
141
        chess_show_create_form3($gametype, $fen, $coloroption, $opponent_uid, $rated);
142
    }
143
} elseif ($submit_challenge3) {
144
    if (_CHESS_GAMETYPE_OPEN == $gametype) {
145
        chess_create_challenge($gametype, $fen, $coloroption, $rated, $notify_accept, $notify_move);
146
147
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_SUCCESS, _MD_CHESS_GAME_CREATED);
148
    } elseif (_CHESS_GAMETYPE_USER == $gametype) {
149
        if (empty($opponent)) {
150
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_MISSING);
151
        } elseif (!$opponent_uid) {
152
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_INVALID);
153
        } elseif ($opponent_uid == $uid) {
154
            chess_show_create_form2($gametype, $fen, $coloroption, $opponent_uid, $rated, _MD_CHESS_OPPONENT_SELF);
155
        } else {
156
            chess_create_challenge($gametype, $fen, $coloroption, $rated, $notify_accept, $notify_move, $opponent_uid);
157
158
            redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_SUCCESS, _MD_CHESS_GAME_CREATED);
159
        }
160
    } elseif (_CHESS_GAMETYPE_SELF == $gametype) {
161
        $game_id = chess_create_game($uid, $uid, $fen, $rated);
162
163
        redirect_header(XOOPS_URL . "/modules/chess/game.php?game_id=$game_id", _CHESS_REDIRECT_DELAY_SUCCESS, _MD_CHESS_GAME_CREATED);
164
    } else {
165
        chess_show_create_form1($gametype, $fen, _MD_CHESS_GAMETYPE_INVALID);
166
    }
167
} elseif ($submit_accept) {
168
    chess_accept_challenge($challenge_id, $coloroption, $notify_move);
169
} elseif ($submit_delete) {
170
    if ($confirm_delete) {
171
        if ($is_arbiter || chess_is_challenger($challenge_id)) {
172
            chess_delete_challenge($challenge_id);
173
174
            redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_SUCCESS, _MD_CHESS_GAME_DELETED);
175
        } else {
176
            redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _NOPERM);
177
        }
178
    } else {
179
        chess_show_delete_form($challenge_id, $show_arbiter_ctrl && $is_arbiter, _MD_CHESS_NO_CONFIRM_DELETE);
180
    }
181
} elseif ($challenge_id) {
182
    if (($show_arbiter_ctrl && $is_arbiter) || chess_is_challenger($challenge_id)) {
183
        chess_show_delete_form($challenge_id, $show_arbiter_ctrl && $is_arbiter);
184
    } else {
185
        chess_show_accept_form($challenge_id);
186
    }
187
} else {
188
    chess_show_create_form1($gametype);
189
}
190
191
require_once XOOPS_ROOT_PATH . '/footer.php';
192
/**#@-*/
193
194
/**
195
 * Generate form to get game type and optional FEN setup.
196
 *
197
 * @param string $gametype  _CHESS_GAMETYPE_OPEN, _CHESS_GAMETYPE_USER or _CHESS_GAMETYPE_SELF
198
 * @param string $fen       FEN setup
199
 * @param string $error_msg Error message to display
200
 */
201
function chess_show_create_form1($gametype = _CHESS_GAMETYPE_OPEN, $fen = '', $error_msg = '')
202
{
203
    $form = new XoopsThemeForm(_MD_CHESS_CREATE_FORM, 'create_form1', 'create.php', 'post', true);
204
205
    if ($error_msg) {
206
        $form->addElement(new XoopsFormLabel(_MD_CHESS_ERROR . ': ', '<div class="errorMsg">' . $error_msg . '</div>'));
207
    }
208
209
    $menu_gametype = new XoopsFormSelect(_MD_CHESS_LABEL_GAMETYPE . ':', 'gametype', $gametype, 1, false);
210
211
    $menu_gametype->addOption(_CHESS_GAMETYPE_OPEN, _MD_CHESS_MENU_GAMETYPE_OPEN);
212
213
    $menu_gametype->addOption(_CHESS_GAMETYPE_USER, _MD_CHESS_MENU_GAMETYPE_USER);
214
215
    $menu_gametype->addOption(_CHESS_GAMETYPE_SELF, _MD_CHESS_MENU_GAMETYPE_SELF);
216
217
    $form->addElement($menu_gametype);
218
219
    if (chess_moduleConfig('allow_setup')) {
220
        $form->addElement(new XoopsFormLabel('', '&nbsp;'));
221
222
        $form->addElement(new XoopsFormLabel('', _MD_CHESS_LABEL_FEN_EXPLAIN));
223
224
        $form->addElement(new XoopsFormText(_MD_CHESS_LABEL_FEN_SETUP . ':', 'fen', 80, _CHESS_TEXTBOX_FEN_MAXLEN, $fen));
225
    }
226
227
    $form->addElement(new XoopsFormLabel('&nbsp;', '&nbsp;'));
228
229
    $buttons = new XoopsFormElementTray('');
230
231
    $buttons->addElement(new XoopsFormButton('', 'submit_challenge1', _MD_CHESS_CREATE_SUBMIT, 'submit'));
232
233
    $buttons->addElement(new XoopsFormButton('', 'cancel_challenge1', _MD_CHESS_CREATE_CANCEL, 'submit'));
234
235
    $form->addElement($buttons);
236
237
    $form->display();
238
}
239
240
/**
241
 * Generate form to get color and rating options and, if game type is _CHESS_GAMETYPE_USER (Individual challenge), get opponent.
242
 *
243
 * @param string $gametype     _CHESS_GAMETYPE_OPEN, _CHESS_GAMETYPE_USER or _CHESS_GAMETYPE_SELF
244
 * @param string $fen          FEN setup
245
 * @param string $coloroption  _CHESS_COLOROPTION_OPPONENT, _CHESS_COLOROPTION_RANDOM, _CHESS_COLOROPTION_WHITE or _CHESS_COLOROPTION_BLACK
246
 * @param int    $opponent_uid Opponent's user ID ('0' for open challenge)
247
 * @param int    $rated        '1' if rated, '0' if not rated
248
 * @param string $error_msg    Error message to display
249
 */
250
function chess_show_create_form2($gametype, $fen, $coloroption = _CHESS_COLOROPTION_OPPONENT, $opponent_uid = 0, $rated = 1, $error_msg = '')
251
{
252
    $form = new XoopsThemeForm(_MD_CHESS_CREATE_FORM, 'create_form2', 'create.php', 'post', true);
253
254
    $form->addElement(new XoopsFormHidden('gametype', $gametype));
255
256
    $form->addElement(new XoopsFormHidden('fen', $fen));
257
258
    if ($error_msg) {
259
        $form->addElement(new XoopsFormLabel(_MD_CHESS_ERROR . ':', '<div class="errorMsg">' . $error_msg . '</div>'));
260
    }
261
262
    $memberHandler = xoops_getHandler('member');
263
264
    $opponent_user = $memberHandler->getUser($opponent_uid);
0 ignored issues
show
Bug introduced by
The method getUser() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsAvatarHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

264
    /** @scrutinizer ignore-call */ 
265
    $opponent_user = $memberHandler->getUser($opponent_uid);
Loading history...
265
266
    $opponent_username = is_object($opponent_user) ? $opponent_user->getVar('uname') : '';
267
268
    if (_CHESS_GAMETYPE_USER == $gametype) {
269
        $form->addElement(
270
            new XoopsFormText(
271
                _MD_CHESS_LABEL_OPPONENT . ':', 'opponent', _CHESS_TEXTBOX_OPPONENT_SIZE, _CHESS_TEXTBOX_OPPONENT_MAXLEN, $opponent_username
272
            )
273
        );
274
    }
275
276
    $radio_color = new XoopsFormRadio(_MD_CHESS_LABEL_COLOR . ':', 'coloroption', $coloroption);
277
278
    $radio_color->addOption(_CHESS_COLOROPTION_OPPONENT, _MD_CHESS_RADIO_COLOR_OPPONENT);
279
280
    $radio_color->addOption(_CHESS_COLOROPTION_RANDOM, _MD_CHESS_RADIO_COLOR_RANDOM);
281
282
    $radio_color->addOption(_CHESS_COLOROPTION_WHITE, _MD_CHESS_RADIO_COLOR_WHITE);
283
284
    $radio_color->addOption(_CHESS_COLOROPTION_BLACK, _MD_CHESS_RADIO_COLOR_BLACK);
285
286
    $form->addElement($radio_color);
287
288
    if ('none' !== chess_moduleConfig('rating_system')) {
289
        if (_CHESS_GAMETYPE_OPEN == $gametype || _CHESS_GAMETYPE_USER == $gametype) {
290
            if (chess_moduleConfig('allow_unrated_games')) {
291
                $radio_rated = new XoopsFormRadio(_MD_CHESS_RATED_GAME . ':', 'rated', $rated);
292
293
                $radio_rated->addOption(1, _YES);
294
295
                $radio_rated->addOption(0, _NO);
296
297
                $form->addElement($radio_rated);
298
            } else {
299
                $form->addElement(new XoopsFormHidden('rated', $rated));
300
            }
301
        }
302
    } else {
303
        $form->addElement(new XoopsFormHidden('rated', 0));
304
    }
305
306
    $buttons = new XoopsFormElementTray('');
307
308
    $buttons->addElement(new XoopsFormButton('', 'submit_challenge2', _MD_CHESS_CREATE_SUBMIT, 'submit'));
309
310
    $buttons->addElement(new XoopsFormButton('', 'cancel_challenge2', _MD_CHESS_CREATE_CANCEL, 'submit'));
311
312
    $form->addElement($buttons);
313
314
    $form->display();
315
}
316
317
/**
318
 * Generate form to get confirmation of a new challenge.
319
 *
320
 * @param string $gametype     _CHESS_GAMETYPE_OPEN, _CHESS_GAMETYPE_USER or _CHESS_GAMETYPE_SELF
321
 * @param string $fen          FEN setup
322
 * @param string $coloroption  _CHESS_COLOROPTION_OPPONENT, _CHESS_COLOROPTION_RANDOM, _CHESS_COLOROPTION_WHITE or _CHESS_COLOROPTION_BLACK
323
 * @param int    $opponent_uid Opponent's user ID ('0' for open challenge)
324
 * @param int    $rated        '1' if rated, '0' if not rated
325
 */
326
function chess_show_create_form3($gametype, $fen, $coloroption, $opponent_uid, $rated)
327
{
328
    $memberHandler = xoops_getHandler('member');
329
330
    $opponent_user = $memberHandler->getUser($opponent_uid);
331
332
    $opponent_username = is_object($opponent_user) ? $opponent_user->getVar('uname') : '';
333
334
    $form = new XoopsThemeForm(_MD_CHESS_CREATE_FORM, 'create_form3', 'create.php', 'post', true);
335
336
    $form->addElement(new XoopsFormHidden('gametype', $gametype));
337
338
    $form->addElement(new XoopsFormHidden('fen', $fen));
339
340
    $form->addElement(new XoopsFormHidden('opponent', $opponent_username));
341
342
    $form->addElement(new XoopsFormHidden('coloroption', $coloroption));
343
344
    $form->addElement(new XoopsFormHidden('rated', $rated));
345
346
    $form->addElement(new XoopsFormLabel('', '<div class="confirmMsg">' . _MD_CHESS_GAME_CONFIRM . '</div>'));
347
348
    switch ($gametype) {
349
        case _CHESS_GAMETYPE_OPEN:
350
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_OPEN;
351
            break;
352
        case _CHESS_GAMETYPE_USER:
353
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_USER;
354
            break;
355
        case _CHESS_GAMETYPE_SELF:
356
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_SELF;
357
            break;
358
        default:
359
            $label_gametype = _MD_CHESS_LABEL_ERROR;
360
            break;
361
    }
362
363
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_GAMETYPE . ':', $label_gametype));
364
365
    if (!empty($fen)) {
366
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_FEN_SETUP . ':', $fen));
367
    }
368
369
    if (_CHESS_GAMETYPE_USER == $gametype) {
370
        $memberHandler = xoops_getHandler('member');
371
372
        $opponent_user = $memberHandler->getUser($opponent_uid);
373
374
        $opponent_username = is_object($opponent_user) ? $opponent_user->getVar('uname') : '';
375
376
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_OPPONENT . ':', $opponent_username));
377
    }
378
379
    if (_CHESS_GAMETYPE_OPEN == $gametype || _CHESS_GAMETYPE_USER == $gametype) {
380
        switch ($coloroption) {
381
            case _CHESS_COLOROPTION_OPPONENT:
382
                $label_coloroption = _MD_CHESS_RADIO_COLOR_OPPONENT;
383
                break;
384
            case _CHESS_COLOROPTION_RANDOM:
385
                $label_coloroption = _MD_CHESS_RADIO_COLOR_RANDOM;
386
                break;
387
            case _CHESS_COLOROPTION_WHITE:
388
                $label_coloroption = _MD_CHESS_RADIO_COLOR_WHITE;
389
                break;
390
            case _CHESS_COLOROPTION_BLACK:
391
                $label_coloroption = _MD_CHESS_RADIO_COLOR_BLACK;
392
                break;
393
            default:
394
                $label_coloroption = _MD_CHESS_LABEL_ERROR;
395
                break;
396
        }
397
398
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_COLOR . ':', $label_coloroption));
399
400
        if ('none' != chess_moduleConfig('rating_system')) {
401
            $form->addElement(new XoopsFormLabel(_MD_CHESS_RATED_GAME . ':', $rated ? _YES : _NO));
402
        }
403
404
        // Determine whether current user is subscribed to receive a notification when his challenge is accepted.
405
406
        global $xoopsModule, $xoopsUser;
407
408
        $uid = $xoopsUser->getVar('uid');
409
410
        $mid = $xoopsModule->getVar('mid');
411
412
        $notificationHandler = xoops_getHandler('notification');
413
414
        $is_subscribed = 0 != $notificationHandler->isSubscribed('global', 0, 'notify_accept_challenge', $mid, $uid);
0 ignored issues
show
Bug introduced by
The method isSubscribed() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

414
        $is_subscribed = 0 != $notificationHandler->/** @scrutinizer ignore-call */ isSubscribed('global', 0, 'notify_accept_challenge', $mid, $uid);
Loading history...
415
416
        // Display checkbox with checked-state reflecting subscription status.
417
418
        $checked_value = 1;
419
420
        $checkbox_notify_acpt_chal = new XoopsFormCheckBox('', 'notify_accept', $is_subscribed ? $checked_value : null);
421
422
        $checkbox_notify_acpt_chal->addOption($checked_value, _MD_CHESS_NEVT_ACPT_CHAL_CAP);
423
424
        $form->addElement($checkbox_notify_acpt_chal);
425
426
        // Display checkbox, initially checked.
427
428
        $checked_value = 1;
429
430
        $checkbox_notify_move = new XoopsFormCheckBox('', 'notify_move', $checked_value);
431
432
        $checkbox_notify_move->addOption($checked_value, _MD_CHESS_NEVT_MOVE_CAP);
433
434
        $form->addElement($checkbox_notify_move);
435
    }
436
437
    $buttons = new XoopsFormElementTray('');
438
439
    $buttons->addElement(new XoopsFormButton('', 'submit_challenge3', _MD_CHESS_CREATE_SUBMIT, 'submit'));
440
441
    $buttons->addElement(new XoopsFormButton('', 'cancel_challenge3', _MD_CHESS_CREATE_CANCEL, 'submit'));
442
443
    $form->addElement($buttons);
444
445
    $form->display();
446
}
447
448
/**
449
 * Generate form to get acceptance of a challenge.
450
 *
451
 * @param int $challenge_id Challenge ID
452
 */
453
function chess_show_accept_form($challenge_id)
454
{
455
    global $xoopsDB, $xoopsUser;
456
457
    $challenges_table = $xoopsDB->prefix('chess_challenges');
458
459
    $result = $xoopsDB->query(
460
        trim(
461
            "
462
        SELECT game_type, fen, color_option, player1_uid, player2_uid, UNIX_TIMESTAMP(create_date) as create_date, is_rated
463
        FROM   $challenges_table
464
        WHERE  challenge_id = '$challenge_id'
465
    "
466
        )
467
    );
468
469
    if ($xoopsDB->getRowsNum($result) < 1) {
470
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_GAME_NOT_FOUND);
471
    }
472
473
    $row = $xoopsDB->fetchArray($result);
474
475
    $xoopsDB->freeRecordSet($result);
476
477
    $form = new XoopsThemeForm(_MD_CHESS_ACCEPT_FORM, 'accept_form', 'create.php', 'post', true);
478
479
    $form->addElement(new XoopsFormHidden('challenge_id', $challenge_id));
480
481
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_DATE_CREATED . ':', formatTimestamp($row['create_date'], 'm')));
482
483
    $memberHandler = xoops_getHandler('member');
484
485
    switch ($row['game_type']) {
486
        case _CHESS_GAMETYPE_OPEN:
487
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_OPEN;
488
            break;
489
        case _CHESS_GAMETYPE_USER:
490
            $player2_user     = $memberHandler->getUser($row['player2_uid']);
491
            $player2_username = is_object($player2_user) ? $player2_user->getVar('uname') : '?';
492
            $label_gametype   = _MD_CHESS_LABEL_GAMETYPE_USER . ': ' . $player2_username;
493
            break;
494
        case _CHESS_GAMETYPE_SELF:
495
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_SELF;
496
            break;
497
        default:
498
            $label_gametype = _MD_CHESS_LABEL_ERROR;
499
            break;
500
    }
501
502
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_GAMETYPE . ':', $label_gametype));
503
504
    $player1_user = $memberHandler->getUser($row['player1_uid']);
505
506
    $player1_username = is_object($player1_user) ? $player1_user->getVar('uname') : '?';
507
508
    $form->addElement(
509
        new XoopsFormLabel(
510
            _MD_CHESS_LABEL_CHALLENGER . ':', "<a href='" . XOOPS_URL . "/modules/chess/player_stats.php?player_uid={$row['player1_uid']}'>$player1_username</a>"
511
        )
512
    );
513
514
    $player2_username = $xoopsUser ? $xoopsUser->getVar('uname') : '?';
515
516
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_OPPONENT . ':', $player2_username));
517
518
    if (!empty($row['fen'])) {
519
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_FEN_SETUP . ':', $row['fen']));
520
    }
521
522
    if (_CHESS_COLOROPTION_OPPONENT == $row['color_option']) {
523
        $radio_color = new XoopsFormRadio(_MD_CHESS_LABEL_COLOR . ':', 'coloroption', _CHESS_COLOROPTION_RANDOM);
524
525
        $radio_color->addOption(_CHESS_COLOROPTION_RANDOM, _MD_CHESS_RADIO_COLOR_RANDOM);
526
527
        $radio_color->addOption(_CHESS_COLOROPTION_WHITE, _MD_CHESS_RADIO_COLOR_WHITE);
528
529
        $radio_color->addOption(_CHESS_COLOROPTION_BLACK, _MD_CHESS_RADIO_COLOR_BLACK);
530
531
        $form->addElement($radio_color);
532
    } else {
533
        switch ($row['color_option']) {
534
            case _CHESS_COLOROPTION_RANDOM:
535
                $label_coloroption = _MD_CHESS_RADIO_COLOR_RANDOM;
536
                break;
537
            case _CHESS_COLOROPTION_WHITE:
538
                $label_coloroption = _MD_CHESS_RADIO_COLOR_BLACK; // player1 white, player2 black
539
                break;
540
            case _CHESS_COLOROPTION_BLACK:
541
                $label_coloroption = _MD_CHESS_RADIO_COLOR_WHITE; // player1 black, player2 white
542
                break;
543
            default:
544
                $label_coloroption = _MD_CHESS_LABEL_ERROR;
545
                break;
546
        }
547
548
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_COLOR . ':', $label_coloroption));
549
    }
550
551
    if ('none' != chess_moduleConfig('rating_system')) {
552
        $form->addElement(new XoopsFormLabel(_MD_CHESS_RATED_GAME . ':', $row['is_rated'] ? _YES : _NO));
553
    }
554
555
    // Display notification-subscribe checkbox, initially checked.
556
557
    $checked_value = 1;
558
559
    $checkbox_notify_move = new XoopsFormCheckBox('', 'notify_move', $checked_value);
560
561
    $checkbox_notify_move->addOption($checked_value, _MD_CHESS_NEVT_MOVE_CAP);
562
563
    $form->addElement($checkbox_notify_move);
564
565
    $tray = new XoopsFormElementTray('');
566
567
    $tray->addElement(new XoopsFormButton('', 'submit_accept', _MD_CHESS_CREATE_ACCEPT, 'submit'));
568
569
    $tray->addElement(new XoopsFormButton('', 'cancel_accept', _MD_CHESS_CREATE_CANCEL, 'submit'));
570
571
    $form->addElement($tray);
572
573
    $form->display();
574
}
575
576
/**
577
 * Generate form to delete challenge.
578
 *
579
 * @param int    $challenge_id      Challenge ID
580
 * @param bool   $show_arbiter_ctrl True if form generated from admin page
581
 * @param string $error_msg         Error message to display
582
 */
583
function chess_show_delete_form($challenge_id, $show_arbiter_ctrl, $error_msg = '')
584
{
585
    global $xoopsDB;
586
587
    $challenges_table = $xoopsDB->prefix('chess_challenges');
588
589
    $result = $xoopsDB->query(
590
        trim(
591
            "
592
        SELECT game_type, fen, color_option, player1_uid, player2_uid, UNIX_TIMESTAMP(create_date) as create_date, is_rated
593
        FROM   $challenges_table
594
        WHERE  challenge_id = '$challenge_id'
595
    "
596
        )
597
    );
598
599
    if ($xoopsDB->getRowsNum($result) < 1) {
600
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_GAME_NOT_FOUND);
601
    }
602
603
    $row = $xoopsDB->fetchArray($result);
604
605
    $xoopsDB->freeRecordSet($result);
606
607
    $form = new XoopsThemeForm(_MD_CHESS_DELETE_FORM, 'delete_form', 'create.php', 'post', true);
608
609
    $form->addElement(new XoopsFormHidden('challenge_id', $challenge_id));
610
611
    if ($show_arbiter_ctrl) {
612
        $form->addElement(new XoopsFormHidden('show_arbiter_ctrl', $show_arbiter_ctrl));
0 ignored issues
show
Bug introduced by
$show_arbiter_ctrl of type true is incompatible with the type string expected by parameter $value of XoopsFormHidden::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

612
        $form->addElement(new XoopsFormHidden('show_arbiter_ctrl', /** @scrutinizer ignore-type */ $show_arbiter_ctrl));
Loading history...
613
    }
614
615
    if ($error_msg) {
616
        $form->addElement(new XoopsFormLabel(_MD_CHESS_ERROR . ': ', '<div class="errorMsg">' . $error_msg . '</div>'));
617
    }
618
619
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_DATE_CREATED . ':', formatTimestamp($row['create_date'], 'm')));
620
621
    $memberHandler = xoops_getHandler('member');
622
623
    switch ($row['game_type']) {
624
        case _CHESS_GAMETYPE_OPEN:
625
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_OPEN;
626
            break;
627
        case _CHESS_GAMETYPE_USER:
628
            $player2_user     = $memberHandler->getUser($row['player2_uid']);
629
            $player2_username = is_object($player2_user) ? $player2_user->getVar('uname') : '?';
630
            $label_gametype   = _MD_CHESS_LABEL_GAMETYPE_USER . ': ' . $player2_username;
631
            break;
632
        case _CHESS_GAMETYPE_SELF:
633
            $label_gametype = _MD_CHESS_LABEL_GAMETYPE_SELF;
634
            break;
635
        default:
636
            $label_gametype = _MD_CHESS_LABEL_ERROR;
637
            break;
638
    }
639
640
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_GAMETYPE . ':', $label_gametype));
641
642
    $player1_user = $memberHandler->getUser($row['player1_uid']);
643
644
    $player1_username = is_object($player1_user) ? $player1_user->getVar('uname') : '?';
645
646
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_CHALLENGER . ':', $player1_username));
647
648
    if (!empty($row['fen'])) {
649
        $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_FEN_SETUP . ':', $row['fen']));
650
    }
651
652
    switch ($row['color_option']) {
653
        case _CHESS_COLOROPTION_OPPONENT:
654
            $label_coloroption = _MD_CHESS_RADIO_COLOR_OPPONENT;
655
            break;
656
        case _CHESS_COLOROPTION_RANDOM:
657
            $label_coloroption = _MD_CHESS_RADIO_COLOR_RANDOM;
658
            break;
659
        case _CHESS_COLOROPTION_WHITE:
660
            $label_coloroption = _MD_CHESS_RADIO_COLOR_WHITE;
661
            break;
662
        case _CHESS_COLOROPTION_BLACK:
663
            $label_coloroption = _MD_CHESS_RADIO_COLOR_BLACK;
664
            break;
665
        default:
666
            $label_coloroption = _MD_CHESS_LABEL_ERROR;
667
            break;
668
    }
669
670
    $form->addElement(new XoopsFormLabel(_MD_CHESS_LABEL_COLOR . ':', $label_coloroption));
671
672
    if ('none' != chess_moduleConfig('rating_system')) {
673
        $form->addElement(new XoopsFormLabel(_MD_CHESS_RATED_GAME . ':', $row['is_rated'] ? _YES : _NO));
674
    }
675
676
    // Display confirm-delete checkbox, initially unchecked.
677
678
    $checked_value = 1;
679
680
    $checkbox_confirm_delete = new XoopsFormCheckBox('', 'confirm_delete', !$checked_value);
681
682
    $checkbox_confirm_delete->addOption($checked_value, _MD_CHESS_CONFIRM_DELETE);
683
684
    $tray = new XoopsFormElementTray('');
685
686
    $tray->addElement(new XoopsFormButton('', 'submit_delete', _MD_CHESS_CREATE_DELETE, 'submit'));
687
688
    $tray->addElement($checkbox_confirm_delete);
689
690
    $form->addElement($tray);
691
692
    $form->display();
693
}
694
695
/**
696
 * Accept a challenge.
697
 *
698
 * @param int    $challenge_id        Challenge ID
699
 * @param string $coloroption         _CHESS_COLOROPTION_OPPONENT, _CHESS_COLOROPTION_RANDOM, _CHESS_COLOROPTION_WHITE or _CHESS_COLOROPTION_BLACK
700
 * @param bool   $notify_move_player2 If true, subscribe the accepter to receive a notification when a new move is made.
701
 * @throws \Exception
702
 */
703
function chess_accept_challenge($challenge_id, $coloroption, $notify_move_player2 = false)
704
{
705
    global $xoopsDB, $xoopsUser;
706
707
    $challenges_table = $xoopsDB->prefix('chess_challenges');
708
709
    $result = $xoopsDB->query(
710
        trim(
711
            "
712
        SELECT game_type, fen, color_option, notify_move_player1, player1_uid, player2_uid, UNIX_TIMESTAMP(create_date) as create_date, is_rated
713
        FROM   $challenges_table
714
        WHERE  challenge_id = '$challenge_id'
715
    "
716
        )
717
    );
718
719
    if ($xoopsDB->getRowsNum($result) < 1) {
720
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_GAME_NOT_FOUND);
721
    }
722
723
    $row = $xoopsDB->fetchArray($result);
724
725
    $xoopsDB->freeRecordSet($result);
726
727
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
728
729
    if (_CHESS_GAMETYPE_USER == $row['game_type'] && $uid != $row['player2_uid']) {
730
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_WRONG_PLAYER2);
731
    } elseif ($uid == $row['player1_uid']) {
732
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_SAME_PLAYER2);
733
    }
734
735
    switch ($row['color_option']) {
736
        case _CHESS_COLOROPTION_OPPONENT:
737
            switch ($coloroption) {
738
                default:
739
                case _CHESS_COLOROPTION_RANDOM:
740
                    if (1 == random_int(1, 2)) {
741
                        $white_uid = $row['player1_uid'];
742
                        $black_uid = $uid;
743
                    } else {
744
                        $white_uid = $uid;
745
                        $black_uid = $row['player1_uid'];
746
                    }
747
                    break;
748
                case _CHESS_COLOROPTION_WHITE:
749
                    $white_uid = $uid;
750
                    $black_uid = $row['player1_uid'];
751
                    break;
752
                case _CHESS_COLOROPTION_BLACK:
753
                    $white_uid = $row['player1_uid'];
754
                    $black_uid = $uid;
755
                    break;
756
            }
757
            break;
758
        default:
759
        case _CHESS_COLOROPTION_RANDOM:
760
            if (1 == random_int(1, 2)) {
761
                $white_uid = $row['player1_uid'];
762
763
                $black_uid = $uid;
764
            } else {
765
                $white_uid = $uid;
766
767
                $black_uid = $row['player1_uid'];
768
            }
769
            break;
770
        case _CHESS_COLOROPTION_WHITE:
771
            $white_uid = $row['player1_uid'];
772
            $black_uid = $uid;
773
            break;
774
        case _CHESS_COLOROPTION_BLACK:
775
            $white_uid = $uid;
776
            $black_uid = $row['player1_uid'];
777
            break;
778
    }
779
780
    $game_id = chess_create_game($white_uid, $black_uid, $row['fen'], $row['is_rated'], $row['notify_move_player1'] ? $row['player1_uid'] : 0, $notify_move_player2);
781
782
    $xoopsDB->query("DELETE FROM $challenges_table WHERE challenge_id = '$challenge_id'");
783
784
    if ($xoopsDB->errno()) {
785
        trigger_error($xoopsDB->errno() . ':' . $xoopsDB->error(), E_USER_ERROR);
786
    }
787
788
    // Notify player 1 that his challenge has been accepted (if he has subscribed to the notification).
789
790
    $player2_username = $xoopsUser ? $xoopsUser->getVar('uname') : '*unknown*';
791
792
    $notificationHandler = xoops_getHandler('notification');
793
794
    $extra_tags = ['CHESS_PLAYER' => $player2_username, 'CHESS_GAME_ID' => $game_id];
795
796
    $notificationHandler->triggerEvent('global', 0, 'notify_accept_challenge', $extra_tags, [$row['player1_uid']]);
0 ignored issues
show
Bug introduced by
The method triggerEvent() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

796
    $notificationHandler->/** @scrutinizer ignore-call */ 
797
                          triggerEvent('global', 0, 'notify_accept_challenge', $extra_tags, [$row['player1_uid']]);
Loading history...
797
798
    redirect_header(XOOPS_URL . "/modules/chess/game.php?game_id=$game_id", _CHESS_REDIRECT_DELAY_SUCCESS, _MD_CHESS_GAME_CREATED);
799
}
800
801
/**
802
 * Determine whether current user offered the specified challenge.
803
 *
804
 * @param int $challenge_id Challenge ID
805
 * @return bool
806
 */
807
function chess_is_challenger($challenge_id)
808
{
809
    global $xoopsDB, $xoopsUser;
810
811
    $challenges_table = $xoopsDB->prefix('chess_challenges');
812
813
    $result = $xoopsDB->query("SELECT player1_uid FROM $challenges_table WHERE challenge_id = '$challenge_id'");
814
815
    if ($xoopsDB->getRowsNum($result) < 1) {
816
        redirect_header(XOOPS_URL . '/modules/chess/', _CHESS_REDIRECT_DELAY_FAILURE, _MD_CHESS_GAME_NOT_FOUND);
817
    }
818
819
    $row = $xoopsDB->fetchArray($result);
820
821
    $xoopsDB->freeRecordSet($result);
822
823
    $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
824
825
    return $uid == $row['player1_uid'];
826
}
827
828
/**
829
 * Create a new challenge in the database.
830
 *
831
 * @param string $gametype            _CHESS_GAMETYPE_OPEN, _CHESS_GAMETYPE_USER or _CHESS_GAMETYPE_SELF
832
 * @param string $fen                 FEN setup
833
 * @param string $coloroption         _CHESS_COLOROPTION_OPPONENT, _CHESS_COLOROPTION_RANDOM, _CHESS_COLOROPTION_WHITE or _CHESS_COLOROPTION_BLACK
834
 * @param int    $rated               '1' if rated, '0' if not rated
835
 * @param bool   $notify_accept       Subscribe/unsubscribe the challenger for receiving a notification when the challenge is accepted.
836
 * @param bool   $notify_move_player1 If true, subscribe the challenger to receive a notification when a new move is made.
837
 * @param int    $opponent_uid        Opponent's user ID ('0' for open challenge)
838
 */
839
function chess_create_challenge($gametype, $fen, $coloroption, $rated, $notify_accept, $notify_move_player1, $opponent_uid = 0)
840
{
841
    #$where = __CLASS__ . '::' . __FUNCTION__;#*#DEBUG#
842
843
    #echo "In $where\n";#*#DEBUG#
844
845
    global $xoopsUser;
846
847
    $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
848
849
    $myts = MyTextSanitizer::getInstance();
850
851
    $fen_q = $myts->addSlashes($fen);
852
853
    #trigger_error("inserting new game'", E_USER_NOTICE);#*#DEBUG#
854
855
    global $xoopsDB;
856
857
    $table = $xoopsDB->prefix('chess_challenges');
858
859
    $xoopsDB->query(
860
        trim(
861
            "
862
        INSERT INTO $table
863
        SET
864
            game_type           = '$gametype',
865
            fen                 = '$fen_q',
866
            color_option        = '$coloroption',
867
            notify_move_player1 = '$notify_move_player1',
868
            player1_uid         = '$uid',
869
            player2_uid         = '$opponent_uid',
870
            create_date         = NOW(),
871
            is_rated            = '$rated'
872
    "
873
        )
874
    );
875
876
    if ($xoopsDB->errno()) {
877
        trigger_error($xoopsDB->errno() . ':' . $xoopsDB->error(), E_USER_ERROR);
878
    }
879
880
    $challenge_id = $xoopsDB->getInsertId();
881
882
    $notificationHandler = xoops_getHandler('notification');
883
884
    // Update the challenger's subscription for receiving a notification when the challenge is accepted.
885
886
    if ($notify_accept) {
887
        $notificationHandler->subscribe('global', 0, 'notify_accept_challenge');
0 ignored issues
show
Bug introduced by
The method subscribe() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

887
        $notificationHandler->/** @scrutinizer ignore-call */ 
888
                              subscribe('global', 0, 'notify_accept_challenge');
Loading history...
888
    } else {
889
        $notificationHandler->unsubscribe('global', 0, 'notify_accept_challenge');
0 ignored issues
show
Bug introduced by
The method unsubscribe() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

889
        $notificationHandler->/** @scrutinizer ignore-call */ 
890
                              unsubscribe('global', 0, 'notify_accept_challenge');
Loading history...
890
    }
891
892
    // Notify any subscribers that a challenge has been offered.
893
894
    $player1_username = $xoopsUser ? $xoopsUser->getVar('uname') : '*unknown*';
895
896
    $extra_tags = ['CHESS_CHALLENGER' => $player1_username, 'CHESS_CHALLENGE_ID' => $challenge_id];
897
898
    if (_CHESS_GAMETYPE_OPEN == $gametype) {
899
        $notificationHandler->triggerEvent('global', 0, 'notify_challenge_open', $extra_tags);
900
    } elseif (_CHESS_GAMETYPE_USER == $gametype) {
901
        $notificationHandler->triggerEvent('global', 0, 'notify_challenge_user', $extra_tags, [$opponent_uid]);
902
    }
903
}
904
905
/**
906
 * Delete a challenge from the database.
907
 *
908
 * @param int $challenge_id Challenge ID
909
 */
910
function chess_delete_challenge($challenge_id)
911
{
912
    global $xoopsDB;
913
914
    $table = $xoopsDB->prefix('chess_challenges');
915
916
    $xoopsDB->query("DELETE FROM $table WHERE challenge_id='$challenge_id'");
917
918
    if ($xoopsDB->errno()) {
919
        trigger_error($xoopsDB->errno() . ':' . $xoopsDB->error(), E_USER_ERROR);
920
    }
921
}
922
923
/**
924
 * Create a new game in the database.
925
 *
926
 * @param int    $white_uid               White's user ID
927
 * @param int    $black_uid               Black's user ID
928
 * @param string $fen                     FEN setup
929
 * @param int    $rated                   '1' if rated, '0' if not rated
930
 * @param int    $notify_move_player1_uid If nonzero, subscribe the challenger to receive a notification when a new move is made.
931
 * @param bool   $notify_move_player2     If true, subscribe the accepter to receive a notification when a new move is made.
932
 * @return int
933
 */
934
function chess_create_game($white_uid, $black_uid, $fen, $rated, $notify_move_player1_uid = 0, $notify_move_player2 = false)
935
{
936
    #$where = __CLASS__ . '::' . __FUNCTION__;#*#DEBUG#
937
938
    #echo "In $where\n";#*#DEBUG#
939
940
    #var_dump('white_uid', $white_uid, 'black_uid', $black_uid);#*#DEBUG#
941
942
    $chessgame = new Chess\ChessGame($fen);
0 ignored issues
show
Bug introduced by
The type XoopsModules\Chess\ChessGame was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
943
944
    empty($chessgame->error) or trigger_error('chessgame invalid', E_USER_ERROR);
945
946
    $gamestate = $chessgame->gamestate();
947
948
    is_array($gamestate) or trigger_error('gamestate invalid', E_USER_ERROR);
949
950
    #trigger_error("inserting new game'", E_USER_NOTICE);#*#DEBUG#
951
952
    $myts = MyTextSanitizer::getInstance();
953
954
    $fen_q = $myts->addSlashes($fen);
955
956
    global $xoopsDB;
957
958
    $table = $xoopsDB->prefix('chess_games');
959
960
    $xoopsDB->query(
961
        trim(
962
            "
963
        INSERT INTO $table
964
        SET
965
            white_uid                    = '$white_uid',
966
            black_uid                    = '$black_uid',
967
            create_date                  = NOW(),
968
            start_date                   = '0000-00-00 00:00:00',
969
            last_date                    = '0000-00-00 00:00:00',
970
            fen_piece_placement          = '{$gamestate['fen_piece_placement']}',
971
            fen_active_color             = '{$gamestate['fen_active_color']}',
972
            fen_castling_availability    = '{$gamestate['fen_castling_availability']}',
973
            fen_en_passant_target_square = '{$gamestate['fen_en_passant_target_square']}',
974
            fen_halfmove_clock           = '{$gamestate['fen_halfmove_clock']}',
975
            fen_fullmove_number          = '{$gamestate['fen_fullmove_number']}',
976
            pgn_fen                      = '$fen_q',
977
            pgn_result                   = '{$gamestate['pgn_result']}',
978
            pgn_movetext                 = '{$gamestate['pgn_movetext']}',
979
            is_rated                     = '$rated'
980
    "
981
        )
982
    );
983
984
    if ($xoopsDB->errno()) {
985
        trigger_error($xoopsDB->errno() . ':' . $xoopsDB->error(), E_USER_ERROR);
986
    }
987
988
    $game_id = $xoopsDB->getInsertId();
989
990
    $notificationHandler = xoops_getHandler('notification');
991
992
    // If requested, subscribe the challenger to receive a notification when a new move is made.
993
994
    if ($notify_move_player1_uid) {
995
        $notificationHandler->subscribe('game', $game_id, 'notify_game_move', null, null, $notify_move_player1_uid);
996
    }
997
998
    // If requested, subscribe the accepter to receive a notification when a new move is made.
999
1000
    if ($notify_move_player2) {
1001
        $notificationHandler->subscribe('game', $game_id, 'notify_game_move');
1002
    }
1003
1004
    return $game_id;
1005
}
1006
1007
/**
1008
 * Check whether a FEN setup is valid.
1009
 *
1010
 * @param string $fen FEN setup
1011
 * @return string  Empty string if FEN setup is valid, otherwise contains error message.
1012
 */
1013
function chess_fen_error($fen)
1014
{
1015
    if (!empty($fen)) {
1016
        $chessgame = new Chess\ChessGame($fen);
1017
1018
        $fen_error = $chessgame->error;
1019
    } else {
1020
        $fen_error = '';
1021
    }
1022
1023
    return $fen_error;
1024
}
1025
1026
/**
1027
 * Get user ID of specified chess opponent.
1028
 *
1029
 * This function is used to check whether the specified opponent is available, when offering an individual challenge.
1030
 *
1031
 * @param string $username Opponent's username
1032
 * @return int Opponent's user ID if opponent is registered and allowed to play chess, otherwise zero.
1033
 */
1034
function chess_opponent_uid($username)
1035
{
1036
    $uid = chess_uname_to_uid($username);
1037
1038
    $can_play = $uid > 0 ? chess_can_play($uid) : false;
1039
1040
    return $can_play ? $uid : 0;
1041
}
1042