summaryrefslogtreecommitdiffstats
path: root/modules-available/locations/inc/autolocation.inc.php
blob: 82c6125122f399867c6228e1e25c7d72d00a376a (plain) (blame)
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
<?php

class AutoLocation
{

	/**
	 * Rebuild the assigned subnetlocationid for clients that currently map to
	 * the given locationids (if given), or all clients, if locationid is false
	 *
	 * @param int[]|false $locations Locations to rebuild, or false for everything
	 */
	public static function rebuildAll($locations = false)
	{
		if (Module::get('statistics') === false)
			return; // Nothing to do
		if ($locations === false) {
			// All
			$res = Database::simpleQuery("SELECT machineuuid, clientip FROM machine");
		} else {
			$res = Database::simpleQuery("SELECT machineuuid, clientip FROM machine
					WHERE fixedlocationid IN(:lid) OR subnetlocationid IN(:lid)", ['lid' => $locations]);
		}
		$updates = array();
		$nulls = array();
		while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
			$loc = Location::mapIpToLocation($row['clientip']);
			if ($loc === false) {
				$nulls[] = $row['machineuuid'];
			} else {
				if (!isset($updates[$loc])) {
					$updates[$loc] = array();
				}
				$updates[$loc][] = $row['machineuuid'];
			}
		}
		if (!empty($nulls)) {
			Database::exec("UPDATE machine SET subnetlocationid = NULL WHERE machineuuid IN (:nulls)",
				['nulls' => $nulls]);
		}
		foreach ($updates as $lid => $machines) {
			if (empty($machines))
				continue;
			Database::exec("UPDATE machine SET subnetlocationid = :lid WHERE machineuuid IN (:machines)",
				['lid' => $lid, 'machines' => $machines]);
		}
		// While we're at it, try to fix invalid entries, having a fixedlocationid but no actual position information
		Database::exec('UPDATE machine SET fixedlocationid = NULL
				WHERE fixedlocationid IS NOT NULL AND Length(position) = 0');
	}

}