m_admin.php 47.4 KB
Newer Older
1
<?php
2
/* 
3 4
 ----------------------------------------------------------------------
 AlternC - Web Hosting System
5 6
 Copyright (C) 2000-2012 by the AlternC Development Team.
 https://alternc.org/
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 ----------------------------------------------------------------------
 LICENSE

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License (GPL)
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html
 ----------------------------------------------------------------------
 Purpose of file: Administrate members and rights.
 ----------------------------------------------------------------------
*/
25

26
/* ----------------------------------------------------------------- */
Alan Garcia's avatar
Alan Garcia committed
27

28
/**
29
* Manage the AlternC's account administration (create/edit/delete)
30 31 32
*/
class m_admin {

33

34
  /* ----------------------------------------------------------------- */
35
  /** $enabled tells if the logged user is super-admin or not
36 37 38 39
   */
  var $enabled=0;

  /* ----------------------------------------------------------------- */
40 41 42 43 44
  /** List of the controls made for each TLD
   *
   * $tldmode is used by the administration panel, while choosing
   * the authorized TLDs. It's an array of strings explaining the current state of the TLD.
   */
45
  public $tldmode=array();
46

47 48
  var $archive='';

49 50 51 52 53
  /**
   * Constructor
   * 
   * @global	type $db
   * @global	type $cuid
54 55 56 57 58 59
   */
  function m_admin() {
    global $db,$cuid;
    $db->query("SELECT su FROM membres WHERE uid='$cuid';");
    $db->next_record();
    $this->enabled=$db->f("su");
60 61 62 63 64 65 66 67 68

    $this->tldmode=array(
			 0 => _("This TLD is forbidden"),
			 1 => _("primary DNS is checked in WHOIS db"),
			 2 => _("primary & secondary DNS are checked in WHOIS db"),
			 3 => _("Domain must exist, but don't do any DNS check"),
			 4 => _("Domain can be installed, no check at all"),
			 5 => _("Domain can be installed, force NO DNS hosting"),
			 );
69
    $this->archive=variable_get('archive_del_data','','If folder specified html folder of deleted user is archived, else it is deleted. ');
70
  }
71 72 73 74 75 76 77 78
  /**
   * 
   * @global	type $mem
   * @global	type $cuid
   * @global	type $debug_alternc
   * @global	type $L_INOTIFY_UPDATE_DOMAIN
   * @return boolean|string
   */
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  function hook_menu() {
    global $mem, $cuid, $debug_alternc, $L_INOTIFY_UPDATE_DOMAIN;
    if (!$mem->checkRight()) return false;

    $obj = array(
      'title'       => _("Administration"),
      'ico'         => 'images/admin.png',
      'link'        => 'toggle',
      'class'       => 'adminmenu',
      'pos'         => 10,
      'links'       => 
        array(
          array(
           'txt'   => _("Manage AlternC accounts"), 
           'url'   => 'adm_list.php',
           'class' => 'adminmenu'
          ),
          array(
           'txt'   => _("User Quotas"), 
           'url'   => 'quotas_users.php?mode=4',
           'class' => 'adminmenu'
          ),
        )
     ) ;

    if ($cuid == 2000) {
      $obj['links'][] = 
        array(
           'txt'   => _("Admin Control Panel"), 
           'url'   => 'adm_panel.php',
           'class' => 'adminmenu'
          );
      $obj['links'][] = 
        array(
           'txt'   => _("PhpMyAdmin"), 
           'url'   => '/alternc-sql/',
115 116
           'class' => 'adminmenu',
           'target' => '_blank',
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
          );
      $obj['links'][] = 
        array(
           'txt'   => ($debug_alternc->status)?_("Switch debug Off"):_("Switch debug On"),
           'url'   => "alternc_debugme.php?enable=".($debug_alternc->status?"0":"1"), 
           'class' => 'adminmenu'
          );
      if (empty($L_INOTIFY_UPDATE_DOMAIN) || file_exists("$L_INOTIFY_UPDATE_DOMAIN") ) {
        $obj['links'][] =
          array(
             'txt'     => _("Applying..."),
             'url'     => 'javascript:alert(\''._("Domain changes are already applying").'\');',
             'class'   => 'adminmenu',
            );
      } else {
        $obj['links'][] =
          array(
             'txt'     => _("Apply changes"),
             'url'     => 'adm_update_domains.php',
             'class'   => 'adminmenu',
             'onclick' => 'return confirm("'.addslashes(_("Server configuration changes are applied every 5 minutes. Do you want to do it right now?")).'");',
            );

      } // L_INOTIFY_UPDATE_DOMAIN

    } // cuid == 2000


    return $obj;
  }

148 149 150
  /**
   * 
   */
Alan Garcia's avatar
Alan Garcia committed
151 152 153 154 155 156 157 158
  function stop_if_jobs_locked() {
    if ( file_exists(ALTERNC_LOCK_JOBS)) {
      echo "There is a file ".ALTERNC_LOCK_JOBS."\n";
      echo "So no jobs are allowed\n";
      echo "Did you launch alternc.install ?\n";
      die();
    }
  }
159

160 161 162 163 164 165 166
  /**
   * return the uid of an alternc account
   * 
   * @global	type $db
   * @param type $login
   * @return null
   */
167 168 169 170 171 172 173 174 175 176
  function get_uid_by_login($login) {
    global $db;
    $db->query("SELECT uid FROM membres WHERE login='$login';");
    if (! $db->next_record()) {
      return null;
    }
    return $db->f('uid');
  }


177 178
  /**
   * Returns the known information about a hosted account
179
   * 
180 181 182
   * Returns all what we know about an account (contents of the tables
   *  <code>membres</code> et <code>local</code>)
   * Ckecks if the account is super-admin
183 184 185 186 187 188 189
   * 
   * @global	   type $err
   * @global	   type $db
   * @global	   string     $lst_users_properties
   * @param     int         $uid a unique integer identifying the account
   * @param     boolean     $recheck
   * @return array|boolean an associative array containing all the fields of the
190 191 192
   * table <code>membres</code> and <code>local</code> of the corresponding account.
   * Returns FALSE if an error occurs.
   */
193 194
  function get($uid,$recheck=false) {
    global $err,$db,$lst_users_properties;
195 196
    //    $err->log("admin","get",$uid);
    if (!$this->enabled) {
197
      $err->raise("admin",_("-- Only administrators can access this page! --"));
198 199
      return false;
    }
200 201 202

    if (!isset($lst_users_properties) || empty($lst_users_properties) || !is_array($lst_users_properties) || $recheck ) {
      $lst_users_properties=array();
203 204 205 206 207 208
      $db->query("
	SELECT 
		m.uid as muid, 
		l.*, 
		m.*, 
		parent.login as parentlogin,
209
		dbs.name as db_server_name,
210 211 212 213 214 215 216 217 218
		m.renewed + INTERVAL m.duration MONTH as expiry,
		CASE 
			WHEN m.duration IS NULL THEN 0 
			WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3	
			WHEN m.renewed <= NOW() THEN 2
		ELSE 1 END 'status'
		
	FROM membres as m 
		LEFT JOIN membres as parent ON (parent.uid = m.creator) 
219
		LEFT JOIN db_servers as dbs ON (m.db_server_id = dbs.id)
220
		LEFT JOIN local as l ON (m.uid = l.uid) ;");
221
       while ($db->next_record()) {
222
         $lst_users_properties[$db->f('muid')]=$db->Record;
223 224 225 226 227 228 229 230
       }
    }

    if ( !isset($lst_users_properties[$uid]) ) {
      if ( !$recheck ) {
        // don't exist, but is not a forced check. Do a forced check
        return $this->get($uid, true);
      } 
231
      $err->raise("admin",_("Account not found"));
232 233
      return false;
    }
234 235

    return $lst_users_properties[$uid];
236 237
  }

238

239 240 241
  /**
   * Returns the known information about a specific hosted account
   * 
242
   * Similar to get_list() but for creators/resellers.
243 244 245 246 247
   * 
   * @global	   type $err
   * @global	   type $db
   * @param     int     $uid
   * @return    boolean
248 249 250 251 252
   */
  function get_creator($uid) {
    global $err,$db;
    //    $err->log("admin","get",$uid);
    if (!$this->enabled) {
253
      $err->raise("admin",_("-- Only administrators can access this page! --"));
254 255 256 257 258 259 260 261 262
      return false;
    }

    $db->query("SELECT m.*, parent.login as parentlogin FROM membres as m LEFT JOIN membres as parent ON (parent.uid = m.creator) WHERE m.uid='$uid';");

    if ($db->num_rows()) {
      $db->next_record();
      $c=$db->Record;
    } else {
263
      $err->raise("admin",_("Account not found"));
264 265 266 267 268 269 270 271
      return false;
    }

    $db->query("SELECT * FROM local WHERE uid='$uid';");
    if ($db->num_rows()) {
      $db->next_record();
      reset($db->Record);
      while (list($key,$val)=each($db->Record)) {
Alan Garcia's avatar
Alan Garcia committed
272
	      $c[$key]=$val;
273 274 275 276 277 278 279 280
      }
    }

    $db->query("SELECT count(*) as nbcreated FROM membres WHERE creator='$uid';");
    if ($db->num_rows()) {
      $db->next_record();
      reset($db->Record);
      while (list($key,$val)=each($db->Record)) {
Alan Garcia's avatar
Alan Garcia committed
281
	      $c[$key]=$val;
282 283 284 285 286 287
      }
    }

    return $c;
  }

288

289 290 291
  /**
   * 
   * @global	type $db
292 293
   * @return boolean TRUE if there is only one admin account
   * (allow the program to prevent the destruction of the last admin account)
294 295 296 297 298 299 300
   */
  function onesu() {
    global $db;
    $db->query("SELECT COUNT(*) AS cnt FROM membres WHERE su=1");
    $db->next_record();
    return ($db->f("cnt")==1);
  }
301

302

303 304
  /** 
   * Returns the list of the hosted accounts
305
   * 
306 307 308 309
   * Returns all what we know about ALL the accounts (contents of the tables
   *  <code>membres</code> et <code>local</code>)
   * Check for super-admin accounts
   * @param
310 311 312 313 314
   * @return 
   * 
   * @global	   type $err
   * @global	   type $mem
   * @global	   type $cuid
fufroma's avatar
fufroma committed
315 316
   * @param     integer $all
   * @param     integer $creator
317 318 319
   * @param     string $pattern
   * @param     string $pattern_type
   * @return    boolean | array an associative array containing all the fields of the
320 321 322
   * table <code>membres</code> and <code>local</code> of all the accounts.
   * Returns FALSE if an error occurs.
   */
323
  function get_list($all=0,$creator=0,$pattern=FALSE,$pattern_type=FALSE) {
324 325 326
    global $err,$mem,$cuid;
    $err->log("admin","get_list");
    if (!$this->enabled) {
327
      $err->raise("admin",_("-- Only administrators can access this page! --"));
328 329 330
      return false;
    }
    $db=new DB_System();
331 332


333
    if ($pattern) {
334

335
  	if ($pattern_type === 'domaine') {
336

337 338 339 340 341
	   $request = 'SELECT compte AS uid FROM domaines WHERE 1';

	   if ($pattern && preg_match('/[.a-zA-Z0-9]+/', $pattern))
		$request .= sprintf(' AND domaine LIKE "%%%s%%"', $pattern);

342 343 344 345 346 347 348
	   if ($creator) 
		$request .= sprintf(' AND compte in (select uid from membres where creator = "%s" ) ', $creator);

	   if ($mem->user['uid']!=2000 && !$all)
		$request .= sprintf(' AND compte in (select uid from membres where creator = "%s") ', $cuid);


349 350
	   $request .= ' GROUP BY uid';

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        } elseif ($pattern_type === 'login') {

	   $request = 'SELECT uid FROM membres WHERE 1';

           if ($pattern && preg_match('/[a-zA-Z0-9]+/', $pattern))
		$request .= sprintf(' AND login LIKE "%%%s%%"', $pattern);

	   if ($creator) 
		$request .= sprintf(' AND creator = "%s"', $creator);

	   if ($mem->user['uid']!=2000 && !$all)
		$request .= sprintf(' AND creator = "%s"', $cuid);

	   $request .= ' ORDER BY login;';

	} else {

 	   $err->raise("admin", _("Invalid pattern type provided. Are you even performing a legitimate action?"));
	   return FALSE;

        }
372

373
    } else {
374 375 376 377 378 379 380 381 382 383
  
	if ($creator)
	{
      	    // Limit listing to a specific reseller
     	    $request = "SELECT uid FROM membres WHERE creator='".$creator."' ORDER BY login;";
	} elseif ($mem->user['uid']==2000 || $all) {
	      $request = "SELECT uid FROM membres ORDER BY login;";
        } else {
              $request = "SELECT uid FROM membres WHERE creator='".$cuid."' ORDER BY login;";
        }
384
    }
385 386 387

    $db->query($request);

388
    if ($db->num_rows()) {
Alan Garcia's avatar
Alan Garcia committed
389
      $c=array();
390
      while ($db->next_record()) {
391
	$c[$db->f("uid")]=$this->get($db->f("uid"));
392 393 394 395 396 397 398
      }
      return $c;
    } else {
      return false;
    }
  }

399

400 401 402 403 404 405 406 407 408 409 410 411
  /**
   * Send an email to all AlternC's accounts
   * 
   * @global	   type $err
   * @global	   type $mem
   * @global	   type $cuid
   * @global	   type $db
   * @param     string  $subject    Subject of the email to send
   * @param     string  $message    Message to send
   * @param     string  $from       Expeditor of that email
   * @return    boolean
   */
Alan Garcia's avatar
Alan Garcia committed
412 413 414 415
  function mailallmembers($subject,$message,$from) {
    global $err,$mem,$cuid,$db;
    $err->log("admin","mailallmembers");
    if (!$this->enabled) {
416
      $err->raise("admin",_("-- Only administrators can access this page! --"));
Alan Garcia's avatar
Alan Garcia committed
417 418 419 420 421 422 423
      return false;
    }
    $subject=trim($subject);
    $message=trim($message);
    $from=trim($from);

    if (empty($subject) || empty($message) || empty($from) ){
424
      $err->raise("admin",_("Subject, message and sender are mandatory"));
Alan Garcia's avatar
Alan Garcia committed
425 426
      return false;
    }
427
    //@todo remove cf functions.php
Alan Garcia's avatar
Alan Garcia committed
428
    if (checkmail($from) != 0) {
429
      $err->raise("admin",_("Sender is syntaxically incorrect"));
Alan Garcia's avatar
Alan Garcia committed
430 431 432 433
      return false;
    }

    @set_time_limit(1200);
434
    $db->query("SELECT DISTINCT mail FROM membres WHERE mail!='';");
Alan Garcia's avatar
Alan Garcia committed
435 436
    while ($db->next_record()) {
      // Can't do BCC due to postfix limitation
437
      // FIXME: use phpmailer, far better for mass-mailing than sendmail (reply-to issue among others)
Alan Garcia's avatar
Alan Garcia committed
438 439 440 441 442
      mail($db->f('mail'), $subject, $message, null, "-f$from");
    }
    return true;
  }

443

444 445
  /** 
   * Returns an array with the known information about resellers (uid, login, number of accounts)
446
   * Does not include account 2000 in the list.
447
   * May only be called by the admin account (2000)
448
   * If there are no reseller accounts, returns an empty array.
449 450 451 452 453
   * 
   * @global    type $err
   * @global    type $mem
   * @global    type $cuid
   * @return    boolean
454 455 456 457
   */
  function get_creator_list() {
    global $err,$mem,$cuid;

458 459
    $creators = array();

460
    $err->log("admin","get_reseller_list");
461 462
    if (!$this->enabled || $cuid!=2000) {
      $err->raise("admin",_("-- Only administrators can access this page! --"));
463 464 465 466
      return false;
    }

    $db=new DB_System();
467
    $db->query("SELECT DISTINCT creator FROM membres WHERE creator <> 0 ORDER BY creator ASC;");
468 469
    if ($db->num_rows()) {
      while ($db->next_record()) {
470
        $creators[] = $this->get_creator($db->f("creator"));
471 472
      }
    }
473 474 475 476 477
    $creators2 = array();
    foreach ($creators as $cc ) {
      $creators2[$cc['uid']] = $cc;
    }
    return $creators2;
478 479
  }

480 481 482 483 484 485 486 487 488
  /** 
   * Check if I am the creator of the member $uid
   * 
   * @global    type $err
   * @global    type $mem
   * @global    type $db
   * @global    type $cuid
   * @param     int     $uid   a unique integer identifying the account
   * @return    boolean         TRUE if I am the creator of that account. FALSE else.
489 490 491 492 493 494 495 496
   */
  function checkcreator($uid) {
    global $err,$mem,$db,$cuid;
    if ($cuid==2000) {
      return true;
    }
    $db->query("SELECT creator FROM membres WHERE uid='$uid';");
    $db->next_record();
497
    if ($db->Record["creator"]!=$cuid) {
498
      $err->raise("admin",_("-- Only administrators can access this page! --"));
499 500 501 502 503
      return false;
    }
    return true;
  }

fufroma's avatar
fufroma committed
504
  /**
505 506 507 508 509 510 511 512 513 514
   * When the admin want to delegate a subdomain to an account
   * 
   * @global    m_mysql $db
   * @global    m_err   $err
   * @global    m_dom   $dom
   * @global    m_mem   $mem
   * @global    int     $cuid
   * @param     string $u
   * @param     string $domain_name
   * @return boolean
fufroma's avatar
fufroma committed
515
   */
Alan Garcia's avatar
Alan Garcia committed
516 517 518
  function add_shared_domain($u, $domain_name) {
    global $db,$err,$dom,$mem,$cuid;
    $err->log("admin","add_shared_domain",$u."/".$domain_name);
519

Alan Garcia's avatar
Alan Garcia committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    if (! $mem->checkright() ) {
      $err->raise("admin",_("-- Only administrators can do that! --"));
      return false;
    } 

    // Check if this domain exist on this admin account
    if (! in_array($domain_name, $dom->enum_domains())) {
      $err->raise("admin",_("You don't seem to be allowed to delegate this domain"));
      $err->log("admin","add_shared_domain","domain not allowed");
      return false;
    } 

    // Clean the domain_name 
    $domain_name=preg_replace("/^\.\.*/", "", $domain_name);

    $mem->su($u);
    $dom->lock();
    // option : 1=hébergement dns, 1=noerase, empeche de modifier, 1=force
    $dom->add_domain($mem->user['login'].".".$domain_name,1,1,1);
    $dom->unlock();
    $mem->unsu();
    return true;
  }
    
544
  /* ----------------------------------------------------------------- */
545
  /** Creates a new hosted account
546
   *  
547 548 549 550
   * Creates a new hosted account (in the tables <code>membres</code>
   * and <code>local</code>). Prevents any manipulation of the account if
   * the account $mid is not super-admin.
   *
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
   * 
   * @global    m_err   $err
   * @global    m_quota $quota
   * @global    array   $classes
   * @global    int     $cuid
   * @global    m_mem   $mem
   * @global    string  $L_MYSQL_DATABASE
   * @global    string  $L_MYSQL_LOGIN
   * @global    m_hooks $hooks
   * @global    m_action $action
   * @param     string  $login          Login name like [a-z][a-z0-9]*
   * @param     string  $pass           Password (max. 64 characters)
   * @param     string  $nom            Name of the account owner
   * @param     string  $prenom         First name of the account owner
   * @param     string  $mail           Email address of the account owner, useful to get
   *                                    one's lost password
fufroma's avatar
fufroma committed
567
   * @param     integer $canpass
568 569 570
   * @param     string  $type           Account type for quotas
   * @param     int     $duration
   * @param     string  $notes
fufroma's avatar
fufroma committed
571
   * @param     integer $force
Alan Garcia's avatar
Alan Garcia committed
572
   * @param     string  $create_dom
573
   * @param     int     $db_server_id
574 575
   * @return boolean Returns FALSE if an error occurs, TRUE if not.
   */
Alan Garcia's avatar
Alan Garcia committed
576
  function add_mem($login, $pass, $nom, $prenom, $mail, $canpass=1, $type='default', $duration=0, $notes = "", $force=0, $create_dom='', $db_server_id) {
577
    global $err,$quota,$classes,$cuid,$mem,$L_MYSQL_DATABASE,$L_MYSQL_LOGIN,$hooks,$action;
578 579
    $err->log("admin","add_mem",$login."/".$mail);
    if (!$this->enabled) {
580
      $err->raise("admin",_("-- Only administrators can access this page! --"));
581 582
      return false;
    }
583 584 585 586
    if (empty($db_server_id)) {
      $err->raise("admin",_("Missing db_server field"));
      return false;
    }
587
    if (($login=="")||($pass=="")) {
588
      $err->raise("admin",_("All fields are mandatory"));
589 590
      return false;
    }
591 592
    if (!$force) {
      if ($mail=="") {
593
	$err->raise("admin",_("All fields are mandatory"));
Alan Garcia's avatar
Alan Garcia committed
594
	      return false;
595
      }
596
        //@todo remove cf functions.php
597
      if (checkmail($mail)!=0){
598
	$err->raise("admin",_("Please enter a valid email address"));
Alan Garcia's avatar
Alan Garcia committed
599
	      return false;
600
      }
601 602
    }
    $login=strtolower($login);
Alan Garcia's avatar
Alan Garcia committed
603
    if (!preg_match("#^[a-z0-9]+$#",$login)) { //$
604
      $err->raise("admin", _("Login can only contains characters a-z and 0-9"));
605 606
      return false;
    }
607 608 609 610 611
    if (strlen($login) > 14) {
      // Not an arbitrary value : MySQL user names can be up to 16 characters long
      // If we want to allow people to create a few mysql_user (and we want to!)
      // we have to limit the login lenght
      $err->raise("admin",_("The login is too long (14 chars max)"));
612 613
      return false;
    }
614
    // Some login are not allowed...
615
    if ($login==$L_MYSQL_DATABASE || $login==$L_MYSQL_LOGIN || $login=="mysql" || $login=="root") {
616
      $err->raise("admin",_("Login can only contains characters a-z, 0-9 and -"));
617 618 619 620
      return false;
    }
    $pass=_md5cr($pass);
    $db=new DB_System();
Alan Garcia's avatar
Alan Garcia committed
621
    $notes = mysql_real_escape_string($notes);
622
    // Already exist?
623 624 625
    $db->query("SELECT count(*) AS cnt FROM membres WHERE login='$login';");
    $db->next_record();
    if (!$db->f("cnt")) {
626
      $db->query("SELECT max(m.uid)+1 as nextid FROM membres m");
627
      if (!$db->next_record()) {
Alan Garcia's avatar
Alan Garcia committed
628
	      $uid=2000;
629
      } else {
Alan Garcia's avatar
Alan Garcia committed
630 631
	      $uid=$db->Record["nextid"];
	      if ($uid<=2000) $uid=2000;
632
      }
633
      $db->query("INSERT INTO membres (uid,login,pass,mail,creator,canpass,type,created,notes,db_server_id) VALUES ('$uid','$login','$pass','$mail','$cuid','$canpass', '$type', NOW(), '$notes', '$db_server_id');");
634 635
      $db->query("INSERT INTO local(uid,nom,prenom) VALUES('$uid','$nom','$prenom');");
      $this->renew_update($uid, $duration);
636 637
      #exec("sudo /usr/lib/alternc/mem_add ".$login." ".$uid);
      $action->create_dir(getuserpath("$login"));
638
      $action->fix_user($uid);
639
      
640
      // Triggering hooks
641
      $mem->su($uid);
642
      // TODO: old hook method FIXME: when unused remove this
643
      /*
644
      foreach($classes as $c) {
Alan Garcia's avatar
Alan Garcia committed
645 646 647
      	if (method_exists($GLOBALS[$c],"alternc_add_member")) {
	        $GLOBALS[$c]->alternc_add_member();
	      }
648
      }
649 650
      */
      $hooks->invoke("alternc_add_member");
651
      // New hook way
Alan Garcia's avatar
Alan Garcia committed
652
      $hooks->invoke("hook_admin_add_member", array(), array('quota')); // First !!! The quota !!! Etherway, we can't be sure to be able to create all
653
      $hooks->invoke("hook_admin_add_member");
654
      $mem->unsu();
Alan Garcia's avatar
Alan Garcia committed
655 656 657 658 659

      if (!empty($create_dom)) { 
        $this->add_shared_domain($uid, $create_dom); 
      }

660 661
      return $uid;
    } else {
662
      $err->raise("admin",_("This login already exists"));
663 664 665 666
      return false;
    }
  }

667 668
  /** 
   * AlternC's standard function called when a user is created
669
   * This sends an email if configured through the interface.
670 671 672 673 674 675
   * 
   * @global    m_err   $err
   * @global    int     $cuid
   * @global    string     $L_FQDN
   * @global    string     $L_HOSTING
   * @return    boolean
676
   */
677
  function hook_admin_add_member() {
678
    global $err, $cuid, $L_FQDN, $L_HOSTING;
Alan Garcia's avatar
Alan Garcia committed
679
    $dest = variable_get('new_email', '0', 'An email will be sent to this address when new accounts are created if set.', array('desc'=>'Enabled','type'=>'boolean'));
680 681 682 683 684
    if (!$dest) {
      return false;
    }
    $db=new DB_System();
    if (!$db->query("SELECT m.*, parent.login as parentlogin FROM membres m LEFT JOIN membres parent ON parent.uid=m.creator WHERE m.uid='$cuid'")) {
685
      $err->raise("admin",sprintf(_("query failed: %s "), $db->Error));
686 687 688
      return false;
    }
    if ($db->next_record()) {
689
      // TODO: put that string into gettext ! 
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
      $mail = <<<EOF
A new AlternC account was created on %fqdn by %creator.

Account details
---------------

login: %login (%uid)
email: %mail
createor: %creator (%cuid)
can change password: %canpass
type: %type
notes: %notes
EOF;
       $mail = strtr($mail, array('%fqdn' => $L_FQDN,
       				  '%creator' => $db->Record['parentlogin'],
				  '%uid' => $db->Record['uid'],
				  '%login' => $db->Record['login'],
				  '%mail' => $db->Record['mail'],
				  '%cuid' => $db->Record['creator'],
				  '%canpass' => $db->Record['canpass'],
				  '%type' => $db->Record['type'],
				  '%notes' => $db->Record['notes']));
712 713 714 715
       $subject=sprintf(_("New account %s from %s on %s"), $db->Record['login'], $db->Record['parentlogin'], $L_HOSTING);
       if (mail($dest,$subject,$mail,"From: postmaster@$L_FQDN")) {
         //sprintf(_("Email successfully sent to %s"), $dest);
         return true;
716
       } else {
717 718
         $err->raise("admin",sprintf(_("Cannot send email to %s"), $dest));
         return false;
719 720
       } 
    } else {
721 722
       $err->raise("admin",sprintf(_("Query failed: %s"), $db->Error));
       return false;
723 724 725
    }
  }

726

727 728
  /** 
   * Edit an account
729
   *  
730
   * Change an account (in the tables <code>membres</code>
731 732
   * and <code>local</code>). Prevents any manipulation of the account if
   * the account $mid is not super-admin.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
   *  
   * @global    m_err   $err
   * @global    m_mysql $db
   * @global    int     $cuid
   * @global    m_quota $quota
   * @param     int     $uid        The uid number of the account we want to modify
   * @param     string  $mail       New email address of the account owner
   * @param     string  $nom        New name of the account owner
   * @param     string  $prenom     New first name of the account owner
   * @param     string  $pass       New password (max. 64 characters)
   * @param     string  $enabled    (value: 0 or 1) activates or desactivates the
   * @param     boolean $canpass
   * @param     int     $type       New type of account
   * @param     int     $duration   
   * @param     string  $notes
   * @param     boolean $reset_quotas
   * @return    boolean Returns     FALSE if an error occurs, TRUE if not
750
   */
Alan Garcia's avatar
Alan Garcia committed
751
  function update_mem($uid, $mail, $nom, $prenom, $pass, $enabled, $canpass, $type='default', $duration=0, $notes = "",$reset_quotas=false) {
752 753 754
    global $err,$db;
    global $cuid, $quota;

Alan Garcia's avatar
Alan Garcia committed
755 756
    $notes=addslashes($notes);

757 758
    $err->log("admin","update_mem",$uid);
    if (!$this->enabled) {
759
      $err->raise("admin",_("-- Only administrators can access this page! --"));
760 761 762 763 764 765 766 767 768
      return false;
    }
    $db=new DB_System();
    if ($pass) {
      $pass=_md5cr($pass);
      $ssq=" ,pass='$pass' ";
    } else {
      $ssq="";
    }
769

Alan Garcia's avatar
Alan Garcia committed
770 771
    $old_mem = $this->get($uid);

772
    if (($db->query("UPDATE local SET nom='$nom', prenom='$prenom' WHERE uid='$uid';"))
Alan Garcia's avatar
Alan Garcia committed
773
	     &&($db->query("UPDATE membres SET mail='$mail', canpass='$canpass', enabled='$enabled', `type`='$type', notes='$notes' $ssq WHERE uid='$uid';"))){
Alan Garcia's avatar
Alan Garcia committed
774
      if($reset_quotas == "on" || $type != $old_mem['type'] ) {
Alan Garcia's avatar
Alan Garcia committed
775 776 777
        $quota->addquotas();
        $quota->synchronise_user_profile();
      }
778 779 780 781
      $this->renew_update($uid, $duration);
      return true;
    }
    else {
782
      $err->raise("admin",_("Account not found"));
783 784 785 786
      return false;
    }
  }

787

788 789 790
  /** 
   * Lock an account
   * 
791
   * Lock an account and prevent the user to access its account.
792 793 794 795 796
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid    The uid number of the account 
   * @return    boolean         Returns FALSE if an error occurs, TRUE if not.
797 798 799 800 801
   */
  function lock_mem($uid) {
    global $err,$db;
    $err->log("admin","lock_mem",$uid);
    if (!$this->enabled) {
802
      $err->raise("admin",_("-- Only administrators can access this page! --"));
803 804 805 806 807 808 809
      return false;
    }
    $db=new DB_System();
    if ($db->query("UPDATE membres SET enabled='0' WHERE uid='$uid';")) {
      return true;
    }
    else {
810
      $err->raise("admin",_("Account not found"));
811 812 813 814 815
      return false;
    }
  }


816 817 818
  /** 
   * UnLock an account
   * 
819
   * UnLock an account and prevent the user to access its account.
820 821 822 823 824 825
   * 
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid    The uid number of the account 
   * @return    boolean         Returns FALSE if an error occurs, TRUE if not.
826 827 828 829 830
   */
  function unlock_mem($uid) {
    global $err,$db;
    $err->log("admin","unlock_mem",$uid);
    if (!$this->enabled) {
831
      $err->raise("admin",_("-- Only administrators can access this page! --"));
832 833 834 835 836 837 838
      return false;
    }
    $db=new DB_System();
    if ($db->query("UPDATE membres SET enabled='1' WHERE uid='$uid';")) {
      return true;
    }
    else {
839
      $err->raise("admin",_("Account not found"));
840 841 842 843 844 845
      return false;
    }
  }


  /* ----------------------------------------------------------------- */
846
  /** Deletes an account
847 848
   * Deletes the specified account. Prevents any manipulation of the account if
   * the account $mid is not super-admin.
849 850 851 852 853 854 855 856 857 858 859
   * 
   * @global    m_err   $err
   * @global    m_quota $quota
   * @global    array   $classes
   * @global    int     $cuid
   * @global    m_mem   $mem
   * @global    m_dom   $dom
   * @global    m_hooks $hooks
   * @global    m_action $action
   * @param     int     $uid    The uid number of the account 
   * @return    boolean         Returns FALSE if an error occurs, TRUE if not.
860 861
   */
  function del_mem($uid) {
862
    global $err,$quota,$classes,$cuid,$mem,$dom,$hooks,$action;
863 864 865
    $err->log("admin","del_mem",$uid);

    if (!$this->enabled) {
866
      $err->raise("admin",_("-- Only administrators can access this page! --"));
867 868 869 870
      return false;
    }
    $db=new DB_System();
    $tt=$this->get($uid);
871
    
872
    $mem->su($uid);
873 874
    // This script may take a long time on big accounts, let's give us some time ... Fixes 1132
    @set_time_limit(0);
875
    // WE MUST call m_dom before all others because of conflicts ...
876
    $dom->hook_admin_del_member();
877

878
    # New way of deleting or backup delted user html folders using action class
879
    $path=getuserpath($tt['login']);
Alan Garcia's avatar
Alan Garcia committed
880
    $action->archive($path);
881

882
    $hooks->invoke("alternc_del_member");
883 884 885 886 887 888 889 890 891
    $hooks->invoke("hook_admin_del_member");
    
    if (($db->query("DELETE FROM membres WHERE uid='$uid';")) &&
	($db->query("DELETE FROM local WHERE uid='$uid';"))) {
      $mem->unsu();
      // If this user was (one day) an administrator one, he may have a list of his own accounts. Let's associate those accounts to nobody as a creator.
      $db->query("UPDATE membres SET creator=2000 WHERE creator='$uid';");
      return true;
    } else {
892
      $err->raise("admin",_("Account not found"));
893 894 895
      $mem->unsu();
      return false;
    }
896 897
  }

898

899 900 901
  /** 
   * Renew an account
   * 
902
   * Renew an account for its duration
903 904 905 906 907 908
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid        The uid number of the account 
   * @param     int     $periods    The new duration, in months, of the account
   * @return    boolean             Returns FALSE if an error occurs, TRUE if not.
909 910 911 912 913 914 915 916
   */
  function renew_mem($uid, $periods=1) {
    global $err,$db;

    $periods = intval($periods);
    if($periods == 0)
      return false;

917
    $query = "UPDATE membres SET renewed = renewed + INTERVAL (duration * $periods) MONTH WHERE uid=${uid};";
918 919 920
    if ($db->query($query)) {
      return true;
    } else {
921
      $err->raise("admin",_("Account not found"));
922 923 924 925
      return false;
    }
  }

926

927 928 929 930 931 932 933 934
  /** 
   * Update the duration information for an account
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid        The uid number of the account 
   * @param     int     $duration   The new duration, in months, of the account
   * @return    boolean             Returns FALSE if an error occurs, TRUE if not.
935 936 937 938 939 940 941 942 943 944 945 946 947
   */
  function renew_update($uid, $duration) {
    global $err,$db;

    if($duration == 0) {
      if($db->query("UPDATE membres SET duration = NULL, renewed = NULL WHERE uid=$uid;"))
	return true;
    } else {
      if($db->query("UPDATE membres SET duration = $duration WHERE uid=$uid") &&
	 $db->query("UPDATE membres SET renewed = NOW() WHERE uid=$uid and renewed is null;"))
	return true;
    }

948
    $err->raise("admin",_("Account not found"));
949 950 951
    return false;
  }

952

953 954 955 956 957
  /** 
   * Get the expiry date for an account
   * 
   * @param     int     $uid        The uid number of the account 
   * @return    string              The expiry date, a string as printed by MySQL
958 959
   */
  function renew_get_expiry($uid) {
960 961 962
    $jj=$this->get($uid);
    if ( isset($jj) && isset($jj['expiry']) && ! empty($jj['expiry']) ) {
      return $jj['expiry'];
963 964 965 966
    }
    return '';
  }

967

968
  /* ----------------------------------------------------------------- */
969 970 971 972 973
  /** 
   * Get the expiry status for an account
   * 
   * @param     int     $uid        The uid number of the account 
   * @return    integer             The expiry status:
974 975 976 977 978 979
   *  0: account does not expire
   *  1: expires in more than duration,
   *  2: expires within the duration
   *  3: has expired past the duration
   */
  function renew_get_status($uid) {
980
    $jj=$this->get($uid);
981

982 983
    if ( isset($jj) && isset($jj['status']) && ! empty($jj['status']) ) {
      return $jj['status'];
984
    }
985

986 987 988
    return 0;
  }

989

990 991 992 993 994
  /** 
   * Get the expired/about to expire accounts.
   * 
   * @global    m_mysql $db
   * @return    array               The recordset of the corresponding accounts
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
   */
  function renew_get_expiring_accounts() {
    global $db;

    if(!$db->query("SELECT *, m.renewed + INTERVAL duration MONTH 'expiry'," .
		   " CASE WHEN m.duration IS NULL THEN 0" .
		   " WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3" .
		   " WHEN m.renewed <= NOW() THEN 2" .
		   " ELSE 1 END 'status' FROM membres m, local l" .
		   " WHERE m.uid = l.uid" .
		   " HAVING status=2 or status=3 ORDER BY status DESC, expiry;"))
      return false;
    else {
Alan Garcia's avatar
Alan Garcia committed
1008
      $res=array();
1009
      while($db->next_record())
Alan Garcia's avatar
Alan Garcia committed
1010
	      $res[] = $db->Record;
1011 1012 1013 1014 1015
      return $res;
    }
  }


1016 1017 1018 1019 1020 1021 1022
  /** 
   * Turns a common account into a super-admin account
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid        The uid number of the account 
   * @return    boolean    
1023 1024 1025 1026 1027
   */
  function normal2su($uid) {
    global $err,$db;
    $db->query("SELECT su FROM membres WHERE uid='$uid';");
    if (!$db->next_record()) {
1028
      $err->raise("admin",_("Account not found"));
1029
      return false;
1030
    } 
1031
    if ($db->Record["su"]!=0) {
1032
      $err->raise("admin",_("This account is ALREADY an administrator account"));
1033 1034 1035 1036 1037 1038
      return false;
    }
    $db->query("UPDATE membres SET su=1 WHERE uid='$uid';");
    return true;
  }

1039

1040 1041 1042 1043 1044 1045 1046
  /** 
   * Turns a super-admin account into a common account
   * 
   * @global    m_err   $err
   * @global    m_mysql $db
   * @param     int     $uid        The uid number of the account 
   * @return boolean                Returns FALSE if an error occurs, TRUE if not.
1047 1048 1049 1050 1051
   */
  function su2normal($uid) {
    global $err,$db;
    $db->query("SELECT su FROM membres WHERE uid='$uid';");
    if (!$db->next_record()) {
1052
      $err->raise("admin",_("Account not found"));
1053 1054 1055
      return false;
    }
    if ($db->Record["su"]!=1) {
1056
      $err->raise("admin",_("This account is NOT an administrator account!"));
1057 1058 1059 1060 1061 1062
      return false;
    }
    $db->query("UPDATE membres SET su=0 WHERE uid='$uid';");
    return true;
  }

1063

1064 1065
  /**
   * List of the authorized TLDs
1066 1067 1068 1069 1070 1071
   * Returns the list of the authorized TLDs and also the way they are
   * authorized. A TLD is the last members (or the last two) of a
   * domain. For example, "com", "org" etc... AlternC keeps a table
   * containing the list of the TLDs authorized to be installed on the
   * server with the instructions to validate the installation of a
   * domain for each TLD (if necessary).
1072 1073 1074
   * 
   * @global    m_mysql $db
   * @return    array   An associative array like $r["tld"], $r["mode"] where tld
1075 1076 1077 1078 1079
   * is the tld and mode is the authorized mode.
   */
  function listtld() {
    global $db;
    $db->query("SELECT tld,mode FROM tld ORDER BY tld;");
Alan Garcia's avatar
Alan Garcia committed
1080
    $c=array();
1081 1082 1083 1084 1085 1086
    while ($db->next_record()) {
      $c[]=$db->Record;
    }
    return $c;
  }

1087

1088 1089 1090
  /**
   * List the hosted domains on this server
   * 
1091
   * Return the list of hosted domains on this server, (an array of associative arrays)
1092 1093 1094 1095
   * 
   * @global    m_mysql $db
   * @param     boolean     $alsocheck      Returns also errstr and errno telling the domains dig checks
   * @param     boolean     $forcecheck     Force the check of dig domain even if a cache exists.
1096 1097
   * @return array $r[$i] / [domaine][member][noerase][gesdns][gesmx]
   */
1098
  function dom_list($alsocheck=false,$forcecheck=false) {
1099
    global $db;
1100 1101 1102 1103
    $cachefile="/tmp/alternc_dig_check_cache";
    $cachetime=3600; // The dns cache file can be up to 1H old
    if ($alsocheck) {
      if (!$forcecheck && file_exists($cachefile) && filemtime($cachefile)+$cachetime>time()) {
1104
	      $checked=unserialize(file_get_contents($cachefile));
1105
      } else {
1106 1107 1108
        // TODO : do the check here (cf checkdom.php) and store it in $checked
        $checked=$this->checkalldom();
        file_put_contents($cachefile,serialize($checked));
1109 1110
      }
    }
1111
    $db->query("SELECT m.uid,m.login,d.domaine,d.gesdns,d.gesmx,d.noerase FROM domaines d LEFT JOIN membres m ON m.uid=d.compte ORDER BY domaine;");
Alan Garcia's avatar
Alan Garcia committed
1112
    $c=array();
1113
    while ($db->next_record()) {
1114 1115
      $tmp=$db->Record;
      if ($alsocheck) {
1116 1117
      	$tmp["errstr"]=$checked[$tmp["domaine"]]["errstr"];
	      $tmp["errno"]=$checked[$tmp["domaine"]]["errno"];
1118 1119
      }
      $c[]=$tmp;
1120 1121 1122 1123
    }
    return $c;
  }

1124

1125 1126 1127 1128 1129 1130 1131 1132 1133
  /** 
   * Check all the domains for their NS MX and IPs
   * 
   * @global    m_mysql $db
   * @global    string  $L_NS1
   * @global    string  $L_NS2
   * @global    string  $L_MX
   * @global    string  $L_PUBLIC_IP
   * @return    int
1134 1135
   */
  function checkalldom() {
1136
    global $db,$L_NS1,$L_NS2,$L_MX,$L_PUBLIC_IP;
1137
    $checked=array();
Alan Garcia's avatar
Alan Garcia committed
1138
    $db->query("SELECT * FROM domaines ORDER BY domaine;");
1139 1140 1141 1142 1143 1144
    $dl=array();
    while ($db->next_record()) {
      $dl[$db->Record["domaine"]]=$db->Record;
    }
    sort($dl);
    foreach($dl as $c) {
1145
      // For each domain check its type:
1146 1147 1148
      $errno=0;
      $errstr="";
      $dontexist=false;
1149
      // Check the domain.
1150
      if ($c["gesdns"]==1) {
1151
	      // Check the NS pointing to us
Alan Garcia's avatar
Alan Garcia committed
1152 1153 1154 1155 1156 1157 1158 1159 1160
	      $out=array();
	      exec("dig +short NS ".escapeshellarg($c["domaine"]),$out);
	      if (count($out)==0) {
	        $dontexist=true;
	      } else {
	        if (!in_array($L_NS1.".",$out) || !in_array($L_NS2.".",$out)) {
	          $errno=1; $errstr.="NS for this domain are not $L_NS1 and $L_NS2 BUT ".implode(",",$out)."\n";
	        }
	      }
1161 1162
      }
      if ($c["gesmx"]==1 && !$dontexist) {
Alan Garcia's avatar
Alan Garcia committed
1163 1164 1165 1166 1167 1168 1169 1170 1171
  	    $out=array();
	      exec("dig +short MX ".escapeshellarg($c["domaine"]),$out);
	      $out2=array();
	      foreach($out as $o) {
	        list($t,$out2[])=explode(" ",$o);
	      }
	      if (!in_array($L_MX.".",$out2)) {
	        $errno=1; $errstr.="MX is not $L_MX BUT ".implode(",",$out2)."\n";
	      }
1172 1173
      }
      if (!$dontexist) {
1174
	      // We list all subdomains and check they are pointing to us.
Alan Garcia's avatar
Alan Garcia committed
1175 1176 1177 1178
	      $db->query("SELECT * FROM sub_domaines WHERE domaine='".addslashes($c["domaine"])."' ORDER BY sub;");
	      while ($db->next_record()) {
	        $d=$db->Record;
	        if ($d["type"]==0) {
1179
	          // Check the IP: 
Alan Garcia's avatar
Alan Garcia committed
1180 1181
	          $out=array();
	          exec("dig +short A ".escapeshellarg($d["sub"].(($d["sub"]!="")?".":"").$c["domaine"]),$out);
Alan Garcia's avatar
Alan Garcia committed
1182 1183 1184 1185 1186 1187 1188 1189
                  if (! is_array($out)) { // exec dig can fail
                    $errno=1; $errstr.="Fail to get the DNS information. Try again.\n";
                  } else {
	            if (!in_array($L_PUBLIC_IP,$out)) {
	              $errstr.="subdomain '".$d["sub"]."' don't point to $L_PUBLIC_IP but to ".implode(",",$out)."\n";
	              $errno=1;
	            }
                  }
Alan Garcia's avatar
Alan Garcia committed
1190 1191
	        }
	      }
1192 1193
      }
      if ($dontexist) {
Alan Garcia's avatar
Alan Garcia committed
1194 1195
        $errno=2;
	      $errstr="Domain don't exist anymore !";
1196 1197 1198 1199 1200 1201 1202 1203
      }
      if ($errno==0) $errstr="OK";
      $checked[$c["domaine"]]=array("errno"=>$errno, "errstr"=>$errstr); 
    }
    return $checked;
  }


1204 1205 1206
  /**
   * Lock / Unlock a domain 
   * 
1207 1208
   * Lock (or unlock) a domain, so that the member will be (not be) able to delete it
   * from its account
1209 1210 1211 1212 1213
   * 
   * @global    m_mysql $db
   * @global    m_err   $err
   * @param     string  $domain     Domain name to lock / unlock
   * @return    boolean             TRUE if the domain has been locked/unlocked or FALSE if it does not exist.
1214 1215 1216 1217 1218
   */
  function dom_lock($domain) {
    global $db,$err;
    $db->query("SELECT compte FROM domaines WHERE domaine='$domain';");
    if (!$db->next_record()) {
1219
      $err->raise("dom",_("Domain '%s' not found."),$domain);
1220 1221 1222 1223 1224 1225 1226
      return false;
    }
    $db->query("UPDATE domaines SET noerase=1-noerase WHERE domaine='$domain';");
    return true;
  }


1227 1228 1229 1230 1231 1232 1233 1234
  /** 
   * Add a new TLD to the list of the authorized TLDs 
   * 
   * @global    m_mysql $db
   * @global    m_err   $err
   * @param     string      $tld    top-level domain to add (org, com...)
   * @return    boolean             TRUE if the tld has been successfully added, FALSE if not.
   */
1235 1236 1237 1238
  function gettld($tld) {
    global $db,$err;
    $db->query("SELECT mode FROM tld WHERE tld='$tld';");
    if (!$db->next_record()) {
1239
      $err->raise("admin",_("This TLD does not exist"));
1240 1241 1242 1243 1244
      return false;
    }
    return $db->Record["mode"];
  }

1245

1246 1247 1248 1249
  /** 
   * Prints the list of the actually authorized TLDs
   * 
   * @param     boolean $current   Value to select in the list
1250 1251 1252 1253 1254
   */
  function selecttldmode($current=false) {
    for($i=0;$i<count($this->tldmode);$i++) {
      echo "<option value=\"$i\"";
      if ($current==$i) echo " selected=\"selected\"";
1255
      echo ">"._($this->tldmode[$i])."</option>\n";
1256 1257 1258
    }
  }

1259

1260 1261
  /** 
   * Deletes the specified tld in the list of the authorized TLDs
1262 1263
   * <b>Note</b> : This function does not delete the domains depending
   * on this TLD
1264 1265 1266 1267 1268
   * 
   * @global    m_mysql $db
   * @global    m_err   $err
   * @param     string  $tld   The TLD you want to delete
   * @return    boolean         returns true if the TLD has been deleted, or
1269 1270 1271 1272 1273 1274
   * false if an error occured.
   */
  function deltld($tld) {
    global $db,$err;
    $db->query("SELECT tld FROM tld WHERE tld='$tld';");
    if (!$db->next_record()) {
1275
      $err->raise("admin",_("This TLD does not exist"));
1276 1277 1278 1279 1280 1281
      return false;
    }
    $db->query("DELETE FROM tld WHERE tld='$tld';");
    return true;
  }

1282

1283
  /* ----------------------------------------------------------------- */
1284
  /** Add a TLD to the list of the authorized TLDs during the installation
1285
   * 
1286 1287
   * <b>Note: </b> If you check in the whois, be sure that
   *  <code>m_domains</code> knows how to name the whois of the specified
1288 1289 1290 1291 1292 1293 1294
   *  domain!
   * 
   * @global    m_mysql $db
   * @global    m_err   $err
   * @param     string  $tld        string TLD we want to authorize
   * @param     boolean $mode       Controls to make on this TLD.
   * @return    boolean             TRUE if the TLD has been successfully
1295 1296 1297 1298 1299
   *  added. FALSE if not.
   */
  function addtld($tld,$mode) {
    global $db,$err;
    if (!$tld) {
1300
      $err->raise("admin",_("The TLD name is mandatory"));
1301 1302
      return false;
    }
1303 1304
    $tld=trim($tld);

1305 1306
    $db->query("SELECT tld FROM tld WHERE tld='$tld';");
    if ($db->next_record()) {
1307
      $err->raise("admin",_("This TLD already exist"));
1308 1309 1310 1311 1312 1313 1314 1315 1316
      return false;
    }
    if (substr($tld,0,1)==".") $tld=substr($tld,1);
    $mode=intval($mode);
    if ($mode==0) $mode="0";
    $db->query("INSERT INTO tld (tld,mode) VALUES ('$tld','$mode');");
    return true;
  }

1317