2eef65e77c1cbaf946888a336132faecabdb18e6
[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(!preg_match("/(?=^.{4,253}$)(^(?:\\*\\.)?((?!-)[a-zA-Z0-9_-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)/i", $CN)) {
302 $cnok = 0;
303 }
304
305 if($cnok == 0) {
306 $_SESSION['_config']['rejected'][] = $CN;
307 continue;
308 }
309
310 if($_SESSION['_config']['row'] != "")
311 $rows[] = $CN;
312 }
313 // if(count($rows) <= 0)
314 // {
315 // 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.");
316 // exit;
317 // }
318
319 $_SESSION['_config']['rows'] = $rows;
320 $_SESSION['_config']['rowid'] = $rowid;
321 }
322
323 function getalt()
324 {
325 unset($_SESSION['_config']['altrows']);
326 unset($_SESSION['_config']['altid']);
327 $altrows=array();
328 $altid=array();
329 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
330 {
331 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
332 if(substr($subalt, 0, 4) == "DNS:")
333 $alt = substr($subalt, 4);
334 else
335 continue;
336
337 $bits = explode(".", $alt);
338 $dom = "";
339 $altok = 0;
340 for($i = count($bits) - 1; $i >= 0; $i--)
341 {
342 if($dom)
343 $dom = $bits[$i].".".$dom;
344 else
345 $dom = $bits[$i];
346 $_SESSION['_config']['altrow'] = "";
347 $dom = mysql_real_escape_string($dom);
348 $query = "select * from domains where `memid`='".intval($_SESSION['profile']['id'])."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
349 $res = mysql_query($query);
350 if(mysql_num_rows($res) > 0)
351 {
352 $altok = 1;
353 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
354 $altid[] = $_SESSION['_config']['altrow']['id'];
355 break;
356 }
357 }
358
359 if(!preg_match("/(?=^.{4,253}$)(^(?:\\*\\.)?((?!-)[a-zA-Z0-9_-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)/i", $alt)) {
360 $altok = 0;
361 }
362
363 if($altok == 0) {
364 $_SESSION['_config']['rejected'][] = $alt;
365 continue;
366 }
367
368 if($_SESSION['_config']['altrow'] != "")
369 $altrows[] = $subalt;
370 }
371 $_SESSION['_config']['altrows'] = $altrows;
372 $_SESSION['_config']['altid'] = $altid;
373 }
374
375 function getcn2()
376 {
377 $rows=array();
378 $rowid=array();
379 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
380 {
381 $CN = $_SESSION['_config']["$cnc.CN"];
382 $bits = explode(".", $CN);
383 $dom = "";
384 for($i = count($bits) - 1; $i >= 0; $i--)
385 {
386 if($dom)
387 $dom = $bits[$i].".".$dom;
388 else
389 $dom = $bits[$i];
390 $_SESSION['_config']['row'] = "";
391 $dom = mysql_real_escape_string($dom);
392 $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
393 `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
394 `org`.`orgid`=`orginfo`.`id` and
395 `orgdomains`.`orgid`=`orginfo`.`id` and
396 `orgdomains`.`domain`='$dom'";
397 $res = mysql_query($query);
398 if(mysql_num_rows($res) > 0)
399 {
400 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
401 $rowid[] = $_SESSION['_config']['row']['id'];
402 break;
403 }
404 }
405
406 if(!preg_match("/(?=^.{4,253}$)(^(?:\\*\\.)?((?!-)[a-zA-Z0-9_-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)/i", $CN)) {
407 continue;
408 }
409
410 if($_SESSION['_config']['row'] != "")
411 $rows[] = $CN;
412 }
413 // if(count($rows) <= 0)
414 // {
415 // 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.");
416 // exit;
417 // }
418 $_SESSION['_config']['rows'] = $rows;
419 $_SESSION['_config']['rowid'] = $rowid;
420 }
421
422 function getalt2()
423 {
424 $altrows=array();
425 $altid=array();
426 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
427 {
428 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
429 if(substr($subalt, 0, 4) == "DNS:")
430 $alt = substr($subalt, 4);
431 else
432 continue;
433
434 $bits = explode(".", $alt);
435 $dom = "";
436 for($i = count($bits) - 1; $i >= 0; $i--)
437 {
438 if($dom)
439 $dom = $bits[$i].".".$dom;
440 else
441 $dom = $bits[$i];
442 $_SESSION['_config']['altrow'] = "";
443 $dom = mysql_real_escape_string($dom);
444 $query = "select * from `orginfo`,`orgdomains`,`org` where
445 `org`.`memid`='".intval($_SESSION['profile']['id'])."' and
446 `org`.`orgid`=`orginfo`.`id` and
447 `orgdomains`.`orgid`=`orginfo`.`id` and
448 `orgdomains`.`domain`='$dom'";
449 $res = mysql_query($query);
450 if(mysql_num_rows($res) > 0)
451 {
452 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
453 $altid[] = $_SESSION['_config']['altrow']['id'];
454 break;
455 }
456 }
457
458 if(!preg_match("/(?=^.{4,253}$)(^(?:\\*\\.)?((?!-)[a-zA-Z0-9_-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)/i", $alt)) {
459 continue;
460 }
461
462 if($_SESSION['_config']['altrow'] != "")
463 $altrows[] = $subalt;
464 }
465 $_SESSION['_config']['altrows'] = $altrows;
466 $_SESSION['_config']['altid'] = $altid;
467 }
468
469 function checkownership($hostname)
470 {
471 $bits = explode(".", $hostname);
472 $dom = "";
473 for($i = count($bits) - 1; $i >= 0; $i--)
474 {
475 if($dom)
476 $dom = $bits[$i].".".$dom;
477 else
478 $dom = $bits[$i];
479 $dom = mysql_real_escape_string($dom);
480 $query = "select * from `org`,`orgdomains`,`orginfo`
481 where `org`.`memid`='".intval($_SESSION['profile']['id'])."'
482 and `orgdomains`.`orgid`=`org`.`orgid`
483 and `orginfo`.`id`=`org`.`orgid`
484 and `orgdomains`.`domain`='$dom'";
485 $res = mysql_query($query);
486 if(mysql_num_rows($res) > 0)
487 {
488 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
489 return(true);
490 }
491 }
492 return(false);
493 }
494
495 function maxpoints($id = 0)
496 {
497 if($id <= 0)
498 $id = $_SESSION['profile']['id'];
499
500 $query = "select sum(`points`) as `points` from `notary` where `to`='$id' and `deleted` = 0 group by `to`";
501 $row = mysql_fetch_assoc(mysql_query($query));
502 $points = $row['points'];
503
504 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
505 $query = "select * from `users` where `id`='".intval($_SESSION['profile']['id'])."' and `dob` < '$dob'";
506 if(mysql_num_rows(mysql_query($query)) < 1)
507 {
508 if($points >= 100)
509 return(10);
510 else
511 return(0);
512 }
513
514 if($points >= 150)
515 return(35);
516 if($points >= 140)
517 return(30);
518 if($points >= 130)
519 return(25);
520 if($points >= 120)
521 return(20);
522 if($points >= 110)
523 return(15);
524 if($points >= 100)
525 return(10);
526 return(0);
527 }
528
529 function gpg_hex2bin($data)
530 {
531 while(strstr($data, "\\x"))
532 {
533 $pos = strlen($data) - strlen(strstr($data, "\\x"));
534 $before = substr($data, 0, $pos);
535 $char = chr(hexdec(substr($data, $pos + 2, 2)));
536 $after = substr($data, $pos + 4);
537 $data = $before.$char.$after;
538 }
539 return(utf8_decode($data));
540 }
541
542 function signmail($to, $subject, $message, $from, $replyto = "")
543 {
544 if($replyto == "")
545 $replyto = $from;
546 $tmpfname = tempnam("/tmp", "CSR");
547 $fp = fopen($tmpfname, "w");
548 fputs($fp, $message);
549 fclose($fp);
550 $to_esc = escapeshellarg($to);
551 $do = shell_exec("/usr/bin/gpg --homedir /home/gpg --clearsign \"$tmpfname\"|/usr/sbin/sendmail ".$to_esc);
552 @unlink($tmpfname);
553 }
554
555 function checkEmail($email)
556 {
557 $myemail = mysql_real_escape_string($email);
558 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
559 {
560 list($username,$domain)=explode('@',$email,2);
561 $mxhostrr = array();
562 $mxweight = array();
563 if( !getmxrr($domain, $mxhostrr, $mxweight) ) {
564 $mxhostrr = array($domain);
565 $mxweight = array(0);
566 } else if ( empty($mxhostrr) ) {
567 $mxhostrr = array($domain);
568 $mxweight = array(0);
569 }
570
571 $mxhostprio = array();
572 for($i = 0; $i < count($mxhostrr); $i++) {
573 $mx_host = trim($mxhostrr[$i], '.');
574 $mx_prio = $mxweight[$i];
575 if(empty($mxhostprio[$mx_prio])) {
576 $mxhostprio[$mx_prio] = array();
577 }
578 $mxhostprio[$mx_prio][] = $mx_host;
579 }
580
581 array_walk($mxhostprio, function(&$mx) { shuffle($mx); } );
582 ksort($mxhostprio);
583
584 $mxhosts = array();
585 foreach($mxhostprio as $mx_prio => $mxhostnames) {
586 foreach($mxhostnames as $mx_host) {
587 $mxhosts[] = $mx_host;
588 }
589 }
590
591 foreach($mxhosts as $key => $domain)
592 {
593 $fp_opt = array(
594 'ssl' => array(
595 'verify_peer' => false, // Opportunistic Encryption
596 )
597 );
598 $fp_ctx = stream_context_create($fp_opt);
599 $fp = @stream_socket_client("tcp://$domain:25",$errno,$errstr,5,STREAM_CLIENT_CONNECT,$fp_ctx);
600 if($fp)
601 {
602 stream_set_blocking($fp, true);
603
604 $has_starttls = false;
605
606 do {
607 $line = fgets($fp, 4096);
608 } while(substr($line, 0, 4) == "220-");
609 if(substr($line, 0, 3) != "220") {
610 fclose($fp);
611 continue;
612 }
613
614 fputs($fp, "EHLO www.cacert.org\r\n");
615 do {
616 $line = fgets($fp, 4096);
617 $has_starttls |= substr(trim($line),4) == "STARTTLS";
618 } while(substr($line, 0, 4) == "250-");
619 if(substr($line, 0, 3) != "250") {
620 fclose($fp);
621 continue;
622 }
623
624 if($has_starttls) {
625 fputs($fp, "STARTTLS\r\n");
626 do {
627 $line = fgets($fp, 4096);
628 } while(substr($line, 0, 4) == "220-");
629 if(substr($line, 0, 3) != "220") {
630 fclose($fp);
631 continue;
632 }
633
634 stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
635
636 fputs($fp, "EHLO www.cacert.org\r\n");
637 do {
638 $line = fgets($fp, 4096);
639 } while(substr($line, 0, 4) == "250-");
640 if(substr($line, 0, 3) != "250") {
641 fclose($fp);
642 continue;
643 }
644 }
645
646 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
647 do {
648 $line = fgets($fp, 4096);
649 } while(substr($line, 0, 4) == "250-");
650 if(substr($line, 0, 3) != "250") {
651 fclose($fp);
652 continue;
653 }
654
655 fputs($fp, "RCPT TO:<$email>\r\n");
656 do {
657 $line = fgets($fp, 4096);
658 } while(substr($line, 0, 4) == "250-");
659 if(substr($line, 0, 3) != "250") {
660 fclose($fp);
661 continue;
662 }
663
664 fputs($fp, "QUIT\r\n");
665 fclose($fp);
666
667 $line = mysql_real_escape_string(trim(strip_tags($line)));
668 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
669 if(is_array($_SESSION['profile'])) $query.=", `uid`='".intval($_SESSION['profile']['id'])."'";
670 mysql_query($query);
671
672 if(substr($line, 0, 3) != "250")
673 return $line;
674 else
675 return "OK";
676 }
677 }
678 }
679 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".intval($_SESSION['profile']['id'])."',
680 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
681 mysql_query($query);
682 return _("Failed to make a connection to the mail server");
683 }
684
685 function waitForResult($table, $certid, $id = 0, $show = 1)
686 {
687 $found = $trycount = 0;
688 if($certid<=0)
689 {
690 if($show) showheader(_("My CAcert.org Account!"));
691 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
692 if($show) showfooter();
693 if($show) exit;
694 return;
695 }
696 while($trycount++ <= 40)
697 {
698 if($table == "gpg")
699 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
700 else
701 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
702 $res = mysql_query($query);
703 if(mysql_num_rows($res) > 0)
704 {
705 $found = 1;
706 break;
707 }
708 sleep(3);
709 }
710
711 if(!$found)
712 {
713 if($show) showheader(_("My CAcert.org Account!"));
714 $query = "select * from `$table` where `id`='".intval($certid)."' ";
715 $res = mysql_query($query);
716 $body="";
717 $subject="";
718 if(mysql_num_rows($res) > 0)
719 {
720 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."));
721 $subject="[CAcert.org] Certificate TIMEOUT";
722 $body = "A certificate has timed out!\n\n";
723 }
724 else
725 {
726 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>");
727 $subject="[CAcert.org] Certificate FAILURE";
728 $body = "A certificate has failed: $table $certid $id $show\n\n";
729 }
730
731 $body .= _("Best regards")."\n"._("CAcert.org Support!");
732
733 sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
734
735 if($show) showfooter();
736 if($show) exit;
737 }
738 }
739
740
741
742 function generateTicket()
743 {
744 $query = "insert into tickets (timestamp) values (now()) ";
745 mysql_query($query);
746 $ticket = mysql_insert_id();
747 return $ticket;
748 }
749
750 function sanitizeHTML($input)
751 {
752 return htmlentities(strip_tags($input), ENT_QUOTES, 'ISO-8859-1');
753 //In case of problems, please use the following line again:
754 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
755 //return htmlspecialchars(strip_tags($input));
756 }
757
758 function make_hash()
759 {
760 if(function_exists("dio_open"))
761 {
762 $rnd = dio_open("/dev/urandom",O_RDONLY);
763 $hash = md5(dio_read($rnd,64));
764 dio_close($rnd);
765 } else {
766 $rnd = fopen("/dev/urandom", "r");
767 $hash = md5(fgets($rnd, 64));
768 fclose($rnd);
769 }
770 return($hash);
771 }
772
773 function csrf_check($nam, $show=1)
774 {
775 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
776 {
777 showheader(_("My CAcert.org Account!"));
778 echo _("CSRF Hash is missing. Please try again.")."\n";
779 showfooter();
780 exit();
781 }
782 if(strlen($_REQUEST['csrf'])!=32)
783 {
784 showheader(_("My CAcert.org Account!"));
785 echo _("CSRF Hash is wrong. Please try again.")."\n";
786 showfooter();
787 exit();
788 }
789 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
790 {
791 showheader(_("My CAcert.org Account!"));
792 echo _("CSRF Hash is wrong. Please try again.")."\n";
793 showfooter();
794 exit();
795 }
796 }
797 function make_csrf($nam)
798 {
799 $hash=make_hash();
800 $_SESSION['csrf_'.$nam][$hash]=1;
801 return($hash);
802 }
803
804 function clean_csr($CSR)
805 {
806 $newcsr = str_replace("\r\n","\n",trim($CSR));
807 $newcsr = str_replace("\n\n","\n",$newcsr);
808 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
809 }
810 function clean_gpgcsr($CSR)
811 {
812 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
813 }
814
815 function sanitizeFilename($text)
816 {
817 $text=preg_replace("/[^\w-.@]/","",$text);
818 return($text);
819 }
820
821
822 // returns text message to be shown to the user given the result of is_no_assurer
823 function no_assurer_text($Status)
824 {
825 if ($Status == 0) {
826 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
827 } elseif ($Status == 3) {
828 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
829 } elseif ($Status == 5) {
830 $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>!';
831 } elseif ($Status == 7) {
832 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
833 } elseif ($Status & 8 > 0) {
834 $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.");
835 } else {
836 $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>.';
837 }
838 return $Result;
839 }
840
841 function is_assurer($userID)
842 {
843 if (get_assurer_status($userID))
844 return 0;
845 else
846 return 1;
847 }
848
849 function get_assurer_reason($userID)
850 {
851 return no_assurer_text(get_assurer_status($userID));
852 }
853
854 function generatecertpath($type,$kind,$id)
855 {
856 $name="../$type/$kind-".intval($id).".$type";
857 $newlayout=1;
858 if($newlayout)
859 {
860 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
861 if (!is_dir("../csr")) { mkdir("../csr",0777); }
862 if (!is_dir("../crt")) { mkdir("../crt",0777); }
863
864 if (!is_dir("../csr/$kind")) { mkdir("../csr/$kind",0777); }
865 if (!is_dir("../crt/$kind")) { mkdir("../crt/$kind",0777); }
866 if (!is_dir("../csr/$kind/".intval($id/1000))) { mkdir("../csr/$kind/".intval($id/1000)); }
867 if (!is_dir("../crt/$kind/".intval($id/1000))) { mkdir("../crt/$kind/".intval($id/1000)); }
868 }
869 return $name;
870 }
871
872 /**
873 * Run the sql query given in $sql.
874 * The resource returned by mysql_query is
875 * returned by this function.
876 *
877 * It should be safe to replace every mysql_query
878 * call by a mysql_extended_query call.
879 */
880 function mysql_timed_query($sql)
881 {
882 global $sql_data_log;
883 $query_start = microtime(true);
884 $res = mysql_query($sql);
885 $query_end = microtime(true);
886 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
887 return $res;
888 }
889
890
891 ?>