source: bureau/class/m_mysql.php @ 427

Revision 427, 14.1 KB checked in by anarcat, 9 years ago (diff)

[project @ alternc: changeset 2004-10-24 19:05:14 by anonymous]
Quota patch : 1st step : ajout de la fonction alternc_get_quota dans
les classes concernées

Original author: anonymous
Date: 2004-10-24 19:05:14

Line 
1<?php
2/*
3 $Id: m_mysql.php,v 1.18 2004/10/24 19:05:14 anonymous 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:
27 Purpose of file:
28 ----------------------------------------------------------------------
29*/
30/**
31* Classe de gestion des bases de données mysql des hébergés.
32*
33* Cette classe permet de gérer les bases de données et login/pass pour mysql
34* Copyleft {@link http://alternc.net/ AlternC Team}
35*
36* @copyright    AlternC-Team 2002-11-01 http://alternc.net/
37*
38*/
39class m_mysql {
40
41  var $server="localhost";
42
43  /*---------------------------------------------------------------------------*/
44  /**
45  * m_mysql([$mid]) Constructeur de la classe m_mysql, initialise le membre concerne
46  */
47  function m_mysql() {
48  }
49
50  /* ----------------------------------------------------------------- */
51  /**
52   * Quota name
53   */
54  function alternc_quota_names() {
55    return "mysql";
56  }
57
58  /*---------------------------------------------------------------------------*/
59  /**
60   * get_dblist() retourne la liste des bases configurées pour le membre.
61   * @return array tableau de tableaux associatifs contenant
62   *  "db" => nom de la base "bck" => "mode de backup" "dir" => "Répertoire de backup
63   *  "size" => Size of the database (in bytes)
64   *  retourne false si l'utilisateur n'a aucune base de données
65   */
66  function get_dblist() {
67    global $db,$err,$bro,$cuid;
68    $err->log("mysql","get_dblist");
69    $db->query("SELECT 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)=explode("_",$db->f("db"));
77      $c[]=array("db"=>$db->f("db"), "name"=>$dbn,"bck"=>$db->f("bck_mode"), "dir"=>$db->f("bck_dir"), "pass"=>$db->f("pass"));
78    }
79   
80    /* trouver la taille de toutes ces DB */
81    foreach ($c as $key => $val) {
82      $c[$key]['size'] = 0;
83      $db->query('SHOW TABLE STATUS FROM '.$c[$key]['db'].';');
84      if (! $db->num_rows()) {
85        continue;
86      }
87      while ($db->next_record()) {
88        $c[$key]['size'] += $db->f('Data_length') + $db->f('Index_length') + $db->f('Data_free');
89      }
90    }
91    return $c;
92  }
93
94  /*---------------------------------------------------------------------------*/
95  /**
96   * get_mysql_details($dbn) retourne les paramètres d'une base d'un membre
97   * $dbn est le nom de la base (après le _) ou rien pour la base $user.
98   * @return array tableau associatif contenant
99   *  "db" => nom de la base "bck" => "mode de backup" "dir" => "Répertoire de backup
100   *  "size" => Size of the database (in bytes)
101   *  retourne false si l'utilisateur n'a aucune base de données ou si la base demandée
102   *  n'existe pas
103   */
104  function get_mysql_details($dbn) {
105    global $db,$err,$bro,$mem,$cuid;
106    $root="/var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"];
107    $err->log("mysql","get_mysql_details");
108    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
109    $db->query("SELECT login,pass,db, bck_mode, bck_gzip, bck_dir, bck_history FROM db WHERE uid='$cuid' AND db='$dbname';");
110    if (!$db->num_rows()) {
111      $err->raise("mysql",4);
112      return array("enabled"=>false);
113    }
114    $c=array();
115    $db->next_record();
116    $size=$bro->fsize("/var/alternc/db/".$db->f("db")."/");
117    list($dbu,$dbn)=explode("_",$db->f("db"));
118    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"));
119  }
120
121  /*---------------------------------------------------------------------------*/
122  /**
123   * Create a new database for the current user.
124   * @param string $dbn Database name ($user_$dbn is the mysql db name)
125   * @return true if the database $user_$db has been successfully created, or false if
126   * an error occured, such as over quota user.
127   */
128  function add_db($dbn) {
129    global $db,$err,$quota,$mem,$cuid;
130    $err->log("mysql","add_db",$dbn);
131    if (!$quota->cancreate("mysql")) {
132      $err->raise("mysql",1);
133      return false;
134    }
135    if (!ereg("^[0-9a-z]*$",$dbn)) {
136      $err->raise("mysql",2);
137      return false;
138    }
139    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
140    $db->query("SELECT * FROM db WHERE db='$dbname';");
141    if ($db->num_rows()) {
142      $err->raise("mysql",3);
143      return false;
144    }
145    // find the login/pass for this user :
146    $db->query("SELECT login,pass FROM db WHERE uid='$cuid' LIMIT 0,1;");
147    if (!$db->num_rows()) {
148      $lo=$mem->user["login"];
149      $pa="";
150    } else {
151      $db->next_record();
152      $lo=addslashes($db->f("login"));
153      $pa=addslashes($db->f("pass"));
154    }
155    // Ok, database does not exist, quota is ok and dbname is compliant. Let's proceed
156    $db->query("INSERT INTO db (uid,login,pass,db,bck_mode) VALUES ('$cuid','$lo','$pa','$dbname',0);");
157    $db->query("INSERT INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('localhost','$dbname','$lo','Y','Y','Y','Y','Y','Y','N','Y','Y','Y');");
158    $db->query("INSERT INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('%','$dbname','$lo','Y','Y','Y','Y','Y','Y','N','Y','Y','Y');");
159    $db->query("CREATE DATABASE $dbname;");
160    exec("/usr/lib/alternc/db_create $cuid /var/alternc/db/$dbname");
161    $db->query("FLUSH PRIVILEGES;");
162    $quota->inc("mysql");
163    return true;
164  }
165
166  /*---------------------------------------------------------------------------*/
167  /**
168   * Delete a database for the current user.
169   * @param string $dbn Name of the database to delete. The db name is $user_$dbn
170   * @return true if the database $user_$db has been successfully deleted, or false if
171   *  an error occured, such as db does not exist.
172   */
173  function del_db($dbn) {
174    global $db,$err,$quota,$mem,$cuid;
175    $login=$mem->user["login"];
176    $err->log("mysql","del_db",$dbn);
177    if (!ereg("^[0-9a-z]*$",$dbn)) {
178      $err->raise("mysql",2);
179      return false;
180    }
181    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
182    $db->query("SELECT * FROM db WHERE db='$dbname';");
183    if (!$db->num_rows()) {
184      $err->raise("mysql",4);
185      return false;
186    }
187    // Ok, database exists and dbname is compliant. Let's proceed
188    $db->query("DELETE FROM db WHERE uid='$cuid' AND db='$dbname';");
189    $db->query("DELETE FROM mysql.db WHERE db='$dbname';");
190    $db->query("DROP DATABASE $dbname;");
191    $quota->dec("mysql");
192    $db->query("SELECT COUNT(*) AS cnt FROM db WHERE uid='$cuid';");
193    $db->next_record();
194    if ($db->f("cnt")==0) {
195      $db->query("DELETE FROM mysql.user WHERE User='".$mem->user["login"]."';");
196    }
197    $db->query("FLUSH PRIVILEGES;");
198    return true;
199  }
200 
201  /*---------------------------------------------------------------------------*/
202  /** Set the backup parameters for db $db
203   * @param $db string database name
204   * @param $bck_mode integer Backup mode (0 = none 1 = daily 2 = weekly)
205   * @param $bck_history integer How many backup should we keep ?
206   * @param $bck_gzip boolean Shall we compress the backup ?
207   * @param $bck_dir string Directory relative to the user account where the backup will be stored
208   * @return boolean true if the backup parameters has been successfully changed, false if not.
209   */
210  function put_mysql_backup($dbn,$bck_mode,$bck_history,$bck_gzip,$bck_dir) {
211    global $db,$err,$mem,$bro,$cuid;
212    $err->log("mysql","put_mysql_backup");
213    if (!ereg("^[0-9a-z]*$",$dbn)) {
214      $err->raise("mysql",2);
215      return false;
216    }
217    $dbname=$mem->user["login"].($dbn?"_":"").$dbn;
218    $db->query("SELECT * FROM db WHERE uid='$cuid' AND db='$dbname';");
219    if (!$db->num_rows()) {
220      $err->raise("mysql",4);
221      return false;
222    }
223    $db->next_record();
224    $login=$db->f("login");
225    $bck_mode=intval($bck_mode);
226    $bck_history=intval($bck_history);
227    if ($bck_gzip)
228      $bck_gzip="1";
229    else
230      $bck_gzip="0";
231    if (!$bck_mode)
232      $bck_mode="0";
233    if (!$bck_history) {
234      $err->raise("mysql",5);
235      return false;
236    }
237    if (($bck_dir=$bro->convertabsolute($bck_dir,0))===false) { // return a full path or FALSE
238      $err->raise("mysql",6);
239      return false;
240    }
241    $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';");
242    return true;
243  }
244
245  /*---------------------------------------------------------------------------*/
246  /** Change the password of the user
247   * @param $password string new password (cleartext)
248   * @return boolean true if the password has been successfully changed, false else.
249   */
250  function put_mysql_details($password) {
251    global $db,$err,$mem,$cuid;
252    $err->log("mysql","put_mysql_details");
253    $db->query("SELECT * FROM db WHERE uid='$cuid';");
254    if (!$db->num_rows()) {
255      $err->raise("mysql",7);
256      return false;
257    }
258    if (strlen($password)>16) {
259      $err->raise("mysql",8);
260      return false;
261    }
262    $login=$mem->user["login"];
263    // Update all the "pass" fields for this user :
264    $db->query("UPDATE db SET pass='$password' WHERE uid='$cuid';");
265    $db->query("UPDATE mysql.user SET password=PASSWORD('$password') WHERE User='$login';");
266    $db->query("FLUSH PRIVILEGES;");
267    return true;
268  }
269
270  /* ----------------------------------------------------------------- */
271  /**
272   * Create a new mysql account for this user
273   * @param string cleartext password for the new account
274   */
275  function new_mysql($password) {
276    global $db,$err,$mem,$quota,$cuid;
277    $err->log("mysql","new_mysql");
278    if (strlen($password)>16) {
279      $err->raise("mysql",2);
280      return false;
281    }
282    $db->query("SELECT * FROM db WHERE uid='$cuid';");
283    if ($db->num_rows()) {
284      $err->raise("mysql",10);
285      return false;
286    }
287    $login=$mem->user["login"];
288    // OK, creation now...
289    $db->query("INSERT INTO db (uid,login,pass,db) VALUES ('$cuid','".$mem->user["login"]."','$password','".$mem->user["login"]."');");
290    $db->query("INSERT INTO mysql.user (Host,User,Password) VALUES ('localhost','".$mem->user["login"]."',PASSWORD('$password'));");
291    $db->query("INSERT INTO mysql.user (Host,User,Password) VALUES ('%','".$mem->user["login"]."',PASSWORD('$password'));");
292    $db->query("INSERT INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('localhost','".$mem->user["login"]."','".$mem->user["login"]."','Y','Y','Y','Y','Y','Y','N','Y','Y','Y');");
293    $db->query("INSERT INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv) VALUES ('%','".$mem->user["login"]."','".$mem->user["login"]."','Y','Y','Y','Y','Y','Y','N','Y','Y','Y');");
294    $db->query("CREATE DATABASE ".$mem->user["login"].";");
295    exec("/usr/lib/alternc/db_create $cuid /var/alternc/db/".$mem->user["login"]);
296    $db->query("FLUSH PRIVILEGES;");
297    $quota->inc("mysql");
298    return true;
299  }
300
301
302  /* ----------------------------------------------------------------- */
303  /**
304   * Restore a sql script on a user's database.
305   */
306  function restore($file,$stdout,$r) {
307    global $err,$bro,$mem,$L_MYSQL_HOST;
308    if (!($fi=$bro->convertabsolute($file,0))) {
309      $err->raise("mysql",9);
310    }
311    if (substr($fi,-3)==".gz") {
312      $exe="/bin/gzip -d -c <\"$fi\" | /usr/bin/mysql -h".$L_MYSQL_HOST." -u".$r["login"]." -p".$r["pass"]." ".$r["db"];
313    } else {
314      $exe="/usr/bin/mysql -h".$L_MYSQL_HOST." -u".$r["login"]." -p".$r["pass"]." ".$r["db"]." <".$fi;
315    }
316   
317    echo "<code><pre>" ;
318    if ($stdout) {
319      passthru($exe,$ret);
320    } else {
321      exec ($exe,$ret);
322    }
323    echo "</pre></code>" ;
324    if ($ret != 0) {
325      return false ;
326    } else {
327      return true ;
328    }
329  }
330 
331  /* ----------------------------------------------------------------- */
332  /**
333   * AlternC's standard function that check a user's qutoa
334   * TODO : remove this function
335   */
336  function alternc_quota_check() {
337    global $err,$quota;
338    $err->log("mysql","alternc_quota_check");
339    $c=$this->get_dblist();
340    if (is_array($c)) {
341      $quota->setquota("mysql",count($c),1);
342    } else {
343      $quota->setquota("mysql",0,1);
344    }
345    return true;
346  }
347
348  /* ----------------------------------------------------------------- */
349  /**
350   * AlternC's standard function that returns a user's qutoa
351   */
352  function alternc_get_quota() {
353    global $err,$db,$cuid;
354    $err->log("mysql","alternc_get_quota");
355    $c=$this->get_dblist();
356    if (is_array($c)) {
357      return count($c);
358    } else {
359      return 0;
360    }
361  }
362
363
364  /* ----------------------------------------------------------------- */
365  /**
366   * AlternC's standard function that delete a member
367   */
368  function alternc_del_member() {
369    global $db,$err,$cuid;
370    $err->log("mysql","alternc_del_member");
371    $c=$this->get_dblist();
372    if (is_array($c)) {
373      for($i=0;$i<count($c);$i++) {
374        $this->del_db($c[$i]["name"]);
375      }
376    }
377    return true;
378  }
379
380} /* Class m_mysql */
381
382?>
Note: See TracBrowser for help on using the repository browser.