Merge remote-tracking branch 'origin/bug-985' 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 $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 >= 300)
491 return(200);
492 if($points >= 200)
493 return(150);
494 if($points >= 150)
495 return(35);
496 if($points >= 140)
497 return(30);
498 if($points >= 130)
499 return(25);
500 if($points >= 120)
501 return(20);
502 if($points >= 110)
503 return(15);
504 if($points >= 100)
505 return(10);
506 return(0);
507 }
508
509 function hex2bin($data)
510 {
511 while(strstr($data, "\\x"))
512 {
513 $pos = strlen($data) - strlen(strstr($data, "\\x"));
514 $before = substr($data, 0, $pos);
515 $char = chr(hexdec(substr($data, $pos + 2, 2)));
516 $after = substr($data, $pos + 4);
517 $data = $before.$char.$after;
518 }
519 return(utf8_decode($data));
520 }
521
522 function signmail($to, $subject, $message, $from, $replyto = "")
523 {
524 if($replyto == "")
525 $replyto = $from;
526 $tmpfname = tempnam("/tmp", "CSR");
527 $fp = fopen($tmpfname, "w");
528 fputs($fp, $message);
529 fclose($fp);
530 $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
531 @unlink($tmpfname);
532 }
533
534 function checkEmail($email)
535 {
536 $myemail = mysql_real_escape_string($email);
537 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
538 {
539 list($username,$domain)=split('@',$email);
540 $dom = escapeshellarg($domain);
541 $line = trim(`dig +short MX $dom 2>&1`);
542 #echo $email."-$dom-$line-\n";
543 #echo `dig +short mx heise.de 2>&1`."-<br>\n";
544
545 $list = explode("\n", $line);
546 foreach($list as $row)
547 list($pri, $mxhosts[]) = explode(" ", substr(trim($row), 0, -1));
548 $mxhosts[] = $domain;
549 #print_r($mxhosts); die;
550 foreach($mxhosts as $key => $domain)
551 {
552 $fp = @fsockopen($domain,25,$errno,$errstr,5);
553 if($fp)
554 {
555
556 $line = fgets($fp, 4096);
557 while(substr($line, 0, 4) == "220-")
558 $line = fgets($fp, 4096);
559 if(substr($line, 0, 3) != "220")
560 continue;
561 fputs($fp, "HELO www.cacert.org\r\n");
562 $line = fgets($fp, 4096);
563 while(substr($line, 0, 3) == "220")
564 $line = fgets($fp, 4096);
565 if(substr($line, 0, 3) != "250")
566 continue;
567 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
568 $line = fgets($fp, 4096);
569
570 if(substr($line, 0, 3) != "250")
571 continue;
572 fputs($fp, "RCPT TO:<$email>\r\n");
573 $line = trim(fgets($fp, 4096));
574 fputs($fp, "QUIT\r\n");
575 fclose($fp);
576
577 $line = mysql_real_escape_string(trim(strip_tags($line)));
578 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
579 if(is_array($_SESSION['profile'])) $query.=", `uid`='".$_SESSION['profile']['id']."'";
580 mysql_query($query);
581
582 if(substr($line, 0, 3) != "250")
583 return $line;
584 else
585 return "OK";
586 }
587 }
588 }
589 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".$_SESSION['profile']['id']."',
590 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
591 mysql_query($query);
592 return _("Failed to make a connection to the mail server");
593 }
594
595 function waitForResult($table, $certid, $id = 0, $show = 1)
596 {
597 $found = $trycount = 0;
598 if($certid<=0)
599 {
600 if($show) showheader(_("My CAcert.org Account!"));
601 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
602 if($show) showfooter();
603 if($show) exit;
604 return;
605 }
606 while($trycount++ <= 40)
607 {
608 if($table == "gpg")
609 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
610 else
611 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
612 $res = mysql_query($query);
613 if(mysql_num_rows($res) > 0)
614 {
615 $found = 1;
616 break;
617 }
618 sleep(3);
619 }
620
621 if(!$found)
622 {
623 if($show) showheader(_("My CAcert.org Account!"));
624 $query = "select * from `$table` where `id`='".intval($certid)."' ";
625 $res = mysql_query($query);
626 $body="";
627 $subject="";
628 if(mysql_num_rows($res) > 0)
629 {
630 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."));
631 $subject="[CAcert.org] Certificate TIMEOUT";
632 $body = "A certificate has timed out!\n\n";
633 }
634 else
635 {
636 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>");
637 $subject="[CAcert.org] Certificate FAILURE";
638 $body = "A certificate has failed: $table $certid $id $show\n\n";
639 }
640
641 $body .= _("Best regards")."\n"._("CAcert.org Support!");
642
643 sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
644
645 if($show) showfooter();
646 if($show) exit;
647 }
648 }
649
650
651
652 function generateTicket()
653 {
654 $query = "insert into tickets (timestamp) values (now()) ";
655 mysql_query($query);
656 $ticket = mysql_insert_id();
657 return $ticket;
658 }
659
660 function sanitizeHTML($input)
661 {
662 return htmlentities(strip_tags($input), ENT_QUOTES);
663 //In case of problems, please use the following line again:
664 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
665 //return htmlspecialchars(strip_tags($input));
666 }
667
668 function make_hash()
669 {
670 if(function_exists("dio_open"))
671 {
672 $rnd = dio_open("/dev/urandom",O_RDONLY);
673 $hash = md5(dio_read($rnd,64));
674 dio_close($rnd);
675 } else {
676 $rnd = fopen("/dev/urandom", "r");
677 $hash = md5(fgets($rnd, 64));
678 fclose($rnd);
679 }
680 return($hash);
681 }
682
683 function csrf_check($nam, $show=1)
684 {
685 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
686 {
687 showheader(_("My CAcert.org Account!"));
688 echo _("CSRF Hash is missing. Please try again.")."\n";
689 showfooter();
690 exit();
691 }
692 if(strlen($_REQUEST['csrf'])!=32)
693 {
694 showheader(_("My CAcert.org Account!"));
695 echo _("CSRF Hash is wrong. Please try again.")."\n";
696 showfooter();
697 exit();
698 }
699 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
700 {
701 showheader(_("My CAcert.org Account!"));
702 echo _("CSRF Hash is wrong. Please try again.")."\n";
703 showfooter();
704 exit();
705 }
706 }
707 function make_csrf($nam)
708 {
709 $hash=make_hash();
710 $_SESSION['csrf_'.$nam][$hash]=1;
711 return($hash);
712 }
713
714 function clean_csr($CSR)
715 {
716 $newcsr = str_replace("\r\n","\n",trim($CSR));
717 $newcsr = str_replace("\n\n","\n",$newcsr);
718 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
719 }
720 function clean_gpgcsr($CSR)
721 {
722 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
723 }
724
725 function sanitizeFilename($text)
726 {
727 $text=preg_replace("/[^\w-.@]/","",$text);
728 return($text);
729 }
730
731 // returns 0 if $userID is an Assurer
732 // Otherwise :
733 // Bit 0 is always set
734 // Bit 1 is set if 100 Assurance Points are not reached
735 // Bit 2 is set if Assurer Test is missing
736 // Bit 3 is set if the user is not allowed to be an Assurer (assurer_blocked > 0)
737 function get_assurer_status($userID)
738 {
739 $Result = 0;
740 $query = mysql_query('SELECT * FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` '.
741 ' WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = \''.(int)intval($userID).'\'');
742 if(mysql_num_rows($query) < 1)
743 {
744 $Result |= 5;
745 }
746
747 $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
748 $row = mysql_fetch_assoc($query);
749 if ($row['points'] < 100) {
750 $Result |= 3;
751 }
752
753 $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
754 $row = mysql_fetch_assoc($query);
755 if ($row['assurer_blocked'] > 0) {
756 $Result |= 9;
757 }
758
759 return $Result;
760 }
761
762 // returns text message to be shown to the user given the result of is_no_assurer
763 function no_assurer_text($Status)
764 {
765 if ($Status == 0) {
766 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
767 } elseif ($Status == 3) {
768 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
769 } elseif ($Status == 5) {
770 $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>!';
771 } elseif ($Status == 7) {
772 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
773 } elseif ($Status & 8 > 0) {
774 $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.");
775 } else {
776 $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>.';
777 }
778 return $Result;
779 }
780
781 function is_assurer($userID)
782 {
783 if (get_assurer_status($userID))
784 return 0;
785 else
786 return 1;
787 }
788
789 function get_assurer_reason($userID)
790 {
791 return no_assurer_text(get_assurer_status($userID));
792 }
793
794 function generatecertpath($type,$kind,$id)
795 {
796 $name="../$type/$kind-".intval($id).".$type";
797 $newlayout=1;
798 if($newlayout)
799 {
800 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
801 if (!is_dir("../csr")) { mkdir("../csr",0777); }
802 if (!is_dir("../crt")) { mkdir("../crt",0777); }
803
804 if (!is_dir("../csr/$kind")) { mkdir("../csr/$kind",0777); }
805 if (!is_dir("../crt/$kind")) { mkdir("../crt/$kind",0777); }
806 if (!is_dir("../csr/$kind/".intval($id/1000))) { mkdir("../csr/$kind/".intval($id/1000)); }
807 if (!is_dir("../crt/$kind/".intval($id/1000))) { mkdir("../crt/$kind/".intval($id/1000)); }
808 }
809 return $name;
810 }
811
812 /**
813 * Run the sql query given in $sql.
814 * The resource returned by mysql_query is
815 * returned by this function.
816 *
817 * It should be safe to replace every mysql_query
818 * call by a mysql_extended_query call.
819 */
820 function mysql_timed_query($sql)
821 {
822 global $sql_data_log;
823 $query_start = microtime(true);
824 $res = mysql_query($sql);
825 $query_end = microtime(true);
826 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
827 return $res;
828 }
829
830 ?>