Merge branch 'bug-637' into release
[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 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 checkpwlight($pwd) {
252 $points = 0;
253
254 if(strlen($pwd) > 15)
255 $points++;
256 if(strlen($pwd) > 20)
257 $points++;
258 if(strlen($pwd) > 25)
259 $points++;
260 if(strlen($pwd) > 30)
261 $points++;
262
263 //echo "Points due to length: $points<br/>";
264
265 if(preg_match("/\d/", $pwd))
266 $points++;
267
268 if(preg_match("/[a-z]/", $pwd))
269 $points++;
270
271 if(preg_match("/[A-Z]/", $pwd))
272 $points++;
273
274 if(preg_match("/\W/", $pwd))
275 $points++;
276
277 if(preg_match("/\s/", $pwd))
278 $points++;
279
280 //echo "Points due to length and charset: $points<br/>";
281
282 // check for historical password proposal
283 if ($pwd === "Fr3d Sm|7h") {
284 return 0;
285 }
286
287 return $points;
288 }
289
290 function checkpw($pwd, $email, $fname, $mname, $lname, $suffix)
291 {
292 $points = checkpwlight($pwd);
293
294 if(@strstr(strtolower($pwd), strtolower($email)))
295 $points--;
296
297 if(@strstr(strtolower($email), strtolower($pwd)))
298 $points--;
299
300 if(@strstr(strtolower($pwd), strtolower($fname)))
301 $points--;
302
303 if(@strstr(strtolower($fname), strtolower($pwd)))
304 $points--;
305
306 if($mname)
307 if(@strstr(strtolower($pwd), strtolower($mname)))
308 $points--;
309
310 if($mname)
311 if(@strstr(strtolower($mname), strtolower($pwd)))
312 $points--;
313
314 if(@strstr(strtolower($pwd), strtolower($lname)))
315 $points--;
316
317 if(@strstr(strtolower($lname), strtolower($pwd)))
318 $points--;
319
320 if($suffix)
321 if(@strstr(strtolower($pwd), strtolower($suffix)))
322 $points--;
323
324 if($suffix)
325 if(@strstr(strtolower($suffix), strtolower($pwd)))
326 $points--;
327
328 //echo "Points due to name matches: $points<br/>";
329
330 $do = `grep '$pwd' /usr/share/dict/american-english`;
331 if($do)
332 $points--;
333
334 //echo "Points due to wordlist: $points<br/>";
335
336 return($points);
337 }
338
339 function extractit()
340 {
341 $bits = explode(": ", $_SESSION['_config']['subject'], 2);
342 $bits = str_replace(", ", "|", str_replace("/", "|", array_key_exists('1',$bits)?$bits['1']:""));
343 $bits = explode("|", $bits);
344
345 $_SESSION['_config']['cnc'] = $_SESSION['_config']['subaltc'] = 0;
346 $_SESSION['_config']['OU'] = "";
347
348 if(is_array($bits))
349 foreach($bits as $val)
350 {
351 if(!strstr($val, "="))
352 continue;
353
354 $split = explode("=", $val);
355
356 $k = $split[0];
357 $split['1'] = trim($split['1']);
358 if($k == "CN" && $split['1'])
359 {
360 $k = $_SESSION['_config']['cnc'].".".$k;
361 $_SESSION['_config']['cnc']++;
362 $_SESSION['_config'][$k] = $split['1'];
363 }
364 if($k == "OU" && $split['1'] && $_SESSION['_config']['OU'] == "")
365 {
366 $_SESSION['_config']['OU'] = $split['1'];
367 }
368 if($k == "subjectAltName" && $split['1'])
369 {
370 $k = $_SESSION['_config']['subaltc'].".".$k;
371 $_SESSION['_config']['subaltc']++;
372 $_SESSION['_config'][$k] = $split['1'];
373 }
374 }
375 }
376
377 function getcn()
378 {
379 unset($_SESSION['_config']['rows']);
380 unset($_SESSION['_config']['rowid']);
381 unset($_SESSION['_config']['rejected']);
382 $rows=array();
383 $rowid=array();
384 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
385 {
386 $CN = $_SESSION['_config']["$cnc.CN"];
387 $bits = explode(".", $CN);
388 $dom = "";
389 $cnok = 0;
390 for($i = count($bits) - 1; $i >= 0; $i--)
391 {
392 if($dom)
393 $dom = $bits[$i].".".$dom;
394 else
395 $dom = $bits[$i];
396 $_SESSION['_config']['row'] = "";
397 $dom = mysql_real_escape_string($dom);
398 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
399 $res = mysql_query($query);
400 if(mysql_num_rows($res) > 0)
401 {
402 $cnok = 1;
403 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
404 $rowid[] = $_SESSION['_config']['row']['id'];
405 break;
406 }
407 }
408
409 if($cnok == 0)
410 $_SESSION['_config']['rejected'][] = $CN;
411
412 if($_SESSION['_config']['row'] != "")
413 $rows[] = $CN;
414 }
415 // if(count($rows) <= 0)
416 // {
417 // 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.");
418 // exit;
419 // }
420
421 $_SESSION['_config']['rows'] = $rows;
422 $_SESSION['_config']['rowid'] = $rowid;
423 }
424
425 function getalt()
426 {
427 unset($_SESSION['_config']['altrows']);
428 unset($_SESSION['_config']['altid']);
429 $altrows=array();
430 $altid=array();
431 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
432 {
433 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
434 if(substr($subalt, 0, 4) == "DNS:")
435 $alt = substr($subalt, 4);
436 else
437 continue;
438
439 $bits = explode(".", $alt);
440 $dom = "";
441 $altok = 0;
442 for($i = count($bits) - 1; $i >= 0; $i--)
443 {
444 if($dom)
445 $dom = $bits[$i].".".$dom;
446 else
447 $dom = $bits[$i];
448 $_SESSION['_config']['altrow'] = "";
449 $dom = mysql_real_escape_string($dom);
450 $query = "select * from domains where `memid`='".$_SESSION['profile']['id']."' and `domain` like '$dom' and `deleted`=0 and `hash`=''";
451 $res = mysql_query($query);
452 if(mysql_num_rows($res) > 0)
453 {
454 $altok = 1;
455 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
456 $altid[] = $_SESSION['_config']['altrow']['id'];
457 break;
458 }
459 }
460
461 if($altok == 0)
462 $_SESSION['_config']['rejected'][] = $alt;
463
464 if($_SESSION['_config']['altrow'] != "")
465 $altrows[] = $subalt;
466 }
467 $_SESSION['_config']['altrows'] = $altrows;
468 $_SESSION['_config']['altid'] = $altid;
469 }
470
471 function getcn2()
472 {
473 $rows=array();
474 $rowid=array();
475 for($cnc = 0; $cnc < $_SESSION['_config']['cnc']; $cnc++)
476 {
477 $CN = $_SESSION['_config']["$cnc.CN"];
478 $bits = explode(".", $CN);
479 $dom = "";
480 for($i = count($bits) - 1; $i >= 0; $i--)
481 {
482 if($dom)
483 $dom = $bits[$i].".".$dom;
484 else
485 $dom = $bits[$i];
486 $_SESSION['_config']['row'] = "";
487 $dom = mysql_real_escape_string($dom);
488 $query = "select *, `orginfo`.`id` as `id` from `orginfo`,`orgdomains`,`org` where
489 `org`.`memid`='".$_SESSION['profile']['id']."' and
490 `org`.`orgid`=`orginfo`.`id` and
491 `orgdomains`.`orgid`=`orginfo`.`id` and
492 `orgdomains`.`domain`='$dom'";
493 $res = mysql_query($query);
494 if(mysql_num_rows($res) > 0)
495 {
496 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
497 $rowid[] = $_SESSION['_config']['row']['id'];
498 break;
499 }
500 }
501
502 if($_SESSION['_config']['row'] != "")
503 $rows[] = $CN;
504 }
505 // if(count($rows) <= 0)
506 // {
507 // 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.");
508 // exit;
509 // }
510 $_SESSION['_config']['rows'] = $rows;
511 $_SESSION['_config']['rowid'] = $rowid;
512 }
513
514 function getalt2()
515 {
516 $altrows=array();
517 $altid=array();
518 for($altc = 0; $altc < $_SESSION['_config']['subaltc']; $altc++)
519 {
520 $subalt = $_SESSION['_config']["$altc.subjectAltName"];
521 if(substr($subalt, 0, 4) == "DNS:")
522 $alt = substr($subalt, 4);
523 else
524 continue;
525
526 $bits = explode(".", $alt);
527 $dom = "";
528 for($i = count($bits) - 1; $i >= 0; $i--)
529 {
530 if($dom)
531 $dom = $bits[$i].".".$dom;
532 else
533 $dom = $bits[$i];
534 $_SESSION['_config']['altrow'] = "";
535 $dom = mysql_real_escape_string($dom);
536 $query = "select * from `orginfo`,`orgdomains`,`org` where
537 `org`.`memid`='".$_SESSION['profile']['id']."' and
538 `org`.`orgid`=`orginfo`.`id` and
539 `orgdomains`.`orgid`=`orginfo`.`id` and
540 `orgdomains`.`domain`='$dom'";
541 $res = mysql_query($query);
542 if(mysql_num_rows($res) > 0)
543 {
544 $_SESSION['_config']['altrow'] = mysql_fetch_assoc($res);
545 $altid[] = $_SESSION['_config']['altrow']['id'];
546 break;
547 }
548 }
549
550 if($_SESSION['_config']['altrow'] != "")
551 $altrows[] = $subalt;
552 }
553 $_SESSION['_config']['altrows'] = $altrows;
554 $_SESSION['_config']['altid'] = $altid;
555 }
556
557 function checkownership($hostname)
558 {
559 $bits = explode(".", $hostname);
560 $dom = "";
561 for($i = count($bits) - 1; $i >= 0; $i--)
562 {
563 if($dom)
564 $dom = $bits[$i].".".$dom;
565 else
566 $dom = $bits[$i];
567 $dom = mysql_real_escape_string($dom);
568 $query = "select * from `org`,`orgdomains`,`orginfo`
569 where `org`.`memid`='".$_SESSION['profile']['id']."'
570 and `orgdomains`.`orgid`=`org`.`orgid`
571 and `orginfo`.`id`=`org`.`orgid`
572 and `orgdomains`.`domain`='$dom'";
573 $res = mysql_query($query);
574 if(mysql_num_rows($res) > 0)
575 {
576 $_SESSION['_config']['row'] = mysql_fetch_assoc($res);
577 return(true);
578 }
579 }
580 return(false);
581 }
582
583 function maxpoints($id = 0)
584 {
585 if($id <= 0)
586 $id = $_SESSION['profile']['id'];
587
588 $query = "select sum(`points`) as `points` from `notary` where `to`='$id' group by `to`";
589 $row = mysql_fetch_assoc(mysql_query($query));
590 $points = $row['points'];
591
592 $dob = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")-18));
593 $query = "select * from `users` where `id`='".$_SESSION['profile']['id']."' and `dob` < '$dob'";
594 if(mysql_num_rows(mysql_query($query)) < 1)
595 {
596 if($points >= 100)
597 return(10);
598 else
599 return(0);
600 }
601
602 if($points >= 300)
603 return(200);
604 if($points >= 200)
605 return(150);
606 if($points >= 150)
607 return(35);
608 if($points >= 140)
609 return(30);
610 if($points >= 130)
611 return(25);
612 if($points >= 120)
613 return(20);
614 if($points >= 110)
615 return(15);
616 if($points >= 100)
617 return(10);
618 return(0);
619 }
620
621 function hex2bin($data)
622 {
623 while(strstr($data, "\\x"))
624 {
625 $pos = strlen($data) - strlen(strstr($data, "\\x"));
626 $before = substr($data, 0, $pos);
627 $char = chr(hexdec(substr($data, $pos + 2, 2)));
628 $after = substr($data, $pos + 4);
629 $data = $before.$char.$after;
630 }
631 return(utf8_decode($data));
632 }
633
634 function screenshot($img)
635 {
636 if(file_exists("../screenshots/".$_SESSION['_config']['language']."/$img"))
637 return("/screenshots/".$_SESSION['_config']['language']."/$img");
638 else
639 return("/screenshots/en/$img");
640 }
641
642 function signmail($to, $subject, $message, $from, $replyto = "")
643 {
644 if($replyto == "")
645 $replyto = $from;
646 $tmpfname = tempnam("/tmp", "CSR");
647 $fp = fopen($tmpfname, "w");
648 fputs($fp, $message);
649 fclose($fp);
650 $do = `/usr/bin/gpg --homedir /home/gpg --clearsign "$tmpfname"|/usr/sbin/sendmail "$to"`;
651 @unlink($tmpfname);
652 }
653
654 function checkEmail($email)
655 {
656 $myemail = mysql_real_escape_string($email);
657 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
658 {
659 list($username,$domain)=split('@',$email);
660 $dom = escapeshellarg($domain);
661 $line = trim(`dig +short MX $dom 2>&1`);
662 #echo $email."-$dom-$line-\n";
663 #echo `dig +short mx heise.de 2>&1`."-<br>\n";
664
665 $list = explode("\n", $line);
666 foreach($list as $row)
667 list($pri, $mxhosts[]) = explode(" ", substr(trim($row), 0, -1));
668 $mxhosts[] = $domain;
669 #print_r($mxhosts); die;
670 foreach($mxhosts as $key => $domain)
671 {
672 $fp = @fsockopen($domain,25,$errno,$errstr,5);
673 if($fp)
674 {
675
676 $line = fgets($fp, 4096);
677 while(substr($line, 0, 4) == "220-")
678 $line = fgets($fp, 4096);
679 if(substr($line, 0, 3) != "220")
680 continue;
681 fputs($fp, "HELO www.cacert.org\r\n");
682 $line = fgets($fp, 4096);
683 while(substr($line, 0, 3) == "220")
684 $line = fgets($fp, 4096);
685 if(substr($line, 0, 3) != "250")
686 continue;
687 fputs($fp, "MAIL FROM:<returns@cacert.org>\r\n");
688 $line = fgets($fp, 4096);
689
690 if(substr($line, 0, 3) != "250")
691 continue;
692 fputs($fp, "RCPT TO:<$email>\r\n");
693 $line = trim(fgets($fp, 4096));
694 fputs($fp, "QUIT\r\n");
695 fclose($fp);
696
697 $line = mysql_real_escape_string(trim(strip_tags($line)));
698 $query = "insert into `pinglog` set `when`=NOW(), `email`='$myemail', `result`='$line'";
699 if(is_array($_SESSION['profile'])) $query.=", `uid`='".$_SESSION['profile']['id']."'";
700 mysql_query($query);
701
702 if(substr($line, 0, 3) != "250")
703 return $line;
704 else
705 return "OK";
706 }
707 }
708 }
709 $query = "insert into `pinglog` set `when`=NOW(), `uid`='".$_SESSION['profile']['id']."',
710 `email`='$myemail', `result`='Failed to make a connection to the mail server'";
711 mysql_query($query);
712 return _("Failed to make a connection to the mail server");
713 }
714
715 function waitForResult($table, $certid, $id = 0, $show = 1)
716 {
717 $found = $trycount = 0;
718 if($certid<=0)
719 {
720 if($show) showheader(_("My CAcert.org Account!"));
721 echo _("ERROR: The new Certificate ID is wrong. Please contact support.\n");
722 if($show) showfooter();
723 if($show) exit;
724 return;
725 }
726 while($trycount++ <= 40)
727 {
728 if($table == "gpg")
729 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt` != ''";
730 else
731 $query = "select * from `$table` where `id`='".intval($certid)."' and `crt_name` != ''";
732 $res = mysql_query($query);
733 if(mysql_num_rows($res) > 0)
734 {
735 $found = 1;
736 break;
737 }
738 sleep(3);
739 }
740
741 if(!$found)
742 {
743 if($show) showheader(_("My CAcert.org Account!"));
744 $query = "select * from `$table` where `id`='".intval($certid)."' ";
745 $res = mysql_query($query);
746 $body="";
747 $subject="";
748 if(mysql_num_rows($res) > 0)
749 {
750 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."));
751 $subject="[CAcert.org] Certificate TIMEOUT";
752 $body = "A certificate has timed out!\n\n";
753 }
754 else
755 {
756 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>");
757 $subject="[CAcert.org] Certificate FAILURE";
758 $body = "A certificate has failed: $table $certid $id $show\n\n";
759 }
760
761 $body .= _("Best regards")."\n"._("CAcert.org Support!");
762
763 sendmail("philipp@cacert.org", $subject, $body, "returns@cacert.org", "", "", "CAcert Support");
764
765 if($show) showfooter();
766 if($show) exit;
767 }
768 }
769
770
771
772 function generateTicket()
773 {
774 $query = "insert into tickets (timestamp) values (now()) ";
775 mysql_query($query);
776 $ticket = mysql_insert_id();
777 return $ticket;
778 }
779
780 function sanitizeHTML($input)
781 {
782 return htmlentities(strip_tags($input), ENT_QUOTES);
783 //In case of problems, please use the following line again:
784 //return htmlentities(strip_tags(utf8_decode($input)), ENT_QUOTES);
785 //return htmlspecialchars(strip_tags($input));
786 }
787
788 function make_hash()
789 {
790 if(function_exists("dio_open"))
791 {
792 $rnd = dio_open("/dev/urandom",O_RDONLY);
793 $hash = md5(dio_read($rnd,64));
794 dio_close($rnd);
795 } else {
796 $rnd = fopen("/dev/urandom", "r");
797 $hash = md5(fgets($rnd, 64));
798 fclose($rnd);
799 }
800 return($hash);
801 }
802
803 function csrf_check($nam, $show=1)
804 {
805 if(!array_key_exists('csrf',$_REQUEST) || !array_key_exists('csrf_'.$nam,$_SESSION))
806 {
807 showheader(_("My CAcert.org Account!"));
808 echo _("CSRF Hash is missing. Please try again.")."\n";
809 showfooter();
810 exit();
811 }
812 if(strlen($_REQUEST['csrf'])!=32)
813 {
814 showheader(_("My CAcert.org Account!"));
815 echo _("CSRF Hash is wrong. Please try again.")."\n";
816 showfooter();
817 exit();
818 }
819 if(!array_key_exists($_REQUEST['csrf'],$_SESSION['csrf_'.$nam]))
820 {
821 showheader(_("My CAcert.org Account!"));
822 echo _("CSRF Hash is wrong. Please try again.")."\n";
823 showfooter();
824 exit();
825 }
826 }
827 function make_csrf($nam)
828 {
829 $hash=make_hash();
830 $_SESSION['csrf_'.$nam][$hash]=1;
831 return($hash);
832 }
833
834 function clean_csr($CSR)
835 {
836 $newcsr = str_replace("\r\n","\n",trim($CSR));
837 $newcsr = str_replace("\n\n","\n",$newcsr);
838 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",$newcsr));
839 }
840 function clean_gpgcsr($CSR)
841 {
842 return(preg_replace("/[^A-Za-z0-9\n\r\-\:\=\+\/ ]/","",trim($CSR)));
843 }
844
845 function sanitizeFilename($text)
846 {
847 $text=preg_replace("/[^\w-.@]/","",$text);
848 return($text);
849 }
850
851 function fix_assurer_flag($userID)
852 {
853 // Update Assurer-Flag on users table if 100 points. Should the number of points be SUM(points) or SUM(awarded)?
854 $query = mysql_query('UPDATE `users` AS `u` SET `assurer` = 1 WHERE `u`.`id` = \''.(int)intval($userID).
855 '\' 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`)'.
856 ' 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
857
858 // Reset flag if requirements are not met
859 $query = mysql_query('UPDATE `users` AS `u` SET `assurer` = 0 WHERE `u`.`id` = \''.(int)intval($userID).
860 '\' 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`)'.
861 ' OR (SELECT SUM(`points`) FROM `notary` AS `n` WHERE `n`.`to` = `u`.`id` AND `n`.`expire` < now()) < 100)');
862 }
863
864 // returns 0 if $userID is an Assurer
865 // Otherwise :
866 // Bit 0 is always set
867 // Bit 1 is set if 100 Assurance Points are not reached
868 // Bit 2 is set if Assurer Test is missing
869 // Bit 3 is set if the user is not allowed to be an Assurer (assurer_blocked > 0)
870 function get_assurer_status($userID)
871 {
872 $Result = 0;
873 $query = mysql_query('SELECT * FROM `cats_passed` AS `tp`, `cats_variant` AS `cv` '.
874 ' WHERE `tp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND `tp`.`user_id` = \''.(int)intval($userID).'\'');
875 if(mysql_num_rows($query) < 1)
876 {
877 $Result |= 5;
878 }
879
880 $query = mysql_query('SELECT SUM(`points`) AS `points` FROM `notary` AS `n` WHERE `n`.`to` = \''.(int)intval($userID).'\' AND `n`.`expire` < now()');
881 $row = mysql_fetch_assoc($query);
882 if ($row['points'] < 100) {
883 $Result |= 3;
884 }
885
886 $query = mysql_query('SELECT `assurer_blocked` FROM `users` WHERE `id` = \''.(int)intval($userID).'\'');
887 $row = mysql_fetch_assoc($query);
888 if ($row['assurer_blocked'] > 0) {
889 $Result |= 9;
890 }
891
892 return $Result;
893 }
894
895 // returns text message to be shown to the user given the result of is_no_assurer
896 function no_assurer_text($Status)
897 {
898 if ($Status == 0) {
899 $Result = _("You have passed the Assurer Challenge and collected at least 100 Assurance Points, you are an Assurer.");
900 } elseif ($Status == 3) {
901 $Result = _("You have passed the Assurer Challenge, but to become an Assurer you still have to reach 100 Assurance Points!");
902 } elseif ($Status == 5) {
903 $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>!';
904 } elseif ($Status == 7) {
905 $Result = _("To become an Assurer you have to collect 100 Assurance Points and pass the").' <a href="https://cats.cacert.org/">'._("Assurer Challenge").'</a>!';
906 } elseif ($Status & 8 > 0) {
907 $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.");
908 } else {
909 $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>.';
910 }
911 return $Result;
912 }
913
914 function is_assurer($userID)
915 {
916 if (get_assurer_status($userID))
917 return 0;
918 else
919 return 1;
920 }
921
922 function get_assurer_reason($userID)
923 {
924 return no_assurer_text(get_assurer_status($userID));
925 }
926
927 function generatecertpath($type,$kind,$id)
928 {
929 $name="../$type/$kind-".intval($id).".$type";
930 $newlayout=1;
931 if($newlayout)
932 {
933 $name="../$type/$kind/".intval($id/1000)."/$kind-".intval($id).".$type";
934 mkdir("../csr/$kind",0777);
935 mkdir("../crt/$kind",0777);
936 mkdir("../csr/$kind/".intval($id/1000));
937 mkdir("../crt/$kind/".intval($id/1000));
938 }
939 return $name;
940 }
941
942 /**
943 * Run the sql query given in $sql.
944 * The resource returned by mysql_query is
945 * returned by this function.
946 *
947 * It should be safe to replace every mysql_query
948 * call by a mysql_extended_query call.
949 */
950 function mysql_timed_query($sql)
951 {
952 global $sql_data_log;
953 $query_start = microtime(true);
954 $res = mysql_query($sql);
955 $query_end = microtime(true);
956 $sql_data_log[] = array("sql" => $sql, "duration" => $query_end - $query_start);
957 return $res;
958 }
959
960 ?>