aboutsummaryrefslogtreecommitdiffstats
path: root/HTPasswdSync.module
blob: 3ac1a77a1d257b78ac5b34bff03dd2bee2135f52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
115
116
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
<?php

/**
 * Returns full file path of the htpasswd file
 * @return string
 */
function _htpasswdsync_passfilename() {
    return variable_get('htpasswdsync_htpasswd', '/etc/httpd/htpasswd');
}


/**
 * Returns full file path of the htgroup file
 * @return string
 */
function _htpasswdsync_grpfilename() {
    return variable_get('htpasswdsync_htgroup', '');
}


/**
 * Returns the age of the htpasswd/group file or "unknown"
 * @param string $file
 * @return string
 */
function _htpasswdsync_fileage($file) {
    if(is_file($file)) {
        return t('last update !time ago', array(
            '!time' => format_interval(time()-filemtime($file))));
    } else {
        return t('unknown');
    }
}


/**
 * Returns an array containing the role ids of the roles to write into
 * the htgroup file. (selected in the admin page)
 * @return array
 */
function _htpasswdsync_roles() {
    return variable_get('htpasswdsync_roles', array());
}


/**
 * Return an array containing the available hashes
 * @return array
 */
function _htpasswdsync_hashes() {
    return array ('crypt' => 'crypt', 'SHA-1' => 'SHA-1', 'SHA-256-crypt' => 'SHA-256-crypt', 'SHA-512-crypt' => 'SHA-512-crypt');
}


/**
 * Returns the selected hash algorithm specified by _htpasswdsync_hashes().
 * @return string
 */
function _htpasswdsync_hash() {
    return variable_get('htpasswdsync_hash', 'SHA-512-crypt');
}


/**
 * Returns if the passwords shall be prefixed with curly braces indicating
 * the hashing algorithm used
 * @return bool
 */
function _htpasswdsync_prefix() {
    return variable_get('htpasswdsync_prefix', true);
}


/**
 * Returns if the htpasswd file shall be overwritten by drupal of not
 * overwritting will erase all manual entered users. Manual make the htpasswd
 * grow and contain renamed users. it will do the same for the htgroup
 * @return bool
 */
function _htpasswdsync_overwrite() {
    return variable_get('htpasswdsync_overwrite', true);
}


/**
 * Returns if spaces in group and user names shall be removed
 * @return bool
 */
function _htpasswdsync_names_without_whitespace() {
    return variable_get('htpasswdsync_names_without_whitespace', true);
}


/**
 * Returns if groups and user names shall be exported lowercase
 * @return bool
 */
function _htpasswdsync_names_lowercase() {
    return variable_get('htpasswdsync_names_lowercase', true);
}


/**
 * Returns the domain of which email addresses shall be exported as well
 * @return string
 */
function _htpasswdsync_email_domain() {
    return variable_get('htpasswdsync_export_email_domain', '');
}


/**
 * Returns a random (safe) string for salts
 * Adopted from phpass by SolarDesigner and TimWolla on Stack Codereview
 * @param int $count
 * @return string
 */
function get_salt($count) {
     $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/\\][{}\'";?.>,<!@#%^&*()-_=+|';
     $randString = "";
     for ($i = 0; $i < $count; $i++) {
         $randString .= $charset[mt_rand(0, strlen($charset) - 1)];
     }
     return $randString;
}


/**
 * Sanitizes the user name to be htpasswd conform. Removes ":" character as it
 * may cause trouble in the files. All non-word characters are removed to
 * be htpasswd/htgroup compliant.
 * @param string $name
 * @return string
 */
function _htpasswdsync_sanitize_name($name) {
    $name = trim(preg_replace('/[^\w\s@\.]/i', '', $name), " \t\n\r");
    if(_htpasswdsync_names_without_whitespace()) $name = str_replace(' ','', $name);
    if(_htpasswdsync_names_lowercase()) $name = strtolower($name);
    return $name;
}


/**
 * Returns the password hashed according to users preferences
 * @param string $password
 * @return string
 */
function _htpasswdsync_crypt($password) {
    $hashes = _htpasswdsync_hashes();
    $prefix = '';
    switch ($hashes[_htpasswdsync_hash()]) {
        case 'crypt':
            return crypt($password, chr(rand(65, 122)) . chr(rand(65, 122)));
            break;
        case 'SHA-1':
            if(_htpasswdsync_prefix()) $prefix = '{SHA}';
            return $prefix . base64_encode(sha1($password, TRUE));
            break;
        case 'SHA-256-crypt':
            if(_htpasswdsync_prefix()) $prefix = '{SHA256-crypt}';
            $salt = get_salt(16);
            return $prefix . crypt($password, '$5$' . $salt . '$');
            break;
        case 'SHA-512-crypt':
            if(_htpasswdsync_prefix()) $prefix = '{SHA512-crypt}';
            $salt = get_salt(16);
            return $prefix . crypt($password, '$6$' . $salt . '$');
            break;

        default:
            return _htpasswdsync_hash();
    }
}


/**
 * Checks if a file (given by path) exitsts and is writable. Returns false
 * on success, an error message on error.
 * @param string $path
 * @return mixed
 */
function _htpasswdsync_check_file($path) {
    if(is_file($path) && is_writable($path) && is_readable($path)) {
        return false;
    } else if(!is_file($path)) {
        if(is_dir($path)) {
            return t("File '!file' that you specified is an existing directory. Please check your path setting.", array('!file' => $path));
        } else if(!is_dir(dirname($path))) {
            return t("File '!file' does not exists and the parent directory does not exist neither. Please check the path you entered or create the file manually.", array('!file' => $path));
        } else if(!is_writable(dirname($path))) {
            return t("File '!file' does not exists and the parent directory is not writable. Please create the file manually.", array('!file' => $path));
        } else if(file_put_contents($path, '') === false || !is_file($path) || !is_writable($path) || !is_readable($path)) {
            return t("File '!file' does not exists, and it could no be created properly. Please create the file manually.", array('!file' => $path));
        }
        return false;
    } else if(!is_readable($path)) {
        return t("File '!file' exists but is not readable for the server. Use chmod command to change this.", array('!file' => $path));
    } else if(!is_writable($path)) {
        return t("File '!file' exists but is not writable for the server. Use chmod command to change this.", array('!file' => $path));
    } else {
        return t("File '!file' (dead branch check): Please inform the maintainer that there is a bug in function _htpasswdsync_check_file().", array('!file' => $path));
    }
}


/**
 * Read htfile in an assoc. array (key=user, value=password hash)
 * @param string $file
 * @return array
 */
function _htpasswdsync_read_htfile($file) {
    $content = file_get_contents($file);
    if($content === false) {
        watchdog('HtPasswdSync', "Failed to read $file", WATCHDOG_ERROR);
    } else {
        $data = array();
        $content = explode("\n", $content);
        foreach($content as $line) {
            $line = trim($line);
            if(!empty($line)) {
                $line = explode(':', $line, 2);
                if(count($line) == 2) {
                    $line[0] = trim($line[0]);
                    $line[1] = trim($line[1]);
                    if(strlen($line[0]) > 0 && strlen($line[1]) > 0) {
                        $data[$line[0]] = $line[1];
                    }
                }
            }
        }
    }
    return $data;
}


/**
 * Write an htfile
 * @param array &$data
 * @param string $file
 * @return void
 */
function _htpasswdsync_write_htfile(&$data, $file) {
    $content = array();
    foreach($data as $u => $p) {
        if(strlen($u) > 0 && strlen($p) > 0) {
            $content[] = "$u:$p";
        }
    }
    if(@file_put_contents($file, implode("\n", $content) . "\n") === false) {
        watchdog('HtPasswdSync', "Failed to write $file", WATCHDOG_ERROR);
    }
}


/**
 * Generate the htgroup content for each role configured (htpasswdsync_roles array),
 * list users and update the htgroup accordingly.
 * @return
 */
function _htpasswdsync_updategroup() {
    $file = _htpasswdsync_grpfilename();
    $groups = array();

    if($file == "") {
        return;
    }

    $mail_domain = _htpasswdsync_email_domain();

    if(! _htpasswdsync_overwrite()) {
        $groups = _htpasswdsync_read_htfile($file);
    }

    foreach(_htpasswdsync_roles() as $rid) {
        $result = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchCol();
        $role = _htpasswdsync_sanitize_name(reset($result));
        if(!empty($role)) {
            $users = db_query('SELECT u.name, u.mail FROM {users} AS u, {users_roles} AS ur WHERE ur.rid = :rid AND ur.uid = u.uid AND status = 1', array(':rid' => $rid));
            $groups[$role] = array();
            $group = &$groups[$role];
            foreach($users as $user) {
                $group[] = _htpasswdsync_sanitize_name($user->name);
                if($mail_domain != '') {
                    $user->mail = strtolower($user->mail);
                    if(strpos($user->mail, $mail_domain) !== false) {
                        $user->mail = reset(explode('@', $user->mail, 2));
                        $group[] = _htpasswdsync_sanitize_name($user->mail);
                    }
                }
            }
            $group = implode(' ', $group);
        }
    }
    _htpasswdsync_write_htfile($groups, $file);
}


/**
 * Removes a group from a file given either by RID or by role name.
 * @param mixed $role
 */
function _htpasswdsync_remove_role($role) {
    if(is_numeric($role)) {
        $role = reset(db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $role))->fetchCol());
    }
    $role = _htpasswdsync_sanitize_name($role);
    $file = _htpasswdsync_grpfilename();
    $groups = _htpasswdsync_read_htfile($file);
    if(isset($groups[$role])) {
        unset($groups[$role]);
        _htpasswdsync_write_htfile($groups, $file);
    }
}


/**
 * Generate the htpasswd content from the database update the htpasswd file
 * from the table htpasswdsync_passwd
 * @return void
 */
 function _htpasswdsync_updatepasswd($removeDrupalUsers=false) {
    $file = _htpasswdsync_passfilename();
    $passwords = array();

    if($file == "") {
        return;
    }

    $overwrite = _htpasswdsync_overwrite();
    $mail_domain = _htpasswdsync_email_domain();

    if(!$overwrite) {
        $passwords = _htpasswdsync_read_htfile($file);
    }

    $res = db_query('SELECT A.username, A.passwd, B.mail FROM {htpasswdsync_htpasswd} AS A, {users} AS B WHERE name=username and status = 1');
    foreach($res as $r) {
        if(!$overwrite) {
            if(isset($passwords[str_replace(' ','', $r->username)])) unset($passwords[str_replace(' ','', $r->username)]);
            if(isset($passwords[str_replace(' ','', strtolower($r->username))])) unset($passwords[str_replace(' ','', strtolower($r->username))]);
            if(isset($passwords[strtolower($r->username)])) unset($passwords[strtolower($r->username)]);
        }
        if(!$removeDrupalUsers) {
            if($r->passwd == "****DELETED" || $r->passwd == '') {
                if(isset($passwords[$r->username])) unset($passwords[$r->username]);
                if(isset($passwords[$r->mail])) unset($passwords[$r->mail]);
            } else {
                $passwords[_htpasswdsync_sanitize_name($r->username)] = $r->passwd;
                if($mail_domain != '') {
                    $r->mail = strtolower($r->mail);
                    if(strpos($r->mail, $mail_domain) !== false) {
                        $r->mail = reset(explode('@', $r->mail, 2));
                        $passwords[_htpasswdsync_sanitize_name($r->mail)] = $r->passwd;
                    }

                }
            }
        }
    }
    _htpasswdsync_write_htfile($passwords, $file);
 }


/**
 * Update htpassword table with the new password of the user
 * @param object $edit
 * @return void
 */
function _htpasswdsync_update($edit) {
    if(isset($edit->pass) && $edit->pass != '' && isset($edit->name) && strlen(trim($edit->name)) > 0) {
        $user = $edit->name;
        $pass = _htpasswdsync_crypt($edit->pass);
        $passwds[$user] = $pass;
        if(isset($edit->uid) && $edit->uid > 0) {
            $ref_user = user_load($edit->uid);
            if($ref_user->name != $user) {
                db_query("DELETE FROM {htpasswdsync_htpasswd} WHERE username = :username", array(':username' => $ref_user->name));
            }
        }
        db_query("DELETE FROM {htpasswdsync_htpasswd} WHERE username = :user", array(':user' => $user));
        db_query("INSERT INTO {htpasswdsync_htpasswd} (username, passwd) VALUES(:user, :pass)", array(':user' => $user, ':pass' => $pass));
        _htpasswdsync_commit_to_htpasswd();
    }
}


/**
 * Update htpassword file with the new password of the user
 * @return void
 */
function _htpasswdsync_commit_to_htpasswd() {
    _htpasswdsync_updatepasswd();
    _htpasswdsync_updategroup();
}


/**
 * Remove the one user for the htpassword file
 * @param string $username
 * @return void
 */
function _htpasswdsync_delete_user($username) {
    db_query("DELETE FROM {htpasswdsync_htpasswd} WHERE username = :username", array(':username' => $username));
    db_query("INSERT INTO {htpasswdsync_htpasswd} (username, passwd) VALUES(:username, :passwd)", array(':username' => $username, ':passwd' => "****DELETED") );
}


/**
 * Remove the user for the htpassword file
 * @param object $account
 * @return void
 */
function _htpasswdsync_delete($account) {
    _htpasswdsync_delete_user($account->name);
    _htpasswdsync_commit_to_htpasswd();
}


/**
 * User cancel hook
 * @param array $edit
 * @param object $account
 * @param string $method
 * @return void
 */
function htpasswdsync_user_cancel($edit, $account, $method) {
    _htpasswdsync_delete($account);
}


/**
 * User delete hook
 * @param object $account
 * @return void
 */
function htpasswdsync_user_delete($account) {
    _htpasswdsync_delete($account);
}


/**
 * User insert/edit hook. Used instead of htpasswdsync_user_insert() and
 * htpasswdsync_user_update() because at these states the password is already
 * hashed.
 * @param string $entity_type
 * @param object $entity
 * @param array $form
 * @param array $form_state
 * @return void
 */
function htpasswdsync_field_attach_submit($entity_type, $entity, $form, &$form_state) {
    if($entity_type != 'user') return;
    if(!empty($entity->name) && !empty($entity->pass)) {
        $result = db_query('SELECT pass FROM {users} WHERE uid=:uid', array(':uid' => $entity->uid))->fetchCol();
        $r = reset($result);
        if($r != $entity->pass) {
            _htpasswdsync_update($entity);
        }
    }
}

/**
 * Run the _htpasswdsync_update function when a user is create;
 */
function htpasswdsync_user_insert(){
  _htpasswdsync_updatepasswd();
}

/**
 * Role delete hook
 * @param object $role
 * @return void
 */
function htpasswdsync_user_role_update($role) {
    _htpasswdsync_updategroup();
}


/**
 * Role delete hook
 * @param object $role
 * @return void
 */
function htpasswdsync_user_role_delete($role) {
    _htpasswdsync_updategroup();
}


/**
 * Returns help and module information
 * @param string $path which path of the site we're displaying help
 * @param array $arg Holds the current path as would be returned from arg() function
 * @return string
 */
function htpasswdsync_help($path, $arg) {
    if($path != 'admin/help#htpasswdsync') return '';
    return '<pre>' . htmlspecialchars(@file_get_contents(dirname(__FILE__) . '/README.txt'), null, 'UTF-8') . '</pre>';
}


/**
* Returns the required permissions for the htpasswdsync module
* @return array
*/
function htpasswdsync_permission() {
    return array(
        'administer htpasswdsync' => array(
            'title' => t('Administer htpasswd synchronization'),
            'restrict access' => true
        )
    );
}


/**
 * Administration menu entry
 * @return array
 */
function htpasswdsync_menu() {
    $items = array();
    $items['admin/config/people/htpasswdsync'] = array(
        'title' => 'Htpasswd file synchronization',
        'description' => 'Preferences for the HTPasswd Sync module',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('htpasswdsync_admin_form'),
        'access arguments' => array('administer htpasswdsync'),
    );
    return $items;
}


/**
 * Returns the configuration form structure
 * @return array
 */
function htpasswdsync_admin_form() {
    // A workaround to update the files directly after saving the config form,
    // Because the form is displayed directly after saving.
    if(variable_get('htpasswdsync_flag_needs_rebuild', false)) {
        variable_del('htpasswdsync_flag_needs_rebuild');
        _htpasswdsync_updatepasswd();
        _htpasswdsync_updategroup();
    }

    $form['htpasswdsync_htpasswd'] = array(
        '#type' => 'textfield',
        '#title' => t('htpasswd file'),
        '#default_value' => _htpasswdsync_passfilename(),
        '#size' => 100,
        '#maxlength' => 200,
        '#description' => t("The full path to the !file file (e.g. !eg_file).", array('!file' => 'htpasswd', '!eg_file' => '/etc/httpd/htpasswd')),
        '#required' => true,
    );
    $form['htpasswdsync_htgroup'] = array(
        '#type' => 'textfield',
        '#title' => t('htgroup file'),
        '#default_value' => _htpasswdsync_grpfilename(),
        '#size' => 100,
        '#maxlength' => 200,
        '#description' => t("The full path to the !file file (e.g. /etc/httpd/htgroup). Leave blank if you don't need a group file. If you enter a group file here, then you must also define a htpasswd file above.", array('!file' => 'htgroup')),
        '#required' => false,
    );
    $form['htpasswdsync_hash'] = array(
        '#type' => 'radios',
        '#title' => t('password hashing algorithm'),
        '#description' => t("How shall the password be hashed crypt (old unix), SHA1 (insecure, not salted!), SHA-256-crypt (safe) or SHA-512-crypt (best)"),
        '#options' => _htpasswdsync_hashes(),
        '#default_value' => _htpasswdsync_hash(),
    );
    $form['htpasswdsync_prefix'] = array(
        '#type' => 'checkbox',
        '#title' => t('Add a curly braces prefix like {SHA512-crypt} to the password field (e.g. for Dovecot)'),
        '#description' => t("If yes, htpasswdsync will prefix all newly save passwords with {algorithm} except old unix-crypt which never gets prefixed for compatibility reasons."),
        '#default_value' => _htpasswdsync_prefix(),
    );
    $form['htpasswdsync_roles'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Roles to be exported into the htgroup file'),
        '#description' => t("Only users of these roles will be syncronized into the htpasswd/htgroup file. If none is specified, no user will be in the file (not 'default all')."),
        '#default_value' => _htpasswdsync_roles(),
        '#options' => user_roles(true),
    );
    $form['htpasswdsync_overwrite'] = array(
        '#type' => 'checkbox',
        '#title' => t('htpasswd file is only managed by this module'),
        '#description' => t("If yes, manually added users in the user file will be removed (simply overwrites the files). If no, only the users stored in the database will be changed/added/deleted (Files will be analyzed and users not existing in the database will be left unchanged)."),
        '#default_value' => _htpasswdsync_overwrite(),
    );
    $form['htpasswdsync_names_lowercase'] = array(
        '#type' => 'checkbox',
        '#title' => t('Export user names and group names lowercase'),
        '#description' => t("If yes, htpasswdsync will export the lowercase user names (e.g. 'User' will be exported as 'user'). Groups will always be exported lowercase (as the user does not need to enter a group, so this makes it easier to design the .htaccess files). Caution: this option may increase the file size of the htuser file."),
        '#default_value' => _htpasswdsync_names_lowercase(),
    );
    $form['htpasswdsync_names_without_whitespace'] = array(
        '#type' => 'checkbox',
        '#title' => t('Remove whitespaces in user names and groups'),
        '#description' => t("If yes, htpasswdsync will remove all whitespaces in user names and groups (e.g. 'User 1' will be exported as 'User1'). Caution: this increases the file size of the htuser file. If you use groups, then you must check this setting because whitespaces are used as separators in the group file. This setting goes along with the checkbox above."),
        '#default_value' => _htpasswdsync_names_without_whitespace(),
    );
    $form['htpasswdsync_export_email_domain'] = array(
        '#type' => 'textfield',
        '#title' => t('Additional user email domain'),
        '#default_value' => _htpasswdsync_email_domain(),
        '#size' => 100,
        '#maxlength' => 200,
        '#description' => t("Enter a domain here if you want that email account names shall be exported into the htpasswd file as well. E.g., if you enter 'example.org', then the email 'user1@example.org' would be exported as 'user1' into the htpasswd file. However, it should be more interesting for your own domain."),
        '#required' => false,
    );

    // Small description ...
    $notewhitespaces = _htpasswdsync_names_lowercase() ? " Enter your login name without whitespaces and special characters." : "";

    $txt = t('This is how a simple .htaccess file could look like:')
            . "<pre>\t[...]\n"
            . "\tAuthType Basic\n"
            . "\tAuthName \"Protected members area.$notewhitespaces\"\n"
            ;

    if(_htpasswdsync_passfilename() != '') {
        $txt .= "\tAuthUserFile " . _htpasswdsync_passfilename() . "\n";
        if(_htpasswdsync_grpfilename() != '') {
            $txt .= "\tAuthGroupFile " . _htpasswdsync_grpfilename() . "\n";
        }

        $txt .=   "\trequire valid-user\n"
                . "\t#require group administrator\n"
                . "\n[OR]\n"
                . "\t[...]</pre></p>";
    }

    $form['htaccess_file_now_looks_like'] = array(
        '#markup' => $txt
    );
    return system_settings_form($form);
}


/**
 * Form validation callback. Checks if htpasswd/htgroup file are writable
 * @param array $form
 * @param array& $form_state
 * @return void
 */
function htpasswdsync_admin_form_validate($form, &$form_state) {
    $form_state['values']['htpasswdsync_htpasswd'] = trim($form_state['values']['htpasswdsync_htpasswd']);
    $form_state['values']['htpasswdsync_htgroup'] = trim($form_state['values']['htpasswdsync_htgroup']);
    $error = false;

    if(empty($form_state['values']['htpasswdsync_htpasswd']) && empty($form_state['values']['htpasswdsync_htgroup'])) {
        form_set_error('htpasswdsync_htpasswd', 'You should at least specify the htpasswd file.');
        $error = true;
    } else if(!empty($form_state['values']['htpasswdsync_htgroup']) && empty($form_state['values']['htpasswdsync_htpasswd'])) {
        form_set_error('htpasswdsync_htpasswd', 'The htgroup file makes no sense without the htpasswd file.');
        $error = true;
    } else if($form_state['values']['htpasswdsync_htgroup'] == $form_state['values']['htpasswdsync_htpasswd']) {
        form_set_error('htpasswdsync_htpasswd', 'The htgroup file and the htpasswd file have to be different files.');
        $error = true;
    }

    $file = $form_state['values']['htpasswdsync_htpasswd'];
    if(!empty($file)) {
        if($msg = _htpasswdsync_check_file($file)) {
            form_set_error('htpasswdsync_htpasswd', $msg);
            $error = true;
        }
    }

    $file = $form_state['values']['htpasswdsync_htgroup'];
    if(!empty($file)) {
        if($msg = _htpasswdsync_check_file($file)) {
            form_set_error('htpasswdsync_htgroup', $msg);
            $error = true;
        }
        if(!$form_state['values']['htpasswdsync_names_without_whitespace']) {
            form_set_error('htpasswdsync_htgroup', 'htgroup file access restriction can only work if you remove the whitespaces in user names and groups (see setting below)');
            $error = true;
        }
    }

    // Directly apply changes if no validation errors
    if($error == false) {
        if($form_state['values']['htpasswdsync_htgroup'] == '' && _htpasswdsync_grpfilename() != '') {
            // Group file was unset, so the groups shpuld be all deleted
            foreach(_htpasswdsync_roles() as $role) {
                _htpasswdsync_remove_role($role);
            }
        } else {
            // Check which roles have to be removed
            // A workaround to update the files directly after saving the config form
            variable_set('htpasswdsync_flag_needs_rebuild', true);
            foreach(_htpasswdsync_roles() as $role) {
                if($role > 0 && !in_array($role, $form_state['values']['htpasswdsync_roles'])) {
                    _htpasswdsync_remove_role($role);
                }
            }
        }
    }
}


/**
 * Runtime phase htgroup / htpasswd file check
 * @param string $phase
 * @return array
 */
function htpasswdsync_requirements($phase) {
    if($phase != 'runtime') {
        return array();
    } else {
        $requirements = array();

        if(_htpasswdsync_passfilename() != "") {
            $htpasswd_status_msg = _htpasswdsync_check_file(_htpasswdsync_passfilename());
            $htpasswd_status_val = REQUIREMENT_ERROR;
            if (!$htpasswd_status_msg) {
                $htpasswd_status_msg = t('!file file is writable', array('!file' => 'htpasswd')) .
                     " (" . _htpasswdsync_fileage(_htpasswdsync_passfilename()) . ")";
                $htpasswd_status_val = REQUIREMENT_OK;
            }
        } else {
            $htpasswd_status_msg = 'Not required';
            $htpasswd_status_val = REQUIREMENT_OK;
        }

        if(_htpasswdsync_grpfilename() != "") {
            $htgroup_status_msg = _htpasswdsync_check_file(_htpasswdsync_grpfilename());
            $htgroup_status_val = REQUIREMENT_ERROR;
            if (!$htgroup_status_msg) {
                $htgroup_status_msg = t('!file file is writable', array('!file' => 'htgroup')) .
                     " (" . _htpasswdsync_fileage(_htpasswdsync_grpfilename()) . ")";
                $htgroup_status_val = REQUIREMENT_OK;
            }
        } else {
            $htgroup_status_msg = 'Not required';
            $htgroup_status_val = REQUIREMENT_OK;
        }

        $status = $htpasswd_status_val != REQUIREMENT_OK && $htgroup_status_val != REQUIREMENT_OK;

        $requirements['htpasswdsync_status'] = array(
            'title' =>  t('HTPasswd Sync Status'),
            'value' =>  "htpasswd: " . $htpasswd_status_msg . "<br>" .
                         "htgroup: " . $htgroup_status_msg . "<br>",
            'severity'    => $status,
        );

        if($status != REQUIREMENT_OK) {
            $requirements['htpasswdsync_status']['description'] =
            t('Cannot access files, please <a href="!url">check configuration</a>.',
            array('!url' => url('admin/user/htpasswdsync')));
        }
        return $requirements;
    }
}


/**
 * Cron hook
 * @return void
 */
function htpasswdsync_cron() {
    db_query('DELETE FROM {htpasswdsync_htpasswd} WHERE username NOT IN (SELECT name from {users})');
}
?>

© 2014-2020 Faster IT GmbH | imprint | privacy policy