83802adc9ac4f8d63828881d1552a3355df75770
[cacert-devel.git] / includes / general.php
1 <? /*
2 LibreSSL - CAcert web application
3 Copyright (C) 2004-2008 CAcert Inc.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 require_once(dirname(__FILE__)."/lib/general.php");
20 require_once(dirname(__FILE__)."/notary.inc.php");
21
22 session_name("cacert");
23 session_start();
24
25 // session_register("_config");
26 // session_register("profile");
27 // session_register("signup");
28 // session_register("lostpw");
29 // if($_SESSION['profile']['id'] > 0)
30 // session_regenerate_id();
31
32 //cf. http://stackoverflow.com/a/14532168
33 if(!defined('ENT_HTML401')) define('ENT_HTML401', 0);
34 if(!defined('ENT_XML1')) define('ENT_XML1', 16);
35 if(!defined('ENT_XHTML')) define('ENT_XHTML', 32);
36 if(!defined('ENT_HTML5')) define('ENT_HTML5', (32|16));
37
38 $pageLoadTime_Start = microtime(true);
39
40 $junk = array(_("Face to Face Meeting"), _("Trusted Third Parties"), _("Thawte Points Transfer"), _("Administrative Increase"),
41 _("CT Magazine - Germany"), _("Temporary Increase"), _("Unknown"));
42
43 $_SESSION['_config']['errmsg']="";
44
45 $id = 0; if(array_key_exists("id",$_REQUEST)) $id=intval($_REQUEST['id']);
46 $oldid = 0; if(array_key_exists("oldid",$_REQUEST)) $oldid=intval($_REQUEST['oldid']);
47
48 $_SESSION['_config']['filepath'] = "/www";
49
50 require_once($_SESSION['_config']['filepath']."/includes/mysql.php");
51 require_once($_SESSION['_config']['filepath'].'/includes/lib/account.php');
52 require_once($_SESSION['_config']['filepath'].'/includes/lib/l10n.php');
53
54 if(array_key_exists('HTTP_HOST',$_SERVER) &&
55 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['normalhostname'] &&
56 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['securehostname'])
57 {
58 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
59 header("location: https://".$_SESSION['_config']['normalhostname']);
60 else
61 header("location: http://".$_SESSION['_config']['normalhostname']);
62 exit;
63 }
64
65 if(array_key_exists('HTTP_HOST',$_SERVER) &&
66 ($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname']))
67 {
68 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
69 {
70 }
71 else
72 {
73 if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname']){
74 header("location: https://". $_SESSION['_config']['securehostname']);
75 }
76 exit;
77
78 }
79 }
80
81 L10n::detect_language();
82 L10n::init_gettext();
83
84 if(array_key_exists('profile',$_SESSION) && is_array($_SESSION['profile']) && array_key_exists('id',$_SESSION['profile']) && $_SESSION['profile']['id'] > 0)
85 {
86 $locked = mysql_fetch_assoc(mysql_query("select `locked` from `users` where `id`='".intval($_SESSION['profile']['id'])."'"));
87 if($locked['locked'] == 0)
88 {
89 update_points_in_profile();
90 } else {
91 $_SESSION['profile'] = "";
92 unset($_SESSION['profile']);
93 }
94 }
95
96 function loadem($section = "index")
97 {
98 if($section != "index" && $section != "account")
99 {
100 $section = "index";
101 }
102
103 if($section == "account"){
104 include_once($_SESSION['_config']['filepath']."/includes/account_stuff.php");
105 }
106
107 if($section == "index"){
108 include_once($_SESSION['_config']['filepath']."/includes/general_stuff.php");
109 }
110 }
111
112 function includeit($id = "0", $section = "index")
113 {
114 $id = intval($id);
115 if($section != "index" && $section != "account" && $section != "wot" && $section != "help" && $section != "gpg" && $section != "disputes" && $section != "advertising")
116 {
117 $section = "index";
118 }
119
120 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
121 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
122 }
123 else {
124 $id = "0";
125
126 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
127 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
128 } else {
129
130 $section = "index";
131 $id = "0";
132
133 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php")){
134 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
135 } else {
136 include_once($_SESSION['_config']['filepath']."/www/error404.php");
137 }
138 }
139 }
140 }
141
142 function checkpwlight($pwd) {
143 $points = 0;
144
145 if(strlen($pwd) > 15)
146 $points++;
147 if(strlen($pwd) > 20)
148 $points++;
149 if(strlen($pwd) > 25)
150 $points++;
151 if(strlen($pwd) > 30)
152 $points++;
153
154 //echo "Points due to length: $points<br/>";
155
156 if(preg_match("/\d/", $pwd))
157 $points++;
158
159 if(preg_match("/[a-z]/", $pwd))
160 $points++;
161
162 if(preg_match("/[A-Z]/", $pwd))
163 $points++;
164
165 if(preg_match("/\W/", $pwd))
166 $points++;
167
168 if(preg_match("/\s/", $pwd))
169 $points++;
170
171 //echo "Points due to length and charset: $points<br/>";
172
173 // check for historical password proposal
174 if ($pwd === "Fr3d Sm|7h") {
175 return 0;
176 }
177
178 return $points;
179 }
180
181 function checkpw($pwd, $email, $fname, $mname, $lname, $suffix)
182 {
183 $points = checkpwlight($pwd);
184
185 if(@strstr(strtolower($pwd), strtolower($email)))
186 $points--;
187
188 if(@strstr(strtolower($email), strtolower($pwd)))
189 $points--;
190
191 if(@strstr(strtolower($pwd), strtolower($fname)))
192 $points--;
193
194 if(@strstr(strtolower($fname), strtolower($pwd)))
195 $points--;
196
197 if($mname)
198 if(@strstr(strtolower($pwd), strtolower($mname)))
199 $points--;
200
201 if($mname)
202 if(@strstr(strtolower($mname), strtolower($pwd)))
203 $points--;
204
205 if(@strstr(strtolower($pwd), strtolower($lname)))
206 $points--;
207
208 if(@strstr(strtolower($lname), strtolower($pwd)))
209 $points--;
210
211 if($suffix)
212 if(@strstr(strtolower($pwd), strtolower($suffix)))
213 $points--;
214
215 if($suffix)
216 if(@strstr(strtolower($suffix), strtolower($pwd)))
217 $points--;
218
219 //echo "Points due to name matches: $points<br/>";
220
221 $shellpwd = escapeshellarg($pwd);
222 $do = shell_exec("grep -F -- $shellpwd /usr/share/dict/american-english");
223 if($do)
224 $points--;
225
226 //echo "Points due to wordlist: $points<br/>";
227
228 return($points);
229 }
230
231 function extractit()
232 {
233 $bits = explode(": ", $_SESSION['_config']['subject'], 2);
234 $bits = str_replace(", ", "|", str_replace("/", "|", array_key_exists('1',$bits)?$bits['1']:""));
235 $bits = explode("|", $bits);
236
237 $_SESSION['_config']['cnc'] = $_SESSION['_config']['subaltc'] = 0;
238 $_SESSION['_config']['OU'] = "";
239
240 if(is_array($bits))
241 foreach($bits as $val)
242 {
243 if(!strstr($val, "="))
244 continue;
245
246 $split = explode("=", $val);
247
248 $k = $split[0];
249 $split['1'] = trim($split['1']);
250 if($k == "CN" && $split['1'])
251 {
252 $k = $_SESSION['_config']['cnc'].".".$k;
253 $_SESSION['_config']['cnc']++;
254 $_SESSION['_config'][$k] = $split['1'];
255 }
256 if($k == "OU" && $split['1'] && $_SESSION['_config']['OU'] == "")
257 {
258 $_SESSION['_config']['OU'] = $split['1'];
259 }
260 if($k == "subjectAltName" && $split['1'])
261 {
262 $k = $_SESSION['_config']['subaltc'].".".$k;
263 $_SESSION['_config']['subaltc']++;
264 $_SESSION['_config'][$k] = $split['1'];
265 }
266 }
267 }
268
269 function isValidWildcard($name){
270 if(substr($name,0,2) == "*."){
271 $name = substr($name, 2);
272 }
273 if(!preg_match('/^(\\.(?!-)[a-z0-9_-]*[a-z0-9])+$/i','.'.$name)){
274 return false;
275 }
276 return strpos($name, "*") === false;
277 }
278
279 function getcn()
280 {
281 unset($_SESSION['_config']['rows']);
282 unset($_SESSION['_config']['rowid']);
283 unset($_SESSION['_config']['rejected']);
284 $rows=array();
285 $rowid=array();
286 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
287 {
288 $CN = $_SESSION['_config']["$cnc.CN"];
289 $bits = explode(".", $CN);
290 $dom = "";
291 $cnok = 0;
292
293 if(!isValidWildcard($CN)){
294 $_SESSION['_config']['rejected'][] = $CN;
295 continue;
296 }
297
298 for($i = count($bits) - 1; $i >= 0; $i--)
299 {
300 if($dom)
301 $dom = $bits[$i].".".$dom;
302 else
303 $dom = $bits[$i];
304 $_SESSION['_config']['row'] = "";
305 $dom = mysql_real_escape_string($dom);
306 $query = "select * from domains where `memid`='".intval($_SESSION['profile']['id'])."' and `domain` = '$dom' and `deleted`=0 and `hash`=''";
307 $res = mysql_query($query);
308 if(mysql_num_rows($res) > 0)
309 {
310 $cnok = 1;
311 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
312 $rowid[] = $_SESSION['_config']['row']['id'];
313 break;
314 }
315 }
316
317 if($cnok == 0)
318 $_SESSION['_config']['rejected'][] = $CN;
319
320 if($_SESSION['_config']['row'] != "")
321 $rows[] = $CN;
322 }
323 // if(count($rows) <= 0)
324 // {
325 // echo _("There were no valid CommonName fields on the CSR, or I was unable to match any of these against your account. Please review your CSR, or add and verify domains contained in it to your account before trying again.");
326 // exit;
327 // }
328
329 $_SESSION['_config']['rows'] = $rows;
330 $_SESSION['_config']['rowid'] = $rowid;
331 }
332
333 function getalt()
334 {
335 unset($_SESSION['_config']['altrows']);
336 unset($_SESSION['_config']['altid']);
337 $altrows=array();
338 $altid=array();
339 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
340 {
341 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
342 if(substr($subalt, 0, 4) == "DNS:")
343 $alt = substr($subalt, 4);
344 else
345 continue;
346
347 if(!isValidWildcard($alt)){
348 $_SESSION['_config']['rejected'][] = $alt;
349 continue;
350 }
351
352 $bits = explode(".", $alt);
353 $dom = "";
354 $altok = 0;
355 for($i = count($bits) - 1; $i >= 0; $i--)
356 {
357 if($dom)
358 $dom = $bits[$i].".".$dom;
359 else
360 $dom = $bits[$i];
361 $_SESSION['_config']['altrow'] = "";
362 $dom = mysql_real_escape_string($dom);
363 $query = "select * from domains where `memid`='".intval($_SESSION['profile']['id'])."' and `domain` = '$dom' and `deleted`=0 and `hash`=''";
364 $res = mysql_query($query);
365 if(mysql_num_rows($res) > 0)
366 {
367 $altok = 1;
368 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
369 $altid[] = $_SESSION['_config']['altrow']['id'];
370 break;
371 }
372 }
373
374 if($altok == 0)
375 $_SESSION['_config']['rejected'][] = $alt;
376
377 if($_SESSION['_config']['altrow'] != "")
378 $altrows[] = $subalt;
379 }
380 $_SESSION['_config']['altrows'] = $altrows;
381 $_SESSION['_config']['altid'] = $altid;
382 }
383
384 function getcn2()
385 {
386 $rows=array();
387 $rowid=array();
388 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
389 {
390 $CN = $_SESSION['_config']["$cnc.CN"];
391 $bits = explode(".", $CN);
392 $dom = "";
393
394 if(!isValidWildcard($CN)){
395 $_SESSION['_config']['rejected'][] = $CN;
396 continue;
397 }
398
399 for($i = count($bits) - 1; $i >= 0; $i--)
400 {
401 if($dom)
402 $dom = $bits[$i].".".$dom;
403 else
404 $dom = $bits[$i];
405 $_SESSION['_config']['row'] = "";
406 $dom = mysql_real_escape_string($dom);
407 $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
408 `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
409 `org`.`orgid`=`orginfo`.`id` and
410 `orgdomains`.`orgid`=`orginfo`.`id` and
411 `orgdomains`.`domain`='$dom'";
412 $res = mysql_query($query);
413 if(mysql_num_rows($res) > 0)
414 {
415 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
416 $rowid[] = $_SESSION['_config']['row']['id'];
417 break;
418 }
419 }
420
421 if($_SESSION['_config']['row'] != "")
422 $rows[] = $CN;
423 }
424 // if(count($rows) <= 0)
425 // {
426 // echo _("There were no valid CommonName fields on the CSR, or I was unable to match any of these against your account. Please review your CSR, or add and verify domains contained in it to your account before trying again.");
427 // exit;
428 // }
429 $_SESSION['_config']['rows'] = $rows;
430 $_SESSION['_config']['rowid'] = $rowid;
431 }
432
433 function getalt2()
434 {
435 $altrows=array();
436 $altid=array();
437 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
438 {
439 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
440 if(substr($subalt, 0, 4) == "DNS:")
441 $alt = substr($subalt, 4);
442 else
443 continue;
444
445 if(!isValidWildcard($alt)){
446 $_SESSION['_config']['rejected'][] = $alt;
447 continue;
448 }
449
450 $bits = explode(".", $alt);
451 $dom = "";
452 for($i = count($bits) - 1; $i >= 0; $i--)
453 {
454 if($dom)
455 $dom = $bits[$i].".".$dom;
456 else
457 $dom = $bits[$i];
458 $_SESSION['_config']['altrow'] = "";
459 $dom = mysql_real_escape_string($dom);
460 $query = "select * from `orginfo`,`orgdomains`,`org` where
461 `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
462 `org`.`orgid`=`orginfo`.`id` and
463 `orgdomains`.`orgid`=`orginfo`.`id` and
464 `orgdomains`.`domain`='$dom'";
465 $res = mysql_query($query);
466 if(mysql_num_rows($res) > 0)
467 {
468 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
469 $altid[] = $_SESSION['_config']['altrow']['id'];
470 break;
471 }
472 }
473
474 if($_SESSION['_config']['altrow'] != "")
475 $altrows[] = $subalt;
476 }
477 $_SESSION['_config']['altrows'] = $altrows;
478 $_SESSION['_config']['altid'] = $altid;
479 }
480
481 function checkownership($hostname)
482 {
483 $bits = explode(".", $hostname);
484 $dom = "";
485 for($i = count($bits) - 1; $i >= 0; $i--)
486 {
487 if($dom)
488 $dom = $bits[$i].".".$dom;
489 else
490 $dom = $bits[$i];
491 $dom = mysql_real_escape_string($dom);
492 $query = "select * from `org`,`orgdomains`,`orginfo`
493 where `org`.`memid`='".intval($_SESSION['profile']['id'])."'
494 and `orgdomains`.`orgid`=`org`.`orgid`
495 and `orginfo`.`id`=`org`.`orgid`
496 and `orgdomains`.`domain`='$dom'";
497 $res = mysql_query($query);
498 if(mysql_num_rows($res) > 0)
499 {
500 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
501 return(true);
502 }
503 }
504 return(false);
505 }
506
507 function maxpoints($id = 0)
508 {
509 if($id <= 0)
510 $id = $_SESSION['profile']['id'];
511
512 $points = get_received_total_points($id);
513
514 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
515 $query = "select * from `users` where `id`='".intval($_SESSION['profile']['id'])."' and `dob` < '$dob'";
516 if(mysql_num_rows(mysql_query($query)) < 1)
517 {
518 if($points >= 100)
519 return(10);
520 else
521 return(0);
522 }
523
524 if($points >= 150)
525 return(35);
526 if($points >= 140)
527 return(30);
528 if($points >= 130)
529 return(25);
530 if($points >= 120)
531 return(20);
532 if($points >= 110)
533 return(15);
534 if($points >= 100)
535 return(10);
536 return(0);
537 }
538
539 /**
540 * Decode UTF-8 byte sequences into HTML entities
541 *
542 * @see https://blog.benny-baumann.de/?p=332
543 */
544 function charset_decode_utf8_callback($match) {
545 $m = $match[0];
546
547 switch(strlen($m)) {
548 case 6:
549 // decode six byte unicode characters
550 return '&#'.((ord($m[0])-252)*1073741824+(ord($m[1])-200)*16777216+(ord($m[2])-200)*262144+(ord($m[3])-128)*4096+(ord($m[4])-128)*64+(ord($m[5])-128)).';';
551 case 5:
552 // decode five byte unicode characters
553 return '&#'.((ord($m[0])-248)*16777216+(ord($m[1])-200)*262144+(ord($m[2])-128)*4096+(ord($m[3])-128)*64+(ord($m[4])-128)).';';
554 case 4:
555 // decode four byte unicode characters
556 return '&#'.((ord($m[0])-240)*262144+(ord($m[1])-128)*4096+(ord($m[2])-128)*64+(ord($m[3])-128)).';';
557 case 3:
558 // decode three byte unicode characters
559 return '&#'.((ord($m[0])-224)*4096+(ord($m[1])-128)*64+(ord($m[2])-128)).';';
560 case 2:
561 // decode two byte unicode characters
562 return '&#'.((ord($m[0])-192)*64+(ord($m[1])-128)).';';
563 default:
564 return $m;
565 }
566 }
567
568 /**
569 * Decode utf-8 strings
570 * @param string $string Encoded string
571 * @return string Decoded string
572 * @see https://blog.benny-baumann.de/?p=332
573 */
574 function charset_decode_utf8 ($string) {
575 // decode 2-6 byte unicode characters
576 $string = preg_replace_callback("/[\374-\375][\200-\277][\200-\277][\200-\277][\200-\277][\200-\277]|".
577 "[\370-\373][\200-\277][\200-\277][\200-\277][\200-\277]|".
578 "[\360-\367][\200-\277][\200-\277][\200-\277]|".
579 "[\340-\357][\200-\277][\200-\277]|".
580 "[\300-\337][\200-\277]/",
581 'charset_decode_utf8_callback', $string);
582
583 // remove broken unicode
584 $string = preg_replace("/[\200-\237]|\240|[\241-\377]/",'?',$string);
585
586 return $string;
587 }
588
589 function gpg_hex2bin($data)
590 {
591 while(strstr($data, "\\x"))
592 {
593 $pos = strlen($data) - strlen(strstr($data, "\\x"));
594 $before = substr($data, 0, $pos);
595 $char = chr(hexdec(substr($data, $pos + 2, 2)));
596 $after = substr($data, $pos + 4);
597 $data = $before.$char.$after;
598 }
599
600 return htmlentities(charset_decode_utf8($data), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);
601 }
602
603 function signmail($to, $subject, $message, $from, $replyto = "")
604 {
605 if($replyto == "")
606 $replyto = $from;
607 $tmpfname = tempnam("/tmp", "CSR");
608 $fp = fopen($tmpfname, "w");
609 fputs($fp, $message);
610 fclose($fp);
611 $to_esc = escapeshellarg($to);
612 $do = shell_exec("/usr/bin/gpg --homedir /home/gpg --clearsign \"$tmpfname\"|/usr/sbin/sendmail ".$to_esc);
613 @unlink($tmpfname);
614 }
615
616 function checkEmail($email)
617 {
618 $myemail = mysql_real_escape_string($email);
619 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
620 {
621 list($username,$domain)=explode('@',$email,2);
622 $mxhostrr = array();
623 $mxweight = array();
624 if( !getmxrr($domain, $mxhostrr, $mxweight) ) {
625 $mxhostrr = array($domain);
626 $mxweight = array(0);
627 } else if ( empty($mxhostrr) ) {
628 $mxhostrr = array($domain);
629 $mxweight = array(0);
630 }
631
632 $mxhostprio = array();
633 for($i = 0; $i < count($mxhostrr); $i++) {
634 $mx_host = trim($mxhostrr[$i], '.');
635 $mx_prio = $mxweight[$i];
636 if(empty($mxhostprio[$mx_prio])) {
637 $mxhostprio[$mx_prio] = array();
638 }
639 $mxhostprio[$mx_prio][] = $mx_host;
640 }
641
642 array_walk($mxhostprio, function(&$mx) { shuffle($mx); } );
643 ksort($mxhostprio);
644
645 $mxhosts = array();
646 foreach($mxhostprio as $mx_prio => $mxhostnames) {
647 foreach($mxhostnames as $mx_host) {
648 $mxhosts[] = $mx_host;
649 }
650 }
651
652 foreach($mxhosts as $key => $domain)
653 {
654 $fp_opt = array(
655 'ssl' => array(
656 'verify_peer' => false, // Opportunistic Encryption
657 )
658 );
659 $fp_ctx = stream_context_create($fp_opt);
660 $fp = @stream_socket_client("tcp://$domain:25",$errno,$errstr,5,STREAM_CLIENT_CONNECT,$fp_ctx);
661 if($fp)
662 {
663 stream_set_blocking($fp, true);
664
665 $has_starttls = false;
666
667 do {
668 $line = fgets($fp, 4096);
669 } while(substr($line, 0, 4) == "220-");
670 if(substr($line, 0, 3) != "220") {
671 fclose($fp);
672 continue;
673 }
674
675 fputs($fp, "EHLO www.cacert.org\r\n");
676 do {
677 $line = fgets($fp, 4096);
678 $has_starttls |= substr(trim($line),4) == "STARTTLS";
679 } while(substr($line, 0, 4) == "250-");
680 if(substr($line, 0, 3) != "250") {
681 fclose($fp);
682 continue;
683 }
684
685 if($has_starttls) {
686 fputs($fp, "STARTTLS\r\n");
687 do {
688 $line = fgets($fp, 4096);
689 } while(substr($line, 0, 4) == "220-");
690 if(substr($line, 0, 3) != "220") {
691 fclose($fp);
692 continue;
693 }
694
695 stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
696
697 fputs($fp, "EHLO www.cacert.org\r\n");
698 do {
699 $line = fgets($fp, 4096);
700 } while(substr($line, 0, 4) == "250-");
701 if(substr($line, 0, 3) != "250") {
702 fclose($fp);
703 continue;
704 }
705 }
706
707 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
708 do {
709 $line = fgets($fp, 4096);
710 } while(substr($line, 0, 4) == "250-");
711 if(substr($line, 0, 3) != "250") {
712 fclose($fp);
713 continue;
714 }
715
716 fputs($fp, "RCPT TO:<$email>\r\n");
717 do {
718 $line = fgets($fp, 4096);
719 } while(substr($line, 0, 4) == "250-");
720 if(substr($line, 0, 3) != "250") {
721 fclose($fp);
722 continue;
723 }
724
725 fputs($fp, "QUIT\r\n");
726 fclose($fp);
727
728 $line = mysql_real_escape_string(trim(strip_tags($line)));
729 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
730 if(isset($_SESSION['profile']) && is_array($_SESSION['profile']) && isset($_SESSION['profile']['id'])) $query.=", `uid`='".intval($_SESSION['profile']['id'])."'";
731 mysql_query($query);
732
733 if(substr($line, 0, 3) != "250")
734 return $line;
735 else
736 return "OK";
737 }
738 }
739 }
740 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".intval($_SESSION['profile']['id'])."',
741 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
742 mysql_query($query);
743 return _("Failed to make a connection to the mail server");
744 }
745
746 function waitForResult($table, $certid, $id = 0, $show = 1)
747 {
748 $found = $trycount = 0;
749 if($certid<=0)
750 {
751 if($show) showheader(_("My CAcert.org Account!"));
752 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
753 if($show) showfooter();
754 if($show) exit;
755 return;
756 }
757 while($trycount++ <= 40)
758 {
759 if($table == "gpg")
760 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
761 else
762 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
763 $res = mysql_query($query);
764 if(mysql_num_rows($res) > 0)
765 {
766 $found = 1;
767 break;
768 }
769 sleep(3);
770 }
771
772 if(!$found)
773 {
774 if($show) showheader(_("My CAcert.org Account!"));
775 $query = "select * from `$table` where `id`='".intval($certid)."' ";
776 $res = mysql_query($query);
777 $body="";
778 $subject="";
779 if(mysql_num_rows($res) > 0)
780 {
781 printf('<p>' . _("Your certificate request is still queued and hasn't been processed yet. Please wait, and go to Certificates -> View to see it's status." . '</p>'));
782 $subject="[CAcert.org] Certificate TIMEOUT";
783 $body = "A certificate has timed out!\n\n";
784 }
785 else
786 {
787 printf('<p>' . _("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.") . " certid:$table:".intval($certid) . '</p>', "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
788 $subject="[CAcert.org] Certificate FAILURE";
789 $body = "A certificate has failed: $table $certid $id $show\n\n";
790 }
791
792 $body .= _("Best regards")."\n"._("CAcert.org Support!");
793
794 sendmail("sw-message@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
795
796 if($show) showfooter();
797 if($show) exit;
798 }
799 }
800
801
802
803 function generateTicket()
804 {
805 $query = "insert into tickets (timestamp) values (now()) ";
806 mysql_query($query);
807 $ticket = mysql_insert_id();
808 return $ticket;
809 }
810
811 function sanitizeHTML($input)
812 {
813 return htmlentities(strip_tags($input), ENT_QUOTES | ENT_SUBSTITUTE, 'ISO-8859-1', false);
814 //In case of problems, please use the following line again:
815 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
816 //return htmlspecialchars(strip_tags($input));
817 }
818
819 function make_hash()
820 {
821 if(function_exists("dio_open"))
822 {
823 $rnd = dio_open("/dev/urandom",O_RDONLY);
824 $hash = md5(dio_read($rnd,64));
825 dio_close($rnd);
826 } else {
827 $rnd = fopen("/dev/urandom", "r");
828 $hash = md5(fgets($rnd, 64));
829 fclose($rnd);
830 }
831 return($hash);
832 }
833
834 function csrf_check($nam, $show=1)
835 {
836 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
837 {
838 showheader(_("My CAcert.org Account!"));
839 echo _("CSRF Hash is missing. Please try again.")."\n";
840 showfooter();
841 exit();
842 }
843 if(strlen($_REQUEST['csrf'])!=32)
844 {
845 showheader(_("My CAcert.org Account!"));
846 echo _("CSRF Hash is wrong. Please try again.")."\n";
847 showfooter();
848 exit();
849 }
850 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
851 {
852 showheader(_("My CAcert.org Account!"));
853 echo _("CSRF Hash is wrong. Please try again.")."\n";
854 showfooter();
855 exit();
856 }
857 }
858 function make_csrf($nam)
859 {
860 $hash=make_hash();
861 $_SESSION['csrf_'.$nam][$hash]=1;
862 return($hash);
863 }
864
865 function clean_csr($CSR)
866 {
867 $newcsr = str_replace("\r\n","\n",trim($CSR));
868 $newcsr = str_replace("\n\n","\n",$newcsr);
869 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
870 }
871 function clean_gpgcsr($CSR)
872 {
873 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
874 }
875
876 function sanitizeFilename($text)
877 {
878 $text=preg_replace("/[^\w-.@]/","",$text);
879 return($text);
880 }
881
882
883 // returns text message to be shown to the user given the result of is_no_assurer
884 function no_assurer_text($Status)
885 {
886 if ($Status == 0) {
887 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
888 } elseif ($Status == 3) {
889 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
890 } elseif ($Status == 5) {
891 $Result = _("You have at least 100 Assurance Points, if you want to become an assurer try the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
892 } elseif ($Status == 7) {
893 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
894 } elseif ($Status & 8 > 0) {
895 $Result = _("Sorry, you are not allowed to be an Assurer. Please contact").' <a href="mailto:cacert-support@lists.cacert.org">cacert-support@lists.cacert.org</a>'._(" if you feel that this is not corect.");
896 } else {
897 $Result = _("You are not an Assurer, but the reason is not stored in the database. Please contact").' <a href="mailto:cacert-support@lists.cacert.org">cacert-support@lists.cacert.org</a>.';
898 }
899 return $Result;
900 }
901
902 function is_assurer($userID)
903 {
904 if (get_assurer_status($userID))
905 return 0;
906 else
907 return 1;
908 }
909
910 function get_assurer_reason($userID)
911 {
912 return no_assurer_text(get_assurer_status($userID));
913 }
914
915 function generatecertpath($type,$kind,$id)
916 {
917 $name="../$type/$kind-".intval($id).".$type";
918 $newlayout=1;
919 if($newlayout)
920 {
921 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
922 if (!is_dir("../csr")) { mkdir("../csr",0777); }
923 if (!is_dir("../crt")) { mkdir("../crt",0777); }
924
925 if (!is_dir("../csr/$kind")) { mkdir("../csr/$kind",0777); }
926 if (!is_dir("../crt/$kind")) { mkdir("../crt/$kind",0777); }
927 if (!is_dir("../csr/$kind/".intval($id/1000))) { mkdir("../csr/$kind/".intval($id/1000)); }
928 if (!is_dir("../crt/$kind/".intval($id/1000))) { mkdir("../crt/$kind/".intval($id/1000)); }
929 }
930 return $name;
931 }
932
933 /**
934 * Run the sql query given in $sql.
935 * The resource returned by mysql_query is
936 * returned by this function.
937 *
938 * It should be safe to replace every mysql_query
939 * call by a mysql_extended_query call.
940 */
941 function mysql_timed_query($sql)
942 {
943 global $sql_data_log;
944 $query_start = microtime(true);
945 $res = mysql_query($sql);
946 $query_end = microtime(true);
947 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
948 return $res;
949 }
950
951 /**
952 * Returns the given ip address truncated to /16 (ipv4) or to /48 (ipv6)
953 */
954 function anonymizeIP($ip){
955 $bits = @inet_pton($ip);
956 if($bits === false) {
957 return false;
958 }
959
960 if(strlen($bits) == 4) {
961 $bits[2] = "\0";
962 $bits[3] = "\0";
963 $newIP = @inet_ntop($bits);
964 if($newIP !== false) {
965 $newIP .= "/16";
966 }
967 return $newIP;
968 } else if(strlen($bits) == 16) {
969 for($i=6;$i<16;$i++){
970 $bits[$i]="\0";
971 }
972 $newIP = @inet_ntop($bits);
973 if($newIP !== false) {
974 $newIP .= "/48";
975 }
976 return $newIP;
977 }
978 return false;
979 }