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