LDAPMemberSyncTask::log()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Class LDAPMemberSyncTask
4
 *
5
 * A task to sync all users to the site using LDAP.
6
 */
7
class LDAPMemberSyncTask extends BuildTask
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
{
9
    private static $dependencies = [
0 ignored issues
show
Unused Code introduced by
The property $dependencies is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
10
        'ldapService' => '%$LDAPService'
11
    ];
12
13
    /**
14
     * Setting this to true causes the sync to delete any local Member
15
     * records that were previously imported, but no longer existing in LDAP.
16
     *
17
     * @config
18
     * @var bool
19
     */
20
    private static $destructive = false;
0 ignored issues
show
Unused Code introduced by
The property $destructive is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
21
22
    public function getTitle()
23
    {
24
        return _t('LDAPMemberSyncJob.SYNCTITLE', 'Sync all users from Active Directory');
25
    }
26
27
    public function run($request)
28
    {
29
        // get all users from LDAP, but only get the attributes we need.
30
        // this is useful to avoid holding onto too much data in memory
31
        // especially in the case where getUser() would return a lot of users
32
        $users = $this->ldapService->getUsers(array_merge(
0 ignored issues
show
Bug introduced by
The property ldapService does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
33
            ['objectguid', 'samaccountname', 'useraccountcontrol', 'memberof'],
34
            array_keys(Config::inst()->get('Member', 'ldap_field_mappings'))
35
        ));
36
37
        $start = time();
38
39
        $created = 0;
40
        $updated = 0;
41
        $deleted = 0;
42
43 View Code Duplication
        foreach ($users as $data) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
44
            $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
45
46
            if (!($member && $member->exists())) {
47
                // create the initial Member with some internal fields
48
                $member = new Member();
49
                $member->GUID = $data['objectguid'];
50
51
                $this->log(sprintf(
52
                    'Creating new Member (GUID: %s, sAMAccountName: %s)',
53
                    $data['objectguid'],
54
                    $data['samaccountname']
55
                ));
56
                $created++;
57
            } else {
58
                $this->log(sprintf(
59
                    'Updating existing Member "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
60
                    $member->getName(),
61
                    $member->ID,
62
                    $data['objectguid'],
63
                    $data['samaccountname']
64
                ));
65
                $updated++;
66
            }
67
68
            // Sync attributes from LDAP to the Member record. This will also write the Member record.
69
            // this is also responsible for putting the user into mapped groups
70
            try {
71
                $this->ldapService->updateMemberFromLDAP($member, $data);
72
            } catch (Exception $e) {
73
                $this->log($e->getMessage());
74
                continue;
75
            }
76
        }
77
78
        // remove Member records that were previously imported, but no longer exist in the directory
79
        // NOTE: DB::query() here is used for performance and so we don't run out of memory
80
        if ($this->config()->destructive) {
81
            foreach (DB::query('SELECT "ID", "GUID" FROM "Member" WHERE "GUID" IS NOT NULL') as $record) {
82
                $member = Member::get()->byId($record['ID']);
83
84
                if (!isset($users[$record['GUID']])) {
85
                    $this->log(sprintf(
86
                        'Removing Member "%s" (GUID: %s) that no longer exists in LDAP.',
87
                        $member->getName(),
88
                        $member->GUID
89
                    ));
90
91
                    try {
92
                        $member->delete();
93
                    } catch (Exception $e) {
94
                        $this->log($e->getMessage());
95
                        continue;
96
                    }
97
98
                    $deleted++;
99
                }
100
            }
101
        }
102
103
        $end = time() - $start;
104
105
        $this->log(sprintf(
106
            'Done. Created %s records. Updated %s records. Deleted %s records. Duration: %s seconds',
107
            $created,
108
            $updated,
109
            $deleted,
110
            round($end, 0)
111
        ));
112
    }
113
114
    protected function log($message)
115
    {
116
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
117
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
118
    }
119
}
120