Alternc  3.2
Alternc logiel libre pour l'hébergement
 All Data Structures Namespaces Files Functions Variables Pages
m_quota.php
Go to the documentation of this file.
1 <?php
2 /*
3  ----------------------------------------------------------------------
4  AlternC - Web Hosting System
5  Copyright (C) 2000-2012 by the AlternC Development Team.
6  https://alternc.org/
7  ----------------------------------------------------------------------
8  LICENSE
9 
10  This program is free software; you can redistribute it and/or
11  modify it under the terms of the GNU General Public License (GPL)
12  as published by the Free Software Foundation; either version 2
13  of the License, or (at your option) any later version.
14 
15  This program is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  GNU General Public License for more details.
19 
20  To read the license please visit http://www.gnu.org/copyleft/gpl.html
21  ----------------------------------------------------------------------
22  Purpose of file: Manage user quota
23  ----------------------------------------------------------------------
24 */
25 
26 /**
27  * Class for hosting quotas management
28  *
29  * This class manages services' quotas for each user of AlternC.
30  * The available quotas for each service is stored in the system.quotas
31  * mysql table. The used value is computed by the class using a
32  * callback function <code>alternc_quota_check($uid)</code> that
33  * may by exported by each service class.<br>
34  * each class may also export a function <code>alternc_quota_names()</code>
35  * that returns an array with the quotas names managed by this class.
36  *
37  */
38 class m_quota {
39 
40  var $disk=Array(); /* disk resource for which we will manage quotas */
41 
43  var $quotas;
44  var $clquota; // Which class manage which quota.
45 
46 
47  /* ----------------------------------------------------------------- */
48  /**
49  * Constructor
50  */
51  function m_quota() {
52  $this->disk_quota_enable = variable_get('disk_quota_enable', 1,'Are disk quota enabled for this server', array(array('desc'=>'Enabled','type'=>'boolean')));
53  if ( $this->disk_quota_enable ) {
54  $this->disk = Array( "web"=>"web" );
55  }
56 
57  }
58 
59  private function dummy_for_translation() {
60  _("quota_web");
61  }
62 
63  function hook_menu() {
64  $obj = array(
65  'title' => _("Show my quotas"),
66  'ico' => 'images/quota.png',
67  'link' => 'toggle',
68  'pos' => 110,
69  'divclass' => 'menu-quota',
70  'links' => array(),
71  ) ;
72 
73  $q=$this->getquota();
74 
75  foreach ( array('web', 'bw_web') as $key ) {
76  if ( ! isset($q[$key]["u"]) || empty($q[$key]["t"])) continue;
77  $usage_percent = (int) ($q[$key]["u"] / $q[$key]["t"] * 100);
78  $obj['links'][] = array( 'txt'=>_("quota_".$key) . " " . sprintf(_("%s%% of %s"),$usage_percent,format_size($q[$key]["t"]*1024)), 'url'=>($key == 'bw_web' ? 'stats_show_per_month.php' : 'quota_show.php') );
79  $obj['links'][] = array( 'txt'=>'progressbar', 'total' => $q[$key]["t"], 'used' => $q[$key]["u"]);
80  }
81 
82  return $obj;
83  }
84 
85  /* ----------------------------------------------------------------- */
86  /** Check if a user can use a ressource.
87  * @param string $ressource the ressource name (a named quota)
88  * @Return TRUE if the user can create a ressource (= is there any quota left ?)
89  */
90  function cancreate($ressource="") {
91  $t=$this->getquota($ressource);
92  return $t["u"]<$t["t"];
93  }
94 
95 
96  /* ----------------------------------------------------------------- */
97  /** List the quota-managed services in the server
98  * @Return array the quota names and description (translated)
99  */
100  function qlist() {
101  global $classes,$hooks;
102  $qlist=array();
103  reset($this->disk);
104  while (list($key,$val)=each($this->disk)) {
105  $qlist[$key]=_("quota_".$key); // those are specific disks quotas.
106  }
107 
108  foreach($this->getquota() as $qq) {
109  if (isset($qq['name'])) {
110  $qlist[$qq['name']]=$qq['description'];
111  }
112  }
113  return $qlist;
114  }
115 
116 
117  /**
118  * Synchronise the quotas of the users with the quota of the
119  * user's profile.
120  * If the user have a greater quota than the profile, no change.
121  * If the quota entry doesn't exist for the user, create it with
122  * the defaults value.
123  */
125  global $db,$err;
126  $err->log("quota","synchronise_user_profile");
127  $q="insert into quotas select m.uid as uid, d.quota as name, d.value as total from membres m, defquotas d left join quotas q on q.name=d.quota where m.type=d.type ON DUPLICATE KEY UPDATE total = greatest(d.value, quotas.total);";
128  if (!$db->query($q)) return false;
129  return true;
130  }
131 
132  /*
133  * Create default quota in the profile
134  * when a new quota appear
135  *
136  */
138  global $db,$quota,$err;
139  $err->log("quota","create_missing_quota_profile");
140  $qt=$quota->getquota('',true);
141  $type=$quota->listtype();
142  foreach($type as $t) {
143  foreach($qt as $q=>$vv) {
144  $db->query("INSERT IGNORE defquotas (value,quota,type) VALUES (0,'$q','$t');");
145  }
146  }
147  return true;
148  }
149 
150  /* ----------------------------------------------------------------- */
151  /** Return a ressource usage (u) and total quota (t)
152  * @param string $ressource ressource to get quota of
153  * @Return array the quota used and total for this ressource (or for all ressource if unspecified)
154  */
155  function getquota($ressource="",$recheck=false) {
156  global $db,$err,$cuid,$get_quota_cache,$hooks,$mem;
157  $err->log("quota","getquota",$ressource);
158  if ($recheck) { // rebuilding quota
159  $get_quota_cache=null;
160  $this->quota=array();
161  }
162  if (! empty($get_quota_cache[$cuid]) ) {
163  // This function is called many time each webpage, so I cache the result
164  $this->quotas = $get_quota_cache[$cuid];
165  } else {
166  $res=$hooks->invoke("hook_quota_get");
167  foreach($res as $r) {
168  $this->quotas[$r['name']]=$r;
169  $this->quotas[$r['name']]['u']=$r['used']; // retrocompatibilité
170  $this->quotas[$r['name']]['t']=0; // Default quota = 0
171  }
172  reset($this->disk);
173 
174  if (!empty ($this->disk)) { // Check if there are some disk quota to check
175  // Look if there are some cached value
176  $disk_cached = $mem->session_tempo_params_get('quota_cache_disk');
177 
178  while (list($key,$val)=each($this->disk)) {
179  $a=array();
180  if (
181  isset($disk_cached[$val])
182  && !empty($disk_cached[$val])
183  && $disk_cached[$val]['uid'] == $cuid
184  && $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde
185  ) {
186  // If there is a cached value
187  $a = $disk_cached[$val];
188  } else {
189  exec("/usr/lib/alternc/quota_get ".$cuid ,$ak);
190  $a['u']=intval($ak[0]);
191  $a['t']=@intval($ak[1]);
192  $a['timestamp'] = time();
193  $a['uid'] = $cuid;
194  $disk_cached = $mem->session_tempo_params_set('quota_cache_disk', array($val=>$a));
195  }
196  $this->quotas[$val]=array("name"=>"$val", 'description'=>_("quota_".$val), "t"=>$a['t'],"u"=>$a['u']);
197  }
198  }
199 
200  // Get the allowed quota from database.
201  $db->query("select name, total from quotas where uid='$cuid';");
202  while ( $db->next_record() ) {
203  $this->quotas[$db->f('name')]['t']=$db->f('total');
204  }
205 
206  $get_quota_cache[$cuid] = $this->quotas;
207  }
208 
209  if ($ressource) {
210  if (isset($this->quotas[$ressource]) ) {
211  return $this->quotas[$ressource];
212  } else {
213  return 0;
214  }
215  } else {
216  return $this->quotas;
217  }
218  }
219 
220 
221  /* ----------------------------------------------------------------- */
222  /** Set the quota for a user (and for a ressource)
223  * @param string $ressource ressource to set quota of
224  * @param integer size of the quota (available or used)
225  */
226  function setquota($ressource,$size) {
227  global $err,$db,$cuid;
228  $err->log("quota","setquota",$ressource."/".$size);
229  if (floatval($size)==0) $size="0";
230  if (isset($this->disk[$ressource])) {
231  // It's a disk resource, update it with shell command
232  exec("sudo /usr/lib/alternc/quota_edit $cuid $size &> /dev/null &");
233  // Now we check that the value has been written properly :
234  exec("sudo /usr/lib/alternc/quota_get $cuid &> /dev/null &",$a);
235  if (!isset($a[1]) || $size!=$a[1]) {
236  $err->raise("quota",_("Error writing the quota entry!"));
237  return false;
238  }
239  }
240  // We check that this ressource exists for this client :
241  $db->query("SELECT * FROM quotas WHERE uid='$cuid' AND name='$ressource'");
242  if ($db->num_rows()) {
243  $db->query("UPDATE quotas SET total='$size' WHERE uid='$cuid' AND name='$ressource';");
244  } else {
245  $db->query("INSERT INTO quotas (uid,name,total) VALUES ('$cuid','$ressource','$size');");
246  }
247  return true;
248  }
249 
250 
251  /* ----------------------------------------------------------------- */
252  /**
253  * Erase all quota information about the user.
254  */
255  function delquotas() {
256  global $db,$err,$cuid;
257  $err->log("quota","delquota");
258  $db->query("DELETE FROM quotas WHERE uid='$cuid';");
259  return true;
260  }
261 
262 
263  /* ----------------------------------------------------------------- */
264  /** Get the default quotas as an associative array
265  * @return array the array of the default quotas
266  */
267  function getdefaults() {
268  global $db;
269  $c=array();
270 
271  $db->query("SELECT type,quota FROM defquotas WHERE type='default'");
272  if(!$db->next_record())
273  $this->addtype('default');
274 
275  $db->query("SELECT value,quota,type FROM defquotas ORDER BY type,quota");
276  while($db->next_record()) {
277  $type = $db->f("type");
278  $c[$type][$db->f("quota")] = $db->f("value");
279  }
280  return $c;
281  }
282 
283 
284  /* ----------------------------------------------------------------- */
285  /** Set the default quotas
286  * @param array associative array of quota (key=>val)
287  */
288  function setdefaults($newq) {
289  global $db;
290  $qlist=$this->qlist();
291 
292  foreach($newq as $type => $quotas) {
293  foreach($quotas as $qname => $value) {
294  if(array_key_exists($qname, $qlist)) {
295  if(!$db->query("REPLACE INTO defquotas (value,quota,type) VALUES ($value,'$qname','$type');"))
296  return false;
297  }
298  }
299  }
300  return true;
301  }
302 
303 
304  /* ----------------------------------------------------------------- */
305  /** Add an account type for quotas
306  * @param string $type account type to be added
307  * @return boolean true if all went ok
308  */
309  function addtype($type) {
310  global $db,$err;
311  $qlist=$this->qlist();
312  if(empty($type)) return false;
313  $type=strtolower($type);
314  if (!preg_match("#^[a-z0-9]*$#",$type)) {
315  $err->raise("quota", "Type can only contains characters a-z and 0-9");
316  return false;
317  }
318  while (list($key,$val)=each($qlist)) {
319  if(!$db->query("INSERT IGNORE INTO defquotas (quota,type) VALUES('$key', '$type');")
320  || $db->affected_rows() == 0)
321  return false;
322  }
323  return true;
324  }
325 
326 
327  /* ----------------------------------------------------------------- */
328  /** List for quotas
329  * @return array
330  */
331  function listtype() {
332  global $db;
333  $db->query("SELECT distinct(type) FROM defquotas ORDER by type");
334  $t=array();
335  while ($db->next_record()) {
336  $t[] = $db->f("type");
337  }
338  return $t;
339  }
340 
341 
342  /* ----------------------------------------------------------------- */
343  /** Delete an account type for quotas
344  * @param string $type account type to be deleted
345  * @return boolean true if all went ok
346  */
347  function deltype($type) {
348  global $db;
349  $qlist=$this->qlist();
350 
351  if($db->query("UPDATE membres SET type='default' WHERE type='$type'") &&
352  $db->query("DELETE FROM defquotas WHERE type='$type'")) {
353  return true;
354  } else {
355  return false;
356  }
357  }
358 
359 
360  /* ----------------------------------------------------------------- */
361  /** Create default quotas entries for a new user.
362  * The user we are talking about is in the global $cuid.
363  */
364  function addquotas() {
365  global $db,$err,$cuid;
366  $err->log("quota","addquota");
367  $ql=$this->qlist();
368  reset($ql);
369 
370  $db->query("SELECT type,quota FROM defquotas WHERE type='default'");
371  if(!$db->next_record())
372  $this->addtype('default');
373 
374  $db->query("SELECT type FROM membres WHERE uid='$cuid'");
375  $db->next_record();
376  $t = $db->f("type");
377 
378  foreach($ql as $res => $val) {
379  $db->query("SELECT value FROM defquotas WHERE quota='$res' AND type='$t'");
380  $q = $db->next_record() ? $db->f("value") : 0;
381  $this->setquota($res, $q);
382  }
383  return true;
384  }
385 
386 
387  /* ----------------------------------------------------------------- */
388  /** Return a quota value with its unit (when it is a space quota)
389  * in MB, GB, TB ...
390  * @param string $type The quota type
391  * @param integer $value The quota value
392  * @return string a quota value with its unit.
393  */
394  function display_val($type, $value) {
395  switch ($type) {
396  case 'bw_web':
397  return format_size($value);
398  case 'web':
399  return format_size($value*1024);
400  default:
401  return $value;
402  }
403  }
404 
405 
406  /* get size_xx function (filled by spoolsize.php) */
407  function _get_sum_sql($sql) {
408  global $db,$err,$cuid;
409  $db->query($sql);
410  if ($db->num_rows() == 0) {
411  return -1;
412  } else {
413  $db->next_record();
414  $r = $db->Record;
415  return $r['sum'];
416  }
417  }
418 
419  function _get_count_sql($sql) {
420  global $db,$err,$cuid;
421  $db->query($sql);
422  if ($db->num_rows() == 0) {
423  return 0;
424  } else {
425  $db->next_record();
426  $r = $db->Record;
427  return $r['count'];
428  }
429  }
430 
431  function _get_size_and_record_sql($sql) {
432  global $db,$err,$cuid;
433  $db->query($sql);
434  if ($db->num_rows() == 0) {
435  return array();
436  } else {
437  $ret = array();
438  while ($db->next_record()) {
439  $ret[] = $db->Record;
440  }
441  return $ret;
442  }
443  }
444 
445  /* sum of websites sizes from all users */
446  function get_size_web_sum_all() {
447  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web;");
448  }
449 
450  /* sum of websites sizes from one user */
451  function get_size_web_sum_user($u) {
452  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web WHERE uid='$u';");
453  }
454 
455  /* sum of mailbox sizes from all domains */
457  return $this->_get_sum_sql("SELECT SUM(bytes) AS sum FROM mailbox;");
458  }
459 
460  /* sum of mailbox sizes for one domain */
462  global $mail;
463  return $mail->get_total_size_for_domain($dom);
464  }
465 
466  /* count of mailbox sizes from all domains */
468  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM mailbox;");
469  }
470 
471  /* count of mailbox for one domain */
473  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_view WHERE user LIKE '%@{$dom}'");
474  }
475 
476  /* get list of mailbox alias and size for one domain */
478  return $this->_get_size_and_record_sql("SELECT user as alias,quota_dovecot as size FROM dovecot_view WHERE user LIKE '%@{$dom}' ORDER BY alias;");
479  }
480 
481  /* sum of mailman lists sizes from all domains */
483  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman;");
484  }
485 
486  /* sum of mailman lists sizes for one domain */
488  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE list LIKE '%@{$dom}'");
489  }
490 
491  /* sum of mailman lists for one user */
493  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE uid = '{$u}'");
494  }
495 
496  /* count of mailman lists sizes from all domains */
498  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman;");
499  }
500 
501  /* count of mailman lists for one user */
503  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman WHERE uid = '{$u}'");
504  }
505 
506  /* get list of mailman list and size for one user */
508  return $this->_get_size_and_record_sql("SELECT s.size,CONCAT(m.list,'@',m.domain) as list FROM size_mailman s LEFT JOIN mailman m ON s.list=m.name WHERE s.uid='{$u}' ORDER BY s.list ASC");
509  }
510 
511  /* sum of databases sizes from all users */
512  function get_size_db_sum_all() {
513  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db;");
514  }
515 
516  /* sum of databases sizes for one user */
517  function get_size_db_sum_user($u) {
518  return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
519  }
520 
521  /* count of databases from all users */
523  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db;");
524  }
525 
526  /* count of databases for one user */
527  function get_size_db_count_user($u) {
528  return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
529  }
530 
531  /* get list of databases name and size for one user */
533  return $this->_get_size_and_record_sql("SELECT db,size FROM size_db WHERE db='{$u}' OR db LIKE '{$u}\_%';");
534  }
535 
536  /* Return appropriate value and unit of a size given in Bytes (e.g. 1024 Bytes -> return 1 KB) */
537  function get_size_unit($size) {
538  $units=array(1073741824=>_("GB"), 1048576=>_("MB"), 1024=>_("KB"), 0=>_("B"));
539  foreach($units as $value=>$unit){
540  if($size>=$value){
541  $size=str_pad(round($size/($value ? $value : 1), 1), 5, ' ', STR_PAD_LEFT);
542  return array('size'=>$size, 'unit'=>$unit);
543  }
544  }
545  }
546 
547  // Affiche des barres de progression
548  // color_type :
549  // 0 = Pas de changement de couleur
550  // 1 = Progression du vert vers le rouge en fonction du porcentage
551  // 2 = Progression du rouge vers le vert en fonction du porcentage
552  function quota_displaybar($usage, $color_type=1) {
553  if ($color_type == 1) {
554  $csscolor = " background-color:".PercentToColor($usage);
555  } elseif ($color_type == 2) {
556  $csscolor = " background-color:".PercentToColor(100-$usage);
557  } else {
558  $csscolor = "";
559  }
560 
561 
562  echo '<div class="progress-bar">';
563  echo '<div class="barre" style="width:'.$usage.'%;'.$csscolor.'" ></div>';
564  echo '<div class="txt">'.$usage.'%</div>';
565  echo '</div>';
566  }
567 
568 
569  /* ==== Hook functions ==== */
570 
571  /* ----------------------------------------------------------------- */
572  /** Hook function call when a user is deleted
573  * AlternC's standard function called when a user is deleted
574  * globals $cuid is the appropriate user
575  */
577  $this->delquotas();
578  }
579 
580 
581  /* ----------------------------------------------------------------- */
582  /** Hook function called when a user is created
583  * This function initialize the user's quotas.
584  * globals $cuid is the appropriate user
585  */
587  global $err;
588  $err->log("quota","hook_admin_add_member");
589  $this->addquotas();
590  $this->getquota('',true); // actualise quota
591  }
592 
593 
594  /* ----------------------------------------------------------------- */
595  /** Exports all the quota related information for an account.
596  * @access private
597  * EXPERIMENTAL function ;)
598  */
599  function alternc_export_conf() {
600  global $db,$err;
601  $err->log("quota","export");
602  $str=" <quota>";
603 
604  $q=$this->getquota();
605  foreach ($q as $k=>$v) {
606  $str.=" <$k>\n";
607  $str.=" <used>".($v["u"])."</used>\n";
608  $str.=" <total>".($v["t"])."</total>\n";
609  $str.=" </$k>\n";
610  }
611  $str.="</quota>\n";
612  return $str;
613  }
614 
615 
616 } /* Class m_quota */
617