class-wpml-site-id.php
2.64 KB
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
<?php
/**
* Class for handling a unique ID of the site.
*
* @author OnTheGo Systems
*/
class WPML_Site_ID {
/**
* The name prefix of the option where the ID is stored.
*/
const SITE_ID_KEY = 'WPML_SITE_ID';
/**
* The default scope.
*/
const SITE_SCOPES_GLOBAL = 'global';
/**
* Memory cache of the IDs.
*
* @var array
*/
private $site_ids = array();
/**
* Read and, if needed, generate the site ID based on the scope.
*
* @param string $scope Defaults to "global".
* Use a different value when the ID is used for specific scopes.
*
* @param bool $create_new Forces the creation of a new ID.
*
* @return string|null The generated/stored ID or null if it wasn't possible to generate/store the value.
*/
public function get_site_id( $scope = self::SITE_SCOPES_GLOBAL, $create_new = false ) {
$generate = ! $this->read_value( $scope ) || $create_new;
if ( $generate && ! $this->generate_site_id( $scope ) ) {
return null;
}
return $this->get_from_cache( $scope );
}
/**
* Geenrates the ID.
*
* @param string $scope The scope of the ID.
*
* @return bool
*/
private function generate_site_id( $scope ) {
$site_url = get_site_url();
$site_uuid = uuid_v5( $site_url, wp_generate_uuid4() );
$time_uuid = uuid_v5( time(), wp_generate_uuid4() );
return $this->write_value( uuid_v5( $site_uuid, $time_uuid ), $scope );
}
/**
* Read the value from cache, if present, or from the DB.
*
* @param string $scope The scope of the ID.
*
* @return string
*/
private function read_value( $scope ) {
if ( ! $this->get_from_cache( $scope ) ) {
$this->site_ids[ $scope ] = get_option( $this->get_option_key( $scope ), null );
}
return $this->site_ids[ $scope ];
}
/**
* Writes the value in DB and cache.
*
* @param string $value The value to write.
* @param string $scope The scope of the ID.
*
* @return bool
*/
private function write_value( $value, $scope ) {
if ( update_option( $this->get_option_key( $scope ), $value, false ) ) {
$this->site_ids[ $scope ] = $value;
return true;
}
return false;
}
/**
* Gets the options key name based on the scope.
*
* @param string $scope The scope of the ID.
*
* @return string
*/
private function get_option_key( $scope ) {
return self::SITE_ID_KEY . ':' . $scope;
}
/**
* Gets the value from the memory cache.
*
* @param string $scope The scope of the ID.
*
* @return mixed|null
*/
private function get_from_cache( $scope ) {
if ( array_key_exists( $scope, $this->site_ids ) && $this->site_ids[ $scope ] ) {
return $this->site_ids[ $scope ];
}
return null;
}
}