Passed
Push — master ( f0fd80...9c2eb6 )
by Michael
33s queued 12s
created

loadTableFromArrayWithReplace()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 25
nc 11
nop 4
dl 0
loc 41
rs 8.8977
c 1
b 0
f 1
1
<?php
2
3
declare(strict_types=1);
4
/*
5
 You may not change or alter any portion of this comment or credits
6
 of supporting developers from this source code or any supporting source code
7
 which is considered copyrighted (c) material of the original comment or credit authors.
8
 
9
 This program is distributed in the hope that it will be useful,
10
 but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
*/
13
14
/**
15
 * @category        Module
16
 * @package         suico
17
 * @copyright       {@link https://xoops.org/ XOOPS Project}
18
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
19
 * @author          Marcello Brandão aka  Suico, Mamba, LioMJ  <https://xoops.org>
20
 */
21
22
use Xmf\Database\TableLoad;
23
use Xmf\Request;
24
use Xmf\Yaml;
25
use XoopsModules\Suico\{
26
    Common,
27
    Helper,
28
    Common\Migrate,
29
    Utility
30
};
31
32
require_once dirname(__DIR__, 3) . '/include/cp_header.php';
33
require dirname(__DIR__) . '/preloads/autoloader.php';
34
$op                 = Request::getCmd('op', '');
35
$moduleDirName      = basename(dirname(__DIR__));
36
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
37
$helper             = Helper::getInstance();
38
// Load language files
39
$helper->loadLanguage('common');
40
switch ($op) {
41
    case 'load':
42
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0, 'REQUEST')) {
43
            if (!$GLOBALS['xoopsSecurity']->check()) {
44
                redirect_header('../admin/index.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
45
            }
46
            loadSampleData();
47
        } else {
48
            xoops_cp_header();
49
            xoops_confirm(
50
                [
51
                    'ok' => 1,
52
                    'op' => 'load',
53
                ],
54
                'index.php',
55
                sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'ADD_SAMPLEDATA_OK')),
56
                constant(
57
                    'CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'
58
                ),
59
                true
60
            );
61
            xoops_cp_footer();
62
        }
63
        break;
64
    case 'save':
65
        saveSampleData();
66
        break;
67
}
68
// XMF TableLoad for SAMPLE data
69
function loadSampleData()
70
{
71
    global $xoopsConfig;
72
    $moduleDirName      = basename(dirname(__DIR__));
73
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
74
    $utility            = new Utility();
75
    $configurator       = new Common\Configurator();
76
    $tables             = Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
77
    $language           = 'english/';
78
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
79
        $language = $xoopsConfig['language'] . '/';
80
    }
81
    // load module tables
82
    foreach ($tables as $table) {
83
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
84
        if (is_array($tabledata)) {
85
            TableLoad::truncateTable($table);
86
            TableLoad::loadTableFromArray($table, $tabledata);
87
        }
88
    }
89
90
    // load permissions
91
    $table     = 'group_permission';
92
    $tabledata = \Xmf\Yaml::readWrapped($language . $table . '.yml');
93
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
94
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
95
96
    //  ---  COPY test folder files ---------------
97
    if (is_array($configurator->copyTestFolders)
98
        && count(
99
               $configurator->copyTestFolders
100
           ) > 0) {
101
        //        $file =  dirname(__DIR__) . '/testdata/images/';
102
        foreach (
103
            array_keys(
104
                $configurator->copyTestFolders
105
            ) as $i
106
        ) {
107
            $src  = $configurator->copyTestFolders[$i][0];
108
            $dest = $configurator->copyTestFolders[$i][1];
109
            $utility::rcopy($src, $dest);
110
        }
111
    }
112
113
    addUsers();
114
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
115
}
116
117
function saveSampleData()
118
{
119
    global $xoopsConfig;
120
    $moduleDirName      = basename(dirname(__DIR__));
121
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
122
    $tables             = Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
123
    $language           = 'english/';
124
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
125
        $language = $xoopsConfig['language'] . '/';
126
    }
127
    $languageFolder = __DIR__ . '/' . $language;
128
    if (!file_exists($languageFolder . '/')) {
129
        Utility::createFolder($languageFolder . '/');
130
    }
131
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
132
    Utility::createFolder($exportFolder);
133
134
    // save module tables
135
    foreach ($tables as $table) {
136
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
137
    }
138
139
    // save permissions
140
    $criteria = new \CriteriaCompo();
141
    $criteria->add(new \Criteria('gperm_modid', \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid')));
0 ignored issues
show
Bug introduced by
It seems like Xmf\Module\Helper::getHe...Module()->getVar('mid') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

141
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid')));
Loading history...
142
    $skipColumns[] = 'gperm_id';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$skipColumns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $skipColumns = array(); before regardless.
Loading history...
143
    \Xmf\Database\TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
144
    unset($criteria);
145
146
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
147
}
148
149
function exportSchema()
150
{
151
    $moduleDirName      = basename(dirname(__DIR__));
152
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
153
    try {
154
        // TODO set exportSchema
155
        //        $migrate = new Migrate($moduleDirName);
156
        //        $migrate->saveCurrentSchema();
157
        //
158
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
159
    } catch (Throwable $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
160
        exit(constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_ERROR'));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
161
    }
162
}
163
164
165
/**
166
 * loadTableFromArrayWithReplace
167
 *
168
 * @param string $table  value with should be used insead of original value of $search
169
 *
170
 * @param array  $data   array of rows to insert
171
 *                       Each element of the outer array represents a single table row.
172
 *                       Each row is an associative array in 'column' => 'value' format.
173
 * @param string $search name of column for which the value should be replaced
174
 * @param        $replace
175
 * @return int number of rows inserted
176
 */
177
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
178
{
179
    /** @var \XoopsMySQLDatabase $db */
180
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
181
182
    $prefixedTable = $db->prefix($table);
183
    $count         = 0;
184
185
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
186
187
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
188
189
    foreach ($data as $row) {
190
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
191
        $valueClause = ' VALUES (';
192
        $first       = true;
193
        foreach ($row as $column => $value) {
194
            if ($first) {
195
                $first = false;
196
            } else {
197
                $insertInto  .= ', ';
198
                $valueClause .= ', ';
199
            }
200
201
            $insertInto .= $column;
202
            if ($search === $column) {
203
                $valueClause .= $db->quote($replace);
204
            } else {
205
                $valueClause .= $db->quote($value);
206
            }
207
        }
208
209
        $sql = $insertInto . ') ' . $valueClause . ')';
210
211
        $result = $db->queryF($sql);
212
        if (false !== $result) {
213
            ++$count;
214
        }
215
    }
216
217
    return $count;
218
}
219
220
/**
221
 * @return bool
222
 */
223
function addUsers()
224
{
225
    $ret = false;
226
    $xoopsDB = \XoopsDatabaseFactory::getDatabaseConnection();
227
228
    $sql = ' INSERT INTO `'
229
           . $xoopsDB->prefix('users')
230
           . '` (`uid`, `name`, `uname`, `email`, `url`, `user_avatar`, `user_regdate`, `user_icq`, `user_from`, `user_sig`, `user_viewemail`, `actkey`, `user_aim`, `user_yim`, `user_msnm`, `pass`, `posts`, `attachsig`, `rank`, `level`, `theme`, `timezone_offset`, `last_login`, `umode`, `uorder`, `notify_method`, `notify_mode`, `user_occ`, `bio`, `user_intrest`, `user_mailok`) VALUES ';
231
232
    $userInfo = [
233
        998  => "998, 'Joe Webmaster', 'webmaster', '[email protected]', 'www.xoops.org', 'avatars/avatar2.jpg', 1587372647, '', '', 'Go XOOPS! ', 0, '', '', '', '', '$2y$10$4NtwDxHimN4uxUya93Egu.VJYkYCKzgX3EtomGyYrf1bkY6rB.DTm', 0, 0, 7, 1, 'xswatch4', -5.0, 1588844591, 'flat', 0, 1, 0, '', '', '', 0",
234
        999  => "999, 'ALL Visitors', 'tester', '0fe6bf283000a9f9376ee72c69322b04', '', 'avatars/avatar4.jpg', 1585429986, '', '', 'User under suspension until 2020/5/3 23:16', 0, '', '', '', '', '$2y$10$tOYz4y.S.g4JYtmDnKfEKOpYh3Vivs8.UNZmdX.DVIBd9G5FZVaUi', 0, 0, 0, 1, '', 0.0, 1588838831, 'flat', 0, 1, 0, '', '', '', 1",
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tOYz4y seems to be never defined.
Loading history...
235
        1000 => "1000, 'Members Only', 'tester2', '[email protected]', '', 'avatars/avatar5.jpg', 1588229043, '', '', '', 0, '', '', '', '', '$2y$10$uYjy3xn0WyoDdUK5iXml/.lRhw/51SKeATx/FTEjZmL.2ibo.cF0q', 0, 0, 0, 1, '', 0.0, 1588844747, 'flat', 0, 1, 0, '', '', '', 1",
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $uYjy3xn0WyoDdUK5iXml seems to be never defined.
Loading history...
236
        1001 => "1001, 'Friends Only', 'tester3', '[email protected]', '', 'avatars/avatar6.jpg', 1588232828, '', '', '', 0, '90853319', '', '', '', '$2y$10$FPO.waxqjq.xXXJggTcSMuXpeXQU5UmuOCpX6Lo33d3o78bCh5w4a', 0, 0, 0, 1, 'xswatch4', 0.0, 1588845446, 'flat', 0, 1, 0, '', '', '', 1",
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $FPO seems to be never defined.
Loading history...
237
        1002 => "1002, 'Only Me', 'tester4', '[email protected]', '', 'avatars/avatar7.jpg', 1588800450, '', '', '', 0, '', '', '', '', '$2y$10$QF2FadecKKaSBFOsB9U5ne2o1FtPhbVWTurv3.zjwSpDxPFu9qqhm', 0, 0, 0, 1, '', 0.0, 1588845425, 'flat', 0, 1, 0, '', '', '', 1",
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $QF2FadecKKaSBFOsB9U5ne2o1FtPhbVWTurv3 seems to be never defined.
Loading history...
238
    ];
239
    // this is where the magic happens
240
    $it = new ArrayIterator($userInfo);
241
    // a new caching iterator gives us access to hasNext()
242
    $cit = new CachingIterator($it);
243
    // loop over the array
244
    foreach ($cit as $key => $value) {
245
        $criteria    = new \Criteria('uid', $key);
246
        $userHandler = xoops_getHandler('user');
247
        if (0 == $userHandler->getCount($criteria)) {
0 ignored issues
show
Bug introduced by
The method getCount() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of said class. However, the method does not exist in XoopsGroupHandler or XoopsConfigCategoryHandler or XoopsRankHandler or XoopsConfigOptionHandler or XoopsBlockHandler or XoopsImagesetHandler. Are you sure you never get one of those? ( Ignorable by Annotation )

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

247
        if (0 == $userHandler->/** @scrutinizer ignore-call */ getCount($criteria)) {
Loading history...
248
            // add to the query
249
            $sql .= '(' . $cit->current() . ')';
250
            // if there is another array member, add a comma
251
            if ($cit->hasNext()) {
252
                $sql .= ',';
253
            }
254
        }
255
    }
256
257
    if (',' === mb_substr($sql, -1)){
258
        $sql = mb_substr($sql, 0, -1);
259
    }
260
261
    $result = $xoopsDB->queryF($sql);
262
    if (false !== $result) {
263
     $ret = true;
264
    }
265
    return $ret;
266
267
}
268