Passed
Push — master ( 9267f6...861b02 )
by Michael
04:59 queued 10s
created

clearSampleData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

125
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()->getVar('mid')));
Loading history...
126
    $skipColumns[] = 'gperm_id';
127
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
128
    unset($criteria);
129
130
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'SAMPLEDATA_SUCCESS'));
131
}
132
133
function exportSchema()
134
{
135
    $moduleDirName      = basename(dirname(__DIR__));
136
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
137
    $helper             = Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
138
139
    try {
140
        // TODO set exportSchema
141
        //        $migrate = new Migrate($moduleDirName);
142
        //        $migrate->saveCurrentSchema();
143
        //
144
        //        redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
145
    } 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...
146
        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...
147
    }
148
}
149
150
/**
151
 * loadTableFromArrayWithReplace
152
 *
153
 * @param string $table  value with should be used insead of original value of $search
154
 *
155
 * @param array  $data   array of rows to insert
156
 *                       Each element of the outer array represents a single table row.
157
 *                       Each row is an associative array in 'column' => 'value' format.
158
 * @param string $search name of column for which the value should be replaced
159
 * @param        $replace
160
 * @return int number of rows inserted
161
 */
162
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
163
{
164
    /** @var \XoopsMySQLDatabase $db */
165
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
166
167
    $prefixedTable = $db->prefix($table);
168
    $count         = 0;
169
170
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
171
172
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
173
174
    foreach ($data as $row) {
175
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
176
        $valueClause = ' VALUES (';
177
        $first       = true;
178
        foreach ($row as $column => $value) {
179
            if ($first) {
180
                $first = false;
181
            } else {
182
                $insertInto  .= ', ';
183
                $valueClause .= ', ';
184
            }
185
186
            $insertInto .= $column;
187
            if ($search === $column) {
188
                $valueClause .= $db->quote($replace);
189
            } else {
190
                $valueClause .= $db->quote($value);
191
            }
192
        }
193
194
        $sql = $insertInto . ') ' . $valueClause . ')';
195
196
        $result = $db->queryF($sql);
197
        if (false !== $result) {
198
            ++$count;
199
        }
200
    }
201
202
    return $count;
203
}
204
205
function clearSampleData(){
206
    $moduleDirName      = basename(dirname(__DIR__));
207
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
208
    $helper             = Helper::getInstance();
209
    // Load language files
210
    $helper->loadLanguage('common');
211
    $tables = $helper->getModule()->getInfo('tables');
212
    // truncate module tables
213
    foreach ($tables as $table) {
214
        \Xmf\Database\TableLoad::truncateTable($table);
215
    }
216
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
217
}
218