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