OnString.php 8.59 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 2/10/18
 * Time: 3:14 PM
 */

namespace qfq;

11
12
require_once(__DIR__ . '/../Constants.php');

13
14
15
16
/**
 * Class OnString
 * @package qfq
 */
17
class OnString {
18
19
20
21
22
23
24
25
26
27
28

    /**
     * Returns part of haystack string starting from and including the last occurrence of needle to the end of haystack.
     *
     * strrstr('hello/world/to/the/limit', '/') = 'limit'
     *
     * @param $haystack
     * @param $needle
     * @return string
     */
    public static function strrstr($haystack, $needle) {
29
30
31
32
        if (empty($needle) || empty($haystack)) {
            return '';
        }

33
        return substr($haystack, strrpos($haystack, $needle) + strlen($needle));
34
    }
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

    /**
     * Strips the first char $c from $data if the first char is equal to $c.
     * Example: with $c='_' the $data='_pId' becomes 'pId'
     *
     * @param $c
     * @param $data
     * @return string
     */
    public static function stripFirstCharIf($c, $data) {

        if (empty($data)) {
            return $data;
        }

        if ($data[0] == $c) {
            $data = substr($data, 1);
        }

        return $data;
    }

    /**
58
     * If the given $str is enclosed in SINGLE_TICK or DOUBLE_TICK, remove it. Only the outermost are removed.
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
     *
     * @param string $str
     * @return string  remove unquoted string
     */
    public static function trimQuote($str) {
        $len = strlen($str);

        if ($len < 2) {
            return $str;
        }

        switch ($str[0]) {
            case SINGLE_TICK:
                if ($str[$len - 1] == SINGLE_TICK) {
                    return substr($str, 1, $len - 2);
                }
                break;
            case DOUBLE_TICK:
                if ($str[$len - 1] == DOUBLE_TICK) {
                    return substr($str, 1, $len - 2);
                }
                break;
            default:
                break;
        }

        return $str;
    }
87
88

    /**
89
90
     * Split an Excel position string line to column and row.
     * E.g.: $pos = 'A1' to [ 'A', '1'], resp.  'ACD4567' to [ 'ACD', '4567' ]
91
92
     *
     * @param $pos
93
94
95
     * @param &$column - return the alpha part of $pos
     * @param &$row - return the digit part of $pos
     * @return bool - true if a alpha string and a numeric string is found, else false.
96
     */
Carsten  Rose's avatar
Carsten Rose committed
97
    public static function splitExcelPos($pos, &$column, &$row) {
98

Elias Villiger's avatar
Elias Villiger committed
99
        preg_match_all('/[A-Z]+|\d+/', $pos, $matches);
100

Carsten  Rose's avatar
Carsten Rose committed
101
        if (count($matches[0]) != 2) {
102
103
104
105
106
107
108
            return false;
        }

        $column = $matches[0][0];
        $row = $matches[0][1];

        return true;
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

    /**
     * Split the wkthtml Parameter between:
     * - general 'urlParam' for the specific website (page which will be converted to PDF).
     * - `wkthml` Parameter. Those will always start with '-' and control wkhtml how to render the PDF.
     * - '_sip' - to activate that `urlParam` parameters will be SIP encoded.
     *
     * @param string $urlParamString
     * @param array $rcArgs
     * @param bool $rcSipEncode
     *
     * @return array The remaining 'real' URL parameter to call the T3 page.
     * @throws UserFormException
     */
    public static function splitParam($urlParamString, array &$rcArgs, &$rcSipEncode) {
        $urlParamNew = array();
        $rcArgs[WKHTML_OPTION_VIEWPORT] = WKHTML_OPTION_VIEWPORT_VALUE; // Forces wkhtml to render Bootstrap page in 'md', not 'xs'

        $urlParam = KeyValueStringParser::parse($urlParamString, '=', '&', KVP_IF_VALUE_EMPTY_COPY_KEY);
        foreach ($urlParam as $key => $value) {
            switch (substr($key, 0, 1)) {
                case '-':
                    $rcArgs[$key] = $value;
                    break;
                case '_':
                    if ($key == DOWNLOAD_SIP_ENCODE_PARAMETER) {
                        $rcSipEncode = true;
                    }
                    break;
                default:
                    $urlParamNew[$key] = $value;
                    break;
            }
        }

        return $urlParamNew;
    }

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    /**
     * Removes new lines (\n) from expressions like {{var:SC0:alnumx}} and replaces them with spaces.
     * Handles nested expressions like {{SELECT {{var::alnumx}}}}
     * This function is useful to allow multiline expressions in form definitions such as:
     *   sqlInsert = {{INSERT INTO test (grId)
     *                 VALUES(123) }}
     *
     * @param $str - the string to be parsed
     * @return string - the resulting string with new lines in expressions replaced
     * @throws UserFormException - alerts the user if the delimiters are not balanced
     */
    public static function removeNewlinesInNestedExpression($str) {
        $delimStart = '{{';
        $delimEnd = '}}';
        $lastDelimPos = -strlen($delimStart);
        $exprDepth = 0; // keeps count of the level of expression depth
        $nestingStart = 0;

        // Process the string one start/end delimiter at a time
Carsten  Rose's avatar
Carsten Rose committed
167
        while (true) {
168
169
170
171
172
173
174
175
176
177
178
179
180
181
            // find the next start/end delimiter
            $nextDelimStartPos = strpos($str, $delimStart, $lastDelimPos + strlen($delimStart));
            $nextDelimEndPos = strpos($str, $delimEnd, $lastDelimPos + strlen($delimEnd));
            if ($nextDelimStartPos === false && $nextDelimEndPos === false) break;
            $nextDelimPos = min($nextDelimStartPos, $nextDelimEndPos);
            if ($nextDelimStartPos === false) $nextDelimPos = $nextDelimEndPos;
            if ($nextDelimEndPos === false) $nextDelimPos = $nextDelimStartPos;

            if ($nextDelimPos == $nextDelimStartPos) { // opening delimiter
                if ($exprDepth == 0) $nestingStart = $nextDelimPos;
                $exprDepth++;
            } else { // closing delimiter
                $exprDepth--;
                if ($exprDepth < 0) {
182
183
184
185
                    throw new UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Too many closing delimiters '$delimEnd'",
                        ERROR_MESSAGE_SUPPORT => "in '$str'"]), ERROR_MISSING_OPEN_DELIMITER);


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                    break;
                } elseif ($exprDepth == 0) {
                    // end of nesting -> replace \n inside nested expression with space
                    $pre = substr($str, 0, $nestingStart);
                    $nest = substr($str, $nestingStart, $nextDelimPos - $nestingStart);
                    $nestNew = str_replace('\n', ' ', $nest);
                    $post = substr($str, $nextDelimPos);
                    $str = substr($str, 0, $nestingStart) .
                        str_replace("\n", " ", substr($str, $nestingStart, $nextDelimPos - $nestingStart)) .
                        substr($str, $nextDelimPos);
                }
            }

            $lastDelimPos = $nextDelimPos;
        }
Carsten  Rose's avatar
Carsten Rose committed
201
        if ($exprDepth > 0) {
202
203
            throw new UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Missing close delimiter '$delimEnd'",
                ERROR_MESSAGE_SUPPORT => "in '$str'"]), ERROR_MISSING_CLOSE_DELIMITER);
204
205
206
207
        }

        return $str;
    }
Carsten  Rose's avatar
Carsten Rose committed
208
209

    /**
210
211
212
     * Split a $_SERVER['PATH_INFO'] of the form '/form1/id1/form2/id2/form3/id3/.../formN[/idN])' to
     *   $rcArrrIds=[ id1, id2, ..., idN]
     *   return: 'formN'
Carsten  Rose's avatar
Carsten Rose committed
213
214
     *
     * @param $pathInfo
215
216
     * @param array $rcArrId
     * @param array $rcArrForm
Carsten  Rose's avatar
Carsten Rose committed
217
218
219
     * @return string
     * @throws UserFormException
     */
Carsten  Rose's avatar
Carsten Rose committed
220
    public static function splitPathInfoToIdForm($pathInfo, array &$rcArrId, array &$rcArrForm) {
Carsten  Rose's avatar
Carsten Rose committed
221

222
        // Empty: do nothing
Carsten  Rose's avatar
Carsten Rose committed
223
224
225
226
        if ($pathInfo == '') {
            return '';
        }

227
        // Remove optional leading '/'
Carsten  Rose's avatar
Carsten Rose committed
228
229
230
231
        if ($pathInfo[0] == '/') {
            $pathInfo = substr($pathInfo, 1);
        }

232
        // Remove optional trailing '/'
Carsten  Rose's avatar
Carsten Rose committed
233
234
235
236
237
        $len = strlen($pathInfo);
        if ($len > 0 && $pathInfo[$len - 1] == '/') {
            $pathInfo = substr($pathInfo, 0, $len - 1);
        }

238
        // Empty? do nothing
239
       if ($pathInfo == '') {
Carsten  Rose's avatar
Carsten Rose committed
240
241
242
243
244
245
            return '';
        }

        $param = explode('/', $pathInfo);
        $cnt = count($param);

246
247
248
        // No 'id'. Append '0'
        if ($cnt % 2 == 1) {
            array_push($param, 0);
Carsten  Rose's avatar
Carsten Rose committed
249
250
        }

251
252
        $rcArrId = array();
        $rcArrForm = array();
Carsten  Rose's avatar
Carsten Rose committed
253

254
        while (count($param)>0) {
Carsten  Rose's avatar
Carsten Rose committed
255

256
            $form= array_shift($param);
257
258
259
            if (!ctype_alnum($form)) {
                throw new UserFormException('Expect alphanumeric string', ERROR_BROKEN_PARAMETER);
            }
260
            $rcArrForm[]=$form;
261
262

            $id = array_shift($param);
263
264
265
266
            if (!ctype_digit((string) $id)) {
                throw new UserFormException('Expect numerical id', ERROR_BROKEN_PARAMETER);
            }
            $rcArrId[] = $id;
Carsten  Rose's avatar
Carsten Rose committed
267
268
        }

269
        return $form;
Carsten  Rose's avatar
Carsten Rose committed
270
    }
271
}