m_quota.php 19.5 KB
Newer Older
1
2
<?php
/*
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  ----------------------------------------------------------------------
  AlternC - Web Hosting System
  Copyright (C) 2000-2012 by the AlternC Development Team.
  https://alternc.org/
  ----------------------------------------------------------------------
  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: Manage user quota
  ----------------------------------------------------------------------
24
25
26
*/

/**
27
28
29
30
31
32
33
34
35
36
37
 * Class for hosting quotas management
 *
 * This class manages services' quotas for each user of AlternC.
 * The available quotas for each service is stored in the system.quotas
 * mysql table. The used value is computed by the class using a
 * callback function <code>alternc_quota_check($uid)</code> that
 * may by exported by each service class.<br>
 * each class may also export a function <code>alternc_quota_names()</code>
 * that returns an array with the quotas names managed by this class.
 *
 */
38
39
class m_quota {

40
  var $disk=Array();  /* disk resource for which we will manage quotas */
41

42
  var $disk_quota_enable;
43
44
45
  var $quotas;
  var $clquota; // Which class manage which quota.

46

47
48
49
50
51
  /* ----------------------------------------------------------------- */
  /**
   * Constructor
   */
  function m_quota() {
Alan Garcia's avatar
Alan Garcia committed
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
54
55
56
    if ( $this->disk_quota_enable ) {
      $this->disk = Array( "web"=>"web" );
    }

57
58
  }

59
  private function dummy_for_translation() {
Alan Garcia's avatar
Alan Garcia committed
60
61
62
    _("quota_web");
  }

63
64
65
66
  function hook_menu() {
    $obj = array(
      'title'       => _("Show my quotas"),
      'ico'         => 'images/quota.png',
67
      'link'        => 'toggle',
68
69
70
71
72
      'pos'         => 110,
      'divclass'    => 'menu-quota',
      'links'       => array(),
     ) ;

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
78
79
80
      $usage_percent = (int) ($q[$key]["u"] / $q[$key]["t"] * 100);
      $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') );
      $obj['links'][] = array( 'txt'=>'progressbar', 'total' => $q[$key]["t"], 'used' => $q[$key]["u"]);
    } 
81
  
82
83
     return $obj;
  }
84

85
86
  /* ----------------------------------------------------------------- */
  /** Check if a user can use a ressource.
87
   * @param string $ressource the ressource name (a named quota)
88
89
90
91
92
93
94
   * @Return TRUE if the user can create a ressource (= is there any quota left ?)
   */
  function cancreate($ressource="") {
    $t=$this->getquota($ressource);
    return $t["u"]<$t["t"];
  }

95

96
  /* ----------------------------------------------------------------- */
97
98
  /** List the quota-managed services in the server
   * @Return array the quota names and description (translated)
99
100
   */
  function qlist() {
101
    global $classes,$hooks;
102
103
104
105
106
    $qlist=array();
    reset($this->disk);
    while (list($key,$val)=each($this->disk)) {
      $qlist[$key]=_("quota_".$key); // those are specific disks quotas.
    }
107
108

    foreach($this->getquota() as $qq) {
109
110
111
      if (isset($qq['name'])) {
        $qlist[$qq['name']]=$qq['description'];
      }
112
113
114
    }
    return $qlist;
  }
Benjamin Sonntag's avatar
Benjamin Sonntag committed
115
  
116
117
118
119
120
121
122
123
124
125

  /**
    * Synchronise the quotas of the users with the quota of the
    * user's profile.
    * If the user have a greater quota than the profile, no change.
    * If the quota entry doesn't exist for the user, create it with
    * the defaults value.
    */
  function synchronise_user_profile() {
    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
130
131
    return true;
  }

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  /*
   * Create default quota in the profile
   * when a new quota appear
   *
   */
  function create_missing_quota_profile() {
    global $db,$quota,$err;
    $err->log("quota","create_missing_quota_profile");
    $qt=$quota->getquota('',true);
    $type=$quota->listtype();
    foreach($type as $t) {
      foreach($qt as $q=>$vv) {
      $db->query("INSERT IGNORE defquotas (value,quota,type) VALUES (0,'$q','$t');");
      }
    }
    return true;
  }

150
  /* ----------------------------------------------------------------- */
151
152
153
  /** Return a ressource usage (u) and total quota (t)
   * @param string $ressource ressource to get quota of
   * @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
159
160
161
    if ($recheck) { // rebuilding quota
      $get_quota_cache=null;
      $this->quota=array();
    }
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
167
168
169
170
	$res=$hooks->invoke("hook_quota_get");
	foreach($res as $r) {
          $this->quotas[$r['name']]=$r;
          $this->quotas[$r['name']]['u']=$r['used']; // retrocompatibilité
          $this->quotas[$r['name']]['t']=0; // Default quota = 0
171
	}
172
	reset($this->disk);
173
174
175
176
177
178
179
180
181
182

        if (!empty ($this->disk)) { // Check if there are some disk quota to check
          // Look if there are some cached value
          $disk_cached = $mem->session_tempo_params_get('quota_cache_disk');

          while (list($key,$val)=each($this->disk)) {
            $a=array(); 
            if ( 
              isset($disk_cached[$val]) 
              && !empty($disk_cached[$val]) 
Alan Garcia's avatar
Alan Garcia committed
183
              && $disk_cached[$val]['uid'] == $cuid
184
185
186
187
188
189
190
191
192
              && $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde
            ) {
              // If there is a cached value
              $a = $disk_cached[$val];
            } else {
              exec("/usr/lib/alternc/quota_get ".$cuid ,$ak);
              $a['u']=intval($ak[0]);
              $a['t']=@intval($ak[1]);
              $a['timestamp'] = time();
Alan Garcia's avatar
Alan Garcia committed
193
              $a['uid'] = $cuid;
194
195
196
197
198
              $disk_cached = $mem->session_tempo_params_set('quota_cache_disk', array($val=>$a));
            }
            $this->quotas[$val]=array("name"=>"$val", 'description'=>_("quota_".$val), "t"=>$a['t'],"u"=>$a['u']);
          }   
        }
199
200
201
202
203
204
205

        // Get the allowed quota from database.
        $db->query("select name, total from quotas where uid='$cuid';");
        while ( $db->next_record() ) {
          $this->quotas[$db->f('name')]['t']=$db->f('total');
        }

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
216
217
218
    } else {
      return $this->quotas;
    }
  }
219
220
  
  
221
222
  /* ----------------------------------------------------------------- */
  /** Set the quota for a user (and for a ressource)
223
   * @param string $ressource ressource to set quota of
224
225
226
227
228
   * @param integer size of the quota (available or used)
   */
  function setquota($ressource,$size) {
    global $err,$db,$cuid;
    $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
238
239
240
241
242
	return false;
      }
    }
    // We check that this ressource exists for this client :
    $db->query("SELECT * FROM quotas WHERE uid='$cuid' AND name='$ressource'");
    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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    }
    return true;
  }


  /* ----------------------------------------------------------------- */
  /**
   * Erase all quota information about the user.
   */
  function delquotas() {
    global $db,$err,$cuid;
    $err->log("quota","delquota");
    $db->query("DELETE FROM quotas WHERE uid='$cuid';");
    return true;
  }

262

263
  /* ----------------------------------------------------------------- */
264
  /** Get the default quotas as an associative array
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
   * @return array the array of the default quotas
   */
  function getdefaults() {
    global $db;
    $c=array();

    $db->query("SELECT type,quota FROM defquotas WHERE type='default'");
    if(!$db->next_record())
      $this->addtype('default');

    $db->query("SELECT value,quota,type FROM defquotas ORDER BY type,quota");
    while($db->next_record()) {
      $type = $db->f("type");
      $c[$type][$db->f("quota")] = $db->f("value");
    }
    return $c;
  }

283

284
  /* ----------------------------------------------------------------- */
285
  /** Set the default quotas
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
   * @param array associative array of quota (key=>val)
   */
  function setdefaults($newq) {
    global $db;
    $qlist=$this->qlist();

    foreach($newq as $type => $quotas) {
      foreach($quotas as $qname => $value) {
	if(array_key_exists($qname, $qlist)) {
	  if(!$db->query("REPLACE INTO defquotas (value,quota,type) VALUES ($value,'$qname','$type');"))
	    return false;
	}
      }
    }
    return true;
  }
302
  
303

304
  /* ----------------------------------------------------------------- */
305
  /** Add an account type for quotas
306
307
   * @param string $type account type to be added
   * @return boolean true if all went ok
308
309
   */
  function addtype($type) {
Alan Garcia's avatar
Alan Garcia committed
310
    global $db,$err;
311
    $qlist=$this->qlist();
Alan Garcia's avatar
Alan Garcia committed
312
313
314
    if(empty($type)) return false;
    $type=strtolower($type);
    if (!preg_match("#^[a-z0-9]*$#",$type)) {
315
      $err->raise("quota", "Type can only contains characters a-z and 0-9");
Alan Garcia's avatar
Alan Garcia committed
316
317
      return false;
    }
318
319
320
321
322
323
324
325
    while (list($key,$val)=each($qlist)) {
      if(!$db->query("INSERT IGNORE INTO defquotas (quota,type) VALUES('$key', '$type');")
	 || $db->affected_rows() == 0)
	return false;
    }
    return true;
  }

326

Alan Garcia's avatar
Alan Garcia committed
327
  /* ----------------------------------------------------------------- */
328
  /** List for quotas
Alan Garcia's avatar
Alan Garcia committed
329
330
331
332
333
334
335
336
337
338
339
340
   * @return array
   */
  function listtype() {
    global $db;
    $db->query("SELECT distinct(type) FROM defquotas ORDER by type");
    $t=array();
    while ($db->next_record()) {
      $t[] = $db->f("type");
    }
    return $t;
  }

341

342
  /* ----------------------------------------------------------------- */
343
  /** Delete an account type for quotas
344
345
   * @param string $type account type to be deleted
   * @return boolean true if all went ok
346
347
348
349
   */
  function deltype($type) {
    global $db;
    $qlist=$this->qlist();
350
    
351
352
353
354
355
356
357
358
    if($db->query("UPDATE membres SET type='default' WHERE type='$type'") &&
       $db->query("DELETE FROM defquotas WHERE type='$type'")) {
      return true;
    } else {
      return false;
    }
  }

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
365
366
367
368
369
370
371
372
373
374
375
376
   */
  function addquotas() {
    global $db,$err,$cuid;
    $err->log("quota","addquota");
    $ql=$this->qlist();
    reset($ql);

    $db->query("SELECT type,quota FROM defquotas WHERE type='default'");
    if(!$db->next_record())
      $this->addtype('default');

    $db->query("SELECT type FROM membres WHERE uid='$cuid'");
    $db->next_record();
    $t = $db->f("type");
377
    
378
379
380
381
382
383
384
    foreach($ql as $res => $val) {
      $db->query("SELECT value FROM defquotas WHERE quota='$res' AND type='$t'");
      $q = $db->next_record() ? $db->f("value") : 0;
      $this->setquota($res, $q);
    }
    return true;
  }
385
386
  
  
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
  /* ----------------------------------------------------------------- */
  /** Return a quota value with its unit (when it is a space quota)
   * in MB, GB, TB ...
   * @param string $type The quota type
   * @param integer $value The quota value
   * @return string a quota value with its unit.
   */
  function display_val($type, $value) {
    switch ($type) {
    case 'bw_web':
      return format_size($value);
    case 'web':
      return format_size($value*1024);
    default:
      return $value;
    }
  }
404
  
405

domi's avatar
   
domi committed
406
407
408
409
410
411
412
413
414
415
416
417
  /* get size_xx function (filled by spoolsize.php) */
  function _get_sum_sql($sql) {
    global $db,$err,$cuid;
    $db->query($sql);
    if ($db->num_rows() == 0) {
      return -1;
    } else {
      $db->next_record();
      $r = $db->Record;
      return $r['sum'];
    }
  }
418
  
domi's avatar
   
domi committed
419
420
421
422
423
424
425
426
427
428
429
430
  function _get_count_sql($sql) {
    global $db,$err,$cuid;
    $db->query($sql);
    if ($db->num_rows() == 0) {
      return 0;
    } else {
      $db->next_record();
      $r = $db->Record;
      return $r['count'];
    }
  }

431
432
433
434
435
436
437
438
439
440
441
442
443
444
  function _get_size_and_record_sql($sql) {
    global $db,$err,$cuid;
    $db->query($sql);
    if ($db->num_rows() == 0) {
      return array();
    } else {
      $ret = array();
      while ($db->next_record()) {
        $ret[] = $db->Record;
      }
      return $ret;
    }
  }

domi's avatar
   
domi committed
445
446
447
448
449
450
451
452
453
454
455
456
  /* sum of websites sizes from all users */
  function get_size_web_sum_all() {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web;");
  }

  /* sum of websites sizes from one user */
  function get_size_web_sum_user($u) {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web WHERE uid='$u';");
  }

  /* sum of mailbox sizes from all domains */
  function get_size_mail_sum_all() {
457
    return $this->_get_sum_sql("SELECT SUM(bytes) AS sum FROM mailbox;");
domi's avatar
   
domi committed
458
459
460
461
  }

  /* sum of mailbox sizes for one domain */
  function get_size_mail_sum_domain($dom) {
462
463
    global $mail;
    return $mail->get_total_size_for_domain($dom);
domi's avatar
   
domi committed
464
465
466
467
  }

  /* count of mailbox sizes from all domains */
  function get_size_mail_count_all() {
468
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM mailbox;");
domi's avatar
   
domi committed
469
470
471
472
  }

  /* count of mailbox for one domain */
  function get_size_mail_count_domain($dom) {
473
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_view WHERE user LIKE '%@{$dom}'");
domi's avatar
   
domi committed
474
475
  }

476
477
  /* get list of mailbox alias and size for one domain */
  function get_size_mail_details_domain($dom) {
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
  }

domi's avatar
   
domi committed
481
482
483
484
485
486
487
488
489
490
  /* sum of mailman lists sizes from all domains */
  function get_size_mailman_sum_all() {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman;");
  }

  /* sum of mailman lists sizes for one domain */
  function get_size_mailman_sum_domain($dom) {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE list LIKE '%@{$dom}'");
  }

491
492
493
494
495
  /* sum of mailman lists for one user */
  function get_size_mailman_sum_user($u) {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE uid = '{$u}'");
  }

domi's avatar
   
domi committed
496
497
498
499
500
501
502
503
504
505
  /* count of mailman lists sizes from all domains */
  function get_size_mailman_count_all() {
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman;");
  }

  /* count of mailman lists for one user */
  function get_size_mailman_count_user($u) {
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman WHERE uid = '{$u}'");
  }

506
507
  /* get list of mailman list and size for one user */
  function get_size_mailman_details_user($u) {
Axel ROGER's avatar
Axel ROGER committed
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
  }

domi's avatar
   
domi committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
  /* sum of databases sizes from all users */
  function get_size_db_sum_all() {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db;");
  }

  /* sum of databases sizes for one user */
  function get_size_db_sum_user($u) {
    return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
  }

  /* count of databases from all users */
  function get_size_db_count_all() {
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db;");
  }

526
  /* count of databases for one user */
domi's avatar
   
domi committed
527
528
529
530
  function get_size_db_count_user($u) {
    return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
  }

531
532
533
534
535
  /* get list of databases name and size for one user */
  function get_size_db_details_user($u) {
    return $this->_get_size_and_record_sql("SELECT db,size FROM size_db WHERE db='{$u}' OR db LIKE '{$u}\_%';");
  }

536
537
538
539
540
541
542
543
544
545
  /* Return appropriate value and unit of a size given in Bytes (e.g. 1024 Bytes -> return 1 KB) */
  function get_size_unit($size) {
    $units=array(1073741824=>_("GB"), 1048576=>_("MB"), 1024=>_("KB"), 0=>_("B"));
    foreach($units as $value=>$unit){
      if($size>=$value){
        $size=str_pad(round($size/($value ? $value : 1), 1), 5, ' ', STR_PAD_LEFT);
        return array('size'=>$size, 'unit'=>$unit);
      }
    }
  }
domi's avatar
   
domi committed
546

547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
  // Affiche des barres de progression
  // color_type :
  //   0 = Pas de changement de couleur
  //   1 = Progression du vert vers le rouge en fonction du porcentage
  //   2 = Progression du rouge vers le vert en fonction du porcentage
  function quota_displaybar($usage, $color_type=1) {
    if ($color_type == 1) {
      $csscolor = " background-color:".PercentToColor($usage);
    } elseif ($color_type == 2) {
      $csscolor = " background-color:".PercentToColor(100-$usage);
    } else {
      $csscolor = "";
    }

    
562
    echo '<div class="progress-bar">';
563
564
    echo '<div class="barre" style="width:'.$usage.'%;'.$csscolor.'" ></div>';
    echo '<div class="txt">'.$usage.'%</div>';
565
566
567
568
    echo '</div>';
  }


domi's avatar
   
domi committed
569
  /* ==== Hook functions ==== */
570

571
  /* ----------------------------------------------------------------- */
572
573
  /** Hook function call when a user is deleted
   * AlternC's standard function called when a user is deleted
574
   * globals $cuid is the appropriate user
575
   */
576
  function hook_admin_del_member() {
577
578
579
    $this->delquotas();
  }

580

581
  /* ----------------------------------------------------------------- */
582
583
  /** Hook function called when a user is created
   * This function initialize the user's quotas.
584
   * globals $cuid is the appropriate user
585
   */
586
  function hook_admin_add_member() {
Alan Garcia's avatar
Alan Garcia committed
587
588
    global $err;
    $err->log("quota","hook_admin_add_member");
589
    $this->addquotas();
Alan Garcia's avatar
Alan Garcia committed
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
601
    global $db,$err;
    $err->log("quota","export");
602
    $str="  <quota>";
603
604
605

    $q=$this->getquota();
    foreach ($q as $k=>$v) {
606
607
608
609
      $str.=" <$k>\n";
      $str.="   <used>".($v["u"])."</used>\n";
      $str.="   <total>".($v["t"])."</total>\n";
      $str.=" </$k>\n";
610
    }
611
    $str.="</quota>\n";
612
613
614
615
616
617
    return $str;
  }


} /* Class m_quota */