Subversion Repositories oidplus

Rev

Rev 698 | Rev 715 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
511 daniel-mar 5
 * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
2 daniel-mar 6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
20
function insertWhitespace($str, $index) {
21
        return substr($str, 0, $index) . ' ' . substr($str, $index);
22
}
23
 
24
function js_escape($data) {
25
        // TODO.... json_encode??
289 daniel-mar 26
        $data = str_replace('\\', '\\\\', $data);
27
        $data = str_replace('\'', '\\\'', $data);
28
        return "'" . $data . "'";
2 daniel-mar 29
}
30
 
11 daniel-mar 31
function trim_br($html) {
386 daniel-mar 32
        $count = 0;
11 daniel-mar 33
        do { $html = preg_replace('@^\s*<\s*br\s*/{0,1}\s*>@isU', '', $html, -1, $count); } while ($count > 0); // left trim
34
        do { $html = preg_replace('@<\s*br\s*/{0,1}\s*>\s*$@isU', '', $html, -1, $count); } while ($count > 0); // right trim
35
        return $html;
36
}
74 daniel-mar 37
 
453 daniel-mar 38
function generateRandomString($length) {
653 daniel-mar 39
        // Note: This function can be used in temporary file names, so you
40
        // may not generate illegal file name characters.
453 daniel-mar 41
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
42
        $charactersLength = strlen($characters);
43
        $randomString = '';
44
        for ($i = 0; $i < $length; $i++) {
45
                $randomString .= $characters[rand(0, $charactersLength - 1)];
46
        }
47
        return $randomString;
48
}
49
 
74 daniel-mar 50
function verify_private_public_key($privKey, $pubKey) {
51
        try {
52
                if (empty($privKey)) return false;
53
                if (empty($pubKey)) return false;
453 daniel-mar 54
                $data = generateRandomString(25);
386 daniel-mar 55
                $encrypted = '';
56
                $decrypted = '';
74 daniel-mar 57
                if (!@openssl_public_encrypt($data, $encrypted, $pubKey)) return false;
58
                if (!@openssl_private_decrypt($encrypted, $decrypted, $privKey)) return false;
59
                return $decrypted == $data;
60
        } catch (Exception $e) {
61
                return false;
62
        }
63
}
64
 
65
function smallhash($data) { // get 31 bits from SHA1. Values 0..2147483647
250 daniel-mar 66
        return (hexdec(substr(sha1($data),-4*2)) & 0x7FFFFFFF);
74 daniel-mar 67
}
180 daniel-mar 68
 
182 daniel-mar 69
function split_firstname_lastname($name) {
70
        $ary = explode(' ', $name);
71
        $last_name = array_pop($ary);
72
        $first_name = implode(' ', $ary);
73
        return array($first_name, $last_name);
74
}
75
 
180 daniel-mar 76
function originHeaders() {
77
        // CORS
78
        // Author: Till Wehowski
426 daniel-mar 79
        // TODO: add to class OIDplus
182 daniel-mar 80
 
180 daniel-mar 81
        header("Access-Control-Allow-Credentials: true");
82
        header("Access-Control-Allow-Origin: ".strip_tags(((isset($_SERVER['HTTP_ORIGIN'])) ? $_SERVER['HTTP_ORIGIN'] : "*")));
83
 
84
        header("Access-Control-Allow-Headers: If-None-Match, X-Requested-With, Origin, X-Frdlweb-Bugs, Etag, X-Forgery-Protection-Token, X-CSRF-Token");
85
 
86
        if (isset($_SERVER['HTTP_ORIGIN'])) {
87
                header('X-Frame-Options: ALLOW-FROM '.$_SERVER['HTTP_ORIGIN']);
88
        } else {
89
                header_remove("X-Frame-Options");
90
        }
91
 
92
        $expose = array('Etag', 'X-CSRF-Token');
93
        foreach (headers_list() as $num => $header) {
94
                $h = explode(':', $header);
95
                $expose[] = trim($h[0]);
96
        }
97
        header("Access-Control-Expose-Headers: ".implode(',',$expose));
98
 
99
        header("Vary: Origin");
100
}
236 daniel-mar 101
 
102
function get_calling_function() {
103
        $ex = new Exception();
104
        $trace = $ex->getTrace();
360 daniel-mar 105
        if (!isset($trace[2])) return _L('(main)');
236 daniel-mar 106
        $final_call = $trace[2];
107
        return $final_call['file'].':'.$final_call['line'].'/'.$final_call['function'].'()';
108
}
346 daniel-mar 109
 
110
if (!function_exists('mb_wordwrap')) {
111
        function mb_wordwrap($str, $width = 75, $break = "\n", $cut = false) {
112
                // https://stackoverflow.com/a/4988494/488539
113
                $lines = explode($break, $str);
114
                foreach ($lines as &$line) {
115
                        $line = rtrim($line);
116
                        if (mb_strlen($line) <= $width) {
117
                                continue;
118
                        }
119
                        $words = explode(' ', $line);
120
                        $line = '';
121
                        $actual = '';
122
                        foreach ($words as $word) {
123
                                if (mb_strlen($actual.$word) <= $width) {
124
                                        $actual .= $word.' ';
125
                                } else {
126
                                        if ($actual != '') {
127
                                                $line .= rtrim($actual).$break;
128
                                        }
129
                                        $actual = $word;
130
                                        if ($cut) {
131
                                                while (mb_strlen($actual) > $width) {
132
                                                        $line .= mb_substr($actual, 0, $width).$break;
133
                                                        $actual = mb_substr($actual, $width);
134
                                                }
135
                                        }
136
                                        $actual .= ' ';
137
                                }
138
                        }
139
                        $line .= trim($actual);
140
                }
141
                return implode($break, $lines);
142
        }
143
}
355 daniel-mar 144
 
379 daniel-mar 145
function httpOutWithETag($out, $contentType, $filename='') {
146
        $etag = md5($out);
147
        header("Etag: $etag");
148
        header("Content-MD5: $etag"); // RFC 2616 clause 14.15
149
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && (trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag)) {
150
                header("HTTP/1.1 304 Not Modified");
151
        } else {
152
                header("Content-Type: $contentType");
153
                if (!empty($filename)) {
154
                        header('Content-Disposition:inline; filename="'.$filename.'"');
155
                }
156
                echo $out;
157
        }
158
        die();
159
}
160
 
360 daniel-mar 161
function my_vsprintf($str, $args) {
162
        $n = 1;
163
        foreach ($args as $val) {
164
                $str = str_replace("%$n", $val, $str);
165
                $n++;
166
        }
370 daniel-mar 167
        $str = str_replace("%%", "%", $str);
360 daniel-mar 168
        return $str;
169
}
170
 
355 daniel-mar 171
function _L($str, ...$sprintfArgs) {
401 daniel-mar 172
        static $translation_array = array();
173
        static $translation_loaded = null;
174
 
506 daniel-mar 175
        $str = trim($str);
176
 
438 daniel-mar 177
        if (!class_exists('OIDplus')) {
178
                return my_vsprintf($str, $sprintfArgs);
179
        }
180
 
360 daniel-mar 181
        $lang = OIDplus::getCurrentLang();
468 daniel-mar 182
        $ta = OIDplus::getTranslationArray($lang);
183
        $res = (isset($ta[$lang]) && isset($ta[$lang][$str])) ? $ta[$lang][$str] : $str;
360 daniel-mar 184
 
185
        $res = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $res);
186
 
187
        $res = my_vsprintf($res, $sprintfArgs);
188
 
189
        return $res;
370 daniel-mar 190
}
386 daniel-mar 191
 
552 daniel-mar 192
function _CheckParamExists($params, $key) {
698 daniel-mar 193
        if (class_exists('OIDplusException')) {
194
                if (!isset($params[$key])) throw new OIDplusException(_L('Parameter %1 is missing', $key));
195
        } else {
196
                if (!isset($params[$key])) throw new Exception(_L('Parameter %1 is missing', $key));
197
        }
552 daniel-mar 198
}
199
 
386 daniel-mar 200
function extractHtmlContents($cont) {
201
        // make sure the program works even if the user provided HTML is not UTF-8
202
        $cont = iconv(mb_detect_encoding($cont, mb_detect_order(), true), 'UTF-8//IGNORE', $cont);
203
        $bom = pack('H*','EFBBBF');
204
        $cont = preg_replace("/^$bom/", '', $cont);
205
 
206
        $out_js = '';
207
        $m = array();
208
        preg_match_all('@<script[^>]*>(.+)</script>@ismU', $cont, $m);
209
        foreach ($m[1] as $x) {
210
                $out_js = $x . "\n\n";
211
        }
212
 
213
        $out_css = '';
214
        $m = array();
215
        preg_match_all('@<style[^>]*>(.+)</style>@ismU', $cont, $m);
216
        foreach ($m[1] as $x) {
217
                $out_css = $x . "\n\n";
218
        }
219
 
220
        $out_html = $cont;
221
        $out_html = preg_replace('@^(.+)<body[^>]*>@isU', '', $out_html);
222
        $out_html = preg_replace('@</body>.+$@isU', '', $out_html);
223
        $out_html = preg_replace('@<title>.+</title>@isU', '', $out_html);
224
        $out_html = preg_replace('@<h1>.+</h1>@isU', '', $out_html, 1);
225
        $out_html = preg_replace('@<script[^>]*>(.+)</script>@ismU', '', $out_html);
226
        $out_html = preg_replace('@<style[^>]*>(.+)</style>@ismU', '', $out_html);
227
 
228
        return array($out_html, $out_js, $out_css);
392 daniel-mar 229
}
230
 
400 daniel-mar 231
function sha3_512($password, $raw_output=false) {
392 daniel-mar 232
        if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
400 daniel-mar 233
                return hash('sha3-512', $password, $raw_output);
392 daniel-mar 234
        } else {
400 daniel-mar 235
                return bb\Sha3\Sha3::hash($password, 512, $raw_output);
392 daniel-mar 236
        }
237
}
486 daniel-mar 238
 
710 daniel-mar 239
function sha3_512_hmac($message, $key, $raw_output=false) {
240
        // RFC 2104 HMAC
241
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
242
                                return hash_hmac('sha3-512', $message, $key, $raw_output);
243
                } else {
244
                $blocksize = 576; // block size of sha-512!
245
 
246
                if (strlen($key) > ($blocksize/8)) {
247
                        $k_ = sha3_512($key,true);
248
                } else {
249
                        $k_ = $key;
250
                }
251
 
252
                $k_opad = str_repeat(chr(0x5C),($blocksize/8));
253
                $k_ipad = str_repeat(chr(0x36),($blocksize/8));
254
                for ($i=0; $i<strlen($k_); $i++) {
255
                        $k_opad[$i] = $k_opad[$i] ^ $k_[$i];
256
                        $k_ipad[$i] = $k_ipad[$i] ^ $k_[$i];
257
                }
258
 
259
                return sha3_512($k_opad . sha3_512($k_ipad . $message, true));
260
                }
261
}
262
 
625 daniel-mar 263
if (!function_exists('str_ends_with')) {
264
        // PHP 7.x compatibility
265
        function str_ends_with($haystack, $needle) {
266
                $length = strlen($needle);
267
                return $length > 0 ? substr($haystack, -$length) === $needle : true;
268
        }
269
}
270
 
271
if (!function_exists('str_starts_with')) {
272
        // PHP 7.x compatibility
273
        function str_starts_with($haystack, $needle) {
274
                return strpos($haystack, $needle) === 0;
275
        }
276
}
277
 
632 daniel-mar 278
function rec_is_dir($dir) {
279
        $dirs = glob($dir);
280
        foreach ($dirs as $dir) {
281
                if (is_dir($dir)) return true;
282
        }
283
        return false;
284
}
285
 
641 daniel-mar 286
function isInternetExplorer() {
287
        // see also includes/oidplus_base.js
288
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
289
        return ((strpos($ua,'MSIE ') !== false) || (strpos($ua,'Trident/') !== false));
290
}
653 daniel-mar 291
 
292
function url_get_contents($url) {
293
        if (function_exists('curl_init')) {
294
                $ch = curl_init();
698 daniel-mar 295
                if (class_exists('OIDplus')) {
296
                        if (ini_get('curl.cainfo') == '') curl_setopt($ch, CURLOPT_CAINFO, OIDplus::localpath() . 'vendor/cacert.pem');
297
                }
653 daniel-mar 298
                curl_setopt($ch, CURLOPT_URL, $url);
299
                curl_setopt($ch, CURLOPT_POST, 0);
300
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
301
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
302
                curl_setopt($ch, CURLOPT_AUTOREFERER, true);
303
                if (!($res = @curl_exec($ch))) return false;
304
                curl_close($ch);
305
        } else {
306
                $res = @file_get_contents($url);
307
                if ($res === false) return false;
308
        }
309
        return $res;
660 daniel-mar 310
}