mytplsadmin.php ➔ copy_templates_db2db()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 3
dl 0
loc 33
rs 9.0808
c 0
b 0
f 0
1
<?php
2
// ------------------------------------------------------------------------- //
3
//                              mytplsadmin.php                              //
4
//               - XOOPS templates admin for each modules -                  //
5
//                          GIJOE <http://www.peak.ne.jp/>                   //
6
// ------------------------------------------------------------------------- //
7
8
include_once dirname(dirname(dirname(__DIR__))) . '/include/cp_header.php';
9
include __DIR__ . '/admin_header.php';
10
//include_once XOOPS_ROOT_PATH . "/modules/" . $xoopsModule->getVar("dirname") . "/class/admin.php";
11
include_once dirname(__DIR__) . '/include/gtickets.php';
12
include_once XOOPS_ROOT_PATH . '/class/template.php';
13
14
// initials
15
$xoops_system_path = XOOPS_ROOT_PATH . '/modules/system';
16
$db                = XoopsDatabaseFactory::getDatabaseConnection();
17
$myts              = MyTextSanitizer::getInstance();
18
19
// determine language
20
$language = $xoopsConfig['language'];
21
if (!file_exists("{$xoops_system_path}/language/{$language}/admin/tplsets.php")) {
22
    $language = 'english';
23
}
24
25
// load language constants
26
// to prevent from notice that constants already defined
27
$error_reporting_level = error_reporting(0);
28
include_once "{$xoops_system_path}/constants.php";
29
include_once "{$xoops_system_path}/language/{$language}/admin.php";
30
include_once "{$xoops_system_path}/language/{$language}/admin/tplsets.php";
31
error_reporting($error_reporting_level);
32
33
// check $xoopsModule
34
if (!is_object($xoopsModule)) {
35
    redirect_header(XOOPS_URL . '/user.php', 1, _NOPERM);
36
}
37
38
// set target_module if specified by $_GET['dirname']
39
$moduleHandler = xoops_getHandler('module');
40
if (!empty($_GET['dirname'])) {
41
    $target_module = $moduleHandler->getByDirname($_GET['dirname']);
42
}
43
44
if (!empty($target_module) && is_object($target_module)) {
45
    // specified by dirname (for tplsadmin as an independent module)
46
    $target_mid         = $target_module->getVar('mid');
47
    $target_dirname     = $target_module->getVar('dirname');
48
    $target_dirname4sql = addslashes($target_dirname);
49
    $target_mname       = $target_module->getVar('name') . '&nbsp;' . sprintf('(%2.2f)', $target_module->getVar('version') / 100.0);
50
    $query4redirect     = '?dirname=' . urlencode(strip_tags($_GET['dirname']));
51
} else {
52
    // not specified by dirname (for 3rd party modules as mytplsadmin)
53
    $target_mid         = $xoopsModule->getVar('mid');
54
    $target_dirname     = $xoopsModule->getVar('dirname');
55
    $target_dirname4sql = addslashes($target_dirname);
56
    $target_mname       = $xoopsModule->getVar('name');
57
    $query4redirect     = '';
58
}
59
60
// check access right (needs system_admin of tplset)
61
$syspermHandler = xoops_getHandler('groupperm');
62 View Code Duplication
if (!$syspermHandler->checkRight('system_admin', XOOPS_SYSTEM_TPLSET, $xoopsUser->getGroups())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
63
    redirect_header(XOOPS_URL . '/user.php', 1, _NOPERM);
64
}
65
66
//**************//
67
// POST stages  //
68
//**************//
69
70
// Newly DB template clone (all of module)
71
if (!empty($_POST['clone_tplset_do']) && !empty($_POST['clone_tplset_from']) && !empty($_POST['clone_tplset_to'])) {
72
    // Ticket Check
73
    if (!$xoopsGTicket->check()) {
74
        redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
75
    }
76
77
    $tplset_from = $myts->stripSlashesGPC($_POST['clone_tplset_from']);
78
    $tplset_to   = $myts->stripSlashesGPC($_POST['clone_tplset_to']);
79
80
    //TODO: move text strings to language files
81
    // check tplset_name "from" and "to"
82
    if (!preg_match('/^[0-9A-Za-z_-]{1,16}$/', $_POST['clone_tplset_from'])) {
83
        die('A wrong template name is specified.');
84
    }
85
    if (!preg_match('/^[0-9A-Za-z_-]{1,16}$/', $_POST['clone_tplset_to'])) {
86
        die('A wrong template name is specified.');
87
    }
88
    list($is_exist) = $db->fetchRow($db->query('SELECT COUNT(*) FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_to) . "'"));
89
    if ($is_exist) {
90
        die('The template already exists.');
91
    }
92
    list($is_exist) = $db->fetchRow($db->query('SELECT COUNT(*) FROM ' . $db->prefix('tplset') . " WHERE tplset_name='" . addslashes($tplset_to) . "'"));
93
    if ($is_exist) {
94
        die('The template already exists.');
95
    }
96
    // insert tplset table
97
    $db->query('INSERT INTO ' . $db->prefix('tplset') . " SET tplset_name='" . addslashes($tplset_to) . "', tplset_desc='Created by tplsadmin', tplset_created=UNIX_TIMESTAMP()");
98
    copy_templates_db2db($tplset_from, $tplset_to, "tpl_module='$target_dirname4sql'");
99
    redirect_header("mytplsadmin.php?dirname={$target_dirname}", 1, _MD_MYLINKS_DBUPDATED);
100
    exit;
101
}
102
103
// DB to DB template copy (checked templates)
104
if (is_array(@$_POST['copy_do'])) {
105
    foreach ($_POST['copy_do'] as $tplset_from_tmp => $val) {
106
        if (!empty($val)) {
107
            // Ticket Check
108
            if (!$xoopsGTicket->check()) {
109
                redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
110
            }
111
112
            $tplset_from = $myts->stripSlashesGPC($tplset_from_tmp);
113
            if (empty($_POST['copy_to'][$tplset_from]) || $_POST['copy_to'][$tplset_from] == $tplset_from) {
114
                die('Specify valid tplset.');
115
            }
116
            if (empty($_POST["{$tplset_from}_check"])) {
117
                die('No template is specified');
118
            }
119
            $tplset_to = $myts->stripSlashesGPC($_POST['copy_to'][$tplset_from]);
120
            foreach ($_POST["{$tplset_from}_check"] as $tplfile_tmp => $val) {
121
                if (empty($val)) {
122
                    continue;
123
                }
124
                $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
125
                copy_templates_db2db($tplset_from, $tplset_to, "tpl_file='" . addslashes($tplfile) . "'");
126
            }
127
            redirect_header("mytplsadmin.php?dirname={$target_dirname}", 1, _MD_MYLINKS_DBUPDATED);
128
            exit;
129
        }
130
    }
131
}
132
133
// File to DB template copy (checked templates)
134
if (!empty($_POST['copyf2db_do'])) {
135
    // Ticket Check
136
    if (!$xoopsGTicket->check()) {
137
        redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
138
    }
139
140
    if (empty($_POST['copyf2db_to'])) {
141
        die('Specify valid tplset.');
142
    }
143
    if (empty($_POST['basecheck'])) {
144
        die('No template is specified');
145
    }
146
    $tplset_to = $myts->stripSlashesGPC($_POST['copyf2db_to']);
147
    foreach ($_POST['basecheck'] as $tplfile_tmp => $val) {
148
        if (empty($val)) {
149
            continue;
150
        }
151
        $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
152
        copy_templates_f2db($tplset_to, "tpl_file='" . addslashes($tplfile) . "'");
153
    }
154
    redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _MD_MYLINKS_DBUPDATED);
155
    exit;
156
}
157
158
// DB template remove (checked templates)
159
if (is_array(@$_POST['del_do'])) {
160
    foreach ($_POST['del_do'] as $tplset_from_tmp => $val) {
161
        if (!empty($val)) {
162
            // Ticket Check
163
            if (!$xoopsGTicket->check()) {
164
                redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
165
            }
166
167
            $tplset_from = $myts->stripSlashesGPC($tplset_from_tmp);
168
            if ($tplset_from == 'default') {
169
                die("You can't remove 'default' template.");
170
            }
171
            foreach ($_POST["{$tplset_from}_check"] as $tplfile_tmp => $val) {
172
                if (empty($val)) {
173
                    continue;
174
                }
175
                $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
176
                $result  = $db->query('SELECT tpl_id FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_from) . "' AND tpl_file='" . addslashes($tplfile) . "'");
177
                while (list($tpl_id) = $db->fetchRow($result)) {
178
                    $tpl_id = (int)$tpl_id;
179
                    $db->query('DELETE FROM ' . $db->prefix('tplfile') . " WHERE tpl_id=$tpl_id");
180
                    $db->query('DELETE FROM ' . $db->prefix('tplsource') . " WHERE tpl_id=$tpl_id");
181
                    //          xoops_template_touch( $tpl_id ); // TODO
182
                }
183
            }
184
            redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _MD_MYLINKS_DBUPDATED);
185
            exit;
186
        }
187
    }
188
}
189
190
//************//
191
// GET stage  //
192
//************//
193
194
// get tplsets
195
$sql             = 'SELECT distinct tpl_tplset FROM ' . $db->prefix('tplfile') . " ORDER BY tpl_tplset='default' DESC,tpl_tplset";
196
$srs             = $db->query($sql);
197
$tplsets         = array();
198
$tplsets_th4disp = '';
199
$tplset_options  = "<option value=''>----</option>\n";
200
while (list($tplset) = $db->fetchRow($srs)) {
201
    $tplset4disp = htmlspecialchars($tplset, ENT_QUOTES);
202
    $tplsets[]   = $tplset;
203
    $th_style    = $tplset == $xoopsConfig['template_set'] ? "style='color: yellow;'" : '';
204
    $tplsets_th4disp .= "<th $th_style><input type='checkbox' onclick=\"with(document.MainForm){for(i=0;i<length;i++){if(elements[i].type=='checkbox'&&elements[i].name.indexOf('{$tplset4disp}_check')>=0){elements[i].checked=this.checked;}}}\">DB-{$tplset4disp}</th>";
205
    $tplset_options .= "<option value='{$tplset4disp}'>{$tplset4disp}</option>\n";
206
}
207
208
// get tpl_file owned by the module
209
$sql = 'SELECT tpl_file,tpl_desc,tpl_type,COUNT(tpl_id) FROM ' . $db->prefix('tplfile') . " WHERE tpl_module='{$target_dirname4sql}' GROUP BY tpl_file ORDER BY tpl_type, tpl_file";
210
$frs = $db->query($sql);
211
212
xoops_cp_header();
213
214
$indexAdmin = new ModuleAdmin();
215
echo $indexAdmin->addNavigation(basename(__FILE__));
216
217
if (file_exists('./mymenu.php')) {
218
    include './mymenu.php';
219
}
220
221
echo "<h3 style='text-align:left;'>" . _AM_MYLINKS_TPLSETS . " : {$target_mname}</h3>\n";
222
223
// beginning of table & form
224
echo "<form name='MainForm' action='?dirname=" . htmlspecialchars($target_dirname, ENT_QUOTES) . "' method='post'>\n" . '  ' . $xoopsGTicket->getTicketHtml(__LINE__) . "\n" . "  <table class='outer'>\n" . "    <tr>\n" . '      <th>' . _AM_MYLINKS_FILENAME . "</th>\n" . "      <th>type</th>\n"
225
     . "      <th><input type='checkbox' onclick=\"with(document.MainForm){for(i=0;i<length;i++){if(elements[i].type=='checkbox'&&elements[i].name.indexOf('basecheck')>=0){elements[i].checked=this.checked;}}}\">file</th>\n" . "        {$tplsets_th4disp}\n" . "    </tr>\n";
226
227
// STYLE for distinguishing fingerprints
228
$fingerprint_styles = array(
229
    '',
230
    'background-color:#00FF00',
231
    'background-color:#00CC88',
232
    'background-color:#00FFFF',
233
    'background-color:#0088FF',
234
    'background-color:#FF8800',
235
    'background-color:#0000FF',
236
    'background-color:#FFFFFF'
237
);
238
239
// template ROWS
240
while (list($tpl_file, $tpl_desc, $type, $count) = $db->fetchRow($frs)) {
241
    $evenodd                 = @$evenodd == 'even' ? 'odd' : 'even';
242
    $fingerprint_style_count = 0;
243
244
    // information about the template
245
    echo "    <tr>\n" . "      <td class='{$evenodd}'>\n" . "        <dl>\n" . '          <dt>' . htmlspecialchars($tpl_file, ENT_QUOTES) . "</dt>\n" . '          <dd>' . htmlspecialchars($tpl_desc, ENT_QUOTES) . "</dd>\n" . "        </dl>\n" . "      </td>\n"
246
         . "      <td class='{$evenodd}'>{$type}<br>({$count})</td>\n";
247
248
    // the base file template column
249
    $basefilepath = XOOPS_ROOT_PATH . "/modules/{$target_dirname}/templates/" . ($type == 'block' ? 'blocks/' : '') . $tpl_file;
250
    if (file_exists($basefilepath)) {
251
        $fingerprint                = get_fingerprint(file($basefilepath));
252
        $fingerprints[$fingerprint] = 1;
253
        echo "      <td class='{$evenodd}'>" . formatTimestamp(filemtime($basefilepath), 'm') . '<br>' . substr($fingerprint, 0, 16) . '' . "<br><input type='checkbox' name='basecheck[$tpl_file]' value='1'></td>\n";
254
    } else {
255
        echo "      <td class='{$evenodd}'><br></td>";
256
    }
257
258
    // db template columns
259
    foreach ($tplsets as $tplset) {
260
        $tplset4disp = htmlspecialchars($tplset, ENT_QUOTES);
261
262
        // query for templates in db
263
        $drs     = $db->query('SELECT * FROM ' . $db->prefix('tplfile') . ' f NATURAL LEFT JOIN ' . $db->prefix('tplsource') . " s WHERE tpl_file='" . addslashes($tpl_file) . "' AND tpl_tplset='" . addslashes($tplset) . "'");
264
        $numrows = $db->getRowsNum($drs);
265
        $tpl     = $db->fetchArray($drs);
266
        if (empty($tpl['tpl_id'])) {
267
            echo "      <td class='{$evenodd}'>($numrows)</td>\n";
268
        } else {
269
            $fingerprint = get_fingerprint(explode("\n", $tpl['tpl_source']));
270
            if (isset($fingerprints[$fingerprint])) {
271
                $style = $fingerprints[$fingerprint];
272
            } else {
273
                $fingerprint_style_count++;
274
                $style                      = $fingerprint_styles[$fingerprint_style_count];
275
                $fingerprints[$fingerprint] = $style;
276
            }
277
            echo "      <td class='$evenodd' style='$style'>" . formatTimestamp($tpl['tpl_lastmodified'], 'm') . '<br>' . substr($fingerprint, 0, 16) . "<br><input type='checkbox' name='{$tplset4disp}_check[{$tpl_file}]' value='1'> &nbsp; <a href='mytplsform.php?tpl_file="
278
                 . htmlspecialchars($tpl['tpl_file'], ENT_QUOTES) . '&amp;tpl_tplset=' . htmlspecialchars($tpl['tpl_tplset'], ENT_QUOTES) . "'>" . _EDIT . "</a> ($numrows)</td>\n";
279
        }
280
    }
281
282
    echo "    </tr>\n";
283
}
284
285
// command submit ROW
286
echo "    <tr>\n" . "      <td class='head'>\n" . '         ' . _CLONE . ": <br>\n" . "         <select name='clone_tplset_from'>{$tplset_options}</select>-&gt;<input type='text' name='clone_tplset_to' size='8'><input type='submit' name='clone_tplset_do' value='" . _AM_MYLINKS_GENERATE . "'>\n"
287
     . "      </td>\n" . "      <td class='head'></td>\n" . "      <td class='head'>\n" . "        <input name='copyf2db_do' type='submit' value='copy to-&gt;'><br>\n" . "        <select name='copyf2db_to'>{$tplset_options}</select>\n" . "      </td>\n";
288
289
foreach ($tplsets as $tplset) {
290
    $tplset4disp = htmlspecialchars($tplset, ENT_QUOTES);
291
    echo "      <td class='head'>\n" . '        ' . ($tplset == 'default' ? '' : "<input name='del_do[{$tplset4disp}]' type='submit' value='" . _DELETE . "' onclick='return confirm(\"" . _DELETE . " OK?\");'><br>") . "\n"
292
         . "        <input name='copy_do[{$tplset4disp}]' type='submit' value='copy to-&gt;'><br>\n" . "        <select name='copy_to[{$tplset4disp}]'>$tplset_options</select>\n" . "      </td>\n";
293
}
294
295
echo "    </tr>\n" . "  </table>\n" . "</form>\n";
296
// end of table & form
297
include __DIR__ . '/admin_footer.php';
298
299
/**
300
 * @param $lines
301
 * @return string
302
 */
303
function get_fingerprint($lines)
304
{
305
    $str = '';
306
    foreach ($lines as $line) {
307
        if (trim($line)) {
308
            $str .= md5(trim($line));
309
        }
310
    }
311
312
    return md5($str);
313
}
314
315
/**
316
 * @param        $tplset_from
317
 * @param        $tplset_to
318
 * @param string $whr_append
319
 */
320
function copy_templates_db2db($tplset_from, $tplset_to, $whr_append = '1')
321
{
322
    global $db;
323
324
    // get tplfile and tplsource
325
    $result = $db->query("SELECT tpl_refid,tpl_module,'" . addslashes($tplset_to) . "',tpl_file,tpl_desc,tpl_lastmodified,tpl_lastimported,tpl_type,tpl_source FROM " . $db->prefix('tplfile') . ' NATURAL LEFT JOIN ' . $db->prefix('tplsource') . " WHERE tpl_tplset='" . addslashes($tplset_from)
326
                         . "' AND ($whr_append)");
327
328
    while ($row = $db->fetchArray($result)) {
329
        $tpl_source = array_pop($row);
330
        $drs        = $db->query('SELECT tpl_id FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_to) . "' AND ($whr_append) AND tpl_file='" . addslashes($row['tpl_file']) . "' AND tpl_refid='" . addslashes($row['tpl_refid']) . "'");
331
332
        if (!$db->getRowsNum($drs)) {
333
            // INSERT mode
334
            $sql = 'INSERT INTO ' . $db->prefix('tplfile') . ' (tpl_refid,tpl_module,tpl_tplset,tpl_file,tpl_desc,tpl_lastmodified,tpl_lastimported,tpl_type) VALUES (';
335
            foreach ($row as $colval) {
336
                $sql .= "'" . addslashes($colval) . "',";
337
            }
338
            $db->query(substr($sql, 0, -1) . ')');
339
            $tpl_id = $db->getInsertId();
340
            $db->query('INSERT INTO ' . $db->prefix('tplsource') . " SET tpl_id='$tpl_id', tpl_source='" . addslashes($tpl_source) . "'");
341
            xoops_template_touch($tpl_id);
342
        } else {
343
            while (list($tpl_id) = $db->fetchRow($drs)) {
344
                // UPDATE mode
345
                $db->query('UPDATE ' . $db->prefix('tplfile') . " SET tpl_refid='" . addslashes($row['tpl_refid']) . "',tpl_desc='" . addslashes($row['tpl_desc']) . "',tpl_lastmodified='" . addslashes($row['tpl_lastmodified']) . "',tpl_lastimported='" . addslashes($row['tpl_lastimported'])
346
                           . "',tpl_type='" . addslashes($row['tpl_type']) . "' WHERE tpl_id='{$tpl_id}'");
347
                $db->query('UPDATE ' . $db->prefix('tplsource') . " SET tpl_source='" . addslashes($tpl_source) . "' WHERE tpl_id='$tpl_id'");
348
                xoops_template_touch($tpl_id);
349
            }
350
        }
351
    }
352
}
353
354
/**
355
 * @param        $tplset_to
356
 * @param string $whr_append
357
 */
358
function copy_templates_f2db($tplset_to, $whr_append = '1')
359
{
360
    global $db;
361
362
    // get tplsource
363
    $result = $db->query('SELECT * FROM ' . $db->prefix('tplfile') . "  WHERE tpl_tplset='default' AND ($whr_append)");
364
365
    while ($row = $db->fetchArray($result)) {
366
        $basefilepath = XOOPS_ROOT_PATH . '/modules/' . $row['tpl_module'] . '/templates/' . ($row['tpl_type'] == 'block' ? 'blocks/' : '') . $row['tpl_file'];
367
368
        $tpl_source   = rtrim(implode('', file($basefilepath)));
369
        $lastmodified = filemtime($basefilepath);
370
371
        $drs = $db->query('SELECT tpl_id FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_to) . "' AND ($whr_append) AND tpl_file='" . addslashes($row['tpl_file']) . "' AND tpl_refid='" . addslashes($row['tpl_refid']) . "'");
372
373
        if (!$db->getRowsNum($drs)) {
374
            // INSERT mode
375
            $sql = 'INSERT INTO ' . $db->prefix('tplfile') . " SET tpl_refid='" . addslashes($row['tpl_refid']) . "',tpl_desc='" . addslashes($row['tpl_desc']) . "',tpl_lastmodified='" . addslashes($lastmodified) . "',tpl_type='" . addslashes($row['tpl_type']) . "',tpl_tplset='"
376
                   . addslashes($tplset_to) . "',tpl_file='" . addslashes($row['tpl_file']) . "',tpl_module='" . addslashes($row['tpl_module']) . "'";
377
            $db->query($sql);
378
            $tpl_id = $db->getInsertId();
379
            $db->query('INSERT INTO ' . $db->prefix('tplsource') . " SET tpl_id='{$tpl_id}', tpl_source='" . addslashes($tpl_source) . "'");
380
            xoops_template_touch($tpl_id);
381
        } else {
382
            while (list($tpl_id) = $db->fetchRow($drs)) {
383
                // UPDATE mode
384
                $db->query('UPDATE ' . $db->prefix('tplfile') . " SET tpl_lastmodified='" . addslashes($lastmodified) . "' WHERE tpl_id='{$tpl_id}'");
385
                $db->query('UPDATE ' . $db->prefix('tplsource') . " SET tpl_source='" . addslashes($tpl_source) . "' WHERE tpl_id='{$tpl_id}'");
386
                xoops_template_touch($tpl_id);
387
            }
388
        }
389
    }
390
}
391