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