mytplsadmin.php ➔ get_fingerprint()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 11
rs 9.9
c 0
b 0
f 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
 *
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
/**
13
 * @copyright   {@link http://xoops.org/ XOOPS Project}
14
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
15
 * @package
16
 * @since
17
 * @author       XOOPS Development Team,
18
 * @author       GIJ=CHECKMATE (PEAK Corp. http://www.peak.ne.jp/)
19
 */
20
21
require_once __DIR__ . '/../../../include/cp_header.php';
22
23
require_once __DIR__ . '/../include/gtickets.php';
24
require_once XOOPS_ROOT_PATH . '/class/template.php';
25
26
// initials
27
$xoops_system_path = XOOPS_ROOT_PATH . '/modules/system';
28
$db                = XoopsDatabaseFactory::getDatabaseConnection();
29
$myts              = MyTextSanitizer::getInstance();
30
31
// determine language
32
$language = $xoopsConfig['language'];
33
if (!file_exists("$xoops_system_path/language/$language/admin/tplsets.php")) {
34
    $language = 'english';
35
}
36
37
// load language constants
38
// to prevent from notice that constants already defined
39
$error_reporting_level = error_reporting(0);
40
require_once "$xoops_system_path/constants.php";
41
require_once "$xoops_system_path/language/$language/admin.php";
42
require_once "$xoops_system_path/language/$language/admin/tplsets.php";
43
error_reporting($error_reporting_level);
44
45
// check $xoopsModule
46
if (!is_object($xoopsModule)) {
47
    redirect_header(XOOPS_URL . '/user.php', 1, _NOPERM);
48
}
49
50
// set target_module if specified by $_GET['dirname']
51
/** @var XoopsModuleHandler $moduleHandler */
52
$moduleHandler = xoops_getHandler('module');
53
if (!empty($_GET['dirname'])) {
54
    $target_module = $moduleHandler->getByDirname($_GET['dirname']);
55
}
56
57
if (!empty($target_module) && is_object($target_module)) {
58
    // specified by dirname (for tplsadmin as an independent module)
59
    $target_mid         = $target_module->getVar('mid');
60
    $target_dirname     = $target_module->getVar('dirname');
61
    $target_dirname4sql = addslashes($target_dirname);
62
    $target_mname       = $target_module->getVar('name') . '&nbsp;' . sprintf('(%2.2f)', $target_module->getVar('version') / 100.0);
63
    $query4redirect     = '?dirname=' . urlencode(strip_tags($_GET['dirname']));
64
} else {
65
    // not specified by dirname (for 3rd party modules as mytplsadmin)
66
    $target_mid         = $xoopsModule->getVar('mid');
67
    $target_dirname     = $xoopsModule->getVar('dirname');
68
    $target_dirname4sql = addslashes($target_dirname);
69
    $target_mname       = $xoopsModule->getVar('name');
70
    $query4redirect     = '';
71
}
72
73
// check access right (needs system_admin of tplset)
74
$syspermHandler = xoops_getHandler('groupperm');
75 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...
76
    redirect_header(XOOPS_URL . '/user.php', 1, _NOPERM);
77
}
78
79
//**************//
80
// POST stages  //
81
//**************//
82
83
// Newly DB template clone (all of module)
84
if (!empty($_POST['clone_tplset_do']) && !empty($_POST['clone_tplset_from']) && !empty($_POST['clone_tplset_to'])) {
85
    // Ticket Check
86
    if (!$xoopsGTicket->check()) {
87
        redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
88
    }
89
90
    $tplset_from = $myts->stripSlashesGPC($_POST['clone_tplset_from']);
91
    $tplset_to   = $myts->stripSlashesGPC($_POST['clone_tplset_to']);
92
    // check tplset_name "from" and "to"
93
    if (!preg_match('/^[0-9A-Za-z_-]{1,16}$/', $_POST['clone_tplset_from'])) {
94
        die('a wrong template name is specified.');
95
    }
96
    if (!preg_match('/^[0-9A-Za-z_-]{1,16}$/', $_POST['clone_tplset_to'])) {
97
        die('a wrong template name is specified.');
98
    }
99
    list($is_exist) = $db->fetchRow($db->query('SELECT COUNT(*) FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_to) . "'"));
100
    if ($is_exist) {
101
        die('The template already exists.');
102
    }
103
    list($is_exist) = $db->fetchRow($db->query('SELECT COUNT(*) FROM ' . $db->prefix('tplset') . " WHERE tplset_name='" . addslashes($tplset_to) . "'"));
104
    if ($is_exist) {
105
        die('The template already exists.');
106
    }
107
    // insert tplset table
108
    $db->query('INSERT INTO ' . $db->prefix('tplset') . " SET tplset_name='" . addslashes($tplset_to) . "', tplset_desc='Created by tplsadmin', tplset_created=UNIX_TIMESTAMP()");
109
    copy_templates_db2db($tplset_from, $tplset_to, "tpl_module='$target_dirname4sql'");
110
    redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _AM_APCALAM_APCALDBUPDATED);
111
    exit;
112
}
113
114
// DB to DB template copy (checked templates)
115
if (is_array(@$_POST['copy_do'])) {
116
    foreach ($_POST['copy_do'] as $tplset_from_tmp => $val) {
117
        if (!empty($val)) {
118
            // Ticket Check
119
            if (!$xoopsGTicket->check()) {
120
                redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
121
            }
122
123
            $tplset_from = $myts->stripSlashesGPC($tplset_from_tmp);
124
            if (empty($_POST['copy_to'][$tplset_from]) || $_POST['copy_to'][$tplset_from] == $tplset_from) {
125
                die('Specify valid tplset.');
126
            }
127
            if (empty($_POST["{$tplset_from}_check"])) {
128
                die('No template is specified');
129
            }
130
            $tplset_to = $myts->stripSlashesGPC($_POST['copy_to'][$tplset_from]);
131
            foreach ($_POST["{$tplset_from}_check"] as $tplfile_tmp => $val) {
132
                if (empty($val)) {
133
                    continue;
134
                }
135
                $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
136
                copy_templates_db2db($tplset_from, $tplset_to, "tpl_file='" . addslashes($tplfile) . "'");
137
            }
138
            redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _AM_APCALAM_APCALDBUPDATED);
139
            exit;
140
        }
141
    }
142
}
143
144
// File to DB template copy (checked templates)
145
if (!empty($_POST['copyf2db_do'])) {
146
    // Ticket Check
147
    if (!$xoopsGTicket->check()) {
148
        redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
149
    }
150
151
    if (empty($_POST['copyf2db_to'])) {
152
        die('Specify valid tplset.');
153
    }
154
    if (empty($_POST['basecheck'])) {
155
        die('No template is specified');
156
    }
157
    $tplset_to = $myts->stripSlashesGPC($_POST['copyf2db_to']);
158
    foreach ($_POST['basecheck'] as $tplfile_tmp => $val) {
159
        if (empty($val)) {
160
            continue;
161
        }
162
        $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
163
        copy_templates_f2db($tplset_to, "tpl_file='" . addslashes($tplfile) . "'");
164
    }
165
    redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _AM_APCALAM_APCALDBUPDATED);
166
    exit;
167
}
168
169
// DB template remove (checked templates)
170
if (is_array(@$_POST['del_do'])) {
171
    foreach ($_POST['del_do'] as $tplset_from_tmp => $val) {
172
        if (!empty($val)) {
173
            // Ticket Check
174
            if (!$xoopsGTicket->check()) {
175
                redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors());
176
            }
177
178
            $tplset_from = $myts->stripSlashesGPC($tplset_from_tmp);
179
            if ($tplset_from === 'default') {
180
                die("You can't remove 'default' template.");
181
            }
182
183
            $tpl                = new XoopsTpl();
184
            $tpl->force_compile = true;
185
186
            foreach ($_POST["{$tplset_from}_check"] as $tplfile_tmp => $val) {
187
                if (empty($val)) {
188
                    continue;
189
                }
190
                $tplfile = $myts->stripSlashesGPC($tplfile_tmp);
191
                $result  = $db->query('SELECT tpl_id FROM ' . $db->prefix('tplfile') . " WHERE tpl_tplset='" . addslashes($tplset_from) . "' AND tpl_file='" . addslashes($tplfile) . "'");
192
                while (list($tpl_id) = $db->fetchRow($result)) {
193
                    $tpl_id = (int)$tpl_id;
194
                    $db->query('DELETE FROM ' . $db->prefix('tplfile') . " WHERE tpl_id=$tpl_id");
195
                    $db->query('DELETE FROM ' . $db->prefix('tplsource') . " WHERE tpl_id=$tpl_id");
196
                }
197
                // remove templates_c
198
                $tpl->clear_cache('db:' . $tplfile);
199
                $tpl->clear_compiled_tpl('db:' . $tplfile);
200
            }
201
            redirect_header('mytplsadmin.php?dirname=' . $target_dirname, 1, _AM_APCALAM_APCALDBUPDATED);
202
            exit;
203
        }
204
    }
205
}
206
207
//************//
208
// GET stage  //
209
//************//
210
211
// get tplsets
212
$sql             = 'SELECT DISTINCT tpl_tplset FROM ' . $db->prefix('tplfile') . " ORDER BY tpl_tplset='default' DESC,tpl_tplset";
213
$srs             = $db->query($sql);
214
$tplsets         = array();
215
$tplsets_th4disp = '';
216
$tplset_options  = "<option value=''>----</option>\n";
217
while (list($tplset) = $db->fetchRow($srs)) {
218
    $tplset4disp     = htmlspecialchars($tplset, ENT_QUOTES);
219
    $tplsets[]       = $tplset;
220
    $th_style        = $tplset == $xoopsConfig['template_set'] ? "style='color:yellow;'" : '';
221
    $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>";
222
    $tplset_options  .= "<option value='$tplset4disp'>$tplset4disp</option>\n";
223
}
224
225
// get tpl_file owned by the module
226
$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";
227
$frs = $db->query($sql);
228
229
xoops_cp_header();
230
231
echo "<h3 style='text-align:left;'>" . _MD_APCAL_TPLSETS . " : $target_mname</h3>\n";
232
233
// beggining of table & form
234
echo "
235
    <form class='apcalForm' id='MainForm' name='MainForm' action='?dirname=" . htmlspecialchars($target_dirname, ENT_QUOTES) . "' method='post'>
236
    " . $xoopsGTicket->getTicketHtml(__LINE__) . "
237
    <table class='outer'>
238
        <tr>
239
            <th>" . _MD_APCAL_FILENAME . "</th>
240
            <th>type</th>
241
            <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>
242
            $tplsets_th4disp
243
        </tr>\n";
244
245
// STYLE for distinguishing fingerprints
246
$fingerprint_styles = array(
247
    '',
248
    'background-color:#00FF00',
249
    'background-color:#00CC88',
250
    'background-color:#00FFFF',
251
    'background-color:#0088FF',
252
    'background-color:#FF8800',
253
    'background-color:#0000FF',
254
    'background-color:#FFFFFF'
255
);
256
257
// template ROWS
258
while (list($tpl_file, $tpl_desc, $type, $count) = $db->fetchRow($frs)) {
259
    $evenodd                 = @$evenodd === 'even' ? 'odd' : 'even';
260
    $fingerprint_style_count = 0;
261
262
    // information about the template
263
    echo "
264
        <tr>
265
            <td class='$evenodd'>
266
                <dl>
267
                    <dt>" . htmlspecialchars($tpl_file, ENT_QUOTES) . '</dt>
268
                    <dd>' . htmlspecialchars($tpl_desc, ENT_QUOTES) . "</dd>
269
                </dl>
270
            </td>
271
            <td class='$evenodd'>" . $type . '<br>(' . $count . ")</td>\n";
272
273
    // the base file template column
274
    $basefilepath = XOOPS_ROOT_PATH . '/modules/' . $target_dirname . '/templates/' . ($type === 'block' ? 'blocks/' : '') . $tpl_file;
275
    if (file_exists($basefilepath)) {
276
        $fingerprint                = get_fingerprint(file($basefilepath));
277
        $fingerprints[$fingerprint] = 1;
278
        echo "<td class='$evenodd'>"
279
             . formatTimestamp(filemtime($basefilepath), 'm')
280
             . '<br>'
281
             . substr($fingerprint, 0, 16)
282
             . "<br><input type='checkbox' name='basecheck[$tpl_file]' value='1' /></td>\n";
283
    } else {
284
        echo "<td class='$evenodd'><br></td>";
285
    }
286
287
    // db template columns
288
    foreach ($tplsets as $tplset) {
289
        $tplset4disp = htmlspecialchars($tplset, ENT_QUOTES);
290
291
        // query for templates in db
292
        $drs     = $db->query('SELECT * FROM '
293
                              . $db->prefix('tplfile')
294
                              . ' f NATURAL LEFT JOIN '
295
                              . $db->prefix('tplsource')
296
                              . " s WHERE tpl_file='"
297
                              . addslashes($tpl_file)
298
                              . "' AND tpl_tplset='"
299
                              . addslashes($tplset)
300
                              . "'");
301
        $numrows = $db->getRowsNum($drs);
302
        $tpl     = $db->fetchArray($drs);
303
        if (empty($tpl['tpl_id'])) {
304
            echo "<td class='$evenodd'>($numrows)</td>\n";
305
        } else {
306
            $fingerprint = get_fingerprint(explode("\n", $tpl['tpl_source']));
307
            if (isset($fingerprints[$fingerprint])) {
308
                $style = $fingerprints[$fingerprint];
309
            } else {
310
                ++$fingerprint_style_count;
311
                $style                      = $fingerprint_styles[$fingerprint_style_count];
312
                $fingerprints[$fingerprint] = $style;
313
            }
314
            echo "<td class='$evenodd' style='$style;'>"
315
                 . formatTimestamp($tpl['tpl_lastmodified'], 'm')
316
                 . '<br>'
317
                 . substr($fingerprint, 0, 16)
318
                 . "<br><input type='checkbox' name='{$tplset4disp}_check[{$tpl_file}]' value='1' /> &nbsp; <a href='mytplsform.php?tpl_file="
319
                 . htmlspecialchars($tpl['tpl_file'], ENT_QUOTES)
320
                 . '&amp;tpl_tplset='
321
                 . htmlspecialchars($tpl['tpl_tplset'], ENT_QUOTES)
322
                 . "'>"
323
                 . _EDIT
324
                 . "</a> ($numrows)</td>\n";
325
        }
326
    }
327
328
    echo "</tr>\n";
329
}
330
331
// command submit ROW
332
echo "
333
    <tr>
334
        <td class='head'>
335
            "
336
     . _CLONE
337
     . ": <br>
338
            <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='"
339
     . _MD_APCAL_GENERATE
340
     . "' />
341
        </td>
342
        <td class='head'></td>
343
        <td class='head'>
344
            <input name='copyf2db_do' type='submit' value='copy to-&gt;' /><br>
345
            <select name='copyf2db_to'>$tplset_options
346
        </td>\n";
347
348
foreach ($tplsets as $tplset) {
349
    $tplset4disp = htmlspecialchars($tplset, ENT_QUOTES);
350
    echo "\t\t<td class='head'>
351
            " . ($tplset === 'default' ? '' : "<input name='del_do[{$tplset4disp}]' type='submit' value='" . _DELETE . "' onclick='return confirm(\"" . _DELETE . " OK?\");' /><br>") . "
352
            <input name='copy_do[{$tplset4disp}]' type='submit' value='copy to-&gt;' /><br>
353
            <select name='copy_to[{$tplset4disp}]'>$tplset_options</select>
354
        </td>\n";
355
}
356
357
echo "  </tr>\n";
358
359
echo '</table></form>';
360
// end of table & form
361
362
xoops_cp_footer();
363
364
/**
365
 * @param $lines
366
 * @return string
367
 */
368
function get_fingerprint($lines)
369
{
370
    $str = '';
371
    foreach ($lines as $line) {
372
        if (trim($line)) {
373
            $str .= md5(trim($line));
374
        }
375
    }
376
377
    return md5($str);
378
}
379
380
/**
381
 * @param        $tplset_from
382
 * @param        $tplset_to
383
 * @param string $whr_append
384
 */
385
function copy_templates_db2db($tplset_from, $tplset_to, $whr_append = '1')
386
{
387
    global $db;
388
389
    // get tplfile and tplsource
390
    $result = $db->query("SELECT tpl_refid,tpl_module,'"
391
                         . addslashes($tplset_to)
392
                         . "',tpl_file,tpl_desc,tpl_lastmodified,tpl_lastimported,tpl_type,tpl_source FROM "
393
                         . $db->prefix('tplfile')
394
                         . ' NATURAL LEFT JOIN '
395
                         . $db->prefix('tplsource')
396
                         . " WHERE tpl_tplset='"
397
                         . addslashes($tplset_from)
398
                         . "' AND ($whr_append)");
399
400
    while ($row = $db->fetchArray($result)) {
401
        $tpl_source = array_pop($row);
402
403
        $drs = $db->query('SELECT tpl_id FROM '
404
                          . $db->prefix('tplfile')
405
                          . " WHERE tpl_tplset='"
406
                          . addslashes($tplset_to)
407
                          . "' AND ($whr_append) AND tpl_file='"
408
                          . addslashes($row['tpl_file'])
409
                          . "' AND tpl_refid='"
410
                          . addslashes($row['tpl_refid'])
411
                          . "'");
412
413
        if (!$db->getRowsNum($drs)) {
414
            // INSERT mode
415
            $sql = 'INSERT INTO ' . $db->prefix('tplfile') . ' (tpl_refid,tpl_module,tpl_tplset,tpl_file,tpl_desc,tpl_lastmodified,tpl_lastimported,tpl_type) VALUES (';
416
            foreach ($row as $colval) {
417
                $sql .= "'" . addslashes($colval) . "',";
418
            }
419
            $db->query(substr($sql, 0, -1) . ')');
420
            $tpl_id = $db->getInsertId();
421
            $db->query('INSERT INTO ' . $db->prefix('tplsource') . " SET tpl_id='$tpl_id', tpl_source='" . addslashes($tpl_source) . "'");
422
            xoops_template_touch($tpl_id);
423
        } else {
424
            while (list($tpl_id) = $db->fetchRow($drs)) {
425
                // UPDATE mode
426
                $db->query('UPDATE '
427
                           . $db->prefix('tplfile')
428
                           . " SET tpl_refid='"
429
                           . addslashes($row['tpl_refid'])
430
                           . "',tpl_desc='"
431
                           . addslashes($row['tpl_desc'])
432
                           . "',tpl_lastmodified='"
433
                           . addslashes($row['tpl_lastmodified'])
434
                           . "',tpl_lastimported='"
435
                           . addslashes($row['tpl_lastimported'])
436
                           . "',tpl_type='"
437
                           . addslashes($row['tpl_type'])
438
                           . "' WHERE tpl_id='$tpl_id'");
439
                $db->query('UPDATE ' . $db->prefix('tplsource') . " SET tpl_source='" . addslashes($tpl_source) . "' WHERE tpl_id='$tpl_id'");
440
                xoops_template_touch($tpl_id);
441
            }
442
        }
443
    }
444
}
445
446
/**
447
 * @param        $tplset_to
448
 * @param string $whr_append
449
 */
450
function copy_templates_f2db($tplset_to, $whr_append = '1')
451
{
452
    global $db;
453
454
    // get tplsource
455
    $result = $db->query('SELECT * FROM ' . $db->prefix('tplfile') . "  WHERE tpl_tplset='default' AND ($whr_append)");
456
457
    while ($row = $db->fetchArray($result)) {
458
        $basefilepath = XOOPS_ROOT_PATH . '/modules/' . $row['tpl_module'] . '/templates/' . ($row['tpl_type'] === 'block' ? 'blocks/' : '') . $row['tpl_file'];
459
460
        $tpl_source   = rtrim(implode('', file($basefilepath)));
461
        $lastmodified = filemtime($basefilepath);
462
463
        $drs = $db->query('SELECT tpl_id FROM '
464
                          . $db->prefix('tplfile')
465
                          . " WHERE tpl_tplset='"
466
                          . addslashes($tplset_to)
467
                          . "' AND ($whr_append) AND tpl_file='"
468
                          . addslashes($row['tpl_file'])
469
                          . "' AND tpl_refid='"
470
                          . addslashes($row['tpl_refid'])
471
                          . "'");
472
473
        if (!$db->getRowsNum($drs)) {
474
            // INSERT mode
475
            $sql = 'INSERT INTO '
476
                   . $db->prefix('tplfile')
477
                   . " SET tpl_refid='"
478
                   . addslashes($row['tpl_refid'])
479
                   . "',tpl_desc='"
480
                   . addslashes($row['tpl_desc'])
481
                   . "',tpl_lastmodified='"
482
                   . addslashes($lastmodified)
483
                   . "',tpl_type='"
484
                   . addslashes($row['tpl_type'])
485
                   . "',tpl_tplset='"
486
                   . addslashes($tplset_to)
487
                   . "',tpl_file='"
488
                   . addslashes($row['tpl_file'])
489
                   . "',tpl_module='"
490
                   . addslashes($row['tpl_module'])
491
                   . "'";
492
            $db->query($sql);
493
            $tpl_id = $db->getInsertId();
494
            $db->query('INSERT INTO ' . $db->prefix('tplsource') . " SET tpl_id='$tpl_id', tpl_source='" . addslashes($tpl_source) . "'");
495
            xoops_template_touch($tpl_id);
496
        } else {
497
            while (list($tpl_id) = $db->fetchRow($drs)) {
498
                // UPDATE mode
499
                $db->query('UPDATE ' . $db->prefix('tplfile') . " SET tpl_lastmodified='" . addslashes($lastmodified) . "' WHERE tpl_id='$tpl_id'");
500
                $db->query('UPDATE ' . $db->prefix('tplsource') . " SET tpl_source='" . addslashes($tpl_source) . "' WHERE tpl_id='$tpl_id'");
501
                xoops_template_touch($tpl_id);
502
            }
503
        }
504
    }
505
}
506