source code taken from cacert-20100709.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
42 if(array_key_exists('HTTP_HOST',$_SERVER) &&
43 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['normalhostname'] &&
44 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['securehostname'] &&
45 $_SERVER['HTTP_HOST'] != $_SESSION['_config']['tverify'] &&
46 $_SERVER['HTTP_HOST'] != "stamp.cacert.org")
47 {
48 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
49 header("location: https://".$_SESSION['_config']['normalhostname']);
50 else
51 header("location: http://".$_SESSION['_config']['normalhostname']);
52 exit;
53 }
54
55 if(array_key_exists('HTTP_HOST',$_SERVER) &&
56 ($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'] ||
57 $_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify']))
58 {
59 if(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS'] == "on")
60 {
61 }
62 else
63 {
64 if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['securehostname'])
65 header("location: https://". $_SESSION['_config']['securehostname']);
66 if($_SERVER['HTTP_HOST'] == $_SESSION['_config']['tverify'])
67 header("location: https://".$_SESSION['_config']['tverify']);
68 exit;
69 }
70 }
71
72 $lang = "";
73 if(array_key_exists("lang",$_REQUEST))
74 $lang=mysql_escape_string(substr(trim($_REQUEST['lang']), 0, 5));
75 if($lang != "")
76 $_SESSION['_config']['language'] = $lang;
77
78 //if($_SESSION['profile']['id'] == 1 && 1 == 2)
79 // echo $_SESSION['_config']['language'];
80
81 $_SESSION['_config']['translations'] = array(
82 "ar_JO" => "&#1575;&#1604;&#1593;&#1585;&#1576;&#1610;&#1577;",
83 "bg_BG" => "&#1041;&#1098;&#1083;&#1075;&#1072;&#1088;&#1089;&#1082;&#1080;",
84 "cs_CZ" => "&#268;e&scaron;tina",
85 "da_DK" => "Dansk",
86 "de_DE" => "Deutsch",
87 "el_GR" => "&Epsilon;&lambda;&lambda;&eta;&nu;&iota;&kappa;&#940;",
88 "en_AU" => "English",
89 "eo_EO" => "Esperanto",
90 "es_ES" => "Espa&#xf1;ol",
91 "fa_IR" => "Farsi",
92 "fi_FI" => "Suomi",
93 "fr_FR" => "Fran&#xe7;ais",
94 "he_IL" => "&#1506;&#1489;&#1512;&#1497;&#1514;",
95 "hr_HR" => "Hrvatski",
96 "hu_HU" => "Magyar",
97 "is_IS" => "&Iacute;slenska",
98 "it_IT" => "Italiano",
99 "ja_JP" => "&#26085;&#26412;&#35486;",
100 "ka_GE" => "Georgian",
101 "nl_NL" => "Nederlands",
102 "pl_PL" => "Polski",
103 "pt_PT" => "Portugu&#xea;s",
104 "pt_BR" => "Portugu&#xea;s Brasileiro",
105 "ru_RU" => "&#x420;&#x443;&#x441;&#x441;&#x43a;&#x438;&#x439;",
106 "ro_RO" => "Rom&acirc;n&#259;",
107 "sv_SE" => "Svenska",
108 "tr_TR" => "T&#xfc;rk&#xe7;e",
109 "zh_CN" => "&#x4e2d;&#x6587;(&#x7b80;&#x4f53;)");
110
111 $value=array();
112
113 if(!(array_key_exists('language',$_SESSION['_config']) && $_SESSION['_config']['language'] != ""))
114 {
115 $bits = explode(",", strtolower(str_replace(" ", "", mysql_real_escape_string(array_key_exists('HTTP_ACCEPT_LANGUAGE',$_SERVER)?$_SERVER['HTTP_ACCEPT_LANGUAGE']:""))));
116 foreach($bits as $lang)
117 {
118 $b = explode(";", $lang);
119 if(count($b)>1 && substr($b[1], 0, 2) == "q=")
120 $c = floatval(substr($b[1], 2));
121 else
122 $c = 1;
123 $value["$c"] = trim($b[0]);
124 }
125
126 krsort($value);
127
128 reset($value);
129
130 foreach($value as $key => $val)
131 {
132 $val = substr(escapeshellarg($val), 1, -1);
133 $short = substr($val, 0, 2);
134 if($val == "en" || $short == "en")
135 {
136 $_SESSION['_config']['language'] = "en";
137 break;
138 }
139 if(file_exists($_SESSION['_config']['filepath']."/locale/$val/LC_MESSAGES/messages.mo"))
140 {
141 $_SESSION['_config']['language'] = $val;
142 break;
143 }
144 if(file_exists($_SESSION['_config']['filepath']."/locale/$short/LC_MESSAGES/messages.mo"))
145 {
146 $_SESSION['_config']['language'] = $short;
147 break;
148 }
149 }
150 }
151 if(!array_key_exists('_config',$_SESSION) || !array_key_exists('language',$_SESSION['_config']) || strlen($_SESSION['_config']['language']) != 5)
152 {
153 $lang = array_key_exists('language',$_SESSION['_config'])?$_SESSION['_config']['language']:"";
154 $_SESSION['_config']['language'] = "en_AU";
155 foreach($_SESSION['_config']['translations'] as $key => $val)
156 {
157 if(substr($lang, 0, 2) == substr($key, 0, 2))
158 {
159 $_SESSION['_config']['language'] = $val;
160 break;
161 }
162 }
163 }
164
165 $_SESSION['_config']['recode'] = "html..latin-1";
166 if($_SESSION['_config']['language'] == "zh_CN")
167 {
168 $_SESSION['_config']['recode'] = "html..gb2312";
169 } else if($_SESSION['_config']['language'] == "pl_PL" || $_SESSION['_config']['language'] == "hu_HU") {
170 $_SESSION['_config']['recode'] = "html..ISO-8859-2";
171 } else if($_SESSION['_config']['language'] == "ja_JP") {
172 $_SESSION['_config']['recode'] = "html..SHIFT-JIS";
173 } else if($_SESSION['_config']['language'] == "ru_RU") {
174 $_SESSION['_config']['recode'] = "html..ISO-8859-5";
175 } else if($_SESSION['_config']['language'] == "lt_LT") {
176 $_SESSION['_config']['recode'] = "html..ISO-8859-13";
177 }
178
179 putenv("LANG=".$_SESSION['_config']['language']);
180 setlocale(LC_ALL, $_SESSION['_config']['language']);
181 $domain = 'messages';
182 bindtextdomain($domain, $_SESSION['_config']['filepath']."/locale");
183 textdomain($domain);
184
185 //if($_SESSION['profile']['id'] == -1)
186 // echo $_SESSION['_config']['language']." - ".$_SESSION['_config']['filepath']."/locale";
187
188
189 if(array_key_exists('profile',$_SESSION) && is_array($_SESSION['profile']) && array_key_exists('id',$_SESSION['profile']) && $_SESSION['profile']['id'] > 0)
190 {
191 $locked = mysql_fetch_assoc(mysql_query("select `locked` from `users` where `id`='".$_SESSION['profile']['id']."'"));
192 if($locked['locked'] == 0)
193 {
194 $query = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
195 $res = mysql_query($query);
196 $row = mysql_fetch_assoc($res);
197 $_SESSION['profile']['points'] = $row['total'];
198 } else {
199 $_SESSION['profile'] = "";
200 unset($_SESSION['profile']);
201 }
202 }
203
204 function loadem($section = "index")
205 {
206 if($section != "index" && $section != "account" && $section != "tverify")
207 {
208 $section = "index";
209 }
210
211 if($section == "account")
212 include_once($_SESSION['_config']['filepath']."/includes/account_stuff.php");
213
214 if($section == "index")
215 include_once($_SESSION['_config']['filepath']."/includes/general_stuff.php");
216
217 if($section == "tverify")
218 include_once($_SESSION['_config']['filepath']."/includes/tverify_stuff.php");
219 }
220
221 function includeit($id = "0", $section = "index")
222 {
223 $id = intval($id);
224 if($section != "index" && $section != "account" && $section != "wot" && $section != "help" && $section != "gpg" && $section != "disputes" && $section != "tverify" && $section != "advertising")
225 {
226 $section = "index";
227 }
228
229 if($section == "tverify" && file_exists($_SESSION['_config']['filepath']."/tverify/index/$id.php"))
230 include_once($_SESSION['_config']['filepath']."/tverify/index/$id.php");
231 else if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
232 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
233 else {
234 $id = "0";
235
236 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
237 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
238 else {
239
240 $section = "index";
241 $id = "0";
242
243 if(file_exists($_SESSION['_config']['filepath']."/pages/$section/$id.php"))
244 include_once($_SESSION['_config']['filepath']."/pages/$section/$id.php");
245 else
246 include_once($_SESSION['_config']['filepath']."/www/error404.php");
247 }
248 }
249 }
250
251 function checkpw($pwd, $email, $fname, $mname, $lname, $suffix)
252 {
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 if(@strstr(strtolower($pwd), strtolower($email)))
284 $points--;
285
286 if(@strstr(strtolower($email), strtolower($pwd)))
287 $points--;
288
289 if(@strstr(strtolower($pwd), strtolower($fname)))
290 $points--;
291
292 if(@strstr(strtolower($fname), strtolower($pwd)))
293 $points--;
294
295 if($mname)
296 if(@strstr(strtolower($pwd), strtolower($mname)))
297 $points--;
298
299 if($mname)
300 if(@strstr(strtolower($mname), strtolower($pwd)))
301 $points--;
302
303 if(@strstr(strtolower($pwd), strtolower($lname)))
304 $points--;
305
306 if(@strstr(strtolower($lname), strtolower($pwd)))
307 $points--;
308
309 if($suffix)
310 if(@strstr(strtolower($pwd), strtolower($suffix)))
311 $points--;
312
313 if($suffix)
314 if(@strstr(strtolower($suffix), strtolower($pwd)))
315 $points--;
316
317 //echo "Points due to name matches: $points<br/>";
318
319 $do = `grep '$pwd' /usr/share/dict/american-english`;
320 if($do)
321 $points--;
322
323 //echo "Points due to wordlist: $points<br/>";
324
325 return($points);
326 }
327
328 function extractit()
329 {
330 $bits = explode(": ", $_SESSION['_config']['subject'], 2);
331 $bits = str_replace(", ", "|", str_replace("/", "|", array_key_exists('1',$bits)?$bits['1']:""));
332 $bits = explode("|", $bits);
333
334 $_SESSION['_config']['cnc'] = $_SESSION['_config']['subaltc'] = 0;
335 $_SESSION['_config']['OU'] = "";
336
337 if(is_array($bits))
338 foreach($bits as $val)
339 {
340 if(!strstr($val, "="))
341 continue;
342
343 $split = explode("=", $val);
344
345 $k = $split[0];
346 $split['1'] = trim($split['1']);
347 if($k == "CN" && $split['1'])
348 {
349 $k = $_SESSION['_config']['cnc'].".".$k;
350 $_SESSION['_config']['cnc']++;
351 $_SESSION['_config'][$k] = $split['1'];
352 }
353 if($k == "OU" && $split['1'] && $_SESSION['_config']['OU'] == "")
354 {
355 $_SESSION['_config']['OU'] = $split['1'];
356 }
357 if($k == "subjectAltName" && $split['1'])
358 {
359 $k = $_SESSION['_config']['subaltc'].".".$k;
360 $_SESSION['_config']['subaltc']++;
361 $_SESSION['_config'][$k] = $split['1'];
362 }
363 }
364 }
365
366 function getcn()
367 {
368 unset($_SESSION['_config']['rows']);
369 unset($_SESSION['_config']['rowid']);
370 unset($_SESSION['_config']['rejected']);
371 $rows=array();
372 $rowid=array();
373 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
374 {
375 $CN = $_SESSION['_config']["$cnc.CN"];
376 $bits = explode(".", $CN);
377 $dom = "";
378 $cnok = 0;
379 for($i = count($bits) - 1; $i >= 0; $i--)
380 {
381 if($dom)
382 $dom = $bits[$i].".".$dom;
383 else
384 $dom = $bits[$i];
385 $_SESSION['_config']['row'] = "";
386 $dom = mysql_real_escape_string($dom);
387 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
388 $res = mysql_query($query);
389 if(mysql_num_rows($res) > 0)
390 {
391 $cnok = 1;
392 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
393 $rowid[] = $_SESSION['_config']['row']['id'];
394 break;
395 }
396 }
397
398 if($cnok == 0)
399 $_SESSION['_config']['rejected'][] = $CN;
400
401 if($_SESSION['_config']['row'] != "")
402 $rows[] = $CN;
403 }
404 // if(count($rows) <= 0)
405 // {
406 // 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.");
407 // exit;
408 // }
409
410 $_SESSION['_config']['rows'] = $rows;
411 $_SESSION['_config']['rowid'] = $rowid;
412 }
413
414 function getalt()
415 {
416 unset($_SESSION['_config']['altrows']);
417 unset($_SESSION['_config']['altid']);
418 $altrows=array();
419 $altid=array();
420 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
421 {
422 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
423 if(substr($subalt, 0, 4) == "DNS:")
424 $alt = substr($subalt, 4);
425 else
426 continue;
427
428 $bits = explode(".", $alt);
429 $dom = "";
430 $altok = 0;
431 for($i = count($bits) - 1; $i >= 0; $i--)
432 {
433 if($dom)
434 $dom = $bits[$i].".".$dom;
435 else
436 $dom = $bits[$i];
437 $_SESSION['_config']['altrow'] = "";
438 $dom = mysql_real_escape_string($dom);
439 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
440 $res = mysql_query($query);
441 if(mysql_num_rows($res) > 0)
442 {
443 $altok = 1;
444 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
445 $altid[] = $_SESSION['_config']['altrow']['id'];
446 break;
447 }
448 }
449
450 if($altok == 0)
451 $_SESSION['_config']['rejected'][] = $alt;
452
453 if($_SESSION['_config']['altrow'] != "")
454 $altrows[] = $subalt;
455 }
456 $_SESSION['_config']['altrows'] = $altrows;
457 $_SESSION['_config']['altid'] = $altid;
458 }
459
460 function getcn2()
461 {
462 $rows=array();
463 $rowid=array();
464 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
465 {
466 $CN = $_SESSION['_config']["$cnc.CN"];
467 $bits = explode(".", $CN);
468 $dom = "";
469 for($i = count($bits) - 1; $i >= 0; $i--)
470 {
471 if($dom)
472 $dom = $bits[$i].".".$dom;
473 else
474 $dom = $bits[$i];
475 $_SESSION['_config']['row'] = "";
476 $dom = mysql_real_escape_string($dom);
477 $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
478 `org`.`memid`='".$_SESSION['profile']['id']."' and
479 `org`.`orgid`=`orginfo`.`id` and
480 `orgdomains`.`orgid`=`orginfo`.`id` and
481 `orgdomains`.`domain`='$dom'";
482 $res = mysql_query($query);
483 if(mysql_num_rows($res) > 0)
484 {
485 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
486 $rowid[] = $_SESSION['_config']['row']['id'];
487 break;
488 }
489 }
490
491 if($_SESSION['_config']['row'] != "")
492 $rows[] = $CN;
493 }
494 // if(count($rows) <= 0)
495 // {
496 // 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.");
497 // exit;
498 // }
499 $_SESSION['_config']['rows'] = $rows;
500 $_SESSION['_config']['rowid'] = $rowid;
501 }
502
503 function getalt2()
504 {
505 $altrows=array();
506 $altid=array();
507 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
508 {
509 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
510 if(substr($subalt, 0, 4) == "DNS:")
511 $alt = substr($subalt, 4);
512 else
513 continue;
514
515 $bits = explode(".", $alt);
516 $dom = "";
517 for($i = count($bits) - 1; $i >= 0; $i--)
518 {
519 if($dom)
520 $dom = $bits[$i].".".$dom;
521 else
522 $dom = $bits[$i];
523 $_SESSION['_config']['altrow'] = "";
524 $dom = mysql_real_escape_string($dom);
525 $query = "select * from `orginfo`,`orgdomains`,`org` where
526 `org`.`memid`='".$_SESSION['profile']['id']."' and
527 `org`.`orgid`=`orginfo`.`id` and
528 `orgdomains`.`orgid`=`orginfo`.`id` and
529 `orgdomains`.`domain`='$dom'";
530 $res = mysql_query($query);
531 if(mysql_num_rows($res) > 0)
532 {
533 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
534 $altid[] = $_SESSION['_config']['altrow']['id'];
535 break;
536 }
537 }
538
539 if($_SESSION['_config']['altrow'] != "")
540 $altrows[] = $subalt;
541 }
542 $_SESSION['_config']['altrows'] = $altrows;
543 $_SESSION['_config']['altid'] = $altid;
544 }
545
546 function checkownership($hostname)
547 {
548 $bits = explode(".", $hostname);
549 $dom = "";
550 for($i = count($bits) - 1; $i >= 0; $i--)
551 {
552 if($dom)
553 $dom = $bits[$i].".".$dom;
554 else
555 $dom = $bits[$i];
556 $dom = mysql_real_escape_string($dom);
557 $query = "select * from `org`,`orgdomains`,`orginfo`
558 where `org`.`memid`='".$_SESSION['profile']['id']."'
559 and `orgdomains`.`orgid`=`org`.`orgid`
560 and `orginfo`.`id`=`org`.`orgid`
561 and `orgdomains`.`domain`='$dom'";
562 $res = mysql_query($query);
563 if(mysql_num_rows($res) > 0)
564 {
565 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
566 return(true);
567 }
568 }
569 return(false);
570 }
571
572 function maxpoints($id = 0)
573 {
574 if($id <= 0)
575 $id = $_SESSION['profile']['id'];
576
577 $query = "select sum(`points`) as `points` from `notary` where `to`='$id' group by `to`";
578 $row = mysql_fetch_assoc(mysql_query($query));
579 $points = $row['points'];
580
581 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
582 $query = "select * from `users` where `id`='".$_SESSION['profile']['id']."' and `dob` < '$dob'";
583 if(mysql_num_rows(mysql_query($query)) < 1)
584 {
585 if($points >= 100)
586 return(10);
587 else
588 return(0);
589 }
590
591 if($points >= 300)
592 return(200);
593 if($points >= 200)
594 return(150);
595 if($points >= 150)
596 return(35);
597 if($points >= 140)
598 return(30);
599 if($points >= 130)
600 return(25);
601 if($points >= 120)
602 return(20);
603 if($points >= 110)
604 return(15);
605 if($points >= 100)
606 return(10);
607 return(0);
608 }
609
610 function hex2bin($data)
611 {
612 while(strstr($data, "\\x"))
613 {
614 $pos = strlen($data) - strlen(strstr($data, "\\x"));
615 $before = substr($data, 0, $pos);
616 $char = chr(hexdec(substr($data, $pos + 2, 2)));
617 $after = substr($data, $pos + 4);
618 $data = $before.$char.$after;
619 }
620 return(utf8_decode($data));
621 }
622
623 function screenshot($img)
624 {
625 if(file_exists("../screenshots/".$_SESSION['_config']['language']."/$img"))
626 return("/screenshots/".$_SESSION['_config']['language']."/$img");
627 else
628 return("/screenshots/en/$img");
629 }
630
631 function signmail($to, $subject, $message, $from, $replyto = "")
632 {
633 if($replyto == "")
634 $replyto = $from;
635 $tmpfname = tempnam("/tmp", "CSR");
636 $fp = fopen($tmpfname, "w");
637 fputs($fp, $message);
638 fclose($fp);
639 $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
640 @unlink($tmpfname);
641 }
642
643 function checkEmail($email)
644 {
645 $myemail = mysql_real_escape_string($email);
646 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
647 {
648 list($username,$domain)=split('@',$email);
649 $dom = escapeshellarg($domain);
650 $line = trim(`dig +short MX $dom 2>&1`);
651 #echo $email."-$dom-$line-\n";
652 #echo `dig +short mx heise.de 2>&1`."-<br>\n";
653
654 $list = explode("\n", $line);
655 foreach($list as $row)
656 list($pri, $mxhosts[]) = explode(" ", substr(trim($row), 0, -1));
657 $mxhosts[] = $domain;
658 #print_r($mxhosts); die;
659 foreach($mxhosts as $key => $domain)
660 {
661 $fp = @fsockopen($domain,25,$errno,$errstr,5);
662 if($fp)
663 {
664
665 $line = fgets($fp, 4096);
666 while(substr($line, 0, 4) == "220-")
667 $line = fgets($fp, 4096);
668 if(substr($line, 0, 3) != "220")
669 continue;
670 fputs($fp, "HELO www.cacert.org\r\n");
671 $line = fgets($fp, 4096);
672 while(substr($line, 0, 3) == "220")
673 $line = fgets($fp, 4096);
674 if(substr($line, 0, 3) != "250")
675 continue;
676 fputs($fp, "MAIL FROM: <returns@cacert.org>\r\n");
677 $line = fgets($fp, 4096);
678
679 if(substr($line, 0, 3) != "250")
680 continue;
681 fputs($fp, "RCPT TO: <$email>\r\n");
682 $line = trim(fgets($fp, 4096));
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(is_array($_SESSION['profile'])) $query.=", `uid`='".$_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`='".$_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(_("Your certificate request is still queued and hasn't been processed yet. Please wait, and go to Certificates -> View to see it's status."));
740 $subject="[CAcert.org] Certificate TIMEOUT";
741 $body = "A certificate has timed out!\n\n";
742 }
743 else
744 {
745 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>");
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("philipp@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);
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 function fix_assurer_flag($userID)
841 {
842 // Update Assurer-Flag on users table if 100 points. Should the number of points be SUM(points) or SUM(awarded)?
843 $query = mysql_query('UPDATE `users` AS `u` SET `assurer` = 1 WHERE `u`.`id` = \''.(int)intval($userID).
844 '\' AND EXISTS(SELECT 1 FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = `u`.`id`)'.
845 ' AND (SELECT SUM(`points`) FROM `notary` AS `n` WHERE `n`.`to` = `u`.`id` AND `expire` < now()) >= 100'); // Challenge has been passed and non-expired points >= 100
846
847 // Reset flag if requirements are not met
848 $query = mysql_query('UPDATE `users` AS `u` SET `assurer` = 0 WHERE `u`.`id` = \''.(int)intval($userID).
849 '\' AND (NOT EXISTS(SELECT 1 FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = `u`.`id`)'.
850 ' OR (SELECT SUM(`points`) FROM `notary` AS `n` WHERE `n`.`to` = `u`.`id` AND `n`.`expire` < now()) < 100)');
851 }
852
853 // returns 0 if $userID is an Assurer
854 // Otherwise :
855 // Bit 0 is always set
856 // Bit 1 is set if 100 Assurance Points are not reached
857 // Bit 2 is set if Assurer Test is missing
858 // Bit 3 is set if the user is not allowed to be an Assurer (assurer_blocked > 0)
859 function get_assurer_status($userID)
860 {
861 $Result = 0;
862 $query = mysql_query('SELECT * FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` '.
863 ' WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = \''.(int)intval($userID).'\'');
864 if(mysql_num_rows($query) < 1)
865 {
866 $Result |= 5;
867 }
868
869 $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
870 $row = mysql_fetch_assoc($query);
871 if ($row['points'] < 100) {
872 $Result |= 3;
873 }
874
875 $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
876 $row = mysql_fetch_assoc($query);
877 if ($row['assurer_blocked'] > 0) {
878 $Result |= 9;
879 }
880
881 return $Result;
882 }
883
884 // returns text message to be shown to the user given the result of is_no_assurer
885 function no_assurer_text($Status)
886 {
887 if ($Status == 0) {
888 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
889 } elseif ($Status == 3) {
890 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
891 } elseif ($Status == 5) {
892 $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>!';
893 } elseif ($Status == 7) {
894 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
895 } elseif ($Status & 8 > 0) {
896 $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.");
897 } else {
898 $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>.';
899 }
900 return $Result;
901 }
902
903 function is_assurer($userID)
904 {
905 if (get_assurer_status($userID))
906 return 0;
907 else
908 return 1;
909 }
910
911 function get_assurer_reason($userID)
912 {
913 return no_assurer_text(get_assurer_status($userID));
914 }
915
916 function generatecertpath($type,$kind,$id)
917 {
918 $name="../$type/$kind-".intval($id).".$type";
919 $newlayout=1;
920 if($newlayout)
921 {
922 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
923 mkdir("../csr/$kind",0777);
924 mkdir("../crt/$kind",0777);
925 mkdir("../csr/$kind/".intval($id/1000));
926 mkdir("../crt/$kind/".intval($id/1000));
927 }
928 return $name;
929 }
930
931 /**
932 * Run the sql query given in $sql.
933 * The resource returned by mysql_query is
934 * returned by this function.
935 *
936 * It should be safe to replace every mysql_query
937 * call by a mysql_extended_query call.
938 */
939 function mysql_timed_query($sql)
940 {
941 global $sql_data_log;
942 $query_start = microtime(true);
943 $res = mysql_query($sql);
944 $query_end = microtime(true);
945 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
946 return $res;
947 }
948
949 ?>