source: alternc/trunk/bureau/class/m_mysql.php @ 1656

Revision 1656, 20.8 KB checked in by nahuel, 7 years ago (diff)

il manquait les ` pour pouvoir avoir des noms de bdd qui commencent pas des chiffres.
Closes: #697

Line 
1<?php
2/*
3 $Id: m_mysql.php,v 1.35 2005/12/18 09:51:32 benjamin Exp $
4 ----------------------------------------------------------------------
5 AlternC - Web Hosting System
6 Copyright (C) 2002 by the AlternC Development Team.
7 http://alternc.org/
8 ----------------------------------------------------------------------
9 Based on:
10 Valentin Lacambre's web hosting softwares: http://altern.org/
11 ----------------------------------------------------------------------
12 LICENSE
13
14 This program is free software; you can redistribute it and/or
15 modify it under the terms of the GNU General Public License (GPL)
16 as published by the Free Software Foundation; either version 2
17 of the License, or (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 GNU General Public License for more details.
23
24 To read the license please visit http://www.gnu.org/copyleft/gpl.html
25 ----------------------------------------------------------------------
26 Original Author of file: Benjamin Sonntag
27 Purpose of file: Manage mysql database for users.
28 ----------------------------------------------------------------------
29*/
30/**
31 * MySQL user database management for AlternC.
32 * This class manage user's databases in MySQL, and user's MySQL accounts.
33 *
34 * @copyright    AlternC-Team 2002-2005 http://alternc.org/
35 */
36class m_mysql {
37
38  var $server;
39  var $client;
40
41  /*---------------------------------------------------------------------------*/
42  /** Constructor
43  * m_mysql([$mid]) Constructeur de la classe m_mysql, initialise le membre concerne
44  */
45  function m_mysql() {
46      $this->server = $GLOBALS['L_MYSQL_HOST'];
47      $this->client = $GLOBALS['L_MYSQL_CLIENT'];
48  }
49
50  /* ----------------------------------------------------------------- */
51  /** Hook called by m_quota to obtain the quota managed by this class.
52   * Quota name
53   */
54  function alternc_quota_names() {
55    return array("mysql","mysql_users");
56  }
57
58  /*---------------------------------------------------------------------------*/
59  /** Get the list of the database for the current user.
60   * @return array returns an associative array as follow : <br>
61   *  "db" => database name "bck" => backup mode for this db
62   *  "dir" => Backup folder.
63   *  "size" => Size of the database (in bytes)
64   *  Returns FALSE if the user has no database.
65   */
66  function get_dblist() {
67    global $db,$err,$bro,$cuid;
68    $err->log("mysql","get_dblist");
69    $db->query("SELECT login,pass,db, bck_mode, bck_dir FROM db WHERE uid='$cuid';");
70    if (!$db->num_rows()) {
71      $err->raise("mysql",11);
72      return false;
73    }
74    $c=array();
75    while ($db->next_record()) {
76      list($dbu,$dbn)=split_mysql_database_name($db->f("db"));
77      $c[]=array("db"=>$db->f("db"), "name"=>$dbn,"bck"=>$db->f("bck_mode"), "dir"=>$db->f("bck_dir"), "login"=>$db->f("login"), "pass"=>$db->f("pass"));
78    }
79   
80    /* find the size of each database */
81    foreach ($c as $key => $val) {
82      $c[$key]['size'] = $this->get_db_size($c[$key]['db']);
83    }
84    return $c;
85  }
86
87  /*---------------------------------------------------------------------------*/
88  /** Returns the details of a user's database.
89   * $dbn is the name of the database (after the _) or nothing for the database "$user"
90   * @return array returns an associative array as follow :
91   *  "db" => Name of the database
92   *  "bck" => Current bckup mode
93   *  "dir" => Backup directory
94   *  "size" => Size of the database (in bytes)
95   *  "pass" => Password of the user
96   *  "history" => Number of backup we keep
97   *  "gzip" => Does we compress the dumps ?
98   *  Returns FALSE if the user has no database of if the database does not exist.
99   */
100  function get_mysql_details($dbn) {
101    global $db,$err,$bro,$mem,$cuid;
102    $root="/var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"];
103    $err->log("mysql","get_mysql_details");
104    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
105    $size=$this->get_db_size($dbname);
106    $db->query("SELECT login,pass,db, bck_mode, bck_gzip, bck_dir, bck_history FROM db WHERE uid='$cuid' AND db='$dbname';");
107    if (!$db->num_rows()) {
108      $err->raise("mysql",4);
109      return array("enabled"=>false);
110    }
111    $c=array();
112    $db->next_record();
113    list($dbu,$dbn)=split_mysql_database_name($db->f("db"));
114    return array("enabled"=>true,"login"=>$db->f("login"),"db"=>$db->f("db"), "name"=>$dbn,"bck"=>$db->f("bck_mode"), "dir"=>substr($db->f("bck_dir"),strlen($root)), "size"=>$size, "pass"=>$db->f("pass"), "history"=>$db->f("bck_history"), "gzip"=>$db->f("bck_gzip"));
115  }
116
117  /*---------------------------------------------------------------------------*/
118  /** Create a new database for the current user.
119   * @param $dbn string Database name ($user_$dbn is the mysql db name)
120   * @return TRUE if the database $user_$db has been successfully created, or FALSE if
121   * an error occured, such as over quota user.
122   */
123  function add_db($dbn) {
124    global $db,$err,$quota,$mem,$cuid;
125    $err->log("mysql","add_db",$dbn);
126    if (!$quota->cancreate("mysql")) {
127      $err->raise("mysql",1);
128      return false;
129    }
130    if (!ereg("^[0-9a-z]*$",$dbn)) {
131      $err->raise("mysql",2);
132      return false;
133    }
134    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
135    if (strlen($dbname) > 64) {
136      $err->raise("mysql",12);
137      return false;
138    }
139    $db->query("SELECT * FROM db WHERE db='$dbname';");
140    if ($db->num_rows()) {
141      $err->raise("mysql",3);
142      return false;
143    }
144    // find the login/pass for this user :
145    $db->query("SELECT login,pass FROM db WHERE uid='$cuid' LIMIT 0,1;");
146    if (!$db->num_rows()) {
147      $lo=$mem->user["login"];
148      $pa="";
149    } else {
150      $db->next_record();
151      $lo=addslashes($db->f("login"));
152      $pa=addslashes($db->f("pass"));
153    }
154    // Ok, database does not exist, quota is ok and dbname is compliant. Let's proceed
155    $db->query("INSERT INTO db (uid,login,pass,db,bck_mode) VALUES ('$cuid','$lo','$pa','$dbname',0);");
156    // give everything but GRANT on db.*
157    // we assume there's already a user
158    $db->query("GRANT ALL PRIVILEGES ON `".$dbname."`.* TO '".$lo."'@'$this->client'");
159    $db->query("CREATE DATABASE `$dbname`;");
160    return true;
161  }
162
163  /*---------------------------------------------------------------------------*/
164  /** Delete a database for the current user.
165   * @param $dbn string Name of the database to delete. The db name is $user_$dbn
166   * @return TRUE if the database $user_$db has been successfully deleted, or FALSE if
167   *  an error occured, such as db does not exist.
168   */
169  function del_db($dbn) {
170    global $db,$err,$mem,$cuid;
171    $err->log("mysql","del_db",$dbn);
172    if (!ereg("^[0-9a-z]*$",$dbn)) {
173      $err->raise("mysql",2);
174      return false;
175    }
176    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
177    $db->query("SELECT login FROM db WHERE db='$dbname';");
178    if (!$db->num_rows()) {
179      $err->raise("mysql",4);
180      return false;
181    }
182    $db->next_record();
183    $login=$db->f("login");
184
185    // Ok, database exists and dbname is compliant. Let's proceed
186    $db->query("DELETE FROM db WHERE uid='$cuid' AND db='$dbname';");
187    $db->query("DROP DATABASE `$dbname`;");
188    $db->query("SELECT COUNT(*) AS cnt FROM db WHERE uid='$cuid';");
189    $db->next_record();
190    $db->query("REVOKE ALL PRIVILEGES ON `".$dbname."`.* FROM '".$login."'@'$this->client'");
191    if ($db->f("cnt")==0) {
192      $db->query("DELETE FROM mysql.user WHERE User='".$login."';");
193      $db->query("FLUSH PRIVILEGES;");
194    }
195    return true;
196  }
197 
198  /*---------------------------------------------------------------------------*/
199  /** Set the backup parameters for the database $db
200   * @param $db string database name
201   * @param $bck_mode integer Backup mode (0 = none 1 = daily 2 = weekly)
202   * @param $bck_history integer How many backup should we keep ?
203   * @param $bck_gzip boolean shall we compress the backup ?
204   * @param $bck_dir string Directory relative to the user account where the backup will be stored
205   * @return boolean true if the backup parameters has been successfully changed, false if not.
206   */
207  function put_mysql_backup($dbn,$bck_mode,$bck_history,$bck_gzip,$bck_dir) {
208    global $db,$err,$mem,$bro,$cuid;
209    $err->log("mysql","put_mysql_backup");
210    if (!ereg("^[0-9a-z]*$",$dbn)) {
211      $err->raise("mysql",2);
212      return false;
213    }
214    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
215    $db->query("SELECT * FROM db WHERE uid='$cuid' AND db='$dbname';");
216    if (!$db->num_rows()) {
217      $err->raise("mysql",4);
218      return false;
219    }
220    $db->next_record();
221    $bck_mode=intval($bck_mode);
222    $bck_history=intval($bck_history);
223    if ($bck_gzip)
224      $bck_gzip="1";
225    else
226      $bck_gzip="0";
227    if (!$bck_mode)
228      $bck_mode="0";
229    if (!$bck_history) {
230      $err->raise("mysql",5);
231      return false;
232    }
233    if (($bck_dir=$bro->convertabsolute($bck_dir,0))===false) { // return a full path or FALSE
234      $err->raise("mysql",6);
235      return false;
236    }
237    $db->query("UPDATE db SET bck_mode='$bck_mode', bck_history='$bck_history', bck_gzip='$bck_gzip', bck_dir='$bck_dir' WHERE uid='$cuid' AND db='$dbname';");
238    return true;
239  }
240
241  /*---------------------------------------------------------------------------*/
242  /** Change the password of the user in MySQL
243   * @param $password string new password (cleartext)
244   * @return boolean TRUE if the password has been successfully changed, FALSE else.
245   */
246  function put_mysql_details($password) {
247    global $db,$err,$mem,$cuid;
248    $err->log("mysql","put_mysql_details");
249    $db->query("SELECT * FROM db WHERE uid='$cuid';");
250    if (!$db->num_rows()) {
251      $err->raise("mysql",7);
252      return false;
253    }
254    $db->next_record();
255    $login=$db->f("login");
256
257    if (strlen($password)>16) {
258      $err->raise("mysql",8);
259      return false;
260    }
261    // Update all the "pass" fields for this user :
262    $db->query("UPDATE db SET pass='$password' WHERE uid='$cuid';");
263    $db->query("SET PASSWORD FOR '$login'@'$this->client' = PASSWORD('$password')");
264    return true;
265  }
266
267  /* ----------------------------------------------------------------- */
268  /** Create a new mysql account for this user
269   * @param string cleartext password for the new account
270   * It also create the first database.
271   */
272  function new_mysql($password) {
273    global $db,$err,$mem,$cuid;
274    $err->log("mysql","new_mysql");
275    if (strlen($password)>16) {
276      $err->raise("mysql",8);
277      return false;
278    }
279    $db->query("SELECT * FROM db WHERE uid='$cuid';");
280    if ($db->num_rows()) {
281      $err->raise("mysql",10);
282      return false;
283    }
284    $login=$mem->user["login"];
285    $dbname=$mem->user["login"];
286    // OK, creation now...
287    $db->query("INSERT INTO db (uid,login,pass,db) VALUES ('$cuid','".$login."','$password','".$dbname."');");
288    // give everything but GRANT on $user.*
289    $db->query("GRANT ALL PRIVILEGES ON `".$dbname."`.* TO '".$login."'@'$this->client' IDENTIFIED BY '".$password."'");
290    $db->query("CREATE DATABASE `".$dbname."`;");
291    return true;
292  }
293
294
295  /* ----------------------------------------------------------------- */
296  /** Restore a sql backup script on a user's database.
297   */
298  function restore($file,$stdout,$id) { 
299    global $err,$bro,$mem,$L_MYSQL_HOST;
300    if (!$r=$this->get_mysql_details($id)) { 
301      return false; 
302    } 
303    if (!($fi=$bro->convertabsolute($file,0))) {
304      $err->raise("mysql",9);
305      return false; 
306    }
307    if (substr($fi,-3)==".gz") {
308      $exe="/bin/gzip -d -c <".escapeshellarg($fi)." | /usr/bin/mysql -h".escapeshellarg($L_MYSQL_HOST)." -u".escapeshellarg($r["login"])." -p".escapeshellarg($r["pass"])." ".escapeshellarg($r["db"]); 
309    } elseif (substr($fi,-4)==".bz2") { 
310      $exe="/bin/bunzip2 -d -c <".escapeshellarg($fi)." | /usr/bin/mysql -h".escapeshellarg($L_MYSQL_HOST)." -u".escapeshellarg($r["login"])." -p".escapeshellarg($r["pass"])." ".escapeshellarg($r["db"]); 
311    } else { 
312      $exe="/usr/bin/mysql -h".escapeshellarg($L_MYSQL_HOST)." -u".escapeshellarg($r["login"])." -p".escapeshellarg($r["pass"])." ".escapeshellarg($r["db"])." <".escapeshellarg($fi); 
313    }
314    $exe .= " 2>&1";
315   
316    echo "<code><pre>" ;
317    if ($stdout) {
318      passthru($exe,$ret);
319    } else {
320      exec ($exe,$ret);
321    }
322    echo "</pre></code>" ;
323    if ($ret != 0) {
324      return false ;
325    } else {
326      return true ;
327    }
328  }
329 
330  /* ----------------------------------------------------------------- */
331  /** Get size of a database
332   * @param $dbname name of the database
333   * @return integer database size
334   * @access private
335   */
336 function get_db_size($dbname) {
337   global $db,$err;
338
339   $db->query("SHOW TABLE STATUS FROM `$dbname`;");
340   $size = 0;
341   while ($db->next_record()) {
342     $size += $db->f('Data_length') + $db->f('Index_length')
343              + $db->f('Data_free');
344   }
345   return $size;
346 }
347 
348  /* ----------------------------------------------------------------- */
349  /** Hook function called by the quota class to compute user used quota
350   * Returns the used quota for the $name service for the current user.
351   * @param $name string name of the quota
352   * @return integer the number of service used or false if an error occured
353   * @access private
354   */
355  function alternc_get_quota($name) {
356    global $err,$db,$cuid;
357    if ($name=="mysql") {
358      $err->log("mysql","alternc_get_quota");
359      $c=$this->get_dblist();
360      if (is_array($c)) {
361        return count($c);
362      } else {
363        return 0;
364      }
365    } elseif ($name=="mysql_users") {
366      $err->log("mysql","alternc_get_quota");
367      $c=$this->get_userslist();
368      if(is_array($c))
369        return count($c);
370      else
371        return 0;
372    } else return false;
373  }
374
375
376  /* ----------------------------------------------------------------- */
377  /** Hook function called when a user is deleted.
378   * AlternC's standard function that delete a member
379   */
380  function alternc_del_member() {
381    global $db,$err,$cuid;
382    $err->log("mysql","alternc_del_member");
383    $c=$this->get_dblist();
384    if (is_array($c)) {
385      for($i=0;$i<count($c);$i++) {
386        $this->del_db($c[$i]["name"]);
387      }
388    }
389    return true;
390  }
391
392
393  /* ----------------------------------------------------------------- */
394  /**
395   * Exporte toutes les informations mysql du compte.
396   * @access private
397   * EXPERIMENTAL 'sid' function ;)
398   */
399  function alternc_export($tmpdir) {
400    global $db,$err,$cuid;
401    $err->log("mysql","export");
402    $db->query("SELECT login, pass, db, bck_mode, bck_dir, bck_history, bck_gzip FROM db WHERE uid='$cuid';");
403    if ($db->next_record()) {
404      $str="<mysql>\n";
405      $str.="  <login>".xml_entities($db->Record["login"])."</login>";
406      $str.="  <pass>".xml_entities($db->Record["pass"])."</pass>";
407      do {
408        // Do the dump :
409        $filename=$tmpdir."/mysql.".$db->Record["db"].".sql.gz";
410        exec("/usr/bin/mysqldump --add-drop-table --allow-keywords -Q -f -q -a -e -u".escapeshellarg($db->Record["login"])." -p".escapeshellarg($db->Record["pass"])." ".escapeshellarg($db->Record["db"])." |/bin/gzip >".escapeshellarg($filename));
411        $str.="  <db>\n";
412        $str.="    <name>".xml_entities($db->Record["db"])."</name>\n";
413        if ($s["bck_mode"]!=0) {
414          $str.="    <backup>\n";
415          $str.="      <mode>".xml_entities($db->Record["bck_mode"])."</mode>\n";
416          $str.="      <dir>".xml_entities($db->Record["bck_dir"])."</dir>\n";
417          $str.="      <history>".xml_entities($db->Record["bck_history"])."</history>\n";
418          $str.="      <gzip>".xml_entities($db->Record["bck_gzip"])."</gzip>\n";
419          $str.="    </backup>\n";
420        }
421        $str.="  </db>\n";
422      } while ($db->next_record());
423      $str.="</mysql>\n";
424    }
425    return $str;
426  }
427
428  function get_userslist() {
429    global $db,$err,$bro,$cuid;
430    $err->log("mysql","get_userslist");
431    $db->query("SELECT name FROM dbusers WHERE uid='$cuid';");
432    if (!$db->num_rows()) {
433      $err->raise("mysql",19);
434      return false;
435    }
436    $c=array();
437    while ($db->next_record()) {
438      $c[]=array("name"=>substr($db->f("name"),strpos($db->f("name"),"_")+1));
439    }
440
441    return $c;
442  }
443
444  function add_user($usern,$password,$passconf) {
445    global $db,$err,$quota,$mem,$cuid;
446    $err->log("mysql","add_user",$usern);
447   
448    $user=addslashes($mem->user["login"]."_$usern");
449    $pass=addslashes($password);
450       
451    if (!$quota->cancreate("mysql_users")) {
452      $err->raise("mysql",13);
453      return false;
454    }
455    if (!ereg("^[0-9a-z]",$usern)) {
456      $err->raise("mysql",14);
457      return false;
458    }
459   
460    if (strlen($user) > 16 || strlen($usern) == 0 ) {
461      $err->raise("mysql",15);
462      return false;
463    }
464    $db->query("SELECT * FROM dbusers WHERE name='$user';");
465    if ($db->num_rows()) {
466      $err->raise("mysql",16);
467      return false;
468    }
469    if ($password != $passconf || !$password) {
470      $err->raise("mysql",17);
471      return false;
472    }
473
474
475    // On créé l'utilisateur
476    $db->query("GRANT USAGE ON *.* TO '$user'@'$this->client' IDENTIFIED BY '$pass';");
477    // On le rajoute dans la table des utilisateurs
478    $db->query("INSERT INTO dbusers (uid,name) VALUES($cuid,'$user');");
479    return true;
480  }
481
482  function del_user($user) {
483    global $db,$err,$mem,$cuid,$L_MYSQL_DATABASE;
484    $err->log("mysql","del_user",$user);
485    if (!ereg("^[0-9a-z]",$user)) {
486      $err->raise("mysql",14);
487      return false;
488    }
489    $db->query("SELECT name FROM dbusers WHERE name='".$mem->user["login"]."_$user';");
490    if (!$db->num_rows()) {
491      $err->raise("mysql",18);
492      return false;
493    }
494    $db->next_record();
495    $login=$db->f("name");
496
497    // Ok, database exists and dbname is compliant. Let's proceed
498    $db->query("REVOKE ALL PRIVILEGES ON *.* FROM '".$mem->user["login"]."_$user'@'$this->client';");
499    $db->query("DELETE FROM mysql.db WHERE User='".$mem->user["login"]."_$user' AND Host='$this->client';");
500    $db->query("DELETE FROM mysql.user WHERE User='".$mem->user["login"]."_$user' AND Host='$this->client';");
501    $db->query("FLUSH PRIVILEGES");
502    $db->query("DELETE FROM dbusers WHERE uid='$cuid' AND name='".$mem->user["login"]."_$user';");
503    return true;
504  }
505
506  function get_user_dblist($user) {
507    global $db,$err,$mem,$cuid,$L_MYSQL_DATABASE;
508    $err->log("mysql","get_user_dblist");
509
510    $r=array();
511    $dblist=$this->get_dblist();
512
513    for ( $i=0 ; $i<count($dblist) ; $i++ ) {
514      $db->query("SELECT Db, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv FROM mysql.db WHERE User='".$mem->user["login"].($user?"_":"").$user."' AND Host='$this->client' AND Db='".$dblist[$i]["db"]."';");
515      if ($db->next_record())
516        $r[]=array("db"=>$dblist[$i]["name"], "select"=>$db->f("Select_priv"), "insert"=>$db->f("Insert_priv"), "update"=>$db->f("Update_priv"), "delete"=>$db->f("Delete_priv"), "create"=>$db->f("Create_priv"), "drop"=>$db->f("Drop_priv"), "references"=>$db->f("References_priv"), "index"=>$db->f("Index_priv"), "alter"=>$db->f("Alter_priv"), "create_tmp"=>$db->f("Create_tmp_table_priv"), "lock"=>$db->f("Lock_tables_priv"));
517      else
518        $r[]=array("db"=>$dblist[$i]["name"], "select"=>"N", "insert"=>"N", "update"=>"N", "delete"=>"N", "create"=>"N", "drop"=>"N", "references"=>"N", "index"=>"N", "alter"=>"N", "Create_tmp"=>"N", "lock"=>"N" );
519    }
520
521    return $r;
522  }
523
524  function set_user_rights($user,$dbn,$rights) {
525    global $mem, $db;
526
527    $usern=addslashes($mem->user["login"].($user?"_":"").$user);
528    $dbname=addslashes($mem->user["login"].($dbn?"_":"").$dbn);
529    // On génère les droits en fonction du tableau de droits
530    for( $i=0 ; $i<count($rights) ; $i++ ) {
531      switch ($rights[$i]) {
532        case "select":
533          $strrights.="SELECT,";
534          break;
535        case "insert":
536          $strrights.="INSERT,";
537          break;
538        case "update":
539          $strrights.="UPDATE,";
540          break;
541        case "delete":
542          $strrights.="DELETE,";
543          break;
544        case "create":
545          $strrights.="CREATE,";
546          break;
547        case "drop":
548          $strrights.="DROP,";
549          break;
550        case "references":
551          $strrights.="REFERENCES,";
552          break;
553        case "index":
554          $strrights.="INDEX,";
555          break;
556        case "alter":
557          $strrights.="ALTER,";
558          break;
559        case "create_tmp":
560          $strrights.="CREATE TEMPORARY TABLES,";
561          break;
562        case "lock":
563          $strrights.="LOCK TABLES,";
564          break;
565      }
566    }
567
568   
569    // On remet à zéro tous les droits de l'utilisateur
570    $db->query("SELECT * FROM mysql.db WHERE User = '$usern' AND Db = '$dbname';");
571    if($db->num_rows())
572      $db->query("REVOKE ALL PRIVILEGES ON $dbname.* FROM '$usern'@'$this->client';");
573    if( $strrights ){
574      $strrights=substr($strrights,0,strlen($strrights)-1);
575      $db->query("GRANT $strrights ON $dbname.* TO '$usern'@'$this->client';");     
576    }
577    $db->query("FLUSH PRIVILEGES");
578    return TRUE;
579  }
580
581} /* Class m_mysql */
582
583?>
Note: See TracBrowser for help on using the repository browser.