Utils.php 13.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2010 Glowbase GmbH <support@glowbase.com>
 *  All rights reserved
 *
 ***************************************************************/

namespace qfq;

//use qfq;

require_once(__DIR__ . '/Define.php');
require_once(__DIR__ . '/Db.php');


class Utils {
    /**
     * @var Db
     */
    private $db = null;

    /**
     * @param $db
     */
    public function __construct($db = null) {
        //TODO: Im Original nachschauen woher die globale Variable $Db kommt??? Ubergangsweise hier im Konstruktor plaziert. Wird aber aktuell nicht initialisiert!!!
        $this->db = null;
    }

    /**
     * Sanitize GET and POST Parameters. Categorize Parameter: name begins with:
     * 'S_' String:                   sanitize via  t3lib_db::quoteStr, htmltospecialchars
     * 'H_' HTML:                     no sanitize at all
     * [Typo3, xdebug, zend debugger] special - no change
     * [rest]                         has to be numeric - if not, will not be copied.
     *
     * @return    Array of sanitized GET and POST Variables. Only correctly filled variables will be returned.
     */
    public function sanitize() {
        $arr = array();
        // Merge GET and POST arrays. GET will be preferred.
        $params = array_merge($_POST, $_GET);

        foreach ($params as $key => $value) {

            // if $value is an array (e.g. when using checkboxes on a 'set' field), convert it to a csv list.
            if (is_array($value)) {
                $value = implode(",", $value);
            }

            switch (substr($key, 0, 2)) {
                //alphanum
                // String values. HTML entitites will be converted, strings escaped.
                case "S_":
//					$arr[$key] = mysql_real_escape_string(htmlspecialchars($value));
//					TA: htmlspecialchars darf hier nicht angewendet werden - Daten sollen so in DB geschrieben werden wie sie angegeben werden		
                    $arr[$key] = mysql_real_escape_string($value);
                    break;
                //default (F_ kommt vom ursprünglichen namen form)
                //Tags werden bis auf die Whitelist LIST_MARKUP_TAGS (siehe define) ersetzt
                case "F_":
                    $arr[$key] = addslashes(strip_tags($value, LIST_MARKUP_TAGS));
                    break;
                //email
                //ExtJs definition (unterstützt nicht alle erlaubten Emailadressen)
                case "E_":
                    $pattern = "/^((\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6})?$/";
                    if (preg_match($pattern, $value) > 0) {
                        $arr[$key] = $value;
                    }
                    break;
                //url
                //Protokoll http / https muss angegeben werden. Definition ExtJs
                case "U_":
                    $pattern = "/((((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?))?$/i";
                    if (preg_match($pattern, $value) > 0) {
                        $arr[$key] = $value;
                    }
                    break;
                //html
                // HTML allowed: no sanitize at all.
                case "H_":
                    $arr[$key] = addslashes($value);
                    break;
                //date
                //DD.MM.YYYY or DD/MM/YYYY
                case "D_":
// 					$pattern = "/^\d\d[(.|\/)]\d\d[(.|\/)]\d\d\d\d$/";
// 					if(preg_match($pattern, $value)>0){
// 						$arr[$key] = $value;
// 					} 

                    // use strtotime instead of a complex regex:
                    // - the function accepts different formats of times / dates (e.g. speaking names) - this is extremely powerful
                    // - the date is automatically converted to a defined format, which makes it easier to process in later steps
                    if (strtotime($value)) {
                        $arr[$key] = date("Y-m-d", strtotime($value));
                    }
                    break;
                //time
                //hh:mm:ss
                case "T_":
                    //$pattern = "/^(((0|1)\d|2[0-4])[:]([0-6]\d)[:]([0-6]\d))?$/";  // CR: restriction to 00-23 is to strong
// 					$pattern = "/^\d?\d[:]\d?\d[:]?\d?\d?$/";
// 					if(preg_match($pattern, $value)>0){
// 						$arr[$key] = $value;
// 					} 

                    // use strtotime instead of a complex regex:
                    // - the function accepts different formats of times / dates (e.g. speaking names) - this is extremely powerful
                    // - the date is automatically converted to a defined format, which makes it easier to process in later steps
                    if (strtotime($value)) {
                        $arr[$key] = date("h:i:s", strtotime($value));
                    }
                    break;
                //date_time
                //DD.MM.YYYY hh:mm:ss
                case "Z_":
                    //$pattern = "/^((0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)\d\d[ ]((0|1)\d|2[0-4])[:]([0-6]\d)[:]([0-6]\d))?$/";
// 					$pattern = "/^(\d*\d[.]\d*\d[.]\d*\d*\d*\d[ ]\d?\d[:]\d?\d[:]?\d?\d?$/";
// 					if(preg_match($pattern, $value)>0){
// 						$arr[$key] = $value;
// 					}

                    // use strtotime instead of a complex regex:
                    // - the function accepts different formats of times / dates (e.g. speaking names) - this is extremely powerful
                    // - the date is automatically converted to a defined format, which makes it easier to process in later steps
                    if (strtotime($value)) {
                        $arr[$key] = date("Y-m-d h:i:s", strtotime($value));
                    }

                    break;
                case "N_":
                    //num
                    //Only numeric-value allowed
                    $pattern = "/^-?[0-9]*$/";
                    if (preg_match($pattern, $value) > 0) {
                        $arr[$key] = $value;
                    }
                    break;
                default:
                    /* 'id' (T3 page identifier) and ZEND 'debugger' GET_VARS won't be sanitized*/
                    ;
                    switch ($key) {
                        case 'id':
                        case 'start_debug':
                        case 'debug_host':
                        case 'send_sess_end':
                        case 'debug_session_id':
                        case 'original_url':
                        case 'debug_start_session':
                        case 'debug_no_cache':
                        case 'debug_port':
                            $arr[$key] = $value;
                            continue 2;
                    }
                    break;
            }
        }
        return ($arr);
    }    // sanitize()

    /**
     * Create a new _unique_ (max 20 tries, else breaks) hash string and saves it in $_SESSION[FORMREPORT][$hash]
     *
     * @return    string        A random alphanumeric hash, or
169
     *                      false if it was not possible to create a unique hash.
170
171
172
173
174
175
176
177
178
179
180
181
182
     */
    public function randomAlphaNumUnique() {

        for ($i = 0; $i < 20; $i++) {

            $hash = $this->randomAlphaNum(LENGTH_HASH);

            if (!isset($_SESSION[FORMREPORT][$hash])) {
                $_SESSION[FORMREPORT][$hash] = array();
                return ($hash);
            }
        }
        // Too much tries without success
183
        return (false);
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    } // randomAlphaNum ()

    /**
     * @param int $length Length of the required hash string
     * @return string       A random alphanumeric hash
     */
    private function randomAlphaNum($length) {
        $possible_characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $string = "";
        while (strlen($string) < $length) {
            $string .= substr($possible_characters, rand() % (strlen($possible_characters)), 1);
        }

        return ($string);
    } // randomAlphaNumUnique()

    /**
     * If record locking has been enabled in ext_localconf.php, create a record in the lock table
     *
     * @param string $form
     * @param int $record_id
     * @param string $tablename
     * @param string $dbalias
     * @param $tx_db_pi1
     */
    function setLockRecord($form, $record_id, $tablename, $dbalias, &$tx_db_pi1) {
        $result = '';
        $mode = $GLOBALS['TYPO3_CONF_VARS'][FORMREPORT]['lock_records']['mode'];
        if ($mode == "warn" || $mode == "lock") {
            $query = "INSERT INTO `" . FR_LOCK . "` (`phpsession_id`, `fe_user_uid`, `form`, `record_id`, `tablename`, `dbalias`) VALUES ('" . session_id() . "', '" . $GLOBALS["TSFE"]->fe_user->user["uid"] . "', '" . $form . "', '" . $record_id . "', '" . $tablename . "', '" . $dbalias . "')";
214
            $this->db->doQuery(DB, $query, $result, ROW_EXPECT_0);
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        } // if
    } // eo setLockRecord


    /**
     * If record locking has been enabled in ext_localconf.php,
     *    delete all expired locking records
     *    check if a record exists in the lock table for the currently edited record
     *
     * @param int $form form_id
     * @param int $record_id record_id
     * @param string $tablename tablename
     * @param Db $dbalias Db class object
     * @param $tx_db_pi1
     * @return array|bool           information on locking mode, locking user and timestamp. false if not locked
     */
    function checkLockRecord($form, $record_id, $tablename, $dbalias, &$tx_db_pi1) {
        // Get config values from localconf or use default from define.php
        $mode = $GLOBALS['TYPO3_CONF_VARS'][FORMREPORT]['lock_records']['mode'];
        $interval = ($GLOBALS['TYPO3_CONF_VARS'][FORMREPORT]['lock_records']['interval']) ?: LOCK_RECORDS_INTERVAL;

        if ($mode == "warn" || $mode == "lock") {
            // Delete all expired locking records
            $query = "DELETE FROM `" . FR_LOCK . "` WHERE timestamp + INTERVAL " . $GLOBALS['TYPO3_CONF_VARS'][FORMREPORT]['lock_records']['interval'] . " SECOND < NOW()";
239
            $this->db->doQuery(DB, $query, $result, ROW_EXPECT_0);
240
241
242

            // Check if locking records exist
            $query = "SELECT fe_user_uid, phpsession_id, date_format(timestamp + INTERVAL " . $interval . " SECOND, \"%H:%i %d.%m.%Y\") as lock_endtime FROM `" . FR_LOCK . "` WHERE `record_id`='" . $record_id . "' and `tablename`='" . $tablename . "' and `dbalias`='" . $dbalias . "' LIMIT 1";
243
            $this->db->doQuery(DB, $query, $result, ROW_REGULAR);
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274

            // If result is empty, return false
            if (empty($result))
                return false;

            // If user is the same as the current one, return false
            // Compare fe_user_uid and session-id
            if ($result[0]['phpsession_id'] == session_id())
                return false;

            // Build array with locking information - will be used to create a warning/error message etc.
            $arr = array();
            $arr['mode'] = $mode;
            $arr['fe_user_uid'] = $result[0]['fe_user_uid'];
            $arr['lock_endtime'] = $result[0]['lock_endtime'];
            return $arr;

        } // if
        // no locking configured
        return false;
    } // eo setLockRecord

    /**
     * Returns username for a fe_user_uid
     *
     * @param int $uid fe_user_uid
     * @param $tx_db_pi1
     * @return string       username
     */
    function getFEUserName($uid, &$tx_db_pi1) {
        $query = "SELECT username FROM `fe_users` WHERE `uid`='" . $uid . "'";
275
        $this->db->doQuery(T3, $query, $result, ROW_EXPECT_1);
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        $username = ($result['username']) ?: "anonymous";
        return $username;
    }

    /**
     * Create a unique directory in $path
     *
     * @param string $path path
     * @return string           path/uniqedir
     * @throws codeException
     */
    function createUniqueDir($path) {
        // Try max. 20 times
        for ($i = 0; $i < 20; $i++) {
            $dirname = $this->randomAlphaNum(5);
            $dirpath = $path . "/" . $dirname;

            if (!file_exists($dirpath)) {
                mkdir($dirpath, 0700, true);
                return $dirpath;
            }
        }
        // Too many tries without success
        throw new CodeReportException ("Could not create unique directory.", __FILE__, __LINE__);
    } // eo createUniqueDir

    /**
     * Create a ToolTip: $toolTip[0] and $toolTip[1] have to inserted in HTML code accordingly.
     *
     * @param    string $note Text to be shown in the tooltip
     * @return    array        $toolTip        $toolTip[0]: JS to show '$toolTip[1]'.
     *                                        $toolTip[1]: '<span>...</span>' with the tooltip text.
     */
    public function createToolTip($note) {
        static $count = 0;

        $toolTipIndex = 'tooltip.' . $GLOBALS["TSFE"]->currentRecord . '.' . ++$count;
        $toolTip = array();

        // Expample: <img src="fileadmin/icons/bullet-gray.gif" onmouseover="document.getElementById('gm167979').style.display='block';" onmouseout="document.getElementById('gm167979').style.display='none';" />
        $toolTip[0] = " onmouseover=\"document.getElementById('" . $toolTipIndex . "').style.display='block';\" onmouseout=\"document.getElementById('" . $toolTipIndex . "').style.display='none';\"";

        // Example: <span id="gm167979" style="display:none; position:absolute; border:solid 1px black; background-color:#F9F3D0; padding:3px;">My pesonal tooltip</span>
        $toolTip[1] = '<span id="' . $toolTipIndex . '" style="display:none; position:absolute; border:solid 1px black; background-color:#F9F3D0; padding:3px;">' . $note . '</span>';

        return ($toolTip);
    } // createToolTip()

}