Merge branch 'bug-1019' into release
[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 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 $shellpwd = escapeshellarg($pwd);
219 $do = `grep $shellpwd /usr/share/dict/american-english`;
220 if($do)
221 $points--;
222
223 //echo "Points due to wordlist: $points<br/>";
224
225 return($points);
226 }
227
228 function extractit()
229 {
230 $bits = explode(": ", $_SESSION['_config']['subject'], 2);
231 $bits = str_replace(", ", "|", str_replace("/", "|", array_key_exists('1',$bits)?$bits['1']:""));
232 $bits = explode("|", $bits);
233
234 $_SESSION['_config']['cnc'] = $_SESSION['_config']['subaltc'] = 0;
235 $_SESSION['_config']['OU'] = "";
236
237 if(is_array($bits))
238 foreach($bits as $val)
239 {
240 if(!strstr($val, "="))
241 continue;
242
243 $split = explode("=", $val);
244
245 $k = $split[0];
246 $split['1'] = trim($split['1']);
247 if($k == "CN" && $split['1'])
248 {
249 $k = $_SESSION['_config']['cnc'].".".$k;
250 $_SESSION['_config']['cnc']++;
251 $_SESSION['_config'][$k] = $split['1'];
252 }
253 if($k == "OU" && $split['1'] && $_SESSION['_config']['OU'] == "")
254 {
255 $_SESSION['_config']['OU'] = $split['1'];
256 }
257 if($k == "subjectAltName" && $split['1'])
258 {
259 $k = $_SESSION['_config']['subaltc'].".".$k;
260 $_SESSION['_config']['subaltc']++;
261 $_SESSION['_config'][$k] = $split['1'];
262 }
263 }
264 }
265
266 function getcn()
267 {
268 unset($_SESSION['_config']['rows']);
269 unset($_SESSION['_config']['rowid']);
270 unset($_SESSION['_config']['rejected']);
271 $rows=array();
272 $rowid=array();
273 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
274 {
275 $CN = $_SESSION['_config']["$cnc.CN"];
276 $bits = explode(".", $CN);
277 $dom = "";
278 $cnok = 0;
279 for($i = count($bits) - 1; $i >= 0; $i--)
280 {
281 if($dom)
282 $dom = $bits[$i].".".$dom;
283 else
284 $dom = $bits[$i];
285 $_SESSION['_config']['row'] = "";
286 $dom = mysql_real_escape_string($dom);
287 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
288 $res = mysql_query($query);
289 if(mysql_num_rows($res) > 0)
290 {
291 $cnok = 1;
292 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
293 $rowid[] = $_SESSION['_config']['row']['id'];
294 break;
295 }
296 }
297
298 if($cnok == 0)
299 $_SESSION['_config']['rejected'][] = $CN;
300
301 if($_SESSION['_config']['row'] != "")
302 $rows[] = $CN;
303 }
304 // if(count($rows) <= 0)
305 // {
306 // 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.");
307 // exit;
308 // }
309
310 $_SESSION['_config']['rows'] = $rows;
311 $_SESSION['_config']['rowid'] = $rowid;
312 }
313
314 function getalt()
315 {
316 unset($_SESSION['_config']['altrows']);
317 unset($_SESSION['_config']['altid']);
318 $altrows=array();
319 $altid=array();
320 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
321 {
322 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
323 if(substr($subalt, 0, 4) == "DNS:")
324 $alt = substr($subalt, 4);
325 else
326 continue;
327
328 $bits = explode(".", $alt);
329 $dom = "";
330 $altok = 0;
331 for($i = count($bits) - 1; $i >= 0; $i--)
332 {
333 if($dom)
334 $dom = $bits[$i].".".$dom;
335 else
336 $dom = $bits[$i];
337 $_SESSION['_config']['altrow'] = "";
338 $dom = mysql_real_escape_string($dom);
339 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
340 $res = mysql_query($query);
341 if(mysql_num_rows($res) > 0)
342 {
343 $altok = 1;
344 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
345 $altid[] = $_SESSION['_config']['altrow']['id'];
346 break;
347 }
348 }
349
350 if($altok == 0)
351 $_SESSION['_config']['rejected'][] = $alt;
352
353 if($_SESSION['_config']['altrow'] != "")
354 $altrows[] = $subalt;
355 }
356 $_SESSION['_config']['altrows'] = $altrows;
357 $_SESSION['_config']['altid'] = $altid;
358 }
359
360 function getcn2()
361 {
362 $rows=array();
363 $rowid=array();
364 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
365 {
366 $CN = $_SESSION['_config']["$cnc.CN"];
367 $bits = explode(".", $CN);
368 $dom = "";
369 for($i = count($bits) - 1; $i >= 0; $i--)
370 {
371 if($dom)
372 $dom = $bits[$i].".".$dom;
373 else
374 $dom = $bits[$i];
375 $_SESSION['_config']['row'] = "";
376 $dom = mysql_real_escape_string($dom);
377 $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
378 `org`.`memid`='".$_SESSION['profile']['id']."' and
379 `org`.`orgid`=`orginfo`.`id` and
380 `orgdomains`.`orgid`=`orginfo`.`id` and
381 `orgdomains`.`domain`='$dom'";
382 $res = mysql_query($query);
383 if(mysql_num_rows($res) > 0)
384 {
385 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
386 $rowid[] = $_SESSION['_config']['row']['id'];
387 break;
388 }
389 }
390
391 if($_SESSION['_config']['row'] != "")
392 $rows[] = $CN;
393 }
394 // if(count($rows) <= 0)
395 // {
396 // 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.");
397 // exit;
398 // }
399 $_SESSION['_config']['rows'] = $rows;
400 $_SESSION['_config']['rowid'] = $rowid;
401 }
402
403 function getalt2()
404 {
405 $altrows=array();
406 $altid=array();
407 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
408 {
409 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
410 if(substr($subalt, 0, 4) == "DNS:")
411 $alt = substr($subalt, 4);
412 else
413 continue;
414
415 $bits = explode(".", $alt);
416 $dom = "";
417 for($i = count($bits) - 1; $i >= 0; $i--)
418 {
419 if($dom)
420 $dom = $bits[$i].".".$dom;
421 else
422 $dom = $bits[$i];
423 $_SESSION['_config']['altrow'] = "";
424 $dom = mysql_real_escape_string($dom);
425 $query = "select * from `orginfo`,`orgdomains`,`org` where
426 `org`.`memid`='".$_SESSION['profile']['id']."' and
427 `org`.`orgid`=`orginfo`.`id` and
428 `orgdomains`.`orgid`=`orginfo`.`id` and
429 `orgdomains`.`domain`='$dom'";
430 $res = mysql_query($query);
431 if(mysql_num_rows($res) > 0)
432 {
433 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
434 $altid[] = $_SESSION['_config']['altrow']['id'];
435 break;
436 }
437 }
438
439 if($_SESSION['_config']['altrow'] != "")
440 $altrows[] = $subalt;
441 }
442 $_SESSION['_config']['altrows'] = $altrows;
443 $_SESSION['_config']['altid'] = $altid;
444 }
445
446 function checkownership($hostname)
447 {
448 $bits = explode(".", $hostname);
449 $dom = "";
450 for($i = count($bits) - 1; $i >= 0; $i--)
451 {
452 if($dom)
453 $dom = $bits[$i].".".$dom;
454 else
455 $dom = $bits[$i];
456 $dom = mysql_real_escape_string($dom);
457 $query = "select * from `org`,`orgdomains`,`orginfo`
458 where `org`.`memid`='".$_SESSION['profile']['id']."'
459 and `orgdomains`.`orgid`=`org`.`orgid`
460 and `orginfo`.`id`=`org`.`orgid`
461 and `orgdomains`.`domain`='$dom'";
462 $res = mysql_query($query);
463 if(mysql_num_rows($res) > 0)
464 {
465 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
466 return(true);
467 }
468 }
469 return(false);
470 }
471
472 function maxpoints($id = 0)
473 {
474 if($id <= 0)
475 $id = $_SESSION['profile']['id'];
476
477 $query = "select sum(`points`) as `points` from `notary` where `to`='$id' group by `to`";
478 $row = mysql_fetch_assoc(mysql_query($query));
479 $points = $row['points'];
480
481 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
482 $query = "select * from `users` where `id`='".$_SESSION['profile']['id']."' and `dob` < '$dob'";
483 if(mysql_num_rows(mysql_query($query)) < 1)
484 {
485 if($points >= 100)
486 return(10);
487 else
488 return(0);
489 }
490
491 if($points >= 150)
492 return(35);
493 if($points >= 140)
494 return(30);
495 if($points >= 130)
496 return(25);
497 if($points >= 120)
498 return(20);
499 if($points >= 110)
500 return(15);
501 if($points >= 100)
502 return(10);
503 return(0);
504 }
505
506 function hex2bin($data)
507 {
508 while(strstr($data, "\\x"))
509 {
510 $pos = strlen($data) - strlen(strstr($data, "\\x"));
511 $before = substr($data, 0, $pos);
512 $char = chr(hexdec(substr($data, $pos + 2, 2)));
513 $after = substr($data, $pos + 4);
514 $data = $before.$char.$after;
515 }
516 return(utf8_decode($data));
517 }
518
519 function signmail($to, $subject, $message, $from, $replyto = "")
520 {
521 if($replyto == "")
522 $replyto = $from;
523 $tmpfname = tempnam("/tmp", "CSR");
524 $fp = fopen($tmpfname, "w");
525 fputs($fp, $message);
526 fclose($fp);
527 $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
528 @unlink($tmpfname);
529 }
530
531 function checkEmail($email)
532 {
533 $myemail = mysql_real_escape_string($email);
534 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
535 {
536 list($username,$domain)=split('@',$email);
537 $dom = escapeshellarg($domain);
538 $line = trim(`dig +short MX $dom 2>&1`);
539 #echo $email."-$dom-$line-\n";
540 #echo `dig +short mx heise.de 2>&1`."-<br>\n";
541
542 $list = explode("\n", $line);
543 foreach($list as $row)
544 list($pri, $mxhosts[]) = explode(" ", substr(trim($row), 0, -1));
545 $mxhosts[] = $domain;
546 #print_r($mxhosts); die;
547 foreach($mxhosts as $key => $domain)
548 {
549 $fp = @fsockopen($domain,25,$errno,$errstr,5);
550 if($fp)
551 {
552
553 $line = fgets($fp, 4096);
554 while(substr($line, 0, 4) == "220-")
555 $line = fgets($fp, 4096);
556 if(substr($line, 0, 3) != "220")
557 continue;
558 fputs($fp, "HELO www.cacert.org\r\n");
559 $line = fgets($fp, 4096);
560 while(substr($line, 0, 3) == "220")
561 $line = fgets($fp, 4096);
562 if(substr($line, 0, 3) != "250")
563 continue;
564 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
565 $line = fgets($fp, 4096);
566
567 if(substr($line, 0, 3) != "250")
568 continue;
569 fputs($fp, "RCPT TO:<$email>\r\n");
570 $line = trim(fgets($fp, 4096));
571 fputs($fp, "QUIT\r\n");
572 fclose($fp);
573
574 $line = mysql_real_escape_string(trim(strip_tags($line)));
575 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
576 if(is_array($_SESSION['profile'])) $query.=", `uid`='".$_SESSION['profile']['id']."'";
577 mysql_query($query);
578
579 if(substr($line, 0, 3) != "250")
580 return $line;
581 else
582 return "OK";
583 }
584 }
585 }
586 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".$_SESSION['profile']['id']."',
587 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
588 mysql_query($query);
589 return _("Failed to make a connection to the mail server");
590 }
591
592 function waitForResult($table, $certid, $id = 0, $show = 1)
593 {
594 $found = $trycount = 0;
595 if($certid<=0)
596 {
597 if($show) showheader(_("My CAcert.org Account!"));
598 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
599 if($show) showfooter();
600 if($show) exit;
601 return;
602 }
603 while($trycount++ <= 40)
604 {
605 if($table == "gpg")
606 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
607 else
608 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
609 $res = mysql_query($query);
610 if(mysql_num_rows($res) > 0)
611 {
612 $found = 1;
613 break;
614 }
615 sleep(3);
616 }
617
618 if(!$found)
619 {
620 if($show) showheader(_("My CAcert.org Account!"));
621 $query = "select * from `$table` where `id`='".intval($certid)."' ";
622 $res = mysql_query($query);
623 $body="";
624 $subject="";
625 if(mysql_num_rows($res) > 0)
626 {
627 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."));
628 $subject="[CAcert.org] Certificate TIMEOUT";
629 $body = "A certificate has timed out!\n\n";
630 }
631 else
632 {
633 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>");
634 $subject="[CAcert.org] Certificate FAILURE";
635 $body = "A certificate has failed: $table $certid $id $show\n\n";
636 }
637
638 $body .= _("Best regards")."\n"._("CAcert.org Support!");
639
640 sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
641
642 if($show) showfooter();
643 if($show) exit;
644 }
645 }
646
647
648
649 function generateTicket()
650 {
651 $query = "insert into tickets (timestamp) values (now()) ";
652 mysql_query($query);
653 $ticket = mysql_insert_id();
654 return $ticket;
655 }
656
657 function sanitizeHTML($input)
658 {
659 return htmlentities(strip_tags($input), ENT_QUOTES);
660 //In case of problems, please use the following line again:
661 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
662 //return htmlspecialchars(strip_tags($input));
663 }
664
665 function make_hash()
666 {
667 if(function_exists("dio_open"))
668 {
669 $rnd = dio_open("/dev/urandom",O_RDONLY);
670 $hash = md5(dio_read($rnd,64));
671 dio_close($rnd);
672 } else {
673 $rnd = fopen("/dev/urandom", "r");
674 $hash = md5(fgets($rnd, 64));
675 fclose($rnd);
676 }
677 return($hash);
678 }
679
680 function csrf_check($nam, $show=1)
681 {
682 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
683 {
684 showheader(_("My CAcert.org Account!"));
685 echo _("CSRF Hash is missing. Please try again.")."\n";
686 showfooter();
687 exit();
688 }
689 if(strlen($_REQUEST['csrf'])!=32)
690 {
691 showheader(_("My CAcert.org Account!"));
692 echo _("CSRF Hash is wrong. Please try again.")."\n";
693 showfooter();
694 exit();
695 }
696 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
697 {
698 showheader(_("My CAcert.org Account!"));
699 echo _("CSRF Hash is wrong. Please try again.")."\n";
700 showfooter();
701 exit();
702 }
703 }
704 function make_csrf($nam)
705 {
706 $hash=make_hash();
707 $_SESSION['csrf_'.$nam][$hash]=1;
708 return($hash);
709 }
710
711 function clean_csr($CSR)
712 {
713 $newcsr = str_replace("\r\n","\n",trim($CSR));
714 $newcsr = str_replace("\n\n","\n",$newcsr);
715 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
716 }
717 function clean_gpgcsr($CSR)
718 {
719 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
720 }
721
722 function sanitizeFilename($text)
723 {
724 $text=preg_replace("/[^\w-.@]/","",$text);
725 return($text);
726 }
727
728 // returns 0 if $userID is an Assurer
729 // Otherwise :
730 // Bit 0 is always set
731 // Bit 1 is set if 100 Assurance Points are not reached
732 // Bit 2 is set if Assurer Test is missing
733 // Bit 3 is set if the user is not allowed to be an Assurer (assurer_blocked > 0)
734 function get_assurer_status($userID)
735 {
736 $Result = 0;
737 $query = mysql_query('SELECT * FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` '.
738 ' WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = \''.(int)intval($userID).'\'');
739 if(mysql_num_rows($query) < 1)
740 {
741 $Result |= 5;
742 }
743
744 $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
745 $row = mysql_fetch_assoc($query);
746 if ($row['points'] < 100) {
747 $Result |= 3;
748 }
749
750 $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
751 $row = mysql_fetch_assoc($query);
752 if ($row['assurer_blocked'] > 0) {
753 $Result |= 9;
754 }
755
756 return $Result;
757 }
758
759 // returns text message to be shown to the user given the result of is_no_assurer
760 function no_assurer_text($Status)
761 {
762 if ($Status == 0) {
763 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
764 } elseif ($Status == 3) {
765 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
766 } elseif ($Status == 5) {
767 $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>!';
768 } elseif ($Status == 7) {
769 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
770 } elseif ($Status & 8 > 0) {
771 $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.");
772 } else {
773 $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>.';
774 }
775 return $Result;
776 }
777
778 function is_assurer($userID)
779 {
780 if (get_assurer_status($userID))
781 return 0;
782 else
783 return 1;
784 }
785
786 function get_assurer_reason($userID)
787 {
788 return no_assurer_text(get_assurer_status($userID));
789 }
790
791 function generatecertpath($type,$kind,$id)
792 {
793 $name="../$type/$kind-".intval($id).".$type";
794 $newlayout=1;
795 if($newlayout)
796 {
797 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
798 if (!is_dir("../csr")) { mkdir("../csr",0777); }
799 if (!is_dir("../crt")) { mkdir("../crt",0777); }
800
801 if (!is_dir("../csr/$kind")) { mkdir("../csr/$kind",0777); }
802 if (!is_dir("../crt/$kind")) { mkdir("../crt/$kind",0777); }
803 if (!is_dir("../csr/$kind/".intval($id/1000))) { mkdir("../csr/$kind/".intval($id/1000)); }
804 if (!is_dir("../crt/$kind/".intval($id/1000))) { mkdir("../crt/$kind/".intval($id/1000)); }
805 }
806 return $name;
807 }
808
809 /**
810 * Run the sql query given in $sql.
811 * The resource returned by mysql_query is
812 * returned by this function.
813 *
814 * It should be safe to replace every mysql_query
815 * call by a mysql_extended_query call.
816 */
817 function mysql_timed_query($sql)
818 {
819 global $sql_data_log;
820 $query_start = microtime(true);
821 $res = mysql_query($sql);
822 $query_end = microtime(true);
823 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
824 return $res;
825 }
826
827 ?>