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