Source code taken from cacert-20120429.tar.bz2
[cacert.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 session_name("cacert");
19 session_start();
20
21 session_register("_config");
22 session_register("profile");
23 session_register("signup");
24 session_register("lostpw");
25 // if($_SESSION['profile']['id'] > 0)
26 // session_regenerate_id();
27
28 $pageLoadTime_Start = microtime(true);
29
30 $junk = array(_("Face to Face Meeting"), _("Trusted Third Parties"), _("Thawte Points Transfer"), _("Administrative Increase"),
31 _("CT Magazine - Germany"), _("Temporary Increase"), _("Unknown"));
32
33 $_SESSION['_config']['errmsg']="";
34
35 $id = 0; if(array_key_exists("id",$_REQUEST)) $id=intval($_REQUEST['id']);
36 $oldid = 0; if(array_key_exists("oldid",$_REQUEST)) $oldid=intval($_REQUEST['oldid']);
37
38 $_SESSION['_config']['filepath'] = "/www";
39
40 require_once($_SESSION['_config']['filepath']."/includes/mysql.php");
41 require_once($_SESSION['_config']['filepath'].'/includes/lib/account.php');
42 require_once($_SESSION['_config']['filepath'].'/includes/lib/l10n.php');
43
44 if(array_key_exists('HTTP_HOST',$_SERVER) &&
45 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['normalhostname'] &&
46 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['securehostname'] &&
47 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['tverify'] &&
48 $_SERVER['HTTP_HOST'] != "stamp.cacert.org")
49 {
50 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
51 header("location: https://".$_SESSION['_config']['normalhostname']);
52 else
53 header("location: http://".$_SESSION['_config']['normalhostname']);
54 exit;
55 }
56
57 if(array_key_exists('HTTP_HOST',$_SERVER) &&
58 ($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] ||
59 $_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify']))
60 {
61 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
62 {
63 }
64 else
65 {
66 if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'])
67 header("location: https://". $_SESSION['_config']['securehostname']);
68 if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify'])
69 header("location: https://".$_SESSION['_config']['tverify']);
70 exit;
71 }
72 }
73
74 L10n::detect_language();
75 L10n::init_gettext();
76
77 if(array_key_exists('profile',$_SESSION) && is_array($_SESSION['profile']) && array_key_exists('id',$_SESSION['profile']) && $_SESSION['profile']['id'] > 0)
78 {
79 $locked = mysql_fetch_assoc(mysql_query("select `locked` from `users` where `id`='".$_SESSION['profile']['id']."'"));
80 if($locked['locked'] == 0)
81 {
82 $query = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
83 $res = mysql_query($query);
84 $row = mysql_fetch_assoc($res);
85 $_SESSION['profile']['points'] = $row['total'];
86 } else {
87 $_SESSION['profile'] = "";
88 unset($_SESSION['profile']);
89 }
90 }
91
92 function loadem($section = "index")
93 {
94 if($section != "index" && $section != "account" && $section != "tverify")
95 {
96 $section = "index";
97 }
98
99 if($section == "account")
100 include_once($_SESSION['_config']['filepath']."/includes/account_stuff.php");
101
102 if($section == "index")
103 include_once($_SESSION['_config']['filepath']."/includes/general_stuff.php");
104
105 if($section == "tverify")
106 include_once($_SESSION['_config']['filepath']."/includes/tverify_stuff.php");
107 }
108
109 function includeit($id = "0", $section = "index")
110 {
111 $id = intval($id);
112 if($section != "index" && $section != "account" && $section != "wot" && $section != "help" && $section != "gpg" && $section != "disputes" && $section != "tverify" && $section != "advertising")
113 {
114 $section = "index";
115 }
116
117 if($section == "tverify" && file_exists($_SESSION['_config']['filepath']."/tverify/index/$id.php"))
118 include_once($_SESSION['_config']['filepath']."/tverify/index/$id.php");
119 else if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
120 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
121 else {
122 $id = "0";
123
124 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
125 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
126 else {
127
128 $section = "index";
129 $id = "0";
130
131 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
132 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
133 else
134 include_once($_SESSION['_config']['filepath']."/www/error404.php");
135 }
136 }
137 }
138
139 function checkpwlight($pwd) {
140 $points = 0;
141
142 if(strlen($pwd) > 15)
143 $points++;
144 if(strlen($pwd) > 20)
145 $points++;
146 if(strlen($pwd) > 25)
147 $points++;
148 if(strlen($pwd) > 30)
149 $points++;
150
151 //echo "Points due to length: $points<br/>";
152
153 if(preg_match("/\d/", $pwd))
154 $points++;
155
156 if(preg_match("/[a-z]/", $pwd))
157 $points++;
158
159 if(preg_match("/[A-Z]/", $pwd))
160 $points++;
161
162 if(preg_match("/\W/", $pwd))
163 $points++;
164
165 if(preg_match("/\s/", $pwd))
166 $points++;
167
168 //echo "Points due to length and charset: $points<br/>";
169
170 // check for historical password proposal
171 if ($pwd === "Fr3d Sm|7h") {
172 return 0;
173 }
174
175 return $points;
176 }
177
178 function checkpw($pwd, $email, $fname, $mname, $lname, $suffix)
179 {
180 $points = checkpwlight($pwd);
181
182 if(@strstr(strtolower($pwd), strtolower($email)))
183 $points--;
184
185 if(@strstr(strtolower($email), strtolower($pwd)))
186 $points--;
187
188 if(@strstr(strtolower($pwd), strtolower($fname)))
189 $points--;
190
191 if(@strstr(strtolower($fname), strtolower($pwd)))
192 $points--;
193
194 if($mname)
195 if(@strstr(strtolower($pwd), strtolower($mname)))
196 $points--;
197
198 if($mname)
199 if(@strstr(strtolower($mname), strtolower($pwd)))
200 $points--;
201
202 if(@strstr(strtolower($pwd), strtolower($lname)))
203 $points--;
204
205 if(@strstr(strtolower($lname), strtolower($pwd)))
206 $points--;
207
208 if($suffix)
209 if(@strstr(strtolower($pwd), strtolower($suffix)))
210 $points--;
211
212 if($suffix)
213 if(@strstr(strtolower($suffix), strtolower($pwd)))
214 $points--;
215
216 //echo "Points due to name matches: $points<br/>";
217
218 $do = `grep '$pwd' /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`='".$_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`='".$_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`='".$_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`='".$_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`='".$_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 $query = "select sum(`points`) as `points` from `notary` where `to`='$id' group by `to`";
477 $row = mysql_fetch_assoc(mysql_query($query));
478 $points = $row['points'];
479
480 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
481 $query = "select * from `users` where `id`='".$_SESSION['profile']['id']."' and `dob` < '$dob'";
482 if(mysql_num_rows(mysql_query($query)) < 1)
483 {
484 if($points >= 100)
485 return(10);
486 else
487 return(0);
488 }
489
490 if($points >= 150)
491 return(35);
492 if($points >= 140)
493 return(30);
494 if($points >= 130)
495 return(25);
496 if($points >= 120)
497 return(20);
498 if($points >= 110)
499 return(15);
500 if($points >= 100)
501 return(10);
502 return(0);
503 }
504
505 function hex2bin($data)
506 {
507 while(strstr($data, "\\x"))
508 {
509 $pos = strlen($data) - strlen(strstr($data, "\\x"));
510 $before = substr($data, 0, $pos);
511 $char = chr(hexdec(substr($data, $pos + 2, 2)));
512 $after = substr($data, $pos + 4);
513 $data = $before.$char.$after;
514 }
515 return(utf8_decode($data));
516 }
517
518 function signmail($to, $subject, $message, $from, $replyto = "")
519 {
520 if($replyto == "")
521 $replyto = $from;
522 $tmpfname = tempnam("/tmp", "CSR");
523 $fp = fopen($tmpfname, "w");
524 fputs($fp, $message);
525 fclose($fp);
526 $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
527 @unlink($tmpfname);
528 }
529
530 function checkEmail($email)
531 {
532 $myemail = mysql_real_escape_string($email);
533 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
534 {
535 list($username,$domain)=split('@',$email);
536 $dom = escapeshellarg($domain);
537 $line = trim(`dig +short MX $dom 2>&1`);
538 #echo $email."-$dom-$line-\n";
539 #echo `dig +short mx heise.de 2>&1`."-<br>\n";
540
541 $list = explode("\n", $line);
542 foreach($list as $row)
543 list($pri, $mxhosts[]) = explode(" ", substr(trim($row), 0, -1));
544 $mxhosts[] = $domain;
545 #print_r($mxhosts); die;
546 foreach($mxhosts as $key => $domain)
547 {
548 $fp = @fsockopen($domain,25,$errno,$errstr,5);
549 if($fp)
550 {
551
552 $line = fgets($fp, 4096);
553 while(substr($line, 0, 4) == "220-")
554 $line = fgets($fp, 4096);
555 if(substr($line, 0, 3) != "220")
556 continue;
557 fputs($fp, "HELO www.cacert.org\r\n");
558 $line = fgets($fp, 4096);
559 while(substr($line, 0, 3) == "220")
560 $line = fgets($fp, 4096);
561 if(substr($line, 0, 3) != "250")
562 continue;
563 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
564 $line = fgets($fp, 4096);
565
566 if(substr($line, 0, 3) != "250")
567 continue;
568 fputs($fp, "RCPT TO:<$email>\r\n");
569 $line = trim(fgets($fp, 4096));
570 fputs($fp, "QUIT\r\n");
571 fclose($fp);
572
573 $line = mysql_real_escape_string(trim(strip_tags($line)));
574 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
575 if(is_array($_SESSION['profile'])) $query.=", `uid`='".$_SESSION['profile']['id']."'";
576 mysql_query($query);
577
578 if(substr($line, 0, 3) != "250")
579 return $line;
580 else
581 return "OK";
582 }
583 }
584 }
585 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".$_SESSION['profile']['id']."',
586 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
587 mysql_query($query);
588 return _("Failed to make a connection to the mail server");
589 }
590
591 function waitForResult($table, $certid, $id = 0, $show = 1)
592 {
593 $found = $trycount = 0;
594 if($certid<=0)
595 {
596 if($show) showheader(_("My CAcert.org Account!"));
597 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
598 if($show) showfooter();
599 if($show) exit;
600 return;
601 }
602 while($trycount++ <= 40)
603 {
604 if($table == "gpg")
605 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
606 else
607 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
608 $res = mysql_query($query);
609 if(mysql_num_rows($res) > 0)
610 {
611 $found = 1;
612 break;
613 }
614 sleep(3);
615 }
616
617 if(!$found)
618 {
619 if($show) showheader(_("My CAcert.org Account!"));
620 $query = "select * from `$table` where `id`='".intval($certid)."' ";
621 $res = mysql_query($query);
622 $body="";
623 $subject="";
624 if(mysql_num_rows($res) > 0)
625 {
626 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."));
627 $subject="[CAcert.org] Certificate TIMEOUT";
628 $body = "A certificate has timed out!\n\n";
629 }
630 else
631 {
632 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>");
633 $subject="[CAcert.org] Certificate FAILURE";
634 $body = "A certificate has failed: $table $certid $id $show\n\n";
635 }
636
637 $body .= _("Best regards")."\n"._("CAcert.org Support!");
638
639 sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
640
641 if($show) showfooter();
642 if($show) exit;
643 }
644 }
645
646
647
648 function generateTicket()
649 {
650 $query = "insert into tickets (timestamp) values (now()) ";
651 mysql_query($query);
652 $ticket = mysql_insert_id();
653 return $ticket;
654 }
655
656 function sanitizeHTML($input)
657 {
658 return htmlentities(strip_tags($input), ENT_QUOTES);
659 //In case of problems, please use the following line again:
660 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
661 //return htmlspecialchars(strip_tags($input));
662 }
663
664 function make_hash()
665 {
666 if(function_exists("dio_open"))
667 {
668 $rnd = dio_open("/dev/urandom",O_RDONLY);
669 $hash = md5(dio_read($rnd,64));
670 dio_close($rnd);
671 } else {
672 $rnd = fopen("/dev/urandom", "r");
673 $hash = md5(fgets($rnd, 64));
674 fclose($rnd);
675 }
676 return($hash);
677 }
678
679 function csrf_check($nam, $show=1)
680 {
681 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
682 {
683 showheader(_("My CAcert.org Account!"));
684 echo _("CSRF Hash is missing. Please try again.")."\n";
685 showfooter();
686 exit();
687 }
688 if(strlen($_REQUEST['csrf'])!=32)
689 {
690 showheader(_("My CAcert.org Account!"));
691 echo _("CSRF Hash is wrong. Please try again.")."\n";
692 showfooter();
693 exit();
694 }
695 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
696 {
697 showheader(_("My CAcert.org Account!"));
698 echo _("CSRF Hash is wrong. Please try again.")."\n";
699 showfooter();
700 exit();
701 }
702 }
703 function make_csrf($nam)
704 {
705 $hash=make_hash();
706 $_SESSION['csrf_'.$nam][$hash]=1;
707 return($hash);
708 }
709
710 function clean_csr($CSR)
711 {
712 $newcsr = str_replace("\r\n","\n",trim($CSR));
713 $newcsr = str_replace("\n\n","\n",$newcsr);
714 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
715 }
716 function clean_gpgcsr($CSR)
717 {
718 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
719 }
720
721 function sanitizeFilename($text)
722 {
723 $text=preg_replace("/[^\w-.@]/","",$text);
724 return($text);
725 }
726
727 // returns 0 if $userID is an Assurer
728 // Otherwise :
729 // Bit 0 is always set
730 // Bit 1 is set if 100 Assurance Points are not reached
731 // Bit 2 is set if Assurer Test is missing
732 // Bit 3 is set if the user is not allowed to be an Assurer (assurer_blocked > 0)
733 function get_assurer_status($userID)
734 {
735 $Result = 0;
736 $query = mysql_query('SELECT * FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` '.
737 ' WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = \''.(int)intval($userID).'\'');
738 if(mysql_num_rows($query) < 1)
739 {
740 $Result |= 5;
741 }
742
743 $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
744 $row = mysql_fetch_assoc($query);
745 if ($row['points'] < 100) {
746 $Result |= 3;
747 }
748
749 $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
750 $row = mysql_fetch_assoc($query);
751 if ($row['assurer_blocked'] > 0) {
752 $Result |= 9;
753 }
754
755 return $Result;
756 }
757
758 // returns text message to be shown to the user given the result of is_no_assurer
759 function no_assurer_text($Status)
760 {
761 if ($Status == 0) {
762 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
763 } elseif ($Status == 3) {
764 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
765 } elseif ($Status == 5) {
766 $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>!';
767 } elseif ($Status == 7) {
768 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
769 } elseif ($Status & 8 > 0) {
770 $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.");
771 } else {
772 $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>.';
773 }
774 return $Result;
775 }
776
777 function is_assurer($userID)
778 {
779 if (get_assurer_status($userID))
780 return 0;
781 else
782 return 1;
783 }
784
785 function get_assurer_reason($userID)
786 {
787 return no_assurer_text(get_assurer_status($userID));
788 }
789
790 function generatecertpath($type,$kind,$id)
791 {
792 $name="../$type/$kind-".intval($id).".$type";
793 $newlayout=1;
794 if($newlayout)
795 {
796 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
797 if (!is_dir("../csr")) { mkdir("../csr",0777); }
798 if (!is_dir("../crt")) { mkdir("../crt",0777); }
799
800 if (!is_dir("../csr/$kind")) { mkdir("../csr/$kind",0777); }
801 if (!is_dir("../crt/$kind")) { mkdir("../crt/$kind",0777); }
802 if (!is_dir("../csr/$kind/".intval($id/1000))) { mkdir("../csr/$kind/".intval($id/1000)); }
803 if (!is_dir("../crt/$kind/".intval($id/1000))) { mkdir("../crt/$kind/".intval($id/1000)); }
804 }
805 return $name;
806 }
807
808 /**
809 * Run the sql query given in $sql.
810 * The resource returned by mysql_query is
811 * returned by this function.
812 *
813 * It should be safe to replace every mysql_query
814 * call by a mysql_extended_query call.
815 */
816 function mysql_timed_query($sql)
817 {
818 global $sql_data_log;
819 $query_start = microtime(true);
820 $res = mysql_query($sql);
821 $query_end = microtime(true);
822 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
823 return $res;
824 }
825
826 ?>