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