Subversion Repositories oidplus

Rev

Rev 719 | Rev 725 | 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) {
721 daniel-mar 51
        if (!function_exists('openssl_public_encrypt')) return false;
74 daniel-mar 52
        try {
53
                if (empty($privKey)) return false;
54
                if (empty($pubKey)) return false;
453 daniel-mar 55
                $data = generateRandomString(25);
386 daniel-mar 56
                $encrypted = '';
57
                $decrypted = '';
74 daniel-mar 58
                if (!@openssl_public_encrypt($data, $encrypted, $pubKey)) return false;
59
                if (!@openssl_private_decrypt($encrypted, $decrypted, $privKey)) return false;
60
                return $decrypted == $data;
61
        } catch (Exception $e) {
62
                return false;
63
        }
64
}
65
 
66
function smallhash($data) { // get 31 bits from SHA1. Values 0..2147483647
250 daniel-mar 67
        return (hexdec(substr(sha1($data),-4*2)) & 0x7FFFFFFF);
74 daniel-mar 68
}
180 daniel-mar 69
 
182 daniel-mar 70
function split_firstname_lastname($name) {
71
        $ary = explode(' ', $name);
72
        $last_name = array_pop($ary);
73
        $first_name = implode(' ', $ary);
74
        return array($first_name, $last_name);
75
}
76
 
180 daniel-mar 77
function originHeaders() {
78
        // CORS
79
        // Author: Till Wehowski
426 daniel-mar 80
        // TODO: add to class OIDplus
182 daniel-mar 81
 
180 daniel-mar 82
        header("Access-Control-Allow-Credentials: true");
83
        header("Access-Control-Allow-Origin: ".strip_tags(((isset($_SERVER['HTTP_ORIGIN'])) ? $_SERVER['HTTP_ORIGIN'] : "*")));
84
 
85
        header("Access-Control-Allow-Headers: If-None-Match, X-Requested-With, Origin, X-Frdlweb-Bugs, Etag, X-Forgery-Protection-Token, X-CSRF-Token");
86
 
87
        if (isset($_SERVER['HTTP_ORIGIN'])) {
88
                header('X-Frame-Options: ALLOW-FROM '.$_SERVER['HTTP_ORIGIN']);
89
        } else {
90
                header_remove("X-Frame-Options");
91
        }
92
 
93
        $expose = array('Etag', 'X-CSRF-Token');
94
        foreach (headers_list() as $num => $header) {
95
                $h = explode(':', $header);
96
                $expose[] = trim($h[0]);
97
        }
98
        header("Access-Control-Expose-Headers: ".implode(',',$expose));
99
 
100
        header("Vary: Origin");
101
}
236 daniel-mar 102
 
103
function get_calling_function() {
104
        $ex = new Exception();
105
        $trace = $ex->getTrace();
360 daniel-mar 106
        if (!isset($trace[2])) return _L('(main)');
236 daniel-mar 107
        $final_call = $trace[2];
108
        return $final_call['file'].':'.$final_call['line'].'/'.$final_call['function'].'()';
109
}
346 daniel-mar 110
 
111
if (!function_exists('mb_wordwrap')) {
112
        function mb_wordwrap($str, $width = 75, $break = "\n", $cut = false) {
113
                // https://stackoverflow.com/a/4988494/488539
114
                $lines = explode($break, $str);
115
                foreach ($lines as &$line) {
116
                        $line = rtrim($line);
117
                        if (mb_strlen($line) <= $width) {
118
                                continue;
119
                        }
120
                        $words = explode(' ', $line);
121
                        $line = '';
122
                        $actual = '';
123
                        foreach ($words as $word) {
124
                                if (mb_strlen($actual.$word) <= $width) {
125
                                        $actual .= $word.' ';
126
                                } else {
127
                                        if ($actual != '') {
128
                                                $line .= rtrim($actual).$break;
129
                                        }
130
                                        $actual = $word;
131
                                        if ($cut) {
132
                                                while (mb_strlen($actual) > $width) {
133
                                                        $line .= mb_substr($actual, 0, $width).$break;
134
                                                        $actual = mb_substr($actual, $width);
135
                                                }
136
                                        }
137
                                        $actual .= ' ';
138
                                }
139
                        }
140
                        $line .= trim($actual);
141
                }
142
                return implode($break, $lines);
143
        }
144
}
355 daniel-mar 145
 
379 daniel-mar 146
function httpOutWithETag($out, $contentType, $filename='') {
147
        $etag = md5($out);
148
        header("Etag: $etag");
149
        header("Content-MD5: $etag"); // RFC 2616 clause 14.15
150
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && (trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag)) {
151
                header("HTTP/1.1 304 Not Modified");
152
        } else {
153
                header("Content-Type: $contentType");
154
                if (!empty($filename)) {
155
                        header('Content-Disposition:inline; filename="'.$filename.'"');
156
                }
157
                echo $out;
158
        }
159
        die();
160
}
161
 
360 daniel-mar 162
function my_vsprintf($str, $args) {
163
        $n = 1;
164
        foreach ($args as $val) {
165
                $str = str_replace("%$n", $val, $str);
166
                $n++;
167
        }
370 daniel-mar 168
        $str = str_replace("%%", "%", $str);
360 daniel-mar 169
        return $str;
170
}
171
 
355 daniel-mar 172
function _L($str, ...$sprintfArgs) {
401 daniel-mar 173
        static $translation_array = array();
174
        static $translation_loaded = null;
175
 
506 daniel-mar 176
        $str = trim($str);
177
 
438 daniel-mar 178
        if (!class_exists('OIDplus')) {
179
                return my_vsprintf($str, $sprintfArgs);
180
        }
181
 
360 daniel-mar 182
        $lang = OIDplus::getCurrentLang();
468 daniel-mar 183
        $ta = OIDplus::getTranslationArray($lang);
184
        $res = (isset($ta[$lang]) && isset($ta[$lang][$str])) ? $ta[$lang][$str] : $str;
360 daniel-mar 185
 
186
        $res = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $res);
187
 
188
        $res = my_vsprintf($res, $sprintfArgs);
189
 
190
        return $res;
370 daniel-mar 191
}
386 daniel-mar 192
 
552 daniel-mar 193
function _CheckParamExists($params, $key) {
698 daniel-mar 194
        if (class_exists('OIDplusException')) {
195
                if (!isset($params[$key])) throw new OIDplusException(_L('Parameter %1 is missing', $key));
196
        } else {
197
                if (!isset($params[$key])) throw new Exception(_L('Parameter %1 is missing', $key));
198
        }
552 daniel-mar 199
}
200
 
721 daniel-mar 201
function convert_to_utf8_no_bom($cont) {
202
        $encoding = mb_detect_encoding($cont, mb_detect_order(), true);
203
 
204
        if (($encoding !== false) && ($encoding !== 'ASCII') && ($encoding !== 'UTF-8')) {
205
                $cont = iconv($encoding, 'UTF-8//IGNORE', $cont);
206
        }
207
 
208
        // Remove BOM
386 daniel-mar 209
        $bom = pack('H*','EFBBBF');
210
        $cont = preg_replace("/^$bom/", '', $cont);
721 daniel-mar 211
        return $cont;
212
}
386 daniel-mar 213
 
721 daniel-mar 214
function extractHtmlContents($cont) {
215
        // make sure the program works even if the user provided HTML is not UTF-8
216
        $cont = convert_to_utf8_no_bom($cont);
217
 
386 daniel-mar 218
        $out_js = '';
219
        $m = array();
220
        preg_match_all('@<script[^>]*>(.+)</script>@ismU', $cont, $m);
221
        foreach ($m[1] as $x) {
222
                $out_js = $x . "\n\n";
223
        }
224
 
225
        $out_css = '';
226
        $m = array();
227
        preg_match_all('@<style[^>]*>(.+)</style>@ismU', $cont, $m);
228
        foreach ($m[1] as $x) {
229
                $out_css = $x . "\n\n";
230
        }
231
 
232
        $out_html = $cont;
233
        $out_html = preg_replace('@^(.+)<body[^>]*>@isU', '', $out_html);
234
        $out_html = preg_replace('@</body>.+$@isU', '', $out_html);
235
        $out_html = preg_replace('@<title>.+</title>@isU', '', $out_html);
236
        $out_html = preg_replace('@<h1>.+</h1>@isU', '', $out_html, 1);
237
        $out_html = preg_replace('@<script[^>]*>(.+)</script>@ismU', '', $out_html);
238
        $out_html = preg_replace('@<style[^>]*>(.+)</style>@ismU', '', $out_html);
239
 
240
        return array($out_html, $out_js, $out_css);
392 daniel-mar 241
}
242
 
400 daniel-mar 243
function sha3_512($password, $raw_output=false) {
392 daniel-mar 244
        if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
400 daniel-mar 245
                return hash('sha3-512', $password, $raw_output);
392 daniel-mar 246
        } else {
400 daniel-mar 247
                return bb\Sha3\Sha3::hash($password, 512, $raw_output);
392 daniel-mar 248
        }
249
}
486 daniel-mar 250
 
710 daniel-mar 251
function sha3_512_hmac($message, $key, $raw_output=false) {
252
        // RFC 2104 HMAC
253
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
254
                                return hash_hmac('sha3-512', $message, $key, $raw_output);
255
                } else {
256
                $blocksize = 576; // block size of sha-512!
257
 
258
                if (strlen($key) > ($blocksize/8)) {
259
                        $k_ = sha3_512($key,true);
260
                } else {
261
                        $k_ = $key;
262
                }
263
 
264
                $k_opad = str_repeat(chr(0x5C),($blocksize/8));
265
                $k_ipad = str_repeat(chr(0x36),($blocksize/8));
266
                for ($i=0; $i<strlen($k_); $i++) {
267
                        $k_opad[$i] = $k_opad[$i] ^ $k_[$i];
268
                        $k_ipad[$i] = $k_ipad[$i] ^ $k_[$i];
269
                }
270
 
271
                return sha3_512($k_opad . sha3_512($k_ipad . $message, true));
272
                }
273
}
274
 
625 daniel-mar 275
if (!function_exists('str_ends_with')) {
276
        // PHP 7.x compatibility
277
        function str_ends_with($haystack, $needle) {
278
                $length = strlen($needle);
279
                return $length > 0 ? substr($haystack, -$length) === $needle : true;
280
        }
281
}
282
 
283
if (!function_exists('str_starts_with')) {
284
        // PHP 7.x compatibility
285
        function str_starts_with($haystack, $needle) {
286
                return strpos($haystack, $needle) === 0;
287
        }
288
}
289
 
632 daniel-mar 290
function rec_is_dir($dir) {
719 daniel-mar 291
        $dirs = @glob($dir);
292
        if ($dirs) foreach ($dirs as $dir) {
632 daniel-mar 293
                if (is_dir($dir)) return true;
294
        }
295
        return false;
296
}
297
 
641 daniel-mar 298
function isInternetExplorer() {
299
        // see also includes/oidplus_base.js
300
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
301
        return ((strpos($ua,'MSIE ') !== false) || (strpos($ua,'Trident/') !== false));
302
}
653 daniel-mar 303
 
304
function url_get_contents($url) {
305
        if (function_exists('curl_init')) {
306
                $ch = curl_init();
698 daniel-mar 307
                if (class_exists('OIDplus')) {
308
                        if (ini_get('curl.cainfo') == '') curl_setopt($ch, CURLOPT_CAINFO, OIDplus::localpath() . 'vendor/cacert.pem');
309
                }
653 daniel-mar 310
                curl_setopt($ch, CURLOPT_URL, $url);
715 daniel-mar 311
                curl_setopt($ch, CURLOPT_USERAGENT, 'ViaThinkSoft-OIDplus/2.0');
653 daniel-mar 312
                curl_setopt($ch, CURLOPT_POST, 0);
313
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
314
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
315
                curl_setopt($ch, CURLOPT_AUTOREFERER, true);
316
                if (!($res = @curl_exec($ch))) return false;
317
                curl_close($ch);
318
        } else {
716 daniel-mar 319
                $opts = [
320
                        "http" => [
321
                                "method" => "GET",
322
                                "header" => "User-Agent: ViaThinkSoft-OIDplus/2.0\r\n"
323
                        ]
324
                ];
325
                $context = stream_context_create($opts);
326
                $res = @file_get_contents($url, false, $context);
653 daniel-mar 327
                if ($res === false) return false;
328
        }
329
        return $res;
660 daniel-mar 330
}