WP Security Audit Log - Version 2.2

Version Description

(2015-11-10) = * New Features * Aded the revision link in content change security alerts allowing you to see the actual content changes that took place on posts, pages and custom post types. Learn More

  • Bug Fixes
    • Fixed an issue where user was allowed to disable all columns in Audit Log Viewer Support ticket. Fix recommendation by Bates College.
Download this release

Release Info

Developer WPWhiteSecurity
Plugin Icon 128x128 WP Security Audit Log
Version 2.2
Comparing to
See all releases

Code changes from version 2.1.1 to 2.2

classes/AuditLogListView.php CHANGED
@@ -144,6 +144,9 @@ class WSAL_AuditLogListView extends WP_List_Table {
144
  case 'source_ip':
145
  $cols['scip'] = __('Source IP', 'wp-security-audit-log');
146
  break;
 
 
 
147
  case 'message':
148
  $cols['mesg'] = __('Message', 'wp-security-audit-log');
149
  break;
@@ -271,6 +274,14 @@ class WSAL_AuditLogListView extends WP_List_Table {
271
  } else {
272
  return "";
273
  }
 
 
 
 
 
 
 
 
274
  case in_array($name, array('%MetaValue%', '%MetaValueOld%', '%MetaValueNew%')):
275
  return '<strong>' . (
276
  strlen($value) > 50 ? (esc_html(substr($value, 0, 50)) . '&hellip;') : esc_html($value)
144
  case 'source_ip':
145
  $cols['scip'] = __('Source IP', 'wp-security-audit-log');
146
  break;
147
+ case 'site':
148
+ $cols['site'] = __('Site', 'wp-security-audit-log');
149
+ break;
150
  case 'message':
151
  $cols['mesg'] = __('Message', 'wp-security-audit-log');
152
  break;
274
  } else {
275
  return "";
276
  }
277
+
278
+ case $name == '%RevisionLink%':
279
+ if (!empty($value) && $value != 'NULL') {
280
+ return ' Click <a target="_blank" href="'.$value.'">here</a> to see the content changes.';
281
+ } else {
282
+ return "";
283
+ }
284
+
285
  case in_array($name, array('%MetaValue%', '%MetaValueOld%', '%MetaValueNew%')):
286
  return '<strong>' . (
287
  strlen($value) > 50 ? (esc_html(substr($value, 0, 50)) . '&hellip;') : esc_html($value)
classes/Connector/AbstractConnector.php CHANGED
@@ -1,36 +1,36 @@
1
- <?php
2
- require_once('ConnectorInterface.php');
3
-
4
- abstract class WSAL_Connector_AbstractConnector
5
- {
6
- protected $connection = null;
7
- protected $adaptersBasePath = null;
8
- protected $adaptersDirName = null;
9
-
10
- public function __construct($adaptersDirName = null)
11
- {
12
- $this->adaptersBasePath = __DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'Models'. DIRECTORY_SEPARATOR .'Adapters'. DIRECTORY_SEPARATOR;
13
-
14
- require_once($this->adaptersBasePath . 'ActiveRecordInterface.php');
15
- require_once($this->adaptersBasePath . 'MetaInterface.php');
16
- require_once($this->adaptersBasePath . 'OccurrenceInterface.php');
17
- require_once($this->adaptersBasePath . 'QueryInterface.php');
18
-
19
- if (!empty($adaptersDirName)) {
20
- $this->adaptersDirName = $adaptersDirName;
21
- require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'ActiveRecordAdapter.php');
22
- require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'MetaAdapter.php');
23
- require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'OccurrenceAdapter.php');
24
- require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'QueryAdapter.php');
25
- }
26
- }
27
-
28
- public function getAdaptersDirectory()
29
- {
30
- if (!empty($this->adaptersBasePath) && !empty($this->adaptersDirName)) {
31
- return $this->adaptersBasePath . $this->adaptersDirName;
32
- } else {
33
- return false;
34
- }
35
- }
36
- }
1
+ <?php
2
+ require_once('ConnectorInterface.php');
3
+
4
+ abstract class WSAL_Connector_AbstractConnector
5
+ {
6
+ protected $connection = null;
7
+ protected $adaptersBasePath = null;
8
+ protected $adaptersDirName = null;
9
+
10
+ public function __construct($adaptersDirName = null)
11
+ {
12
+ $this->adaptersBasePath = __DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'Models'. DIRECTORY_SEPARATOR .'Adapters'. DIRECTORY_SEPARATOR;
13
+
14
+ require_once($this->adaptersBasePath . 'ActiveRecordInterface.php');
15
+ require_once($this->adaptersBasePath . 'MetaInterface.php');
16
+ require_once($this->adaptersBasePath . 'OccurrenceInterface.php');
17
+ require_once($this->adaptersBasePath . 'QueryInterface.php');
18
+
19
+ if (!empty($adaptersDirName)) {
20
+ $this->adaptersDirName = $adaptersDirName;
21
+ require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'ActiveRecordAdapter.php');
22
+ require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'MetaAdapter.php');
23
+ require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'OccurrenceAdapter.php');
24
+ require_once($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . 'QueryAdapter.php');
25
+ }
26
+ }
27
+
28
+ public function getAdaptersDirectory()
29
+ {
30
+ if (!empty($this->adaptersBasePath) && !empty($this->adaptersDirName)) {
31
+ return $this->adaptersBasePath . $this->adaptersDirName;
32
+ } else {
33
+ return false;
34
+ }
35
+ }
36
+ }
classes/Connector/ConnectorFactory.php CHANGED
@@ -1,87 +1,87 @@
1
- <?php
2
- require_once(__DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'Settings.php');
3
- require_once('MySQLDBConnector.php');
4
-
5
- abstract class WSAL_Connector_ConnectorFactory
6
- {
7
- public static $connector;
8
- public static $defaultConnector;
9
- public static $adapter;
10
-
11
- /**
12
- * Returns the a default WPDB connector for saving options
13
- */
14
- public static function GetDefaultConnector()
15
- {
16
- return new WSAL_Connector_MySQLDB();
17
- }
18
-
19
- /**
20
- * Returns a connector singleton
21
- * @return WSAL_Connector_ConnectorInterface
22
- */
23
- public static function GetConnector($config = null)
24
- {
25
- if (!empty($config)) {
26
- $connectionConfig = $config;
27
- } else {
28
- $connectionConfig = self::GetConfig();
29
- }
30
-
31
- //TO DO: Load connection config
32
- if (self::$connector == null || !empty($config)) {
33
- switch (strtolower($connectionConfig['type'])) {
34
- //TO DO: Add other connectors
35
- case 'mysql':
36
- default:
37
- //use config
38
- self::$connector = new WSAL_Connector_MySQLDB($connectionConfig);
39
- }
40
- }
41
- return self::$connector;
42
- }
43
-
44
- public static function GetConfig()
45
- {
46
- $conf = new WSAL_Settings(new WpSecurityAuditLog());
47
- $type = $conf->GetAdapterConfig('adapter-type');
48
- if (empty($type)) {
49
- return null;
50
- } else {
51
- return array(
52
- 'type' => $conf->GetAdapterConfig('adapter-type'),
53
- 'user' => $conf->GetAdapterConfig('adapter-user'),
54
- 'password' => $conf->GetAdapterConfig('adapter-password'),
55
- 'name' => $conf->GetAdapterConfig('adapter-name'),
56
- 'hostname' => $conf->GetAdapterConfig('adapter-hostname'),
57
- 'base_prefix' => $conf->GetAdapterConfig('adapter-base-prefix')
58
- );
59
- }
60
- }
61
-
62
- public static function CheckConfig($type, $user, $password, $name, $hostname, $base_prefix)
63
- {
64
- $result = false;
65
- $config = self::GetConfigArray($type, $user, $password, $name, $hostname, $base_prefix);
66
- switch (strtolower($type)) {
67
- //TO DO: Add other connectors
68
- case 'mysql':
69
- default:
70
- $test = new WSAL_Connector_MySQLDB($config);
71
- $result = $test->TestConnection();
72
- }
73
- return $result;
74
- }
75
-
76
- public static function GetConfigArray($type, $user, $password, $name, $hostname, $base_prefix)
77
- {
78
- return array(
79
- 'type' => $type,
80
- 'user' => $user,
81
- 'password' => $password,
82
- 'name' => $name,
83
- 'hostname' => $hostname,
84
- 'base_prefix' => $base_prefix
85
- );
86
- }
87
- }
1
+ <?php
2
+ require_once(__DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'Settings.php');
3
+ require_once('MySQLDBConnector.php');
4
+
5
+ abstract class WSAL_Connector_ConnectorFactory
6
+ {
7
+ public static $connector;
8
+ public static $defaultConnector;
9
+ public static $adapter;
10
+
11
+ /**
12
+ * Returns the a default WPDB connector for saving options
13
+ */
14
+ public static function GetDefaultConnector()
15
+ {
16
+ return new WSAL_Connector_MySQLDB();
17
+ }
18
+
19
+ /**
20
+ * Returns a connector singleton
21
+ * @return WSAL_Connector_ConnectorInterface
22
+ */
23
+ public static function GetConnector($config = null)
24
+ {
25
+ if (!empty($config)) {
26
+ $connectionConfig = $config;
27
+ } else {
28
+ $connectionConfig = self::GetConfig();
29
+ }
30
+
31
+ //TO DO: Load connection config
32
+ if (self::$connector == null || !empty($config)) {
33
+ switch (strtolower($connectionConfig['type'])) {
34
+ //TO DO: Add other connectors
35
+ case 'mysql':
36
+ default:
37
+ //use config
38
+ self::$connector = new WSAL_Connector_MySQLDB($connectionConfig);
39
+ }
40
+ }
41
+ return self::$connector;
42
+ }
43
+
44
+ public static function GetConfig()
45
+ {
46
+ $conf = new WSAL_Settings(new WpSecurityAuditLog());
47
+ $type = $conf->GetAdapterConfig('adapter-type');
48
+ if (empty($type)) {
49
+ return null;
50
+ } else {
51
+ return array(
52
+ 'type' => $conf->GetAdapterConfig('adapter-type'),
53
+ 'user' => $conf->GetAdapterConfig('adapter-user'),
54
+ 'password' => $conf->GetAdapterConfig('adapter-password'),
55
+ 'name' => $conf->GetAdapterConfig('adapter-name'),
56
+ 'hostname' => $conf->GetAdapterConfig('adapter-hostname'),
57
+ 'base_prefix' => $conf->GetAdapterConfig('adapter-base-prefix')
58
+ );
59
+ }
60
+ }
61
+
62
+ public static function CheckConfig($type, $user, $password, $name, $hostname, $base_prefix)
63
+ {
64
+ $result = false;
65
+ $config = self::GetConfigArray($type, $user, $password, $name, $hostname, $base_prefix);
66
+ switch (strtolower($type)) {
67
+ //TO DO: Add other connectors
68
+ case 'mysql':
69
+ default:
70
+ $test = new WSAL_Connector_MySQLDB($config);
71
+ $result = $test->TestConnection();
72
+ }
73
+ return $result;
74
+ }
75
+
76
+ public static function GetConfigArray($type, $user, $password, $name, $hostname, $base_prefix)
77
+ {
78
+ return array(
79
+ 'type' => $type,
80
+ 'user' => $user,
81
+ 'password' => $password,
82
+ 'name' => $name,
83
+ 'hostname' => $hostname,
84
+ 'base_prefix' => $base_prefix
85
+ );
86
+ }
87
+ }
classes/Connector/ConnectorInterface.php CHANGED
@@ -1,11 +1,11 @@
1
- <?php
2
-
3
- interface WSAL_Connector_ConnectorInterface
4
- {
5
- public function getAdapter($class_name);
6
- public function getConnection();
7
- public function isInstalled();
8
- public function canMigrate();
9
- public function installAll();
10
- public function uninstallAll();
11
- }
1
+ <?php
2
+
3
+ interface WSAL_Connector_ConnectorInterface
4
+ {
5
+ public function getAdapter($class_name);
6
+ public function getConnection();
7
+ public function isInstalled();
8
+ public function canMigrate();
9
+ public function installAll();
10
+ public function uninstallAll();
11
+ }
classes/Connector/MySQLDBConnector.php CHANGED
@@ -1,257 +1,257 @@
1
- <?php
2
- require_once('ConnectorInterface.php');
3
- require_once('AbstractConnector.php');
4
- require_once('wp-db-custom.php');
5
-
6
- class WSAL_Connector_MySQLDB extends WSAL_Connector_AbstractConnector implements WSAL_Connector_ConnectorInterface
7
- {
8
- protected $connectionConfig = null;
9
-
10
- public function __construct($connectionConfig = null)
11
- {
12
- $this->connectionConfig = $connectionConfig;
13
- parent::__construct("MySQL");
14
- require_once($this->getAdaptersDirectory() . '/OptionAdapter.php');
15
- }
16
-
17
- public function TestConnection()
18
- {
19
- error_reporting(E_ALL ^ E_WARNING);
20
- $connectionConfig = $this->connectionConfig;
21
- $password = $this->decryptString($connectionConfig['password']);
22
- $newWpdb = new wpdbCustom($connectionConfig['user'], $password, $connectionConfig['name'], $connectionConfig['hostname']);
23
- if (!$newWpdb->has_connected) { // Database Error
24
- throw new Exception("Connection failed. Please check your connection details.");
25
- }
26
- }
27
-
28
- /**
29
- * Creates a connection and returns it
30
- * @return Instance of WPDB
31
- */
32
- private function createConnection()
33
- {
34
- if (!empty($this->connectionConfig)) {
35
- //TO DO: Use the provided connection config
36
- $connectionConfig = $this->connectionConfig;
37
- $password = $this->decryptString($connectionConfig['password']);
38
- $newWpdb = new wpdb($connectionConfig['user'], $password, $connectionConfig['name'], $connectionConfig['hostname']);
39
- $newWpdb->set_prefix($connectionConfig['base_prefix']);
40
- return $newWpdb;
41
- } else {
42
- global $wpdb;
43
- return $wpdb;
44
- }
45
- }
46
-
47
- /**
48
- * Returns a wpdb instance
49
- */
50
- public function getConnection()
51
- {
52
- if (!empty($this->connection)) {
53
- return $this->connection;
54
- } else {
55
- $this->connection = $this->createConnection();
56
- return $this->connection;
57
- }
58
- }
59
-
60
- /**
61
- * Gets an adapter for the specified model
62
- */
63
- public function getAdapter($class_name)
64
- {
65
- $objName = $this->getAdapterClassName($class_name);
66
- return new $objName($this->getConnection());
67
- }
68
-
69
- protected function getAdapterClassName($class_name)
70
- {
71
- return 'WSAL_Adapters_MySQL_'.$class_name;
72
- }
73
-
74
- /**
75
- * Checks if the necessary tables are available
76
- */
77
- public function isInstalled()
78
- {
79
- global $wpdb;
80
- $table = $wpdb->base_prefix . 'wsal_occurrences';
81
- return ($wpdb->get_var('SHOW TABLES LIKE "'.$table.'"') == $table);
82
- }
83
-
84
- /**
85
- * Checks if old version tables are available
86
- */
87
- public function canMigrate()
88
- {
89
- $wpdb = $this->getConnection();
90
- $table = $wpdb->base_prefix . 'wordpress_auditlog_events';
91
- return ($wpdb->get_var('SHOW TABLES LIKE "'.$table.'"') == $table);
92
- }
93
-
94
- /**
95
- * Install all DB tables.
96
- */
97
- public function installAll($excludeOptions = false)
98
- {
99
- $plugin = WpSecurityAuditLog::GetInstance();
100
-
101
- foreach (glob($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . '*.php') as $file) {
102
- $filePath = explode(DIRECTORY_SEPARATOR, $file);
103
- $fileName = $filePath[count($filePath) - 1];
104
- $className = $this->getAdapterClassName(str_replace("Adapter.php", "", $fileName));
105
-
106
- $class = new $className($this->getConnection());
107
- if ($excludeOptions && $class instanceof WSAL_Adapters_MySQL_Option) {
108
- continue;
109
- }
110
-
111
- if (is_subclass_of($class, "WSAL_Adapters_MySQL_ActiveRecord")) {
112
- $class->Install();
113
- }
114
- }
115
- }
116
-
117
- /**
118
- * Uninstall all DB tables.
119
- */
120
- public function uninstallAll()
121
- {
122
- $plugin = WpSecurityAuditLog::GetInstance();
123
-
124
- foreach (glob($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . '*.php') as $file) {
125
- $filePath = explode(DIRECTORY_SEPARATOR, $file);
126
- $fileName = $filePath[count($filePath) - 1];
127
- $className = $this->getAdapterClassName(str_replace("Adapter.php", "", $fileName));
128
-
129
- $class = new $className($this->getConnection());
130
- if (is_subclass_of($class, "WSAL_Adapters_MySQL_ActiveRecord")) {
131
- $class->Uninstall();
132
- }
133
- }
134
- }
135
-
136
- public function Migrate()
137
- {
138
- global $wpdb;
139
- $_wpdb = $this->getConnection();
140
-
141
- // Load data Occurrences from WP
142
- $occurrence = new WSAL_Adapters_MySQL_Occurrence($wpdb);
143
- if (!$occurrence->IsInstalled()) die("No alerts to import");
144
- $sql = 'SELECT * FROM ' . $occurrence->GetWPTable();
145
- $occurrences = $wpdb->get_results($sql, ARRAY_A);
146
-
147
- // Insert data to External DB
148
- $occurrenceNew = new WSAL_Adapters_MySQL_Occurrence($_wpdb);
149
- $increase_id = 0;
150
- $sql = 'SELECT MAX(id) FROM ' . $occurrenceNew->GetTable();
151
- $increase_id = (int)$_wpdb->get_var($sql);
152
-
153
- $sql = 'INSERT INTO ' . $occurrenceNew->GetTable() . ' (site_id, alert_id, created_on, is_read, is_migrated) VALUES ' ;
154
- foreach ($occurrences as $entry) {
155
- $sql .= '('.$entry['site_id'].', '.$entry['alert_id'].', '.$entry['created_on'].', '.$entry['is_read'].', 1), ';
156
- }
157
- $sql = rtrim($sql, ", ");
158
- $_wpdb->query($sql);
159
-
160
- // Load data Meta from WP
161
- $meta = new WSAL_Adapters_MySQL_Meta($wpdb);
162
- if (!$meta->IsInstalled()) die("No alerts to import");
163
- $sql = 'SELECT * FROM ' . $meta->GetWPTable();
164
- $metadata = $wpdb->get_results($sql, ARRAY_A);
165
-
166
- // Insert data to External DB
167
- $metaNew = new WSAL_Adapters_MySQL_Meta($_wpdb);
168
- $sql = 'INSERT INTO ' . $metaNew->GetTable() . ' (occurrence_id, name, value) VALUES ' ;
169
- foreach ($metadata as $entry) {
170
- $occurrence_id = $entry['occurrence_id'] + $increase_id;
171
- $sql .= '('.$occurrence_id.', \''.$entry['name'].'\', \''.$entry['value'].'\'), ';
172
- }
173
- $sql = rtrim($sql, ", ");
174
- $_wpdb->query($sql);
175
- $this->DeleteAfterMigrate($occurrence);
176
- $this->DeleteAfterMigrate($meta);
177
- }
178
-
179
- public function MigrateBack()
180
- {
181
- global $wpdb;
182
- $_wpdb = $this->getConnection();
183
-
184
- // Load data Occurrences from External DB
185
- $occurrence = new WSAL_Adapters_MySQL_Occurrence($_wpdb);
186
- if (!$occurrence->IsInstalled()) die("No alerts to import");
187
- $sql = 'SELECT * FROM ' . $occurrence->GetTable();
188
- $occurrences = $_wpdb->get_results($sql, ARRAY_A);
189
-
190
- // Insert data to WP
191
- $occurrenceWP = new WSAL_Adapters_MySQL_Occurrence($wpdb);
192
-
193
- $sql = 'INSERT INTO ' . $occurrenceWP->GetWPTable() . ' (site_id, alert_id, created_on, is_read, is_migrated) VALUES ' ;
194
- foreach ($occurrences as $entry) {
195
- $sql .= '('.$entry['site_id'].', '.$entry['alert_id'].', '.$entry['created_on'].', '.$entry['is_read'].', 1), ';
196
- }
197
- $sql = rtrim($sql, ", ");
198
- $wpdb->query($sql);
199
-
200
- // Load data Meta from External DB
201
- $meta = new WSAL_Adapters_MySQL_Meta($_wpdb);
202
- if (!$meta->IsInstalled()) die("No alerts to import");
203
- $sql = 'SELECT * FROM ' . $meta->GetTable();
204
- $metadata = $_wpdb->get_results($sql, ARRAY_A);
205
-
206
- // Insert data to WP
207
- $metaWP = new WSAL_Adapters_MySQL_Meta($wpdb);
208
- $sql = 'INSERT INTO ' . $metaWP->GetWPTable() . ' (occurrence_id, name, value) VALUES ' ;
209
- foreach ($metadata as $entry) {
210
- $sql .= '('.$entry['occurrence_id'].', \''.$entry['name'].'\', \''.$entry['value'].'\'), ';
211
- }
212
- $sql = rtrim($sql, ", ");
213
- $wpdb->query($sql);
214
- }
215
-
216
- private function DeleteAfterMigrate($record)
217
- {
218
- global $wpdb;
219
- $sql = 'DROP TABLE IF EXISTS ' . $record->GetTable();
220
- $wpdb->query($sql);
221
- }
222
-
223
- public function encryptString($plaintext)
224
- {
225
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
226
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
227
- $key = $this->truncateKey();
228
- $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
229
- $ciphertext = $iv . $ciphertext;
230
- $ciphertext_base64 = base64_encode($ciphertext);
231
-
232
- return $ciphertext_base64;
233
- }
234
-
235
- private function decryptString($ciphertext_base64)
236
- {
237
- $ciphertext_dec = base64_decode($ciphertext_base64);
238
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
239
-
240
- $iv_dec = substr($ciphertext_dec, 0, $iv_size);
241
- $ciphertext_dec = substr($ciphertext_dec, $iv_size);
242
- $key = $this->truncateKey();
243
- $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
244
-
245
- return rtrim($plaintext_dec, "\0");
246
- }
247
-
248
- private function truncateKey()
249
- {
250
- $key_size = strlen(AUTH_KEY);
251
- if ($key_size > 32) {
252
- return substr(AUTH_KEY, 0, 32);
253
- } else {
254
- return AUTH_KEY;
255
- }
256
- }
257
- }
1
+ <?php
2
+ require_once('ConnectorInterface.php');
3
+ require_once('AbstractConnector.php');
4
+ require_once('wp-db-custom.php');
5
+
6
+ class WSAL_Connector_MySQLDB extends WSAL_Connector_AbstractConnector implements WSAL_Connector_ConnectorInterface
7
+ {
8
+ protected $connectionConfig = null;
9
+
10
+ public function __construct($connectionConfig = null)
11
+ {
12
+ $this->connectionConfig = $connectionConfig;
13
+ parent::__construct("MySQL");
14
+ require_once($this->getAdaptersDirectory() . '/OptionAdapter.php');
15
+ }
16
+
17
+ public function TestConnection()
18
+ {
19
+ error_reporting(E_ALL ^ E_WARNING);
20
+ $connectionConfig = $this->connectionConfig;
21
+ $password = $this->decryptString($connectionConfig['password']);
22
+ $newWpdb = new wpdbCustom($connectionConfig['user'], $password, $connectionConfig['name'], $connectionConfig['hostname']);
23
+ if (!$newWpdb->has_connected) { // Database Error
24
+ throw new Exception("Connection failed. Please check your connection details.");
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Creates a connection and returns it
30
+ * @return Instance of WPDB
31
+ */
32
+ private function createConnection()
33
+ {
34
+ if (!empty($this->connectionConfig)) {
35
+ //TO DO: Use the provided connection config
36
+ $connectionConfig = $this->connectionConfig;
37
+ $password = $this->decryptString($connectionConfig['password']);
38
+ $newWpdb = new wpdb($connectionConfig['user'], $password, $connectionConfig['name'], $connectionConfig['hostname']);
39
+ $newWpdb->set_prefix($connectionConfig['base_prefix']);
40
+ return $newWpdb;
41
+ } else {
42
+ global $wpdb;
43
+ return $wpdb;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Returns a wpdb instance
49
+ */
50
+ public function getConnection()
51
+ {
52
+ if (!empty($this->connection)) {
53
+ return $this->connection;
54
+ } else {
55
+ $this->connection = $this->createConnection();
56
+ return $this->connection;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Gets an adapter for the specified model
62
+ */
63
+ public function getAdapter($class_name)
64
+ {
65
+ $objName = $this->getAdapterClassName($class_name);
66
+ return new $objName($this->getConnection());
67
+ }
68
+
69
+ protected function getAdapterClassName($class_name)
70
+ {
71
+ return 'WSAL_Adapters_MySQL_'.$class_name;
72
+ }
73
+
74
+ /**
75
+ * Checks if the necessary tables are available
76
+ */
77
+ public function isInstalled()
78
+ {
79
+ global $wpdb;
80
+ $table = $wpdb->base_prefix . 'wsal_occurrences';
81
+ return ($wpdb->get_var('SHOW TABLES LIKE "'.$table.'"') == $table);
82
+ }
83
+
84
+ /**
85
+ * Checks if old version tables are available
86
+ */
87
+ public function canMigrate()
88
+ {
89
+ $wpdb = $this->getConnection();
90
+ $table = $wpdb->base_prefix . 'wordpress_auditlog_events';
91
+ return ($wpdb->get_var('SHOW TABLES LIKE "'.$table.'"') == $table);
92
+ }
93
+
94
+ /**
95
+ * Install all DB tables.
96
+ */
97
+ public function installAll($excludeOptions = false)
98
+ {
99
+ $plugin = WpSecurityAuditLog::GetInstance();
100
+
101
+ foreach (glob($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . '*.php') as $file) {
102
+ $filePath = explode(DIRECTORY_SEPARATOR, $file);
103
+ $fileName = $filePath[count($filePath) - 1];
104
+ $className = $this->getAdapterClassName(str_replace("Adapter.php", "", $fileName));
105
+
106
+ $class = new $className($this->getConnection());
107
+ if ($excludeOptions && $class instanceof WSAL_Adapters_MySQL_Option) {
108
+ continue;
109
+ }
110
+
111
+ if (is_subclass_of($class, "WSAL_Adapters_MySQL_ActiveRecord")) {
112
+ $class->Install();
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Uninstall all DB tables.
119
+ */
120
+ public function uninstallAll()
121
+ {
122
+ $plugin = WpSecurityAuditLog::GetInstance();
123
+
124
+ foreach (glob($this->getAdaptersDirectory() . DIRECTORY_SEPARATOR . '*.php') as $file) {
125
+ $filePath = explode(DIRECTORY_SEPARATOR, $file);
126
+ $fileName = $filePath[count($filePath) - 1];
127
+ $className = $this->getAdapterClassName(str_replace("Adapter.php", "", $fileName));
128
+
129
+ $class = new $className($this->getConnection());
130
+ if (is_subclass_of($class, "WSAL_Adapters_MySQL_ActiveRecord")) {
131
+ $class->Uninstall();
132
+ }
133
+ }
134
+ }
135
+
136
+ public function Migrate()
137
+ {
138
+ global $wpdb;
139
+ $_wpdb = $this->getConnection();
140
+
141
+ // Load data Occurrences from WP
142
+ $occurrence = new WSAL_Adapters_MySQL_Occurrence($wpdb);
143
+ if (!$occurrence->IsInstalled()) die("No alerts to import");
144
+ $sql = 'SELECT * FROM ' . $occurrence->GetWPTable();
145
+ $occurrences = $wpdb->get_results($sql, ARRAY_A);
146
+
147
+ // Insert data to External DB
148
+ $occurrenceNew = new WSAL_Adapters_MySQL_Occurrence($_wpdb);
149
+ $increase_id = 0;
150
+ $sql = 'SELECT MAX(id) FROM ' . $occurrenceNew->GetTable();
151
+ $increase_id = (int)$_wpdb->get_var($sql);
152
+
153
+ $sql = 'INSERT INTO ' . $occurrenceNew->GetTable() . ' (site_id, alert_id, created_on, is_read, is_migrated) VALUES ' ;
154
+ foreach ($occurrences as $entry) {
155
+ $sql .= '('.$entry['site_id'].', '.$entry['alert_id'].', '.$entry['created_on'].', '.$entry['is_read'].', 1), ';
156
+ }
157
+ $sql = rtrim($sql, ", ");
158
+ $_wpdb->query($sql);
159
+
160
+ // Load data Meta from WP
161
+ $meta = new WSAL_Adapters_MySQL_Meta($wpdb);
162
+ if (!$meta->IsInstalled()) die("No alerts to import");
163
+ $sql = 'SELECT * FROM ' . $meta->GetWPTable();
164
+ $metadata = $wpdb->get_results($sql, ARRAY_A);
165
+
166
+ // Insert data to External DB
167
+ $metaNew = new WSAL_Adapters_MySQL_Meta($_wpdb);
168
+ $sql = 'INSERT INTO ' . $metaNew->GetTable() . ' (occurrence_id, name, value) VALUES ' ;
169
+ foreach ($metadata as $entry) {
170
+ $occurrence_id = $entry['occurrence_id'] + $increase_id;
171
+ $sql .= '('.$occurrence_id.', \''.$entry['name'].'\', \''.$entry['value'].'\'), ';
172
+ }
173
+ $sql = rtrim($sql, ", ");
174
+ $_wpdb->query($sql);
175
+ $this->DeleteAfterMigrate($occurrence);
176
+ $this->DeleteAfterMigrate($meta);
177
+ }
178
+
179
+ public function MigrateBack()
180
+ {
181
+ global $wpdb;
182
+ $_wpdb = $this->getConnection();
183
+
184
+ // Load data Occurrences from External DB
185
+ $occurrence = new WSAL_Adapters_MySQL_Occurrence($_wpdb);
186
+ if (!$occurrence->IsInstalled()) die("No alerts to import");
187
+ $sql = 'SELECT * FROM ' . $occurrence->GetTable();
188
+ $occurrences = $_wpdb->get_results($sql, ARRAY_A);
189
+
190
+ // Insert data to WP
191
+ $occurrenceWP = new WSAL_Adapters_MySQL_Occurrence($wpdb);
192
+
193
+ $sql = 'INSERT INTO ' . $occurrenceWP->GetWPTable() . ' (site_id, alert_id, created_on, is_read, is_migrated) VALUES ' ;
194
+ foreach ($occurrences as $entry) {
195
+ $sql .= '('.$entry['site_id'].', '.$entry['alert_id'].', '.$entry['created_on'].', '.$entry['is_read'].', 1), ';
196
+ }
197
+ $sql = rtrim($sql, ", ");
198
+ $wpdb->query($sql);
199
+
200
+ // Load data Meta from External DB
201
+ $meta = new WSAL_Adapters_MySQL_Meta($_wpdb);
202
+ if (!$meta->IsInstalled()) die("No alerts to import");
203
+ $sql = 'SELECT * FROM ' . $meta->GetTable();
204
+ $metadata = $_wpdb->get_results($sql, ARRAY_A);
205
+
206
+ // Insert data to WP
207
+ $metaWP = new WSAL_Adapters_MySQL_Meta($wpdb);
208
+ $sql = 'INSERT INTO ' . $metaWP->GetWPTable() . ' (occurrence_id, name, value) VALUES ' ;
209
+ foreach ($metadata as $entry) {
210
+ $sql .= '('.$entry['occurrence_id'].', \''.$entry['name'].'\', \''.$entry['value'].'\'), ';
211
+ }
212
+ $sql = rtrim($sql, ", ");
213
+ $wpdb->query($sql);
214
+ }
215
+
216
+ private function DeleteAfterMigrate($record)
217
+ {
218
+ global $wpdb;
219
+ $sql = 'DROP TABLE IF EXISTS ' . $record->GetTable();
220
+ $wpdb->query($sql);
221
+ }
222
+
223
+ public function encryptString($plaintext)
224
+ {
225
+ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
226
+ $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
227
+ $key = $this->truncateKey();
228
+ $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
229
+ $ciphertext = $iv . $ciphertext;
230
+ $ciphertext_base64 = base64_encode($ciphertext);
231
+
232
+ return $ciphertext_base64;
233
+ }
234
+
235
+ private function decryptString($ciphertext_base64)
236
+ {
237
+ $ciphertext_dec = base64_decode($ciphertext_base64);
238
+ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
239
+
240
+ $iv_dec = substr($ciphertext_dec, 0, $iv_size);
241
+ $ciphertext_dec = substr($ciphertext_dec, $iv_size);
242
+ $key = $this->truncateKey();
243
+ $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
244
+
245
+ return rtrim($plaintext_dec, "\0");
246
+ }
247
+
248
+ private function truncateKey()
249
+ {
250
+ $key_size = strlen(AUTH_KEY);
251
+ if ($key_size > 32) {
252
+ return substr(AUTH_KEY, 0, 32);
253
+ } else {
254
+ return AUTH_KEY;
255
+ }
256
+ }
257
+ }
classes/Connector/wp-db-custom.php CHANGED
@@ -1,36 +1,36 @@
1
- <?php
2
-
3
- class wpdbCustom extends wpdb
4
- {
5
- /*
6
- * overwrite wpdb class for set $allow_bail to false
7
- * and hide the print of the error
8
- */
9
- public function __construct($dbuser, $dbpassword, $dbname, $dbhost)
10
- {
11
- register_shutdown_function(array($this, '__destruct'));
12
- if (WP_DEBUG && WP_DEBUG_DISPLAY) {
13
- $this->show_errors();
14
- }
15
- if (function_exists('mysqli_connect')) {
16
- if (defined('WP_USE_EXT_MYSQL')) {
17
- $this->use_mysqli = ! WP_USE_EXT_MYSQL;
18
- } elseif (version_compare(phpversion(), '5.5', '>=') || !function_exists('mysql_connect')) {
19
- $this->use_mysqli = true;
20
- } elseif (false !== strpos($GLOBALS['wp_version'], '-')) {
21
- $this->use_mysqli = true;
22
- }
23
- }
24
- $this->dbuser = $dbuser;
25
- $this->dbpassword = $dbpassword;
26
- $this->dbname = $dbname;
27
- $this->dbhost = $dbhost;
28
- // wp-config.php creation will manually connect when ready.
29
- if (defined('WP_SETUP_CONFIG')) {
30
- return;
31
- }
32
-
33
- $this->db_connect(false);
34
- }
35
-
36
- }
1
+ <?php
2
+
3
+ class wpdbCustom extends wpdb
4
+ {
5
+ /*
6
+ * overwrite wpdb class for set $allow_bail to false
7
+ * and hide the print of the error
8
+ */
9
+ public function __construct($dbuser, $dbpassword, $dbname, $dbhost)
10
+ {
11
+ register_shutdown_function(array($this, '__destruct'));
12
+ if (WP_DEBUG && WP_DEBUG_DISPLAY) {
13
+ $this->show_errors();
14
+ }
15
+ if (function_exists('mysqli_connect')) {
16
+ if (defined('WP_USE_EXT_MYSQL')) {
17
+ $this->use_mysqli = ! WP_USE_EXT_MYSQL;
18
+ } elseif (version_compare(phpversion(), '5.5', '>=') || !function_exists('mysql_connect')) {
19
+ $this->use_mysqli = true;
20
+ } elseif (false !== strpos($GLOBALS['wp_version'], '-')) {
21
+ $this->use_mysqli = true;
22
+ }
23
+ }
24
+ $this->dbuser = $dbuser;
25
+ $this->dbpassword = $dbpassword;
26
+ $this->dbname = $dbname;
27
+ $this->dbhost = $dbhost;
28
+ // wp-config.php creation will manually connect when ready.
29
+ if (defined('WP_SETUP_CONFIG')) {
30
+ return;
31
+ }
32
+
33
+ $this->db_connect(false);
34
+ }
35
+
36
+ }
classes/EDD_SL_Plugin_Updater.php CHANGED
@@ -1,170 +1,170 @@
1
- <?php
2
-
3
- // uncomment this line for testing
4
- //set_site_transient( 'update_plugins', null );
5
-
6
- /**
7
- * Allows plugins to use their own update API.
8
- *
9
- * @author Pippin Williamson
10
- * @version 1.2
11
- */
12
- class EDD_SL_Plugin_Updater {
13
- private $api_url = '';
14
- private $api_data = array();
15
- private $name = '';
16
- private $slug = '';
17
- private $do_check = false;
18
-
19
- /**
20
- * Class constructor.
21
- *
22
- * @uses plugin_basename()
23
- * @uses hook()
24
- *
25
- * @param string $_api_url The URL pointing to the custom API endpoint.
26
- * @param string $_plugin_file Path to the plugin file.
27
- * @param array $_api_data Optional data to send with API calls.
28
- * @return void
29
- */
30
- function __construct( $_api_url, $_plugin_file, $_api_data = null ) {
31
- $this->api_url = trailingslashit( $_api_url );
32
- $this->api_data = urlencode_deep( $_api_data );
33
- $this->name = plugin_basename( $_plugin_file );
34
- $this->slug = basename( $_plugin_file, '.php');
35
- $this->version = $_api_data['version'];
36
-
37
- // Set up hooks.
38
- $this->hook();
39
- }
40
-
41
- /**
42
- * Set up WordPress filters to hook into WP's update process.
43
- *
44
- * @uses add_filter()
45
- *
46
- * @return void
47
- */
48
- private function hook() {
49
- add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'pre_set_site_transient_update_plugins_filter' ) );
50
- add_filter( 'plugins_api', array( $this, 'plugins_api_filter' ), 10, 3 );
51
- add_filter( 'http_request_args', array( $this, 'http_request_args' ), 10, 2 );
52
- }
53
-
54
- /**
55
- * Check for Updates at the defined API endpoint and modify the update array.
56
- *
57
- * This function dives into the update API just when WordPress creates its update array,
58
- * then adds a custom API call and injects the custom plugin data retrieved from the API.
59
- * It is reassembled from parts of the native WordPress plugin update code.
60
- * See wp-includes/update.php line 121 for the original wp_update_plugins() function.
61
- *
62
- * @uses api_request()
63
- *
64
- * @param array $_transient_data Update array build by WordPress.
65
- * @return array Modified update array with custom plugin data.
66
- */
67
- function pre_set_site_transient_update_plugins_filter( $_transient_data ) {
68
-
69
- if( empty( $_transient_data ) || ! $this->do_check ) {
70
-
71
- // This ensures that the custom API request only runs on the second time that WP fires the update check
72
- $this->do_check = true;
73
-
74
- return $_transient_data;
75
- }
76
-
77
- $to_send = array( 'slug' => $this->slug );
78
-
79
- $api_response = $this->api_request( 'plugin_latest_version', $to_send );
80
-
81
- if( false !== $api_response && is_object( $api_response ) && isset( $api_response->new_version ) ) {
82
-
83
- if( version_compare( $this->version, $api_response->new_version, '<' ) ) {
84
- $_transient_data->response[$this->name] = $api_response;
85
- }
86
- }
87
- return $_transient_data;
88
- }
89
-
90
-
91
- /**
92
- * Updates information on the "View version x.x details" page with custom data.
93
- *
94
- * @uses api_request()
95
- *
96
- * @param mixed $_data
97
- * @param string $_action
98
- * @param object $_args
99
- * @return object $_data
100
- */
101
- function plugins_api_filter( $_data, $_action = '', $_args = null ) {
102
- if ( ( $_action != 'plugin_information' ) || !isset( $_args->slug ) || ( $_args->slug != $this->slug ) ) return $_data;
103
-
104
- $to_send = array( 'slug' => $this->slug );
105
-
106
- $api_response = $this->api_request( 'plugin_information', $to_send );
107
- if ( false !== $api_response ) $_data = $api_response;
108
-
109
- return $_data;
110
- }
111
-
112
-
113
- /**
114
- * Disable SSL verification in order to prevent download update failures
115
- *
116
- * @param array $args
117
- * @param string $url
118
- * @return object $array
119
- */
120
- function http_request_args( $args, $url ) {
121
- // If it is an https request and we are performing a package download, disable ssl verification
122
- if( strpos( $url, 'https://' ) !== false && strpos( $url, 'edd_action=package_download' ) ) {
123
- $args['sslverify'] = false;
124
- }
125
- return $args;
126
- }
127
-
128
- /**
129
- * Calls the API and, if successfull, returns the object delivered by the API.
130
- *
131
- * @uses get_bloginfo()
132
- * @uses wp_remote_post()
133
- * @uses is_wp_error()
134
- *
135
- * @param string $_action The requested action.
136
- * @param array $_data Parameters for the API action.
137
- * @return false||object
138
- */
139
- private function api_request( $_action, $_data ) {
140
-
141
- global $wp_version;
142
-
143
- $data = array_merge( $this->api_data, $_data );
144
-
145
- if( $data['slug'] != $this->slug )
146
- return;
147
-
148
- if( empty( $data['license'] ) )
149
- return;
150
-
151
- $api_params = array(
152
- 'edd_action' => 'get_version',
153
- 'license' => $data['license'],
154
- 'name' => $data['item_name'],
155
- 'slug' => $this->slug,
156
- 'author' => $data['author'],
157
- 'url' => home_url()
158
- );
159
- $request = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
160
-
161
- if ( ! is_wp_error( $request ) ):
162
- $request = json_decode( wp_remote_retrieve_body( $request ) );
163
- if( $request && isset( $request->sections ) )
164
- $request->sections = maybe_unserialize( $request->sections );
165
- return $request;
166
- else:
167
- return false;
168
- endif;
169
- }
170
- }
1
+ <?php
2
+
3
+ // uncomment this line for testing
4
+ //set_site_transient( 'update_plugins', null );
5
+
6
+ /**
7
+ * Allows plugins to use their own update API.
8
+ *
9
+ * @author Pippin Williamson
10
+ * @version 1.2
11
+ */
12
+ class EDD_SL_Plugin_Updater {
13
+ private $api_url = '';
14
+ private $api_data = array();
15
+ private $name = '';
16
+ private $slug = '';
17
+ private $do_check = false;
18
+
19
+ /**
20
+ * Class constructor.
21
+ *
22
+ * @uses plugin_basename()
23
+ * @uses hook()
24
+ *
25
+ * @param string $_api_url The URL pointing to the custom API endpoint.
26
+ * @param string $_plugin_file Path to the plugin file.
27
+ * @param array $_api_data Optional data to send with API calls.
28
+ * @return void
29
+ */
30
+ function __construct( $_api_url, $_plugin_file, $_api_data = null ) {
31
+ $this->api_url = trailingslashit( $_api_url );
32
+ $this->api_data = urlencode_deep( $_api_data );
33
+ $this->name = plugin_basename( $_plugin_file );
34
+ $this->slug = basename( $_plugin_file, '.php');
35
+ $this->version = $_api_data['version'];
36
+
37
+ // Set up hooks.
38
+ $this->hook();
39
+ }
40
+
41
+ /**
42
+ * Set up WordPress filters to hook into WP's update process.
43
+ *
44
+ * @uses add_filter()
45
+ *
46
+ * @return void
47
+ */
48
+ private function hook() {
49
+ add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'pre_set_site_transient_update_plugins_filter' ) );
50
+ add_filter( 'plugins_api', array( $this, 'plugins_api_filter' ), 10, 3 );
51
+ add_filter( 'http_request_args', array( $this, 'http_request_args' ), 10, 2 );
52
+ }
53
+
54
+ /**
55
+ * Check for Updates at the defined API endpoint and modify the update array.
56
+ *
57
+ * This function dives into the update API just when WordPress creates its update array,
58
+ * then adds a custom API call and injects the custom plugin data retrieved from the API.
59
+ * It is reassembled from parts of the native WordPress plugin update code.
60
+ * See wp-includes/update.php line 121 for the original wp_update_plugins() function.
61
+ *
62
+ * @uses api_request()
63
+ *
64
+ * @param array $_transient_data Update array build by WordPress.
65
+ * @return array Modified update array with custom plugin data.
66
+ */
67
+ function pre_set_site_transient_update_plugins_filter( $_transient_data ) {
68
+
69
+ if( empty( $_transient_data ) || ! $this->do_check ) {
70
+
71
+ // This ensures that the custom API request only runs on the second time that WP fires the update check
72
+ $this->do_check = true;
73
+
74
+ return $_transient_data;
75
+ }
76
+
77
+ $to_send = array( 'slug' => $this->slug );
78
+
79
+ $api_response = $this->api_request( 'plugin_latest_version', $to_send );
80
+
81
+ if( false !== $api_response && is_object( $api_response ) && isset( $api_response->new_version ) ) {
82
+
83
+ if( version_compare( $this->version, $api_response->new_version, '<' ) ) {
84
+ $_transient_data->response[$this->name] = $api_response;
85
+ }
86
+ }
87
+ return $_transient_data;
88
+ }
89
+
90
+
91
+ /**
92
+ * Updates information on the "View version x.x details" page with custom data.
93
+ *
94
+ * @uses api_request()
95
+ *
96
+ * @param mixed $_data
97
+ * @param string $_action
98
+ * @param object $_args
99
+ * @return object $_data
100
+ */
101
+ function plugins_api_filter( $_data, $_action = '', $_args = null ) {
102
+ if ( ( $_action != 'plugin_information' ) || !isset( $_args->slug ) || ( $_args->slug != $this->slug ) ) return $_data;
103
+
104
+ $to_send = array( 'slug' => $this->slug );
105
+
106
+ $api_response = $this->api_request( 'plugin_information', $to_send );
107
+ if ( false !== $api_response ) $_data = $api_response;
108
+
109
+ return $_data;
110
+ }
111
+
112
+
113
+ /**
114
+ * Disable SSL verification in order to prevent download update failures
115
+ *
116
+ * @param array $args
117
+ * @param string $url
118
+ * @return object $array
119
+ */
120
+ function http_request_args( $args, $url ) {
121
+ // If it is an https request and we are performing a package download, disable ssl verification
122
+ if( strpos( $url, 'https://' ) !== false && strpos( $url, 'edd_action=package_download' ) ) {
123
+ $args['sslverify'] = false;
124
+ }
125
+ return $args;
126
+ }
127
+
128
+ /**
129
+ * Calls the API and, if successfull, returns the object delivered by the API.
130
+ *
131
+ * @uses get_bloginfo()
132
+ * @uses wp_remote_post()
133
+ * @uses is_wp_error()
134
+ *
135
+ * @param string $_action The requested action.
136
+ * @param array $_data Parameters for the API action.
137
+ * @return false||object
138
+ */
139
+ private function api_request( $_action, $_data ) {
140
+
141
+ global $wp_version;
142
+
143
+ $data = array_merge( $this->api_data, $_data );
144
+
145
+ if( $data['slug'] != $this->slug )
146
+ return;
147
+
148
+ if( empty( $data['license'] ) )
149
+ return;
150
+
151
+ $api_params = array(
152
+ 'edd_action' => 'get_version',
153
+ 'license' => $data['license'],
154
+ 'name' => $data['item_name'],
155
+ 'slug' => $this->slug,
156
+ 'author' => $data['author'],
157
+ 'url' => home_url()
158
+ );
159
+ $request = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
160
+
161
+ if ( ! is_wp_error( $request ) ):
162
+ $request = json_decode( wp_remote_retrieve_body( $request ) );
163
+ if( $request && isset( $request->sections ) )
164
+ $request->sections = maybe_unserialize( $request->sections );
165
+ return $request;
166
+ else:
167
+ return false;
168
+ endif;
169
+ }
170
+ }
classes/Helpers/DataHelper.php CHANGED
@@ -1,23 +1,23 @@
1
- <?php
2
-
3
- class WSAL_Helpers_DataHelper
4
- {
5
-
6
- /**
7
- * A wrapper for JSON encoding that fixes potential issues.
8
- * @param mixed $data The data to encode.
9
- * @return string JSON string.
10
- */
11
- public static function JsonEncode($data){
12
- return @json_encode($data);
13
- }
14
-
15
- /**
16
- * A wrapper for JSON encoding that fixes potential issues.
17
- * @param string $data The JSON string to decode.
18
- * @return mixed Decoded data.
19
- */
20
- public static function JsonDecode($data){
21
- return @json_decode($data);
22
- }
23
  }
1
+ <?php
2
+
3
+ class WSAL_Helpers_DataHelper
4
+ {
5
+
6
+ /**
7
+ * A wrapper for JSON encoding that fixes potential issues.
8
+ * @param mixed $data The data to encode.
9
+ * @return string JSON string.
10
+ */
11
+ public static function JsonEncode($data){
12
+ return @json_encode($data);
13
+ }
14
+
15
+ /**
16
+ * A wrapper for JSON encoding that fixes potential issues.
17
+ * @param string $data The JSON string to decode.
18
+ * @return mixed Decoded data.
19
+ */
20
+ public static function JsonDecode($data){
21
+ return @json_decode($data);
22
+ }
23
  }
classes/Models/ActiveRecord.php CHANGED
@@ -1,267 +1,267 @@
1
- <?php
2
- require_once(__DIR__ . '/../Connector/ConnectorFactory.php');
3
-
4
- abstract class WSAL_Models_ActiveRecord
5
- {
6
-
7
- /**
8
- * @var_$connector Data connector;
9
- */
10
- protected $connector;
11
-
12
- protected $id = false;
13
-
14
- protected $adapterName = null;
15
-
16
- protected $useDefaultAdapter = false;
17
-
18
- /**
19
- * @return array Returns this records' fields.
20
- */
21
- public function GetFields()
22
- {
23
- if(!isset($this->_column_cache)){
24
- $this->_column_cache = array();
25
- foreach(array_keys(get_object_vars($this)) as $col)
26
- if(trim($col) && $col[0] != '_')
27
- $this->_column_cache[] = $col;
28
- }
29
- return $this->_column_cache;
30
- }
31
-
32
- public function setId($id)
33
- {
34
- $this->id = $id;
35
- }
36
-
37
- public function getId()
38
- {
39
- return $this->id;
40
- }
41
-
42
- const STATE_UNKNOWN = 'unknown';
43
- const STATE_CREATED = 'created';
44
- const STATE_UPDATED = 'updated';
45
- const STATE_DELETED = 'deleted';
46
- const STATE_LOADED = 'loaded';
47
-
48
- protected $_state = self::STATE_UNKNOWN;
49
-
50
- public function __construct($data = null)
51
- {
52
- if (!$this->adapterName) {
53
- throw new Exception('Class "' . __CLASS__ . '" requires "adapterName" to be set.');
54
- }
55
- if (!is_null($data)) {
56
- $this->LoadData($data);
57
- $this->_state = self::STATE_LOADED;
58
- }
59
- }
60
-
61
- protected function getConnector()
62
- {
63
- if (!empty($this->connector)) {
64
- return $this->connector;
65
- }
66
- if ($this->useDefaultAdapter) {
67
- $this->connector = WSAL_Connector_ConnectorFactory::GetDefaultConnector();
68
- } else {
69
- $this->connector = WSAL_Connector_ConnectorFactory::GetConnector();
70
- }
71
- return $this->connector;
72
- }
73
-
74
- public function getAdapter()
75
- {
76
- return $this->getConnector()->getAdapter($this->adapterName);
77
- }
78
-
79
-
80
- /**
81
- * Load record from DB.
82
- * @param string $cond (Optional) Load condition.
83
- * @param array $args (Optional) Load condition arguments.
84
- */
85
- public function Load($cond = '%d', $args = array(1)){
86
- $this->_state = self::STATE_UNKNOWN;
87
-
88
- $data = $this->getAdapter()->Load($cond, $args);
89
- if(!is_null($data)){
90
- $this->LoadData($data);
91
- $this->_state = self::STATE_LOADED;
92
- }
93
- }
94
-
95
- /**
96
- * Load object data from variable.
97
- * @param array|object $data Data array or object.
98
- */
99
- public function LoadData($data){
100
- $copy = get_class($this);
101
- $copy = new $copy;
102
- foreach((array)$data as $key => $val){
103
- if(isset($copy->$key)){
104
- switch(true){
105
- case is_array($copy->$key):
106
- case is_object($copy->$key):
107
- $jsonDecodedVal = WSAL_Helpers_DataHelper::JsonDecode($val);
108
- $this->$key = ($jsonDecodedVal == null) ? $val : $jsonDecodedVal;
109
- break;
110
- case is_int($copy->$key):
111
- $this->$key = (int)$val;
112
- break;
113
- case is_float($copy->$key):
114
- $this->$key = (float)$val;
115
- break;
116
- case is_bool($copy->$key):
117
- $this->$key = (bool)$val;
118
- break;
119
- case is_string($copy->$key):
120
- $this->$key = (string)$val;
121
- break;
122
- default:
123
- throw new Exception('Unsupported type "'.gettype($copy->$key).'"');
124
- }
125
- }
126
- }
127
- return $this;
128
- }
129
-
130
- /**
131
- * Save this active record
132
- * @return integer|boolean Either the number of modified/inserted rows or false on failure.
133
- */
134
- public function Save()
135
- {
136
- $this->_state = self::STATE_UNKNOWN;
137
-
138
- // use today's date if not set up
139
- if (is_null($this->created_on)) {
140
- $this->created_on = $this->GetMicrotime();
141
- }
142
- $updateId = $this->getId();
143
- $result = $this->getAdapter()->Save($this);
144
-
145
- if ($result !== false) {
146
- $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
147
- }
148
- return $result;
149
- }
150
-
151
- /**
152
- * Deletes this active record
153
- */
154
- public function Delete()
155
- {
156
- $this->_state = self::STATE_UNKNOWN;
157
- $result = $this->getAdapter()->Delete($this);
158
- if($result !== false)
159
- $this->_state = self::STATE_DELETED;
160
-
161
- return $result;
162
- }
163
-
164
- public function Count($cond = '%d', $args = array(1)) {
165
- $result = $this->getAdapter()->Count($cond, $args);
166
- return $result;
167
- }
168
-
169
- /**
170
- * @return boolean
171
- */
172
- public function IsLoaded(){
173
- return $this->_state == self::STATE_LOADED;
174
- }
175
-
176
- /**
177
- * @return boolean
178
- */
179
- public function IsSaved(){
180
- return $this->_state == self::STATE_CREATED
181
- || $this->_state == self::STATE_UPDATED;
182
- }
183
-
184
- /**
185
- * @return boolean
186
- */
187
- public function IsCreated(){
188
- return $this->_state == self::STATE_CREATED;
189
- }
190
-
191
- /**
192
- * @return boolean
193
- */
194
- public function IsUpdated()
195
- {
196
- return $this->_state == self::STATE_UPDATED;
197
- }
198
-
199
- /**
200
- * @return boolean
201
- */
202
- public function IsInstalled()
203
- {
204
- return $this->getAdapter()->IsInstalled();
205
- }
206
-
207
- public function Install()
208
- {
209
- return $this->getAdapter()->Install();
210
- }
211
-
212
- /**
213
- * @return boolean
214
- */
215
- public function IsDeleted()
216
- {
217
- return $this->_state == self::STATE_DELETED;
218
- }
219
-
220
- protected static $_cache = array();
221
-
222
- /**
223
- * Load ActiveRecord from DB or cache.
224
- * @param string $target ActiveRecord class name.
225
- * @param string $query Load condition.
226
- * @param array $args Arguments used in condition.
227
- * @return WSAL_Models_ActiveRecord
228
- */
229
- protected static function CacheLoad($target, $query, $args){
230
- $index = $target . '::' . vsprintf($query, $args);
231
- if(!isset(self::$_cache[$index])){
232
- self::$_cache[$index] = new $target();
233
- self::$_cache[$index]->Load($query, $args);
234
- }
235
- return self::$_cache[$index];
236
- }
237
-
238
- /**
239
- * Remove ActiveRecord cache.
240
- * @param string $target ActiveRecord class name.
241
- * @param string $query Load condition.
242
- * @param array $args Arguments used in condition.
243
- */
244
- protected static function CacheRemove($target, $query, $args){
245
- $index = $target . '::' . sprintf($query, $args);
246
- if(!isset(self::$_cache[$index])){
247
- unset(self::$_cache[$index]);
248
- }
249
- }
250
-
251
- /**
252
- * Clear the cache.
253
- */
254
- protected static function CacheClear()
255
- {
256
- self::$_cache = array();
257
- }
258
-
259
- /**
260
- * Function used in WSAL reporting extension
261
- */
262
- public function GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp)
263
- {
264
- return $this->getAdapter()->GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp);
265
- }
266
-
267
- }
1
+ <?php
2
+ require_once(__DIR__ . '/../Connector/ConnectorFactory.php');
3
+
4
+ abstract class WSAL_Models_ActiveRecord
5
+ {
6
+
7
+ /**
8
+ * @var_$connector Data connector;
9
+ */
10
+ protected $connector;
11
+
12
+ protected $id = false;
13
+
14
+ protected $adapterName = null;
15
+
16
+ protected $useDefaultAdapter = false;
17
+
18
+ /**
19
+ * @return array Returns this records' fields.
20
+ */
21
+ public function GetFields()
22
+ {
23
+ if(!isset($this->_column_cache)){
24
+ $this->_column_cache = array();
25
+ foreach(array_keys(get_object_vars($this)) as $col)
26
+ if(trim($col) && $col[0] != '_')
27
+ $this->_column_cache[] = $col;
28
+ }
29
+ return $this->_column_cache;
30
+ }
31
+
32
+ public function setId($id)
33
+ {
34
+ $this->id = $id;
35
+ }
36
+
37
+ public function getId()
38
+ {
39
+ return $this->id;
40
+ }
41
+
42
+ const STATE_UNKNOWN = 'unknown';
43
+ const STATE_CREATED = 'created';
44
+ const STATE_UPDATED = 'updated';
45
+ const STATE_DELETED = 'deleted';
46
+ const STATE_LOADED = 'loaded';
47
+
48
+ protected $_state = self::STATE_UNKNOWN;
49
+
50
+ public function __construct($data = null)
51
+ {
52
+ if (!$this->adapterName) {
53
+ throw new Exception('Class "' . __CLASS__ . '" requires "adapterName" to be set.');
54
+ }
55
+ if (!is_null($data)) {
56
+ $this->LoadData($data);
57
+ $this->_state = self::STATE_LOADED;
58
+ }
59
+ }
60
+
61
+ protected function getConnector()
62
+ {
63
+ if (!empty($this->connector)) {
64
+ return $this->connector;
65
+ }
66
+ if ($this->useDefaultAdapter) {
67
+ $this->connector = WSAL_Connector_ConnectorFactory::GetDefaultConnector();
68
+ } else {
69
+ $this->connector = WSAL_Connector_ConnectorFactory::GetConnector();
70
+ }
71
+ return $this->connector;
72
+ }
73
+
74
+ public function getAdapter()
75
+ {
76
+ return $this->getConnector()->getAdapter($this->adapterName);
77
+ }
78
+
79
+
80
+ /**
81
+ * Load record from DB.
82
+ * @param string $cond (Optional) Load condition.
83
+ * @param array $args (Optional) Load condition arguments.
84
+ */
85
+ public function Load($cond = '%d', $args = array(1)){
86
+ $this->_state = self::STATE_UNKNOWN;
87
+
88
+ $data = $this->getAdapter()->Load($cond, $args);
89
+ if(!is_null($data)){
90
+ $this->LoadData($data);
91
+ $this->_state = self::STATE_LOADED;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Load object data from variable.
97
+ * @param array|object $data Data array or object.
98
+ */
99
+ public function LoadData($data){
100
+ $copy = get_class($this);
101
+ $copy = new $copy;
102
+ foreach((array)$data as $key => $val){
103
+ if(isset($copy->$key)){
104
+ switch(true){
105
+ case is_array($copy->$key):
106
+ case is_object($copy->$key):
107
+ $jsonDecodedVal = WSAL_Helpers_DataHelper::JsonDecode($val);
108
+ $this->$key = ($jsonDecodedVal == null) ? $val : $jsonDecodedVal;
109
+ break;
110
+ case is_int($copy->$key):
111
+ $this->$key = (int)$val;
112
+ break;
113
+ case is_float($copy->$key):
114
+ $this->$key = (float)$val;
115
+ break;
116
+ case is_bool($copy->$key):
117
+ $this->$key = (bool)$val;
118
+ break;
119
+ case is_string($copy->$key):
120
+ $this->$key = (string)$val;
121
+ break;
122
+ default:
123
+ throw new Exception('Unsupported type "'.gettype($copy->$key).'"');
124
+ }
125
+ }
126
+ }
127
+ return $this;
128
+ }
129
+
130
+ /**
131
+ * Save this active record
132
+ * @return integer|boolean Either the number of modified/inserted rows or false on failure.
133
+ */
134
+ public function Save()
135
+ {
136
+ $this->_state = self::STATE_UNKNOWN;
137
+
138
+ // use today's date if not set up
139
+ if (is_null($this->created_on)) {
140
+ $this->created_on = $this->GetMicrotime();
141
+ }
142
+ $updateId = $this->getId();
143
+ $result = $this->getAdapter()->Save($this);
144
+
145
+ if ($result !== false) {
146
+ $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
147
+ }
148
+ return $result;
149
+ }
150
+
151
+ /**
152
+ * Deletes this active record
153
+ */
154
+ public function Delete()
155
+ {
156
+ $this->_state = self::STATE_UNKNOWN;
157
+ $result = $this->getAdapter()->Delete($this);
158
+ if($result !== false)
159
+ $this->_state = self::STATE_DELETED;
160
+
161
+ return $result;
162
+ }
163
+
164
+ public function Count($cond = '%d', $args = array(1)) {
165
+ $result = $this->getAdapter()->Count($cond, $args);
166
+ return $result;
167
+ }
168
+
169
+ /**
170
+ * @return boolean
171
+ */
172
+ public function IsLoaded(){
173
+ return $this->_state == self::STATE_LOADED;
174
+ }
175
+
176
+ /**
177
+ * @return boolean
178
+ */
179
+ public function IsSaved(){
180
+ return $this->_state == self::STATE_CREATED
181
+ || $this->_state == self::STATE_UPDATED;
182
+ }
183
+
184
+ /**
185
+ * @return boolean
186
+ */
187
+ public function IsCreated(){
188
+ return $this->_state == self::STATE_CREATED;
189
+ }
190
+
191
+ /**
192
+ * @return boolean
193
+ */
194
+ public function IsUpdated()
195
+ {
196
+ return $this->_state == self::STATE_UPDATED;
197
+ }
198
+
199
+ /**
200
+ * @return boolean
201
+ */
202
+ public function IsInstalled()
203
+ {
204
+ return $this->getAdapter()->IsInstalled();
205
+ }
206
+
207
+ public function Install()
208
+ {
209
+ return $this->getAdapter()->Install();
210
+ }
211
+
212
+ /**
213
+ * @return boolean
214
+ */
215
+ public function IsDeleted()
216
+ {
217
+ return $this->_state == self::STATE_DELETED;
218
+ }
219
+
220
+ protected static $_cache = array();
221
+
222
+ /**
223
+ * Load ActiveRecord from DB or cache.
224
+ * @param string $target ActiveRecord class name.
225
+ * @param string $query Load condition.
226
+ * @param array $args Arguments used in condition.
227
+ * @return WSAL_Models_ActiveRecord
228
+ */
229
+ protected static function CacheLoad($target, $query, $args){
230
+ $index = $target . '::' . vsprintf($query, $args);
231
+ if(!isset(self::$_cache[$index])){
232
+ self::$_cache[$index] = new $target();
233
+ self::$_cache[$index]->Load($query, $args);
234
+ }
235
+ return self::$_cache[$index];
236
+ }
237
+
238
+ /**
239
+ * Remove ActiveRecord cache.
240
+ * @param string $target ActiveRecord class name.
241
+ * @param string $query Load condition.
242
+ * @param array $args Arguments used in condition.
243
+ */
244
+ protected static function CacheRemove($target, $query, $args){
245
+ $index = $target . '::' . sprintf($query, $args);
246
+ if(!isset(self::$_cache[$index])){
247
+ unset(self::$_cache[$index]);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Clear the cache.
253
+ */
254
+ protected static function CacheClear()
255
+ {
256
+ self::$_cache = array();
257
+ }
258
+
259
+ /**
260
+ * Function used in WSAL reporting extension
261
+ */
262
+ public function GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp)
263
+ {
264
+ return $this->getAdapter()->GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp);
265
+ }
266
+
267
+ }
classes/Models/Adapters/ActiveRecordInterface.php CHANGED
@@ -1,15 +1,15 @@
1
- <?php
2
-
3
- interface WSAL_Adapters_ActiveRecordInterface {
4
-
5
- public function IsInstalled();
6
- public function Install();
7
- public function Uninstall();
8
- public function Load($cond = '%d', $args = array(1));
9
- public function Save($activeRecord);
10
- public function Delete($activeRecord);
11
- public function LoadMulti($cond, $args = array());
12
- public function LoadAndCallForEach($callback, $cond = '%d', $args = array(1));
13
- public function Count($cond = '%d', $args = array(1));
14
- public function LoadMultiQuery($query, $args = array());
15
- }
1
+ <?php
2
+
3
+ interface WSAL_Adapters_ActiveRecordInterface {
4
+
5
+ public function IsInstalled();
6
+ public function Install();
7
+ public function Uninstall();
8
+ public function Load($cond = '%d', $args = array(1));
9
+ public function Save($activeRecord);
10
+ public function Delete($activeRecord);
11
+ public function LoadMulti($cond, $args = array());
12
+ public function LoadAndCallForEach($callback, $cond = '%d', $args = array(1));
13
+ public function Count($cond = '%d', $args = array(1));
14
+ public function LoadMultiQuery($query, $args = array());
15
+ }
classes/Models/Adapters/MetaInterface.php CHANGED
@@ -1,13 +1,13 @@
1
- <?php
2
-
3
- interface WSAL_Adapters_MetaInterface {
4
- /**
5
- * Create a meta object
6
- * @param $metaData Array of meta data
7
- * @return int ID of the new meta data
8
- */
9
- public function deleteByOccurenceIds($occurenceIds);
10
-
11
- public function loadByNameAndOccurenceId($metaName, $occurenceId);
12
-
13
- }
1
+ <?php
2
+
3
+ interface WSAL_Adapters_MetaInterface {
4
+ /**
5
+ * Create a meta object
6
+ * @param $metaData Array of meta data
7
+ * @return int ID of the new meta data
8
+ */
9
+ public function deleteByOccurenceIds($occurenceIds);
10
+
11
+ public function loadByNameAndOccurenceId($metaName, $occurenceId);
12
+
13
+ }
classes/Models/Adapters/MySQL/ActiveRecordAdapter.php CHANGED
@@ -1,474 +1,474 @@
1
- <?php
2
-
3
- class WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_ActiveRecordInterface {
4
-
5
- protected $connection;
6
-
7
- /**
8
- * Contains the table name
9
- * @var string
10
- */
11
- protected $_table;
12
-
13
- /**
14
- * Contains primary key column name, override as required.
15
- * @var string
16
- */
17
- protected $_idkey = '';
18
-
19
- public function __construct($conn)
20
- {
21
- $this->connection = $conn;
22
- }
23
-
24
- public function GetModel()
25
- {
26
- return new WSAL_Models_ActiveRecord();
27
- }
28
-
29
- /**
30
- * @return string Returns table name.
31
- */
32
- public function GetTable()
33
- {
34
- $_wpdb = $this->connection;
35
- return $_wpdb->base_prefix . $this->_table;
36
- }
37
-
38
- /**
39
- * Used for WordPress prefix
40
- * @return string Returns table name of WordPress.
41
- */
42
- public function GetWPTable()
43
- {
44
- global $wpdb;
45
- return $wpdb->base_prefix . $this->_table;
46
- }
47
-
48
- /**
49
- * @return string SQL table options (constraints, foreign keys, indexes etc).
50
- */
51
- protected function GetTableOptions()
52
- {
53
- return ' PRIMARY KEY (' . $this->_idkey . ')';
54
- }
55
-
56
- /**
57
- * @return array Returns this records' columns.
58
- */
59
- public function GetColumns()
60
- {
61
- $model = $this->GetModel();
62
-
63
- if(!isset($this->_column_cache)){
64
- $this->_column_cache = array();
65
- foreach(array_keys(get_object_vars($model)) as $col)
66
- if(trim($col) && $col[0] != '_')
67
- $this->_column_cache[] = $col;
68
- }
69
- return $this->_column_cache;
70
- }
71
-
72
- /**
73
- * @deprecated
74
- * @return boolean Returns whether table structure is installed or not.
75
- */
76
- public function IsInstalled(){
77
- //global $wpdb;
78
- $_wpdb = $this->connection;
79
- $sql = 'SHOW TABLES LIKE "' . $this->GetTable() . '"';
80
- return strtolower($_wpdb->get_var($sql)) == strtolower($this->GetTable());
81
- }
82
-
83
- /**
84
- * Install this ActiveRecord structure into DB.
85
- */
86
- public function Install(){
87
- $_wpdb = $this->connection;
88
- $_wpdb->query($this->_GetInstallQuery());
89
- }
90
-
91
- /**
92
- * Install this ActiveRecord structure into DB WordPress.
93
- */
94
- public function InstallOriginal(){
95
- global $wpdb;
96
- $wpdb->query($this->_GetInstallQuery(true));
97
- }
98
-
99
- /**
100
- * Remove this ActiveRecord structure into DB.
101
- */
102
- public function Uninstall()
103
- {
104
- //global $wpdb;
105
- $_wpdb = $this->connection;
106
- $_wpdb->query($this->_GetUninstallQuery());
107
- }
108
-
109
- /**
110
- * Save an active record to DB.
111
- * @return integer|boolean Either the number of modified/inserted rows or false on failure.
112
- */
113
- public function Save($activeRecord)
114
- {
115
- //global $wpdb;
116
- $_wpdb = $this->connection;
117
- $copy = $activeRecord;
118
- $data = array();
119
- $format = array();
120
- foreach ($this->GetColumns() as $key) {
121
-
122
- $val = $copy->$key;
123
- $deffmt = '%s';
124
- if (is_int($copy->$key)) {
125
- $deffmt = '%d';
126
- }
127
- if (is_float($copy->$key)) {
128
- $deffmt = '%f';
129
- }
130
- if (is_array($copy->$key) || is_object($copy->$key)) {
131
- $data[$key] = WSAL_Helpers_DataHelper::JsonEncode($val);
132
- } else {
133
- $data[$key] = $val;
134
- }
135
- $format[] = $deffmt;
136
- }
137
- $result = $_wpdb->replace($this->GetTable(), $data, $format);
138
-
139
- if ($result !== false) {
140
- if ($_wpdb->insert_id) {
141
- $copy->setId($_wpdb->insert_id);
142
- }
143
- }
144
- return $result;
145
- }
146
-
147
- /**
148
- * Load record from DB.
149
- * @param string $cond (Optional) Load condition.
150
- * @param array $args (Optional) Load condition arguments.
151
- */
152
- public function Load($cond = '%d', $args = array(1))
153
- {
154
- //global $wpdb;
155
- $_wpdb = $this->connection;
156
-
157
- $sql = $_wpdb->prepare('SELECT * FROM '.$this->GetTable().' WHERE '. $cond, $args);
158
- $data = $_wpdb->get_row($sql, ARRAY_A);
159
-
160
- return $data;
161
- }
162
-
163
- public function LoadArray($cond, $args = array())
164
- {
165
- //global $wpdb;
166
- $_wpdb = $this->connection;
167
- $result = array();
168
- $sql = $_wpdb->prepare('SELECT * FROM '.$this->GetTable().' WHERE '. $cond, $args);
169
- foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
170
- $result[] = $this->getModel()->LoadData($data);
171
- }
172
- return $result;
173
- }
174
-
175
- /**
176
- * Delete DB record.
177
- * @return int|boolean Either the amount of deleted rows or False on error.
178
- */
179
- public function Delete($activeRecord)
180
- {
181
- //global $wpdb;
182
- $_wpdb = $this->connection;
183
- $result = $_wpdb->delete(
184
- $this->GetTable(),
185
- $activeRecord->getId()
186
- );
187
- return $result;
188
- }
189
-
190
- /**
191
- * Delete records in DB matching a query.
192
- * @param string $query Full SQL query.
193
- * @param array $args (Optional) Query arguments.
194
- */
195
- public function DeleteQuery($query, $args = array())
196
- {
197
- $_wpdb = $this->connection;
198
- $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
199
- $result = $_wpdb->query($sql);
200
- return $result;
201
- }
202
-
203
- /**
204
- * Load multiple records from DB.
205
- * @param string $cond (Optional) Load condition (eg: 'some_id = %d' ).
206
- * @param array $args (Optional) Load condition arguments (rg: array(45) ).
207
- * @return self[] List of loaded records.
208
- */
209
- public function LoadMulti($cond, $args = array())
210
- {
211
- //global $wpdb;
212
- $_wpdb = $this->connection;
213
- $result = array();
214
- $sql = (!is_array($args) || !count($args)) // do we really need to prepare() or not?
215
- ? ($cond)
216
- : $_wpdb->prepare($cond, $args)
217
- ;
218
- foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
219
- $result[] = $this->getModel()->LoadData($data);
220
- }
221
- return $result;
222
-
223
- }
224
-
225
- /**
226
- * Load multiple records from DB and call a callback for each record.
227
- * This function is very memory-efficient, it doesn't load records in bulk.
228
- * @param callable $callback The callback to invoke.
229
- * @param string $cond (Optional) Load condition.
230
- * @param array $args (Optional) Load condition arguments.
231
- */
232
- public function LoadAndCallForEach($callback, $cond = '%d', $args = array(1))
233
- {
234
- //global $wpdb;
235
- $_wpdb = $this->connection;
236
- $class = get_called_class();
237
- $sql = $_wpdb->prepare('SELECT * FROM ' . $this->GetTable() . ' WHERE '.$cond, $args);
238
- foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
239
- call_user_func($callback, new $class($data));
240
- }
241
- }
242
-
243
- /**
244
- * Count records in the DB matching a condition.
245
- * If no parameters are given, this counts the number of records in the DB table.
246
- * @param string $cond (Optional) Query condition.
247
- * @param array $args (Optional) Condition arguments.
248
- * @return int Number of matching records.
249
- */
250
- public function Count($cond = '%d', $args = array(1))
251
- {
252
- //global $wpdb;
253
- $_wpdb = $this->connection;
254
- $class = get_called_class();
255
- $sql = $_wpdb->prepare('SELECT COUNT(*) FROM ' . $this->GetTable() . ' WHERE ' . $cond, $args);
256
- return (int)$_wpdb->get_var($sql);
257
- }
258
-
259
- /**
260
- * Count records in the DB matching a query.
261
- * @param string $query Full SQL query.
262
- * @param array $args (Optional) Query arguments.
263
- * @return int Number of matching records.
264
- */
265
- public function CountQuery($query, $args = array())
266
- {
267
- //global $wpdb;
268
- $_wpdb = $this->connection;
269
- $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
270
- return (int)$_wpdb->get_var($sql);
271
- }
272
-
273
- /**
274
- * Similar to LoadMulti but allows the use of a full SQL query.
275
- * @param string $query Full SQL query.
276
- * @param array $args (Optional) Query arguments.
277
- * @return self[] List of loaded records.
278
- */
279
- public function LoadMultiQuery($query, $args = array())
280
- {
281
- //global $wpdb;
282
- $_wpdb = $this->connection;
283
- $class = get_called_class();
284
- $result = array();
285
- $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
286
- foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
287
- $result[] = $this->getModel()->LoadData($data);
288
- }
289
- return $result;
290
- }
291
-
292
- /**
293
- * @return string Must return SQL for creating table.
294
- */
295
- protected function _GetInstallQuery($prefix = false)
296
- {
297
- $_wpdb = $this->connection;
298
-
299
- $class = get_class($this);
300
- $copy = new $class($this->connection);
301
- $table_name = ($prefix) ? $this->GetWPTable() : $this->GetTable();
302
- $sql = 'CREATE TABLE IF NOT EXISTS ' . $table_name . ' (' . PHP_EOL;
303
-
304
- foreach ($this->GetColumns() as $key) {
305
- $sql .= ' ';
306
- switch (true) {
307
- case $key == $copy->_idkey:
308
- $sql .= $key . ' BIGINT NOT NULL AUTO_INCREMENT,' . PHP_EOL;
309
- break;
310
- case is_integer($copy->$key):
311
- $sql .= $key . ' BIGINT NOT NULL,' . PHP_EOL;
312
- break;
313
- case is_float($copy->$key):
314
- $sql .= $key . ' DOUBLE NOT NULL,' . PHP_EOL;
315
- break;
316
- case is_string($copy->$key):
317
- $maxlength = $key . '_maxlength';
318
- if (property_exists($class, $maxlength)) {
319
- $sql .= $key . ' VARCHAR(' . intval($class::$$maxlength) . ') NOT NULL,' . PHP_EOL;
320
- } else {
321
- $sql .= $key . ' TEXT NOT NULL,' . PHP_EOL;
322
- }
323
- break;
324
- case is_bool($copy->$key):
325
- $sql .= $key . ' BIT NOT NULL,' . PHP_EOL;
326
- break;
327
- case is_array($copy->$key):
328
- case is_object($copy->$key):
329
- $sql .= $key . ' LONGTEXT NOT NULL,' . PHP_EOL;
330
- break;
331
- }
332
- }
333
-
334
- $sql .= $this->GetTableOptions() . PHP_EOL;
335
-
336
- $sql .= ')';
337
-
338
- if (! empty($_wpdb->charset)) {
339
- $sql .= ' DEFAULT CHARACTER SET ' . $_wpdb->charset;
340
- }
341
-
342
- return $sql;
343
-
344
- }
345
-
346
- /**
347
- * @return string Must return SQL for removing table (at a minimum, it should be ` 'DROP TABLE ' . $this->_table `).
348
- */
349
- protected function _GetUninstallQuery(){
350
- return 'DROP TABLE ' . $this->GetTable();
351
- }
352
-
353
- /**
354
- * Function used in WSAL reporting extension
355
- */
356
- public function GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp)
357
- {
358
- global $wpdb;
359
- $tableUsers = $wpdb->users;
360
- $_wpdb = $this->connection;
361
- // tables
362
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
363
- $tableMeta = $meta->GetTable(); // metadata
364
- $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
365
- $tableOcc = $occurrence->GetTable(); // occurrences
366
-
367
- $user_names = '0';
368
- if (!empty($_userId) && $_userId != "null") {
369
- $sql = 'SELECT user_login FROM '.$tableUsers.' WHERE find_in_set(ID, @userId) > 0';
370
- $wpdb->query("SET @userId = $_userId");
371
- $result = $wpdb->get_results($sql, ARRAY_A);
372
- $aUsers = array();
373
- foreach ($result as $item) {
374
- $aUsers[] = '"'.$item['user_login'].'"';
375
- }
376
- $user_names = implode(', ', $aUsers);
377
- }
378
-
379
- $sql = "SELECT DISTINCT
380
- occ.id,
381
- occ.alert_id,
382
- occ.site_id,
383
- occ.created_on,
384
- replace(replace(replace((
385
- SELECT t1.value FROM $tableMeta AS t1 WHERE t1.name = 'CurrentUserRoles' AND t1.occurrence_id = occ.id), '[', ''), ']', ''), '\\'', '') AS roles,
386
- (SELECT replace(t2.value, '\"','') FROM $tableMeta as t2 WHERE t2.name = 'ClientIP' AND t2.occurrence_id = occ.id) AS ip,
387
- (SELECT replace(t3.value, '\"', '') FROM $tableMeta as t3 WHERE t3.name = 'UserAgent' AND t3.occurrence_id = occ.id) AS ua,
388
- COALESCE(
389
- (SELECT replace(t4.value, '\"', '') FROM $tableMeta as t4 WHERE t4.name = 'Username' AND t4.occurrence_id = occ.id),
390
- (SELECT replace(t5.value, '\"', '') FROM $tableMeta as t5 WHERE t5.name = 'CurrentUserID' AND t5.occurrence_id = occ.id)
391
- ) as user_id
392
- FROM $tableOcc AS occ
393
- JOIN $tableMeta AS meta ON meta.occurrence_id = occ.id
394
- WHERE
395
- (@siteId is NULL OR find_in_set(occ.site_id, @siteId) > 0)
396
- AND (@userId is NULL OR (
397
- (meta.name = 'CurrentUserID' AND find_in_set(meta.value, @userId) > 0)
398
- OR (meta.name = 'Username' AND replace(meta.value, '\"', '') IN ($user_names))
399
- ))
400
- AND (@roleName is NULL OR (meta.name = 'CurrentUserRoles'
401
- AND replace(replace(replace(meta.value, ']', ''), '[', ''), '\\'', '') REGEXP @roleName
402
- ))
403
- AND (@alertCode is NULL OR find_in_set(occ.alert_id, @alertCode) > 0)
404
- AND (@startTimestamp is NULL OR occ.created_on >= @startTimestamp)
405
- AND (@endTimestamp is NULL OR occ.created_on <= @endTimestamp)
406
- ORDER BY
407
- site_id, created_on DESC
408
- ";
409
- $_wpdb->query("SET @siteId = $_siteId");
410
- $_wpdb->query("SET @userId = $_userId");
411
- $_wpdb->query("SET @roleName = $_roleName");
412
- $_wpdb->query("SET @alertCode = $_alertCode");
413
- $_wpdb->query("SET @startTimestamp = $_startTimestamp");
414
- $_wpdb->query("SET @endTimestamp = $_endTimestamp");
415
- $results = $_wpdb->get_results($sql);
416
-
417
- foreach ($results as $row) {
418
- $sql = "SELECT t6.ID FROM $tableUsers AS t6 WHERE t6.user_login = \"$row->user_id\"";
419
- $userId = $wpdb->get_var($sql);
420
- if ($userId == null) {
421
- $sql = "SELECT t4.ID FROM $tableUsers AS t4 WHERE t4.ID = \"$row->user_id\"";
422
- $userId = $wpdb->get_var($sql);
423
- }
424
- $row->user_id = $userId;
425
- }
426
- return $results;
427
- /*
428
- $query = <<<query
429
- SELECT DISTINCT
430
- occ.id,
431
- occ.alert_id,
432
- occ.site_id,
433
- occ.created_on,
434
- replace(replace(replace(replace((select t1.value from $tableMeta as t1 where t1.name = 'CurrentUserRoles' and t1.occurrence_id = occ.id), '[', ''), ']', ''), '"', ''), '\\'', '') as roles,
435
- (select replace(t2.value, '"','') from $tableMeta as t2 where t2.name = 'ClientIP' and t2.occurrence_id = occ.id) as ip,
436
- (select replace(t3.value, '"', '') from $tableMeta as t3 where t3.name = 'UserAgent' and t3.occurrence_id = occ.id) as ua,
437
-
438
- COALESCE(
439
- (select t6.ID from $tableUsers as t6 where t6.user_login = (select replace(t7.value, '"', '') from $tableMeta as t7 where t7.name = 'Username' and t7.occurrence_id = occ.id)),
440
- (select t4.ID from $tableUsers as t4 where t4.ID = (select t5.value from $tableMeta as t5 where t5.name = 'CurrentUserID' and t5.occurrence_id = occ.id))
441
- ) as user_id
442
- FROM
443
- $tableOcc as occ
444
- JOIN
445
- $tableMeta as meta on meta.occurrence_id = occ.id
446
- WHERE
447
- (@siteId is null or find_in_set(occ.site_id, @siteId) > 0)
448
- and (@userId is null or (
449
- (meta.name = 'CurrentUserID' and find_in_set(meta.value, @userId) > 0)
450
- or (meta.name = 'Username' and replace(meta.value, '"', '') in (select user_login from $tableUsers where find_in_set(ID, @userId) > 0))
451
- ))
452
- and (@roleName is null or (meta.name = 'CurrentUserRoles'
453
- and replace(replace(replace(replace(meta.value, '"', ''), ']', ''), '[', ''), '\\'', '') REGEXP @roleName
454
- ))
455
- and (@alertCode is null or find_in_set(occ.alert_id, @alertCode) > 0)
456
- and (@startTimestamp is null or occ.created_on >= @startTimestamp)
457
- and (@endTimestamp is null or occ.created_on <= @endTimestamp)
458
- order by
459
- site_id, created_on DESC;
460
- query;
461
- //#! Set variables first
462
- $_wpdb->query("SET @siteId = $_siteId");
463
- $_wpdb->query("SET @userId = $_userId");
464
- $_wpdb->query("SET @roleName = $_roleName");
465
- $_wpdb->query("SET @alertCode = $_alertCode");
466
- $_wpdb->query("SET @startTimestamp = $_startTimestamp");
467
- $_wpdb->query("SET @endTimestamp = $_endTimestamp");
468
-
469
- //#! Then run query
470
- return $_wpdb->get_results($query);
471
- */
472
- }
473
-
474
- }
1
+ <?php
2
+
3
+ class WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_ActiveRecordInterface {
4
+
5
+ protected $connection;
6
+
7
+ /**
8
+ * Contains the table name
9
+ * @var string
10
+ */
11
+ protected $_table;
12
+
13
+ /**
14
+ * Contains primary key column name, override as required.
15
+ * @var string
16
+ */
17
+ protected $_idkey = '';
18
+
19
+ public function __construct($conn)
20
+ {
21
+ $this->connection = $conn;
22
+ }
23
+
24
+ public function GetModel()
25
+ {
26
+ return new WSAL_Models_ActiveRecord();
27
+ }
28
+
29
+ /**
30
+ * @return string Returns table name.
31
+ */
32
+ public function GetTable()
33
+ {
34
+ $_wpdb = $this->connection;
35
+ return $_wpdb->base_prefix . $this->_table;
36
+ }
37
+
38
+ /**
39
+ * Used for WordPress prefix
40
+ * @return string Returns table name of WordPress.
41
+ */
42
+ public function GetWPTable()
43
+ {
44
+ global $wpdb;
45
+ return $wpdb->base_prefix . $this->_table;
46
+ }
47
+
48
+ /**
49
+ * @return string SQL table options (constraints, foreign keys, indexes etc).
50
+ */
51
+ protected function GetTableOptions()
52
+ {
53
+ return ' PRIMARY KEY (' . $this->_idkey . ')';
54
+ }
55
+
56
+ /**
57
+ * @return array Returns this records' columns.
58
+ */
59
+ public function GetColumns()
60
+ {
61
+ $model = $this->GetModel();
62
+
63
+ if(!isset($this->_column_cache)){
64
+ $this->_column_cache = array();
65
+ foreach(array_keys(get_object_vars($model)) as $col)
66
+ if(trim($col) && $col[0] != '_')
67
+ $this->_column_cache[] = $col;
68
+ }
69
+ return $this->_column_cache;
70
+ }
71
+
72
+ /**
73
+ * @deprecated
74
+ * @return boolean Returns whether table structure is installed or not.
75
+ */
76
+ public function IsInstalled(){
77
+ //global $wpdb;
78
+ $_wpdb = $this->connection;
79
+ $sql = 'SHOW TABLES LIKE "' . $this->GetTable() . '"';
80
+ return strtolower($_wpdb->get_var($sql)) == strtolower($this->GetTable());
81
+ }
82
+
83
+ /**
84
+ * Install this ActiveRecord structure into DB.
85
+ */
86
+ public function Install(){
87
+ $_wpdb = $this->connection;
88
+ $_wpdb->query($this->_GetInstallQuery());
89
+ }
90
+
91
+ /**
92
+ * Install this ActiveRecord structure into DB WordPress.
93
+ */
94
+ public function InstallOriginal(){
95
+ global $wpdb;
96
+ $wpdb->query($this->_GetInstallQuery(true));
97
+ }
98
+
99
+ /**
100
+ * Remove this ActiveRecord structure into DB.
101
+ */
102
+ public function Uninstall()
103
+ {
104
+ //global $wpdb;
105
+ $_wpdb = $this->connection;
106
+ $_wpdb->query($this->_GetUninstallQuery());
107
+ }
108
+
109
+ /**
110
+ * Save an active record to DB.
111
+ * @return integer|boolean Either the number of modified/inserted rows or false on failure.
112
+ */
113
+ public function Save($activeRecord)
114
+ {
115
+ //global $wpdb;
116
+ $_wpdb = $this->connection;
117
+ $copy = $activeRecord;
118
+ $data = array();
119
+ $format = array();
120
+ foreach ($this->GetColumns() as $key) {
121
+
122
+ $val = $copy->$key;
123
+ $deffmt = '%s';
124
+ if (is_int($copy->$key)) {
125
+ $deffmt = '%d';
126
+ }
127
+ if (is_float($copy->$key)) {
128
+ $deffmt = '%f';
129
+ }
130
+ if (is_array($copy->$key) || is_object($copy->$key)) {
131
+ $data[$key] = WSAL_Helpers_DataHelper::JsonEncode($val);
132
+ } else {
133
+ $data[$key] = $val;
134
+ }
135
+ $format[] = $deffmt;
136
+ }
137
+ $result = $_wpdb->replace($this->GetTable(), $data, $format);
138
+
139
+ if ($result !== false) {
140
+ if ($_wpdb->insert_id) {
141
+ $copy->setId($_wpdb->insert_id);
142
+ }
143
+ }
144
+ return $result;
145
+ }
146
+
147
+ /**
148
+ * Load record from DB.
149
+ * @param string $cond (Optional) Load condition.
150
+ * @param array $args (Optional) Load condition arguments.
151
+ */
152
+ public function Load($cond = '%d', $args = array(1))
153
+ {
154
+ //global $wpdb;
155
+ $_wpdb = $this->connection;
156
+
157
+ $sql = $_wpdb->prepare('SELECT * FROM '.$this->GetTable().' WHERE '. $cond, $args);
158
+ $data = $_wpdb->get_row($sql, ARRAY_A);
159
+
160
+ return $data;
161
+ }
162
+
163
+ public function LoadArray($cond, $args = array())
164
+ {
165
+ //global $wpdb;
166
+ $_wpdb = $this->connection;
167
+ $result = array();
168
+ $sql = $_wpdb->prepare('SELECT * FROM '.$this->GetTable().' WHERE '. $cond, $args);
169
+ foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
170
+ $result[] = $this->getModel()->LoadData($data);
171
+ }
172
+ return $result;
173
+ }
174
+
175
+ /**
176
+ * Delete DB record.
177
+ * @return int|boolean Either the amount of deleted rows or False on error.
178
+ */
179
+ public function Delete($activeRecord)
180
+ {
181
+ //global $wpdb;
182
+ $_wpdb = $this->connection;
183
+ $result = $_wpdb->delete(
184
+ $this->GetTable(),
185
+ $activeRecord->getId()
186
+ );
187
+ return $result;
188
+ }
189
+
190
+ /**
191
+ * Delete records in DB matching a query.
192
+ * @param string $query Full SQL query.
193
+ * @param array $args (Optional) Query arguments.
194
+ */
195
+ public function DeleteQuery($query, $args = array())
196
+ {
197
+ $_wpdb = $this->connection;
198
+ $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
199
+ $result = $_wpdb->query($sql);
200
+ return $result;
201
+ }
202
+
203
+ /**
204
+ * Load multiple records from DB.
205
+ * @param string $cond (Optional) Load condition (eg: 'some_id = %d' ).
206
+ * @param array $args (Optional) Load condition arguments (rg: array(45) ).
207
+ * @return self[] List of loaded records.
208
+ */
209
+ public function LoadMulti($cond, $args = array())
210
+ {
211
+ //global $wpdb;
212
+ $_wpdb = $this->connection;
213
+ $result = array();
214
+ $sql = (!is_array($args) || !count($args)) // do we really need to prepare() or not?
215
+ ? ($cond)
216
+ : $_wpdb->prepare($cond, $args)
217
+ ;
218
+ foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
219
+ $result[] = $this->getModel()->LoadData($data);
220
+ }
221
+ return $result;
222
+
223
+ }
224
+
225
+ /**
226
+ * Load multiple records from DB and call a callback for each record.
227
+ * This function is very memory-efficient, it doesn't load records in bulk.
228
+ * @param callable $callback The callback to invoke.
229
+ * @param string $cond (Optional) Load condition.
230
+ * @param array $args (Optional) Load condition arguments.
231
+ */
232
+ public function LoadAndCallForEach($callback, $cond = '%d', $args = array(1))
233
+ {
234
+ //global $wpdb;
235
+ $_wpdb = $this->connection;
236
+ $class = get_called_class();
237
+ $sql = $_wpdb->prepare('SELECT * FROM ' . $this->GetTable() . ' WHERE '.$cond, $args);
238
+ foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
239
+ call_user_func($callback, new $class($data));
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Count records in the DB matching a condition.
245
+ * If no parameters are given, this counts the number of records in the DB table.
246
+ * @param string $cond (Optional) Query condition.
247
+ * @param array $args (Optional) Condition arguments.
248
+ * @return int Number of matching records.
249
+ */
250
+ public function Count($cond = '%d', $args = array(1))
251
+ {
252
+ //global $wpdb;
253
+ $_wpdb = $this->connection;
254
+ $class = get_called_class();
255
+ $sql = $_wpdb->prepare('SELECT COUNT(*) FROM ' . $this->GetTable() . ' WHERE ' . $cond, $args);
256
+ return (int)$_wpdb->get_var($sql);
257
+ }
258
+
259
+ /**
260
+ * Count records in the DB matching a query.
261
+ * @param string $query Full SQL query.
262
+ * @param array $args (Optional) Query arguments.
263
+ * @return int Number of matching records.
264
+ */
265
+ public function CountQuery($query, $args = array())
266
+ {
267
+ //global $wpdb;
268
+ $_wpdb = $this->connection;
269
+ $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
270
+ return (int)$_wpdb->get_var($sql);
271
+ }
272
+
273
+ /**
274
+ * Similar to LoadMulti but allows the use of a full SQL query.
275
+ * @param string $query Full SQL query.
276
+ * @param array $args (Optional) Query arguments.
277
+ * @return self[] List of loaded records.
278
+ */
279
+ public function LoadMultiQuery($query, $args = array())
280
+ {
281
+ //global $wpdb;
282
+ $_wpdb = $this->connection;
283
+ $class = get_called_class();
284
+ $result = array();
285
+ $sql = count($args) ? $_wpdb->prepare($query, $args) : $query;
286
+ foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
287
+ $result[] = $this->getModel()->LoadData($data);
288
+ }
289
+ return $result;
290
+ }
291
+
292
+ /**
293
+ * @return string Must return SQL for creating table.
294
+ */
295
+ protected function _GetInstallQuery($prefix = false)
296
+ {
297
+ $_wpdb = $this->connection;
298
+
299
+ $class = get_class($this);
300
+ $copy = new $class($this->connection);
301
+ $table_name = ($prefix) ? $this->GetWPTable() : $this->GetTable();
302
+ $sql = 'CREATE TABLE IF NOT EXISTS ' . $table_name . ' (' . PHP_EOL;
303
+
304
+ foreach ($this->GetColumns() as $key) {
305
+ $sql .= ' ';
306
+ switch (true) {
307
+ case $key == $copy->_idkey:
308
+ $sql .= $key . ' BIGINT NOT NULL AUTO_INCREMENT,' . PHP_EOL;
309
+ break;
310
+ case is_integer($copy->$key):
311
+ $sql .= $key . ' BIGINT NOT NULL,' . PHP_EOL;
312
+ break;
313
+ case is_float($copy->$key):
314
+ $sql .= $key . ' DOUBLE NOT NULL,' . PHP_EOL;
315
+ break;
316
+ case is_string($copy->$key):
317
+ $maxlength = $key . '_maxlength';
318
+ if (property_exists($class, $maxlength)) {
319
+ $sql .= $key . ' VARCHAR(' . intval($class::$$maxlength) . ') NOT NULL,' . PHP_EOL;
320
+ } else {
321
+ $sql .= $key . ' TEXT NOT NULL,' . PHP_EOL;
322
+ }
323
+ break;
324
+ case is_bool($copy->$key):
325
+ $sql .= $key . ' BIT NOT NULL,' . PHP_EOL;
326
+ break;
327
+ case is_array($copy->$key):
328
+ case is_object($copy->$key):
329
+ $sql .= $key . ' LONGTEXT NOT NULL,' . PHP_EOL;
330
+ break;
331
+ }
332
+ }
333
+
334
+ $sql .= $this->GetTableOptions() . PHP_EOL;
335
+
336
+ $sql .= ')';
337
+
338
+ if (! empty($_wpdb->charset)) {
339
+ $sql .= ' DEFAULT CHARACTER SET ' . $_wpdb->charset;
340
+ }
341
+
342
+ return $sql;
343
+
344
+ }
345
+
346
+ /**
347
+ * @return string Must return SQL for removing table (at a minimum, it should be ` 'DROP TABLE ' . $this->_table `).
348
+ */
349
+ protected function _GetUninstallQuery(){
350
+ return 'DROP TABLE ' . $this->GetTable();
351
+ }
352
+
353
+ /**
354
+ * Function used in WSAL reporting extension
355
+ */
356
+ public function GetReporting($_siteId, $_userId, $_roleName, $_alertCode, $_startTimestamp, $_endTimestamp)
357
+ {
358
+ global $wpdb;
359
+ $tableUsers = $wpdb->users;
360
+ $_wpdb = $this->connection;
361
+ // tables
362
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
363
+ $tableMeta = $meta->GetTable(); // metadata
364
+ $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
365
+ $tableOcc = $occurrence->GetTable(); // occurrences
366
+
367
+ $user_names = '0';
368
+ if (!empty($_userId) && $_userId != "null") {
369
+ $sql = 'SELECT user_login FROM '.$tableUsers.' WHERE find_in_set(ID, @userId) > 0';
370
+ $wpdb->query("SET @userId = $_userId");
371
+ $result = $wpdb->get_results($sql, ARRAY_A);
372
+ $aUsers = array();
373
+ foreach ($result as $item) {
374
+ $aUsers[] = '"'.$item['user_login'].'"';
375
+ }
376
+ $user_names = implode(', ', $aUsers);
377
+ }
378
+
379
+ $sql = "SELECT DISTINCT
380
+ occ.id,
381
+ occ.alert_id,
382
+ occ.site_id,
383
+ occ.created_on,
384
+ replace(replace(replace((
385
+ SELECT t1.value FROM $tableMeta AS t1 WHERE t1.name = 'CurrentUserRoles' AND t1.occurrence_id = occ.id), '[', ''), ']', ''), '\\'', '') AS roles,
386
+ (SELECT replace(t2.value, '\"','') FROM $tableMeta as t2 WHERE t2.name = 'ClientIP' AND t2.occurrence_id = occ.id) AS ip,
387
+ (SELECT replace(t3.value, '\"', '') FROM $tableMeta as t3 WHERE t3.name = 'UserAgent' AND t3.occurrence_id = occ.id) AS ua,
388
+ COALESCE(
389
+ (SELECT replace(t4.value, '\"', '') FROM $tableMeta as t4 WHERE t4.name = 'Username' AND t4.occurrence_id = occ.id),
390
+ (SELECT replace(t5.value, '\"', '') FROM $tableMeta as t5 WHERE t5.name = 'CurrentUserID' AND t5.occurrence_id = occ.id)
391
+ ) as user_id
392
+ FROM $tableOcc AS occ
393
+ JOIN $tableMeta AS meta ON meta.occurrence_id = occ.id
394
+ WHERE
395
+ (@siteId is NULL OR find_in_set(occ.site_id, @siteId) > 0)
396
+ AND (@userId is NULL OR (
397
+ (meta.name = 'CurrentUserID' AND find_in_set(meta.value, @userId) > 0)
398
+ OR (meta.name = 'Username' AND replace(meta.value, '\"', '') IN ($user_names))
399
+ ))
400
+ AND (@roleName is NULL OR (meta.name = 'CurrentUserRoles'
401
+ AND replace(replace(replace(meta.value, ']', ''), '[', ''), '\\'', '') REGEXP @roleName
402
+ ))
403
+ AND (@alertCode is NULL OR find_in_set(occ.alert_id, @alertCode) > 0)
404
+ AND (@startTimestamp is NULL OR occ.created_on >= @startTimestamp)
405
+ AND (@endTimestamp is NULL OR occ.created_on <= @endTimestamp)
406
+ ORDER BY
407
+ site_id, created_on DESC
408
+ ";
409
+ $_wpdb->query("SET @siteId = $_siteId");
410
+ $_wpdb->query("SET @userId = $_userId");
411
+ $_wpdb->query("SET @roleName = $_roleName");
412
+ $_wpdb->query("SET @alertCode = $_alertCode");
413
+ $_wpdb->query("SET @startTimestamp = $_startTimestamp");
414
+ $_wpdb->query("SET @endTimestamp = $_endTimestamp");
415
+ $results = $_wpdb->get_results($sql);
416
+
417
+ foreach ($results as $row) {
418
+ $sql = "SELECT t6.ID FROM $tableUsers AS t6 WHERE t6.user_login = \"$row->user_id\"";
419
+ $userId = $wpdb->get_var($sql);
420
+ if ($userId == null) {
421
+ $sql = "SELECT t4.ID FROM $tableUsers AS t4 WHERE t4.ID = \"$row->user_id\"";
422
+ $userId = $wpdb->get_var($sql);
423
+ }
424
+ $row->user_id = $userId;
425
+ }
426
+ return $results;
427
+ /*
428
+ $query = <<<query
429
+ SELECT DISTINCT
430
+ occ.id,
431
+ occ.alert_id,
432
+ occ.site_id,
433
+ occ.created_on,
434
+ replace(replace(replace(replace((select t1.value from $tableMeta as t1 where t1.name = 'CurrentUserRoles' and t1.occurrence_id = occ.id), '[', ''), ']', ''), '"', ''), '\\'', '') as roles,
435
+ (select replace(t2.value, '"','') from $tableMeta as t2 where t2.name = 'ClientIP' and t2.occurrence_id = occ.id) as ip,
436
+ (select replace(t3.value, '"', '') from $tableMeta as t3 where t3.name = 'UserAgent' and t3.occurrence_id = occ.id) as ua,
437
+
438
+ COALESCE(
439
+ (select t6.ID from $tableUsers as t6 where t6.user_login = (select replace(t7.value, '"', '') from $tableMeta as t7 where t7.name = 'Username' and t7.occurrence_id = occ.id)),
440
+ (select t4.ID from $tableUsers as t4 where t4.ID = (select t5.value from $tableMeta as t5 where t5.name = 'CurrentUserID' and t5.occurrence_id = occ.id))
441
+ ) as user_id
442
+ FROM
443
+ $tableOcc as occ
444
+ JOIN
445
+ $tableMeta as meta on meta.occurrence_id = occ.id
446
+ WHERE
447
+ (@siteId is null or find_in_set(occ.site_id, @siteId) > 0)
448
+ and (@userId is null or (
449
+ (meta.name = 'CurrentUserID' and find_in_set(meta.value, @userId) > 0)
450
+ or (meta.name = 'Username' and replace(meta.value, '"', '') in (select user_login from $tableUsers where find_in_set(ID, @userId) > 0))
451
+ ))
452
+ and (@roleName is null or (meta.name = 'CurrentUserRoles'
453
+ and replace(replace(replace(replace(meta.value, '"', ''), ']', ''), '[', ''), '\\'', '') REGEXP @roleName
454
+ ))
455
+ and (@alertCode is null or find_in_set(occ.alert_id, @alertCode) > 0)
456
+ and (@startTimestamp is null or occ.created_on >= @startTimestamp)
457
+ and (@endTimestamp is null or occ.created_on <= @endTimestamp)
458
+ order by
459
+ site_id, created_on DESC;
460
+ query;
461
+ //#! Set variables first
462
+ $_wpdb->query("SET @siteId = $_siteId");
463
+ $_wpdb->query("SET @userId = $_userId");
464
+ $_wpdb->query("SET @roleName = $_roleName");
465
+ $_wpdb->query("SET @alertCode = $_alertCode");
466
+ $_wpdb->query("SET @startTimestamp = $_startTimestamp");
467
+ $_wpdb->query("SET @endTimestamp = $_endTimestamp");
468
+
469
+ //#! Then run query
470
+ return $_wpdb->get_results($query);
471
+ */
472
+ }
473
+
474
+ }
classes/Models/Adapters/MySQL/MetaAdapter.php CHANGED
@@ -1,53 +1,53 @@
1
- <?php
2
-
3
- class WSAL_Adapters_MySQL_Meta extends WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_MetaInterface {
4
-
5
- protected $_table = 'wsal_metadata';
6
- protected $_idkey = 'id';
7
-
8
- public $id = 0;
9
- public $occurrence_id = 0;
10
- public $name = '';
11
- public static $name_maxlength = 100;
12
- public $value = array(); // force mixed type
13
-
14
- public function GetModel()
15
- {
16
- return new WSAL_Models_Meta();
17
- }
18
-
19
- public function __construct($conn)
20
- {
21
- parent::__construct($conn);
22
- }
23
-
24
- protected function GetTableOptions(){
25
- return parent::GetTableOptions() . ',' . PHP_EOL
26
- . ' KEY occurrence_name (occurrence_id,name)';
27
- }
28
-
29
- public function DeleteByOccurenceIds($occurenceIds)
30
- {
31
- if (!empty($occurenceIds)) {
32
- $sql = 'DELETE FROM ' . $this->GetTable() . ' WHERE occurrence_id IN (' . implode(',', $occurenceIds) . ')';
33
- // execute query
34
- parent::DeleteQuery($sql);
35
- }
36
- }
37
-
38
- public function LoadByNameAndOccurenceId($metaName, $occurenceId)
39
- {
40
- return $this->Load('occurrence_id = %d AND name = %s', array($occurenceId, $metaName));
41
- }
42
-
43
- public function GetMatchingIPs()
44
- {
45
- $_wpdb = $this->connection;
46
- $ips = $_wpdb->get_col("SELECT DISTINCT value FROM {$this->GetTable()} WHERE name = \"ClientIP\"");
47
- foreach ($ips as $key => $ip) {
48
- $ips[$key] = str_replace('"', '', $ip);
49
- }
50
- return array_unique($ips);
51
- }
52
-
53
- }
1
+ <?php
2
+
3
+ class WSAL_Adapters_MySQL_Meta extends WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_MetaInterface {
4
+
5
+ protected $_table = 'wsal_metadata';
6
+ protected $_idkey = 'id';
7
+
8
+ public $id = 0;
9
+ public $occurrence_id = 0;
10
+ public $name = '';
11
+ public static $name_maxlength = 100;
12
+ public $value = array(); // force mixed type
13
+
14
+ public function GetModel()
15
+ {
16
+ return new WSAL_Models_Meta();
17
+ }
18
+
19
+ public function __construct($conn)
20
+ {
21
+ parent::__construct($conn);
22
+ }
23
+
24
+ protected function GetTableOptions(){
25
+ return parent::GetTableOptions() . ',' . PHP_EOL
26
+ . ' KEY occurrence_name (occurrence_id,name)';
27
+ }
28
+
29
+ public function DeleteByOccurenceIds($occurenceIds)
30
+ {
31
+ if (!empty($occurenceIds)) {
32
+ $sql = 'DELETE FROM ' . $this->GetTable() . ' WHERE occurrence_id IN (' . implode(',', $occurenceIds) . ')';
33
+ // execute query
34
+ parent::DeleteQuery($sql);
35
+ }
36
+ }
37
+
38
+ public function LoadByNameAndOccurenceId($metaName, $occurenceId)
39
+ {
40
+ return $this->Load('occurrence_id = %d AND name = %s', array($occurenceId, $metaName));
41
+ }
42
+
43
+ public function GetMatchingIPs()
44
+ {
45
+ $_wpdb = $this->connection;
46
+ $ips = $_wpdb->get_col("SELECT DISTINCT value FROM {$this->GetTable()} WHERE name = \"ClientIP\"");
47
+ foreach ($ips as $key => $ip) {
48
+ $ips[$key] = str_replace('"', '', $ip);
49
+ }
50
+ return array_unique($ips);
51
+ }
52
+
53
+ }
classes/Models/Adapters/MySQL/OccurrenceAdapter.php CHANGED
@@ -1,170 +1,170 @@
1
- <?php
2
-
3
- class WSAL_Adapters_MySQL_Occurrence extends WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_OccurrenceInterface {
4
-
5
- protected $_table = 'wsal_occurrences';
6
- protected $_idkey = 'id';
7
- protected $_meta;
8
-
9
- public $id = 0;
10
- public $site_id = 0;
11
- public $alert_id = 0;
12
- public $created_on = 0.0;
13
- public $is_read = false;
14
- public $is_migrated = false;
15
-
16
- public function __construct($conn) {
17
- parent::__construct($conn);
18
- }
19
-
20
- protected function GetTableOptions(){
21
- return parent::GetTableOptions() . ',' . PHP_EOL
22
- . ' KEY site_alert_created (site_id,alert_id,created_on)';
23
- }
24
-
25
- public function GetModel()
26
- {
27
- return new WSAL_Models_Occurrence();
28
- }
29
- /**
30
- * Returns all meta data related to this event.
31
- * @return WSAL_Meta[]
32
- */
33
- public function GetMeta($occurence){
34
- if(!isset($this->_meta)){
35
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
36
- $this->_meta = $meta->Load('occurrence_id = %d', array($occurence->id));
37
- }
38
- return $this->_meta;
39
- }
40
-
41
- public function GetMultiMeta($occurence){
42
- if(!isset($this->_meta)){
43
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
44
- $this->_meta = $meta->LoadArray('occurrence_id = %d', array($occurence->id));
45
- }
46
- return $this->_meta;
47
- }
48
-
49
- /**
50
- * Loads a meta item given its name.
51
- * @param string $name Meta name.
52
- * @return WSAL_Meta The meta item, be sure to checked if it was loaded successfully.
53
- */
54
- public function GetNamedMeta($occurence, $name){
55
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
56
- $this->_meta = $meta->Load('occurrence_id = %d AND name = %s', array($occurence->id, $name));
57
-
58
- return $this->_meta;
59
- }
60
-
61
- /**
62
- * Returns the first meta value from a given set of names. Useful when you have a mix of items that could provide a particular detail.
63
- * @param array $names List of meta names.
64
- * @return WSAL_Meta The first meta item that exists.
65
- */
66
- public function GetFirstNamedMeta($occurence, $names){
67
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
68
- $query = '(' . str_repeat('name = %s OR ', count($names)).'0)';
69
- $query = 'occurrence_id = %d AND ' . $query . ' ORDER BY name DESC LIMIT 1';
70
- array_unshift($names, $occurence->id); // prepend args with occurrence id
71
-
72
- $this->_meta = $meta->Load($query, $names);
73
- return $meta->getModel()->LoadData($this->_meta);
74
-
75
- //TO DO: Do we want to reintroduce is loaded check/logic?
76
- //return $meta->IsLoaded() ? $meta : null;
77
- }
78
-
79
- /**
80
- * Returns newest unique occurrences.
81
- * @param integer $limit Maximum limit.
82
- * @return WSAL_Occurrence[]
83
- */
84
- public static function GetNewestUnique($limit = PHP_INT_MAX){
85
- $temp = new self();
86
- return self::LoadMultiQuery('
87
- SELECT *, COUNT(alert_id) as count
88
- FROM (
89
- SELECT *
90
- FROM ' . $temp->GetTable() . '
91
- ORDER BY created_on DESC
92
- ) AS temp_table
93
- GROUP BY alert_id
94
- LIMIT %d
95
- ', array($limit));
96
- }
97
-
98
- /**
99
- * Gets occurences of the same type by IP and Username within specified time frame
100
- * @param string $ipAddress
101
- * @param string $username
102
- * @param int $alertId Alert type we are lookign for
103
- * @param int $siteId
104
- * @param $startTime mktime
105
- * @param $endTime mktime
106
- */
107
- public function CheckKnownUsers($args = array())
108
- {
109
- $tt2 = new WSAL_Adapters_MySQL_Meta($this->connection);
110
- return self::LoadMultiQuery(
111
- 'SELECT occurrence.* FROM `' . $this->GetTable() . '` occurrence
112
- INNER JOIN `' . $tt2->GetTable() . '` ipMeta on ipMeta.occurrence_id = occurrence.id
113
- and ipMeta.name = "ClientIP"
114
- and ipMeta.value = %s
115
- INNER JOIN `' . $tt2->GetTable() . '` usernameMeta on usernameMeta.occurrence_id = occurrence.id
116
- and usernameMeta.name = "Username"
117
- and usernameMeta.value = %s
118
- WHERE occurrence.alert_id = %d AND occurrence.site_id = %d
119
- AND (created_on BETWEEN %d AND %d)
120
- GROUP BY occurrence.id',
121
- $args
122
- );
123
- }
124
-
125
- public function CheckUnKnownUsers($args = array())
126
- {
127
- $tt2 = new WSAL_Adapters_MySQL_Meta($this->connection);
128
- return self::LoadMultiQuery('
129
- SELECT occurrence.* FROM `' . $this->GetTable() . '` occurrence
130
- INNER JOIN `' . $tt2->GetTable() . '` ipMeta on ipMeta.occurrence_id = occurrence.id
131
- and ipMeta.name = "ClientIP" and ipMeta.value = %s
132
- WHERE occurrence.alert_id = %d AND occurrence.site_id = %d
133
- AND (created_on BETWEEN %d AND %d)
134
- GROUP BY occurrence.id',
135
- $args
136
- );
137
- }
138
-
139
- protected function prepareOccurrenceQuery($query)
140
- {
141
- $searchQueryParameters = array();
142
- $searchConditions = array();
143
- $conditions = $query->getConditions();
144
-
145
- //BUG: not all conditions are occurence related. maybe it's just a field site_id. need seperate arrays
146
- if (!empty($conditions)) {
147
- $tmp = new WSAL_Adapters_MySQL_Meta($this->connection);
148
- $sWhereClause = "";
149
- foreach ($conditions as $field => $value) {
150
- if (!empty($sWhereClause)) {
151
- $sWhereClause .= " AND ";
152
- }
153
- $sWhereClause .= "name = %s AND value = %s";
154
- $searchQueryParameters[] = $field;
155
- $searchQueryParameters[] = $value;
156
- }
157
-
158
- $searchConditions[] = 'id IN (
159
- SELECT DISTINCT occurrence_id
160
- FROM ' . $tmp->GetTable() . '
161
- WHERE ' . $sWhereClause . '
162
- )';
163
- }
164
-
165
- //do something with search query parameters and search conditions - give them to the query adapter?
166
- return $searchConditions;
167
- }
168
-
169
-
170
- }
1
+ <?php
2
+
3
+ class WSAL_Adapters_MySQL_Occurrence extends WSAL_Adapters_MySQL_ActiveRecord implements WSAL_Adapters_OccurrenceInterface {
4
+
5
+ protected $_table = 'wsal_occurrences';
6
+ protected $_idkey = 'id';
7
+ protected $_meta;
8
+
9
+ public $id = 0;
10
+ public $site_id = 0;
11
+ public $alert_id = 0;
12
+ public $created_on = 0.0;
13
+ public $is_read = false;
14
+ public $is_migrated = false;
15
+
16
+ public function __construct($conn) {
17
+ parent::__construct($conn);
18
+ }
19
+
20
+ protected function GetTableOptions(){
21
+ return parent::GetTableOptions() . ',' . PHP_EOL
22
+ . ' KEY site_alert_created (site_id,alert_id,created_on)';
23
+ }
24
+
25
+ public function GetModel()
26
+ {
27
+ return new WSAL_Models_Occurrence();
28
+ }
29
+ /**
30
+ * Returns all meta data related to this event.
31
+ * @return WSAL_Meta[]
32
+ */
33
+ public function GetMeta($occurence){
34
+ if(!isset($this->_meta)){
35
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
36
+ $this->_meta = $meta->Load('occurrence_id = %d', array($occurence->id));
37
+ }
38
+ return $this->_meta;
39
+ }
40
+
41
+ public function GetMultiMeta($occurence){
42
+ if(!isset($this->_meta)){
43
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
44
+ $this->_meta = $meta->LoadArray('occurrence_id = %d', array($occurence->id));
45
+ }
46
+ return $this->_meta;
47
+ }
48
+
49
+ /**
50
+ * Loads a meta item given its name.
51
+ * @param string $name Meta name.
52
+ * @return WSAL_Meta The meta item, be sure to checked if it was loaded successfully.
53
+ */
54
+ public function GetNamedMeta($occurence, $name){
55
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
56
+ $this->_meta = $meta->Load('occurrence_id = %d AND name = %s', array($occurence->id, $name));
57
+
58
+ return $this->_meta;
59
+ }
60
+
61
+ /**
62
+ * Returns the first meta value from a given set of names. Useful when you have a mix of items that could provide a particular detail.
63
+ * @param array $names List of meta names.
64
+ * @return WSAL_Meta The first meta item that exists.
65
+ */
66
+ public function GetFirstNamedMeta($occurence, $names){
67
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
68
+ $query = '(' . str_repeat('name = %s OR ', count($names)).'0)';
69
+ $query = 'occurrence_id = %d AND ' . $query . ' ORDER BY name DESC LIMIT 1';
70
+ array_unshift($names, $occurence->id); // prepend args with occurrence id
71
+
72
+ $this->_meta = $meta->Load($query, $names);
73
+ return $meta->getModel()->LoadData($this->_meta);
74
+
75
+ //TO DO: Do we want to reintroduce is loaded check/logic?
76
+ //return $meta->IsLoaded() ? $meta : null;
77
+ }
78
+
79
+ /**
80
+ * Returns newest unique occurrences.
81
+ * @param integer $limit Maximum limit.
82
+ * @return WSAL_Occurrence[]
83
+ */
84
+ public static function GetNewestUnique($limit = PHP_INT_MAX){
85
+ $temp = new self();
86
+ return self::LoadMultiQuery('
87
+ SELECT *, COUNT(alert_id) as count
88
+ FROM (
89
+ SELECT *
90
+ FROM ' . $temp->GetTable() . '
91
+ ORDER BY created_on DESC
92
+ ) AS temp_table
93
+ GROUP BY alert_id
94
+ LIMIT %d
95
+ ', array($limit));
96
+ }
97
+
98
+ /**
99
+ * Gets occurences of the same type by IP and Username within specified time frame
100
+ * @param string $ipAddress
101
+ * @param string $username
102
+ * @param int $alertId Alert type we are lookign for
103
+ * @param int $siteId
104
+ * @param $startTime mktime
105
+ * @param $endTime mktime
106
+ */
107
+ public function CheckKnownUsers($args = array())
108
+ {
109
+ $tt2 = new WSAL_Adapters_MySQL_Meta($this->connection);
110
+ return self::LoadMultiQuery(
111
+ 'SELECT occurrence.* FROM `' . $this->GetTable() . '` occurrence
112
+ INNER JOIN `' . $tt2->GetTable() . '` ipMeta on ipMeta.occurrence_id = occurrence.id
113
+ and ipMeta.name = "ClientIP"
114
+ and ipMeta.value = %s
115
+ INNER JOIN `' . $tt2->GetTable() . '` usernameMeta on usernameMeta.occurrence_id = occurrence.id
116
+ and usernameMeta.name = "Username"
117
+ and usernameMeta.value = %s
118
+ WHERE occurrence.alert_id = %d AND occurrence.site_id = %d
119
+ AND (created_on BETWEEN %d AND %d)
120
+ GROUP BY occurrence.id',
121
+ $args
122
+ );
123
+ }
124
+
125
+ public function CheckUnKnownUsers($args = array())
126
+ {
127
+ $tt2 = new WSAL_Adapters_MySQL_Meta($this->connection);
128
+ return self::LoadMultiQuery('
129
+ SELECT occurrence.* FROM `' . $this->GetTable() . '` occurrence
130
+ INNER JOIN `' . $tt2->GetTable() . '` ipMeta on ipMeta.occurrence_id = occurrence.id
131
+ and ipMeta.name = "ClientIP" and ipMeta.value = %s
132
+ WHERE occurrence.alert_id = %d AND occurrence.site_id = %d
133
+ AND (created_on BETWEEN %d AND %d)
134
+ GROUP BY occurrence.id',
135
+ $args
136
+ );
137
+ }
138
+
139
+ protected function prepareOccurrenceQuery($query)
140
+ {
141
+ $searchQueryParameters = array();
142
+ $searchConditions = array();
143
+ $conditions = $query->getConditions();
144
+
145
+ //BUG: not all conditions are occurence related. maybe it's just a field site_id. need seperate arrays
146
+ if (!empty($conditions)) {
147
+ $tmp = new WSAL_Adapters_MySQL_Meta($this->connection);
148
+ $sWhereClause = "";
149
+ foreach ($conditions as $field => $value) {
150
+ if (!empty($sWhereClause)) {
151
+ $sWhereClause .= " AND ";
152
+ }
153
+ $sWhereClause .= "name = %s AND value = %s";
154
+ $searchQueryParameters[] = $field;
155
+ $searchQueryParameters[] = $value;
156
+ }
157
+
158
+ $searchConditions[] = 'id IN (
159
+ SELECT DISTINCT occurrence_id
160
+ FROM ' . $tmp->GetTable() . '
161
+ WHERE ' . $sWhereClause . '
162
+ )';
163
+ }
164
+
165
+ //do something with search query parameters and search conditions - give them to the query adapter?
166
+ return $searchConditions;
167
+ }
168
+
169
+
170
+ }
classes/Models/Adapters/MySQL/OptionAdapter.php CHANGED
@@ -1,79 +1,79 @@
1
- <?php
2
-
3
- class WSAL_Adapters_MySQL_Option extends WSAL_Adapters_MySQL_ActiveRecord
4
- {
5
-
6
- protected $_table = 'wsal_options';
7
- protected $_idkey = 'id';
8
-
9
- public $id = 0;
10
- public $option_name = '';
11
- public static $option_name_maxlength = 100;
12
- public $option_value = '';
13
-
14
- public function __construct($conn)
15
- {
16
- parent::__construct($conn);
17
- }
18
-
19
- public function GetModel()
20
- {
21
- return new WSAL_Models_Option();
22
- }
23
-
24
- public function GetNamedOption($name)
25
- { if ($this->IsInstalled()) {
26
- return $this->Load('option_name = %s', array($name));
27
- } else {
28
- return null;
29
- }
30
- }
31
-
32
- public function GetNotificationsSetting($opt_prefix)
33
- {
34
- if ($this->IsInstalled()) {
35
- return $this->LoadArray('option_name LIKE %s', array($opt_prefix."%"));
36
- } else {
37
- return null;
38
- }
39
- }
40
-
41
- public function GetNotification($id)
42
- {
43
- if ($this->IsInstalled()) {
44
- return $this->Load('id = %d', array($id));
45
- } else {
46
- return null;
47
- }
48
- }
49
-
50
- public function DeleteByName($name)
51
- {
52
- if (!empty($name)) {
53
- $sql = "DELETE FROM " . $this->GetTable() . " WHERE option_name = '". $name ."'";
54
- // execute query
55
- return parent::DeleteQuery($sql);
56
- } else {
57
- return false;
58
- }
59
- }
60
-
61
- public function DeleteByPrefix($opt_prefix)
62
- {
63
- if (!empty($opt_prefix)) {
64
- $sql = "DELETE FROM " . $this->GetTable() . " WHERE option_name LIKE '". $opt_prefix ."%'";
65
- // execute query
66
- return parent::DeleteQuery($sql);
67
- } else {
68
- return false;
69
- }
70
- }
71
-
72
- public function CountNotifications($opt_prefix)
73
- {
74
- $_wpdb = $this->connection;
75
- $sql = "SELECT COUNT(id) FROM " . $this->GetTable() . " WHERE option_name LIKE '". $opt_prefix ."%'";
76
- return (int)$_wpdb->get_var($sql);
77
- }
78
-
79
- }
1
+ <?php
2
+
3
+ class WSAL_Adapters_MySQL_Option extends WSAL_Adapters_MySQL_ActiveRecord
4
+ {
5
+
6
+ protected $_table = 'wsal_options';
7
+ protected $_idkey = 'id';
8
+
9
+ public $id = 0;
10
+ public $option_name = '';
11
+ public static $option_name_maxlength = 100;
12
+ public $option_value = '';
13
+
14
+ public function __construct($conn)
15
+ {
16
+ parent::__construct($conn);
17
+ }
18
+
19
+ public function GetModel()
20
+ {
21
+ return new WSAL_Models_Option();
22
+ }
23
+
24
+ public function GetNamedOption($name)
25
+ { if ($this->IsInstalled()) {
26
+ return $this->Load('option_name = %s', array($name));
27
+ } else {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ public function GetNotificationsSetting($opt_prefix)
33
+ {
34
+ if ($this->IsInstalled()) {
35
+ return $this->LoadArray('option_name LIKE %s', array($opt_prefix."%"));
36
+ } else {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ public function GetNotification($id)
42
+ {
43
+ if ($this->IsInstalled()) {
44
+ return $this->Load('id = %d', array($id));
45
+ } else {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ public function DeleteByName($name)
51
+ {
52
+ if (!empty($name)) {
53
+ $sql = "DELETE FROM " . $this->GetTable() . " WHERE option_name = '". $name ."'";
54
+ // execute query
55
+ return parent::DeleteQuery($sql);
56
+ } else {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ public function DeleteByPrefix($opt_prefix)
62
+ {
63
+ if (!empty($opt_prefix)) {
64
+ $sql = "DELETE FROM " . $this->GetTable() . " WHERE option_name LIKE '". $opt_prefix ."%'";
65
+ // execute query
66
+ return parent::DeleteQuery($sql);
67
+ } else {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ public function CountNotifications($opt_prefix)
73
+ {
74
+ $_wpdb = $this->connection;
75
+ $sql = "SELECT COUNT(id) FROM " . $this->GetTable() . " WHERE option_name LIKE '". $opt_prefix ."%'";
76
+ return (int)$_wpdb->get_var($sql);
77
+ }
78
+
79
+ }
classes/Models/Adapters/MySQL/QueryAdapter.php CHANGED
@@ -1,219 +1,219 @@
1
- <?php
2
-
3
- class WSAL_Adapters_MySQL_Query implements WSAL_Adapters_QueryInterface
4
- {
5
- protected $connection;
6
-
7
- public function __construct($conn)
8
- {
9
- $this->connection = $conn;
10
- }
11
-
12
- /**
13
- * @return string Generated sql.
14
- */
15
- protected function GetSql($query, &$args = array())
16
- {
17
- $conditions = $query->getConditions();
18
- $searchCondition = $this->SearchCondition($query);
19
-
20
- $sWhereClause = "";
21
- foreach ($conditions as $fieldName => $fieldValue) {
22
- if (empty($sWhereClause)) {
23
- $sWhereClause .= " WHERE ";
24
- } else {
25
- $sWhereClause .= " AND ";
26
- }
27
-
28
- if (is_array($fieldValue)) {
29
- $subWhereClause = "(";
30
- foreach($fieldValue as $orFieldName => $orFieldValue) {
31
- if ($subWhereClause != '(') {
32
- $subWhereClause .= " OR ";
33
- }
34
- $subWhereClause .= $orFieldName;
35
- $args[] = $orFieldValue;
36
- }
37
- $subWhereClause .= ")";
38
- $sWhereClause .= $subWhereClause;
39
- } else {
40
- $sWhereClause .= $fieldName;
41
- $args[] = $fieldValue;
42
- }
43
- }
44
-
45
- $fromDataSets = $query->getFrom();
46
- $columns = $query->getColumns();
47
- $orderBys = $query->getOrderBy();
48
-
49
- $sLimitClause = "";
50
- if ($query->getLimit()) {
51
- $sLimitClause .= " LIMIT ";
52
- if ($query->getOffset()) {
53
- $sLimitClause .= $query->getOffset() . ", ";
54
- }
55
- $sLimitClause .= $query->getLimit();
56
- }
57
- $joinClause = '';
58
- if ($query->hasMetaJoin()) {
59
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
60
- $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
61
- $joinClause = ' LEFT JOIN '. $meta->GetTable() .' AS meta ON meta.occurrence_id = '. $occurrence->GetTable() .'.id ';
62
- }
63
- $fields = (empty($columns))? $fromDataSets[0] . '.*' : implode(',', $columns);
64
- if (!empty($searchCondition)) {
65
- $args[] = $searchCondition['args'];
66
- }
67
- return 'SELECT ' . $fields
68
- . ' FROM ' . implode(',', $fromDataSets)
69
- . $joinClause
70
- . $sWhereClause
71
- . (!empty($searchCondition) ? (empty($sWhereClause) ? " WHERE ".$searchCondition['sql'] : " AND ".$searchCondition['sql']) : '')
72
- // @todo GROUP BY goes here
73
- . (!empty($orderBys) ? (' ORDER BY ' . implode(', ', array_keys($orderBys)) . ' ' . implode(', ', array_values($orderBys))) : '')
74
- . $sLimitClause;
75
- }
76
-
77
- protected function getActiveRecordAdapter()
78
- {
79
- return new WSAL_Adapters_MySQL_ActiveRecord($this->connection);
80
- }
81
-
82
- /**
83
- * @return WSAL_Models_ActiveRecord[] Execute query and return data as $ar_cls objects.
84
- */
85
- public function Execute($query)
86
- {
87
- $args = array();
88
- $sql = $this->GetSql($query, $args);
89
-
90
- $occurenceAdapter = $query->getConnector()->getAdapter("Occurrence");
91
-
92
- if (in_array($occurenceAdapter->GetTable(), $query->getFrom())) {
93
- return $occurenceAdapter->LoadMulti($sql, $args);
94
- } else {
95
- return $this->getActiveRecordAdapter()->LoadMulti($sql, $args);
96
- }
97
- }
98
-
99
- /**
100
- * @return int Use query for counting records.
101
- */
102
- public function Count($query)
103
- {
104
- // back up columns, use COUNT as default column and generate sql
105
- $cols = $query->getColumns();
106
- $query->clearColumns();
107
- $query->addColumn('COUNT(*)');
108
-
109
- $args = array();
110
- $sql = $this->GetSql($query, $args);
111
-
112
- // restore columns
113
- $query->setColumns($cols);
114
- // execute query and return result
115
- return $this->getActiveRecordAdapter()->CountQuery($sql, $args);
116
- }
117
-
118
- public function CountDelete($query)
119
- {
120
- $result = $this->GetSqlDelete($query, true);
121
- // execute query and return result
122
- return $this->getActiveRecordAdapter()->CountQuery($result['sql'], $result['args']);
123
- }
124
-
125
- /**
126
- * Use query for deleting records.
127
- */
128
- public function Delete($query)
129
- {
130
- $result = $this->GetSqlDelete($query);
131
- $this->DeleteMetas($query, $result['args']);
132
- return $this->getActiveRecordAdapter()->DeleteQuery($result['sql'], $result['args']);
133
- }
134
-
135
- public function DeleteMetas($query, $args)
136
- {
137
- // back up columns, use COUNT as default column and generate sql
138
- $cols = $query->getColumns();
139
- $query->clearColumns();
140
- $query->addColumn('id');
141
- $sql = $this->GetSql($query);
142
- // restore columns
143
- $query->setColumns($cols);
144
-
145
- $_wpdb = $this->connection;
146
- $occ_ids = array();
147
- $sql = (!empty($args) ? $_wpdb->prepare($sql, $args) : $sql);
148
- foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
149
- $occ_ids[] = $data['id'];
150
- }
151
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
152
- $meta->DeleteByOccurenceIds($occ_ids);
153
- }
154
-
155
- public function GetSqlDelete($query, $getCount = false)
156
- {
157
- $result = array();
158
- $args = array();
159
- // back up columns, remove them for DELETE and generate sql
160
- $cols = $query->getColumns();
161
- $query->clearColumns();
162
-
163
- $conditions = $query->getConditions();
164
-
165
- $sWhereClause = "";
166
- foreach ($conditions as $fieldName => $fieldValue) {
167
- if (empty($sWhereClause)) {
168
- $sWhereClause .= " WHERE ";
169
- } else {
170
- $sWhereClause .= " AND ";
171
- }
172
- $sWhereClause .= $fieldName;
173
- $args[] = $fieldValue;
174
- }
175
-
176
- $fromDataSets = $query->getFrom();
177
- $orderBys = $query->getOrderBy();
178
-
179
- $sLimitClause = "";
180
- if ($query->getLimit()) {
181
- $sLimitClause .= " LIMIT ";
182
- if ($query->getOffset()) {
183
- $sLimitClause .= $query->getOffset() . ", ";
184
- }
185
- $sLimitClause .= $query->getLimit();
186
- }
187
- $result['sql'] = ($getCount ? 'SELECT COUNT(*) FROM ' : 'DELETE FROM ')
188
- . implode(',', $fromDataSets)
189
- . $sWhereClause
190
- . (!empty($orderBys) ? (' ORDER BY ' . implode(', ', array_keys($orderBys)) . ' ' . implode(', ', array_values($orderBys))) : '')
191
- . $sLimitClause;
192
- $result['args'] = $args;
193
- //restore columns
194
- $query->setColumns($cols);
195
-
196
- return $result;
197
- }
198
-
199
- public function SearchCondition($query)
200
- {
201
- $condition = $query->getSearchCondition();
202
- if (empty($condition)) return null;
203
- $searchConditions = array();
204
- $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
205
- $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
206
- if (is_numeric($condition) && strlen($condition) == 4) {
207
- $searchConditions['sql'] = $occurrence->GetTable() .'.alert_id LIKE %s';
208
- } else {
209
- $searchConditions['sql'] = $occurrence->GetTable() .'.id IN (
210
- SELECT DISTINCT occurrence_id
211
- FROM ' . $meta->GetTable() . '
212
- WHERE TRIM(BOTH "\"" FROM value) LIKE %s
213
- )';
214
- }
215
- $searchConditions['args'] = "%". $condition. "%";
216
- return $searchConditions;
217
- }
218
-
219
- }
1
+ <?php
2
+
3
+ class WSAL_Adapters_MySQL_Query implements WSAL_Adapters_QueryInterface
4
+ {
5
+ protected $connection;
6
+
7
+ public function __construct($conn)
8
+ {
9
+ $this->connection = $conn;
10
+ }
11
+
12
+ /**
13
+ * @return string Generated sql.
14
+ */
15
+ protected function GetSql($query, &$args = array())
16
+ {
17
+ $conditions = $query->getConditions();
18
+ $searchCondition = $this->SearchCondition($query);
19
+
20
+ $sWhereClause = "";
21
+ foreach ($conditions as $fieldName => $fieldValue) {
22
+ if (empty($sWhereClause)) {
23
+ $sWhereClause .= " WHERE ";
24
+ } else {
25
+ $sWhereClause .= " AND ";
26
+ }
27
+
28
+ if (is_array($fieldValue)) {
29
+ $subWhereClause = "(";
30
+ foreach($fieldValue as $orFieldName => $orFieldValue) {
31
+ if ($subWhereClause != '(') {
32
+ $subWhereClause .= " OR ";
33
+ }
34
+ $subWhereClause .= $orFieldName;
35
+ $args[] = $orFieldValue;
36
+ }
37
+ $subWhereClause .= ")";
38
+ $sWhereClause .= $subWhereClause;
39
+ } else {
40
+ $sWhereClause .= $fieldName;
41
+ $args[] = $fieldValue;
42
+ }
43
+ }
44
+
45
+ $fromDataSets = $query->getFrom();
46
+ $columns = $query->getColumns();
47
+ $orderBys = $query->getOrderBy();
48
+
49
+ $sLimitClause = "";
50
+ if ($query->getLimit()) {
51
+ $sLimitClause .= " LIMIT ";
52
+ if ($query->getOffset()) {
53
+ $sLimitClause .= $query->getOffset() . ", ";
54
+ }
55
+ $sLimitClause .= $query->getLimit();
56
+ }
57
+ $joinClause = '';
58
+ if ($query->hasMetaJoin()) {
59
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
60
+ $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
61
+ $joinClause = ' LEFT JOIN '. $meta->GetTable() .' AS meta ON meta.occurrence_id = '. $occurrence->GetTable() .'.id ';
62
+ }
63
+ $fields = (empty($columns))? $fromDataSets[0] . '.*' : implode(',', $columns);
64
+ if (!empty($searchCondition)) {
65
+ $args[] = $searchCondition['args'];
66
+ }
67
+ return 'SELECT ' . $fields
68
+ . ' FROM ' . implode(',', $fromDataSets)
69
+ . $joinClause
70
+ . $sWhereClause
71
+ . (!empty($searchCondition) ? (empty($sWhereClause) ? " WHERE ".$searchCondition['sql'] : " AND ".$searchCondition['sql']) : '')
72
+ // @todo GROUP BY goes here
73
+ . (!empty($orderBys) ? (' ORDER BY ' . implode(', ', array_keys($orderBys)) . ' ' . implode(', ', array_values($orderBys))) : '')
74
+ . $sLimitClause;
75
+ }
76
+
77
+ protected function getActiveRecordAdapter()
78
+ {
79
+ return new WSAL_Adapters_MySQL_ActiveRecord($this->connection);
80
+ }
81
+
82
+ /**
83
+ * @return WSAL_Models_ActiveRecord[] Execute query and return data as $ar_cls objects.
84
+ */
85
+ public function Execute($query)
86
+ {
87
+ $args = array();
88
+ $sql = $this->GetSql($query, $args);
89
+
90
+ $occurenceAdapter = $query->getConnector()->getAdapter("Occurrence");
91
+
92
+ if (in_array($occurenceAdapter->GetTable(), $query->getFrom())) {
93
+ return $occurenceAdapter->LoadMulti($sql, $args);
94
+ } else {
95
+ return $this->getActiveRecordAdapter()->LoadMulti($sql, $args);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * @return int Use query for counting records.
101
+ */
102
+ public function Count($query)
103
+ {
104
+ // back up columns, use COUNT as default column and generate sql
105
+ $cols = $query->getColumns();
106
+ $query->clearColumns();
107
+ $query->addColumn('COUNT(*)');
108
+
109
+ $args = array();
110
+ $sql = $this->GetSql($query, $args);
111
+
112
+ // restore columns
113
+ $query->setColumns($cols);
114
+ // execute query and return result
115
+ return $this->getActiveRecordAdapter()->CountQuery($sql, $args);
116
+ }
117
+
118
+ public function CountDelete($query)
119
+ {
120
+ $result = $this->GetSqlDelete($query, true);
121
+ // execute query and return result
122
+ return $this->getActiveRecordAdapter()->CountQuery($result['sql'], $result['args']);
123
+ }
124
+
125
+ /**
126
+ * Use query for deleting records.
127
+ */
128
+ public function Delete($query)
129
+ {
130
+ $result = $this->GetSqlDelete($query);
131
+ $this->DeleteMetas($query, $result['args']);
132
+ return $this->getActiveRecordAdapter()->DeleteQuery($result['sql'], $result['args']);
133
+ }
134
+
135
+ public function DeleteMetas($query, $args)
136
+ {
137
+ // back up columns, use COUNT as default column and generate sql
138
+ $cols = $query->getColumns();
139
+ $query->clearColumns();
140
+ $query->addColumn('id');
141
+ $sql = $this->GetSql($query);
142
+ // restore columns
143
+ $query->setColumns($cols);
144
+
145
+ $_wpdb = $this->connection;
146
+ $occ_ids = array();
147
+ $sql = (!empty($args) ? $_wpdb->prepare($sql, $args) : $sql);
148
+ foreach ($_wpdb->get_results($sql, ARRAY_A) as $data) {
149
+ $occ_ids[] = $data['id'];
150
+ }
151
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
152
+ $meta->DeleteByOccurenceIds($occ_ids);
153
+ }
154
+
155
+ public function GetSqlDelete($query, $getCount = false)
156
+ {
157
+ $result = array();
158
+ $args = array();
159
+ // back up columns, remove them for DELETE and generate sql
160
+ $cols = $query->getColumns();
161
+ $query->clearColumns();
162
+
163
+ $conditions = $query->getConditions();
164
+
165
+ $sWhereClause = "";
166
+ foreach ($conditions as $fieldName => $fieldValue) {
167
+ if (empty($sWhereClause)) {
168
+ $sWhereClause .= " WHERE ";
169
+ } else {
170
+ $sWhereClause .= " AND ";
171
+ }
172
+ $sWhereClause .= $fieldName;
173
+ $args[] = $fieldValue;
174
+ }
175
+
176
+ $fromDataSets = $query->getFrom();
177
+ $orderBys = $query->getOrderBy();
178
+
179
+ $sLimitClause = "";
180
+ if ($query->getLimit()) {
181
+ $sLimitClause .= " LIMIT ";
182
+ if ($query->getOffset()) {
183
+ $sLimitClause .= $query->getOffset() . ", ";
184
+ }
185
+ $sLimitClause .= $query->getLimit();
186
+ }
187
+ $result['sql'] = ($getCount ? 'SELECT COUNT(*) FROM ' : 'DELETE FROM ')
188
+ . implode(',', $fromDataSets)
189
+ . $sWhereClause
190
+ . (!empty($orderBys) ? (' ORDER BY ' . implode(', ', array_keys($orderBys)) . ' ' . implode(', ', array_values($orderBys))) : '')
191
+ . $sLimitClause;
192
+ $result['args'] = $args;
193
+ //restore columns
194
+ $query->setColumns($cols);
195
+
196
+ return $result;
197
+ }
198
+
199
+ public function SearchCondition($query)
200
+ {
201
+ $condition = $query->getSearchCondition();
202
+ if (empty($condition)) return null;
203
+ $searchConditions = array();
204
+ $meta = new WSAL_Adapters_MySQL_Meta($this->connection);
205
+ $occurrence = new WSAL_Adapters_MySQL_Occurrence($this->connection);
206
+ if (is_numeric($condition) && strlen($condition) == 4) {
207
+ $searchConditions['sql'] = $occurrence->GetTable() .'.alert_id LIKE %s';
208
+ } else {
209
+ $searchConditions['sql'] = $occurrence->GetTable() .'.id IN (
210
+ SELECT DISTINCT occurrence_id
211
+ FROM ' . $meta->GetTable() . '
212
+ WHERE TRIM(BOTH "\"" FROM value) LIKE %s
213
+ )';
214
+ }
215
+ $searchConditions['args'] = "%". $condition. "%";
216
+ return $searchConditions;
217
+ }
218
+
219
+ }
classes/Models/Adapters/OccurrenceInterface.php CHANGED
@@ -1,11 +1,11 @@
1
- <?php
2
-
3
- interface WSAL_Adapters_OccurrenceInterface
4
- {
5
- public function GetMeta($occurence);
6
- public function GetNamedMeta($occurence, $name);
7
- public function GetFirstNamedMeta($occurence, $names);
8
- public static function GetNewestUnique($limit = PHP_INT_MAX);
9
- public function CheckKnownUsers($args = array());
10
- public function CheckUnKnownUsers($args = array());
11
- }
1
+ <?php
2
+
3
+ interface WSAL_Adapters_OccurrenceInterface
4
+ {
5
+ public function GetMeta($occurence);
6
+ public function GetNamedMeta($occurence, $name);
7
+ public function GetFirstNamedMeta($occurence, $names);
8
+ public static function GetNewestUnique($limit = PHP_INT_MAX);
9
+ public function CheckKnownUsers($args = array());
10
+ public function CheckUnKnownUsers($args = array());
11
+ }
classes/Models/Adapters/QueryInterface.php CHANGED
@@ -1,8 +1,8 @@
1
- <?php
2
-
3
- interface WSAL_Adapters_QueryInterface
4
- {
5
- public function Execute($query);
6
- public function Count($query);
7
- public function Delete($query);
8
- }
1
+ <?php
2
+
3
+ interface WSAL_Adapters_QueryInterface
4
+ {
5
+ public function Execute($query);
6
+ public function Count($query);
7
+ public function Delete($query);
8
+ }
classes/Models/Meta.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
-
3
- class WSAL_Models_Meta extends WSAL_Models_ActiveRecord {
4
-
5
- protected $adapterName = "Meta";
6
-
7
- public $id = 0;
8
- public $occurrence_id = 0;
9
- public $name = '';
10
- public $value = array(); // force mixed type
11
-
12
- public function SaveMeta()
13
- {
14
- $this->_state = self::STATE_UNKNOWN;
15
- $updateId = $this->getId();
16
- $result = $this->getAdapter()->Save($this);
17
-
18
- if ($result !== false) {
19
- $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
20
- }
21
- return $result;
22
- }
23
-
24
- public function UpdateByNameAndOccurenceId($name, $value, $occurrenceId)
25
- {
26
- $meta = $this->getAdapter()->LoadByNameAndOccurenceId($name, $occurrenceId);
27
- $this->id = $meta['id'];
28
- $this->occurrence_id = $meta['occurrence_id'];
29
- $this->name = $meta['name'];
30
- $this->value = $value;
31
- $this->saveMeta();
32
- }
33
-
34
- }
1
+ <?php
2
+
3
+ class WSAL_Models_Meta extends WSAL_Models_ActiveRecord {
4
+
5
+ protected $adapterName = "Meta";
6
+
7
+ public $id = 0;
8
+ public $occurrence_id = 0;
9
+ public $name = '';
10
+ public $value = array(); // force mixed type
11
+
12
+ public function SaveMeta()
13
+ {
14
+ $this->_state = self::STATE_UNKNOWN;
15
+ $updateId = $this->getId();
16
+ $result = $this->getAdapter()->Save($this);
17
+
18
+ if ($result !== false) {
19
+ $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
20
+ }
21
+ return $result;
22
+ }
23
+
24
+ public function UpdateByNameAndOccurenceId($name, $value, $occurrenceId)
25
+ {
26
+ $meta = $this->getAdapter()->LoadByNameAndOccurenceId($name, $occurrenceId);
27
+ $this->id = $meta['id'];
28
+ $this->occurrence_id = $meta['occurrence_id'];
29
+ $this->name = $meta['name'];
30
+ $this->value = $value;
31
+ $this->saveMeta();
32
+ }
33
+
34
+ }
classes/Models/Occurrence.php CHANGED
@@ -1,193 +1,193 @@
1
- <?php
2
-
3
- class WSAL_Models_Occurrence extends WSAL_Models_ActiveRecord
4
- {
5
-
6
- public $id = 0;
7
- public $site_id = 0;
8
- public $alert_id = 0;
9
- public $created_on = 0.0;
10
- public $is_read = false;
11
- public $is_migrated = false;
12
- protected $adapterName = "Occurrence";
13
-
14
- /**
15
- * Returns the alert related to this occurrence.
16
- * @return WSAL_Alert
17
- */
18
- public function GetAlert()
19
- {
20
- return WpSecurityAuditLog::GetInstance()->alerts->GetAlert($this->alert_id);
21
- }
22
-
23
- /**
24
- * Returns the value of a meta item.
25
- * @param string $name Name of meta item.
26
- * @param mixed $default Default value returned when meta does not exist.
27
- * @return mixed The value, if meta item does not exist $default returned.
28
- */
29
- public function GetMetaValue($name, $default = array())
30
- {
31
- //get meta adapter
32
- //call the function ($name, $this->getId())
33
- $meta = $this->getAdapter()->GetNamedMeta($this, $name);
34
- return maybe_unserialize($meta['value']);
35
-
36
- //TO DO: re-introduce add is loaded check before running query
37
- //return $meta->IsLoaded() ? $meta->value : $default;
38
- }
39
-
40
- /**
41
- * Set the value of a meta item (creates or updates meta item).
42
- * @param string $name Meta name.
43
- * @param mixed $value Meta value.
44
- */
45
- public function SetMetaValue($name, $value)
46
- {
47
- //get meta adapter
48
- $model = new WSAL_Models_Meta();
49
- $model->occurrence_id = $this->getId();
50
- $model->name = $name;
51
- $model->value = maybe_serialize($value);
52
- $model->SaveMeta();
53
- }
54
-
55
- public function UpdateMetaValue($name, $value)
56
- {
57
- $model = new WSAL_Models_Meta();
58
- $model->UpdateByNameAndOccurenceId($name, $value, $this->getId());
59
- }
60
-
61
- /**
62
- * Returns a key-value pair of meta data.
63
- * @return array
64
- */
65
- public function GetMetaArray()
66
- {
67
- $result = array();
68
- $metas = $this->getAdapter()->GetMultiMeta($this);
69
- foreach ($metas as $meta) {
70
- $result[$meta->name] = maybe_unserialize($meta->value);
71
- }
72
- return $result;
73
- }
74
-
75
- /**
76
- * Creates or updates all meta data passed as an array of meta-key/meta-value pairs.
77
- * @param array $data New meta data.
78
- */
79
- public function SetMeta($data)
80
- {
81
- foreach ((array)$data as $key => $val) {
82
- $this->SetMetaValue($key, $val);
83
- }
84
- }
85
-
86
- /**
87
- * @param callable|null $metaFormatter (Optional) Meta formatter callback.
88
- * @return string Full-formatted message.
89
- */
90
- public function GetMessage($metaFormatter = null)
91
- {
92
- if (!isset($this->_cachedmessage)) {
93
- // get correct message entry
94
- if ($this->is_migrated) {
95
- $this->_cachedmessage = $this->GetMetaValue('MigratedMesg', false);
96
- }
97
- if (!$this->is_migrated || !$this->_cachedmessage) {
98
- $this->_cachedmessage = $this->GetAlert()->mesg;
99
- }
100
- // fill variables in message
101
- $this->_cachedmessage = $this->GetAlert()->GetMessage($this->GetMetaArray(), $metaFormatter, $this->_cachedmessage);
102
- }
103
- return $this->_cachedmessage;
104
- }
105
-
106
- /**
107
- * Delete occurrence as well as associated meta data.
108
- * @return boolean True on success, false on failure.
109
- */
110
- public function Delete()
111
- {
112
- foreach ($this->getAdapter()->GetMeta() as $meta) {
113
- $meta->Delete();
114
- }
115
- return parent::Delete();
116
- }
117
-
118
- /**
119
- * @return string User's username.
120
- */
121
- public function GetUsername()
122
- {
123
- $meta = $this->getAdapter()->GetFirstNamedMeta($this, array('Username', 'CurrentUserID'));
124
- if ($meta) {
125
- switch(true){
126
- case $meta->name == 'Username':
127
- return $meta->value;
128
- case $meta->name == 'CurrentUserID':
129
- return ($data = get_userdata($meta->value)) ? $data->user_login : null;
130
- }
131
- }
132
- return null;
133
- }
134
-
135
- /**
136
- * @return string IP address of request.
137
- */
138
- public function GetSourceIP()
139
- {
140
- return $this->GetMetaValue('ClientIP', '');
141
- }
142
-
143
- /**
144
- * @return string IP address of request (from proxies etc).
145
- */
146
- public function GetOtherIPs()
147
- {
148
- $result = array();
149
- $data = (array)$this->GetMetaValue('OtherIPs', array());
150
- foreach ($data as $ips) {
151
- foreach ($ips as $ip) {
152
- $result[] = $ip;
153
- }
154
- }
155
- return array_unique($result);
156
- }
157
-
158
- /**
159
- * @return array Array of user roles.
160
- */
161
- public function GetUserRoles()
162
- {
163
- return $this->GetMetaValue('CurrentUserRoles', array());
164
- }
165
-
166
- /**
167
- * @return float Number of seconds (and microseconds as fraction) since unix Day 0.
168
- * @todo This needs some caching.
169
- */
170
- protected function GetMicrotime()
171
- {
172
- return microtime(true);// + get_option('gmt_offset') * HOUR_IN_SECONDS;
173
- }
174
-
175
- /**
176
- * Finds occurences of the same type by IP and Username within specified time frame
177
- * @param string $ipAddress
178
- * @param string $username
179
- * @param int $alertId Alert type we are lookign for
180
- * @param int $siteId
181
- * @param $startTime mktime
182
- * @param $endTime mktime
183
- */
184
- public function CheckKnownUsers($args = array())
185
- {
186
- return $this->getAdapter()->CheckKnownUsers($args);
187
- }
188
-
189
- public function CheckUnKnownUsers($args = array())
190
- {
191
- return $this->getAdapter()->CheckUnKnownUsers($args);
192
- }
193
- }
1
+ <?php
2
+
3
+ class WSAL_Models_Occurrence extends WSAL_Models_ActiveRecord
4
+ {
5
+
6
+ public $id = 0;
7
+ public $site_id = 0;
8
+ public $alert_id = 0;
9
+ public $created_on = 0.0;
10
+ public $is_read = false;
11
+ public $is_migrated = false;
12
+ protected $adapterName = "Occurrence";
13
+
14
+ /**
15
+ * Returns the alert related to this occurrence.
16
+ * @return WSAL_Alert
17
+ */
18
+ public function GetAlert()
19
+ {
20
+ return WpSecurityAuditLog::GetInstance()->alerts->GetAlert($this->alert_id);
21
+ }
22
+
23
+ /**
24
+ * Returns the value of a meta item.
25
+ * @param string $name Name of meta item.
26
+ * @param mixed $default Default value returned when meta does not exist.
27
+ * @return mixed The value, if meta item does not exist $default returned.
28
+ */
29
+ public function GetMetaValue($name, $default = array())
30
+ {
31
+ //get meta adapter
32
+ //call the function ($name, $this->getId())
33
+ $meta = $this->getAdapter()->GetNamedMeta($this, $name);
34
+ return maybe_unserialize($meta['value']);
35
+
36
+ //TO DO: re-introduce add is loaded check before running query
37
+ //return $meta->IsLoaded() ? $meta->value : $default;
38
+ }
39
+
40
+ /**
41
+ * Set the value of a meta item (creates or updates meta item).
42
+ * @param string $name Meta name.
43
+ * @param mixed $value Meta value.
44
+ */
45
+ public function SetMetaValue($name, $value)
46
+ {
47
+ //get meta adapter
48
+ $model = new WSAL_Models_Meta();
49
+ $model->occurrence_id = $this->getId();
50
+ $model->name = $name;
51
+ $model->value = maybe_serialize($value);
52
+ $model->SaveMeta();
53
+ }
54
+
55
+ public function UpdateMetaValue($name, $value)
56
+ {
57
+ $model = new WSAL_Models_Meta();
58
+ $model->UpdateByNameAndOccurenceId($name, $value, $this->getId());
59
+ }
60
+
61
+ /**
62
+ * Returns a key-value pair of meta data.
63
+ * @return array
64
+ */
65
+ public function GetMetaArray()
66
+ {
67
+ $result = array();
68
+ $metas = $this->getAdapter()->GetMultiMeta($this);
69
+ foreach ($metas as $meta) {
70
+ $result[$meta->name] = maybe_unserialize($meta->value);
71
+ }
72
+ return $result;
73
+ }
74
+
75
+ /**
76
+ * Creates or updates all meta data passed as an array of meta-key/meta-value pairs.
77
+ * @param array $data New meta data.
78
+ */
79
+ public function SetMeta($data)
80
+ {
81
+ foreach ((array)$data as $key => $val) {
82
+ $this->SetMetaValue($key, $val);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * @param callable|null $metaFormatter (Optional) Meta formatter callback.
88
+ * @return string Full-formatted message.
89
+ */
90
+ public function GetMessage($metaFormatter = null)
91
+ {
92
+ if (!isset($this->_cachedmessage)) {
93
+ // get correct message entry
94
+ if ($this->is_migrated) {
95
+ $this->_cachedmessage = $this->GetMetaValue('MigratedMesg', false);
96
+ }
97
+ if (!$this->is_migrated || !$this->_cachedmessage) {
98
+ $this->_cachedmessage = $this->GetAlert()->mesg;
99
+ }
100
+ // fill variables in message
101
+ $this->_cachedmessage = $this->GetAlert()->GetMessage($this->GetMetaArray(), $metaFormatter, $this->_cachedmessage);
102
+ }
103
+ return $this->_cachedmessage;
104
+ }
105
+
106
+ /**
107
+ * Delete occurrence as well as associated meta data.
108
+ * @return boolean True on success, false on failure.
109
+ */
110
+ public function Delete()
111
+ {
112
+ foreach ($this->getAdapter()->GetMeta() as $meta) {
113
+ $meta->Delete();
114
+ }
115
+ return parent::Delete();
116
+ }
117
+
118
+ /**
119
+ * @return string User's username.
120
+ */
121
+ public function GetUsername()
122
+ {
123
+ $meta = $this->getAdapter()->GetFirstNamedMeta($this, array('Username', 'CurrentUserID'));
124
+ if ($meta) {
125
+ switch(true){
126
+ case $meta->name == 'Username':
127
+ return $meta->value;
128
+ case $meta->name == 'CurrentUserID':
129
+ return ($data = get_userdata($meta->value)) ? $data->user_login : null;
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * @return string IP address of request.
137
+ */
138
+ public function GetSourceIP()
139
+ {
140
+ return $this->GetMetaValue('ClientIP', '');
141
+ }
142
+
143
+ /**
144
+ * @return string IP address of request (from proxies etc).
145
+ */
146
+ public function GetOtherIPs()
147
+ {
148
+ $result = array();
149
+ $data = (array)$this->GetMetaValue('OtherIPs', array());
150
+ foreach ($data as $ips) {
151
+ foreach ($ips as $ip) {
152
+ $result[] = $ip;
153
+ }
154
+ }
155
+ return array_unique($result);
156
+ }
157
+
158
+ /**
159
+ * @return array Array of user roles.
160
+ */
161
+ public function GetUserRoles()
162
+ {
163
+ return $this->GetMetaValue('CurrentUserRoles', array());
164
+ }
165
+
166
+ /**
167
+ * @return float Number of seconds (and microseconds as fraction) since unix Day 0.
168
+ * @todo This needs some caching.
169
+ */
170
+ protected function GetMicrotime()
171
+ {
172
+ return microtime(true);// + get_option('gmt_offset') * HOUR_IN_SECONDS;
173
+ }
174
+
175
+ /**
176
+ * Finds occurences of the same type by IP and Username within specified time frame
177
+ * @param string $ipAddress
178
+ * @param string $username
179
+ * @param int $alertId Alert type we are lookign for
180
+ * @param int $siteId
181
+ * @param $startTime mktime
182
+ * @param $endTime mktime
183
+ */
184
+ public function CheckKnownUsers($args = array())
185
+ {
186
+ return $this->getAdapter()->CheckKnownUsers($args);
187
+ }
188
+
189
+ public function CheckUnKnownUsers($args = array())
190
+ {
191
+ return $this->getAdapter()->CheckUnKnownUsers($args);
192
+ }
193
+ }
classes/Models/OccurrenceQuery.php CHANGED
@@ -1,29 +1,29 @@
1
- <?php
2
-
3
- class WSAL_Models_OccurrenceQuery extends WSAL_Models_Query
4
- {
5
- protected $arguments = array();
6
-
7
- public function addArgument($field, $value)
8
- {
9
- $this->arguments[$field] = $value;
10
- return $this;
11
- }
12
-
13
- public function clearArguments()
14
- {
15
- $this->arguments = array();
16
- return $this;
17
- }
18
-
19
- public function __construct()
20
- {
21
- parent::__construct();
22
-
23
- //TO DO: Consider if Get Table is the right method to call given that this is mysql specific
24
- $this->addFrom(
25
- $this->getConnector()->getAdapter("Occurrence")->GetTable()
26
- );
27
- }
28
-
29
- }
1
+ <?php
2
+
3
+ class WSAL_Models_OccurrenceQuery extends WSAL_Models_Query
4
+ {
5
+ protected $arguments = array();
6
+
7
+ public function addArgument($field, $value)
8
+ {
9
+ $this->arguments[$field] = $value;
10
+ return $this;
11
+ }
12
+
13
+ public function clearArguments()
14
+ {
15
+ $this->arguments = array();
16
+ return $this;
17
+ }
18
+
19
+ public function __construct()
20
+ {
21
+ parent::__construct();
22
+
23
+ //TO DO: Consider if Get Table is the right method to call given that this is mysql specific
24
+ $this->addFrom(
25
+ $this->getConnector()->getAdapter("Occurrence")->GetTable()
26
+ );
27
+ }
28
+
29
+ }
classes/Models/Option.php CHANGED
@@ -1,80 +1,80 @@
1
- <?php
2
-
3
- /**
4
- * Wordpress options are always loaded from the default wordpress database.
5
- */
6
- class WSAL_Models_Option extends WSAL_Models_ActiveRecord
7
- {
8
-
9
- protected $adapterName = "Option";
10
- public $id = '';
11
- public $option_name = '';
12
- public $option_value = '';
13
- /**
14
- * Options are always stored in WPDB. This setting ensures that
15
- */
16
- protected $useDefaultAdapter = true;
17
-
18
- public function SetOptionValue($name, $value)
19
- {
20
- $option = $this->getAdapter()->GetNamedOption($name);
21
- $this->id = $option['id'];
22
- $this->option_name = $name;
23
- // Serialize if $value is array or object
24
- $value = maybe_serialize($value);
25
- $this->option_value = $value;
26
- return $this->Save();
27
- }
28
-
29
- public function GetOptionValue($name, $default = array())
30
- {
31
- $option = $this->getAdapter()->GetNamedOption($name);
32
- $this->option_value = (!empty($option)) ? $option['option_value'] : null;
33
- if (!empty($this->option_value)) {
34
- $this->_state = self::STATE_LOADED;
35
- }
36
- // Unerialize if $value is array or object
37
- $this->option_value = maybe_unserialize($this->option_value);
38
- return $this->IsLoaded() ? $this->option_value : $default;
39
- }
40
-
41
- public function Save()
42
- {
43
- $this->_state = self::STATE_UNKNOWN;
44
-
45
- $updateId = $this->getId();
46
- $result = $this->getAdapter()->Save($this);
47
-
48
- if ($result !== false) {
49
- $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
50
- }
51
- return $result;
52
- }
53
-
54
- public function GetNotificationsSetting($opt_prefix)
55
- {
56
- return $this->getAdapter()->GetNotificationsSetting($opt_prefix);
57
- }
58
-
59
- public function GetNotification($id)
60
- {
61
- return $this->LoadData(
62
- $this->getAdapter()->GetNotification($id)
63
- );
64
- }
65
-
66
- public function DeleteByName($name)
67
- {
68
- return $this->getAdapter()->DeleteByName($name);
69
- }
70
-
71
- public function DeleteByPrefix($opt_prefix)
72
- {
73
- return $this->getAdapter()->DeleteByPrefix($opt_prefix);
74
- }
75
-
76
- public function CountNotifications($opt_prefix)
77
- {
78
- return $this->getAdapter()->CountNotifications($opt_prefix);
79
- }
80
- }
1
+ <?php
2
+
3
+ /**
4
+ * Wordpress options are always loaded from the default wordpress database.
5
+ */
6
+ class WSAL_Models_Option extends WSAL_Models_ActiveRecord
7
+ {
8
+
9
+ protected $adapterName = "Option";
10
+ public $id = '';
11
+ public $option_name = '';
12
+ public $option_value = '';
13
+ /**
14
+ * Options are always stored in WPDB. This setting ensures that
15
+ */
16
+ protected $useDefaultAdapter = true;
17
+
18
+ public function SetOptionValue($name, $value)
19
+ {
20
+ $option = $this->getAdapter()->GetNamedOption($name);
21
+ $this->id = $option['id'];
22
+ $this->option_name = $name;
23
+ // Serialize if $value is array or object
24
+ $value = maybe_serialize($value);
25
+ $this->option_value = $value;
26
+ return $this->Save();
27
+ }
28
+
29
+ public function GetOptionValue($name, $default = array())
30
+ {
31
+ $option = $this->getAdapter()->GetNamedOption($name);
32
+ $this->option_value = (!empty($option)) ? $option['option_value'] : null;
33
+ if (!empty($this->option_value)) {
34
+ $this->_state = self::STATE_LOADED;
35
+ }
36
+ // Unerialize if $value is array or object
37
+ $this->option_value = maybe_unserialize($this->option_value);
38
+ return $this->IsLoaded() ? $this->option_value : $default;
39
+ }
40
+
41
+ public function Save()
42
+ {
43
+ $this->_state = self::STATE_UNKNOWN;
44
+
45
+ $updateId = $this->getId();
46
+ $result = $this->getAdapter()->Save($this);
47
+
48
+ if ($result !== false) {
49
+ $this->_state = (!empty($updateId))?self::STATE_UPDATED:self::STATE_CREATED;
50
+ }
51
+ return $result;
52
+ }
53
+
54
+ public function GetNotificationsSetting($opt_prefix)
55
+ {
56
+ return $this->getAdapter()->GetNotificationsSetting($opt_prefix);
57
+ }
58
+
59
+ public function GetNotification($id)
60
+ {
61
+ return $this->LoadData(
62
+ $this->getAdapter()->GetNotification($id)
63
+ );
64
+ }
65
+
66
+ public function DeleteByName($name)
67
+ {
68
+ return $this->getAdapter()->DeleteByName($name);
69
+ }
70
+
71
+ public function DeleteByPrefix($opt_prefix)
72
+ {
73
+ return $this->getAdapter()->DeleteByPrefix($opt_prefix);
74
+ }
75
+
76
+ public function CountNotifications($opt_prefix)
77
+ {
78
+ return $this->getAdapter()->CountNotifications($opt_prefix);
79
+ }
80
+ }
classes/Models/Query.php CHANGED
@@ -1,187 +1,187 @@
1
- <?php
2
-
3
- class WSAL_Models_Query
4
- {
5
- protected $columns = array();
6
- protected $conditions = array();
7
- protected $orderBy = array();
8
- protected $offset = null;
9
- protected $limit = null;
10
- protected $from = array();
11
- protected $meta_join = false;
12
- protected $searchCondition = null;
13
- protected $useDefaultAdapter = false;
14
-
15
- public function __construct()
16
- {
17
-
18
- }
19
-
20
- public function getConnector()
21
- {
22
- if (!empty($this->connector)) {
23
- return $this->connector;
24
- }
25
- if ($this->useDefaultAdapter) {
26
- $this->connector = WSAL_Connector_ConnectorFactory::GetDefaultConnector();
27
- } else {
28
- $this->connector = WSAL_Connector_ConnectorFactory::GetConnector();
29
- }
30
- return $this->connector;
31
- }
32
-
33
- public function getAdapter()
34
- {
35
- return $this->getConnector()->getAdapter('Query');
36
- }
37
-
38
- public function addColumn($column)
39
- {
40
- $this->columns[] = $column;
41
- return $this;
42
- }
43
-
44
- public function clearColumns()
45
- {
46
- $this->columns = array();
47
- return $this;
48
- }
49
-
50
- public function getColumns()
51
- {
52
- return $this->columns;
53
- }
54
-
55
- public function setColumns($columns)
56
- {
57
- $this->columns = $columns;
58
- return $this;
59
- }
60
-
61
- public function addCondition($field, $value)
62
- {
63
- $this->conditions[$field] = $value;
64
- return $this;
65
- }
66
-
67
- public function addORCondition($aConditions)
68
- {
69
- $this->conditions[] = $aConditions;
70
- }
71
-
72
- public function clearConditions()
73
- {
74
- $this->conditions = array();
75
- return $this;
76
- }
77
-
78
- public function getConditions()
79
- {
80
- return $this->conditions;
81
- }
82
-
83
- public function addOrderBy($field, $isDescending = false)
84
- {
85
- $order = ($isDescending) ? 'DESC' : 'ASC';
86
- $this->orderBy[$field] = $order;
87
- return $this;
88
- }
89
-
90
- public function clearOrderBy()
91
- {
92
- $this->orderBy = array();
93
- return $this;
94
- }
95
-
96
- public function getOrderBy()
97
- {
98
- return $this->orderBy;
99
- }
100
-
101
- public function addFrom($fromDataSet)
102
- {
103
- $this->from[] = $fromDataSet;
104
- return $this;
105
- }
106
-
107
- public function clearFrom()
108
- {
109
- $this->from = array();
110
- return $this;
111
- }
112
-
113
- public function getFrom()
114
- {
115
- return $this->from;
116
- }
117
-
118
- /**
119
- * Gets the value of limit.
120
- *
121
- * @return mixed
122
- */
123
- public function getLimit()
124
- {
125
- return $this->limit;
126
- }
127
-
128
- /**
129
- * Sets the value of limit.
130
- *
131
- * @param mixed $limit the limit
132
- *
133
- * @return self
134
- */
135
- public function setLimit($limit)
136
- {
137
- $this->limit = $limit;
138
-
139
- return $this;
140
- }
141
-
142
- /**
143
- * Gets the value of offset.
144
- *
145
- * @return mixed
146
- */
147
- public function getOffset()
148
- {
149
- return $this->offset;
150
- }
151
-
152
- /**
153
- * Sets the value of offset.
154
- *
155
- * @param mixed $offset the offset
156
- *
157
- * @return self
158
- */
159
- public function setOffset($offset)
160
- {
161
- $this->offset = $offset;
162
-
163
- return $this;
164
- }
165
-
166
- public function addSearchCondition($value)
167
- {
168
- $this->searchCondition = $value;
169
- return $this;
170
- }
171
-
172
- public function getSearchCondition()
173
- {
174
- return $this->searchCondition;
175
- }
176
-
177
- public function hasMetaJoin()
178
- {
179
- return $this->meta_join;
180
- }
181
-
182
- public function addMetaJoin()
183
- {
184
- $this->meta_join = true;
185
- return $this;
186
- }
187
- }
1
+ <?php
2
+
3
+ class WSAL_Models_Query
4
+ {
5
+ protected $columns = array();
6
+ protected $conditions = array();
7
+ protected $orderBy = array();
8
+ protected $offset = null;
9
+ protected $limit = null;
10
+ protected $from = array();
11
+ protected $meta_join = false;
12
+ protected $searchCondition = null;
13
+ protected $useDefaultAdapter = false;
14
+
15
+ public function __construct()
16
+ {
17
+
18
+ }
19
+
20
+ public function getConnector()
21
+ {
22
+ if (!empty($this->connector)) {
23
+ return $this->connector;
24
+ }
25
+ if ($this->useDefaultAdapter) {
26
+ $this->connector = WSAL_Connector_ConnectorFactory::GetDefaultConnector();
27
+ } else {
28
+ $this->connector = WSAL_Connector_ConnectorFactory::GetConnector();
29
+ }
30
+ return $this->connector;
31
+ }
32
+
33
+ public function getAdapter()
34
+ {
35
+ return $this->getConnector()->getAdapter('Query');
36
+ }
37
+
38
+ public function addColumn($column)
39
+ {
40
+ $this->columns[] = $column;
41
+ return $this;
42
+ }
43
+
44
+ public function clearColumns()
45
+ {
46
+ $this->columns = array();
47
+ return $this;
48
+ }
49
+
50
+ public function getColumns()
51
+ {
52
+ return $this->columns;
53
+ }
54
+
55
+ public function setColumns($columns)
56
+ {
57
+ $this->columns = $columns;
58
+ return $this;
59
+ }
60
+
61
+ public function addCondition($field, $value)
62
+ {
63
+ $this->conditions[$field] = $value;
64
+ return $this;
65
+ }
66
+
67
+ public function addORCondition($aConditions)
68
+ {
69
+ $this->conditions[] = $aConditions;
70
+ }
71
+
72
+ public function clearConditions()
73
+ {
74
+ $this->conditions = array();
75
+ return $this;
76
+ }
77
+
78
+ public function getConditions()
79
+ {
80
+ return $this->conditions;
81
+ }
82
+
83
+ public function addOrderBy($field, $isDescending = false)
84
+ {
85
+ $order = ($isDescending) ? 'DESC' : 'ASC';
86
+ $this->orderBy[$field] = $order;
87
+ return $this;
88
+ }
89
+
90
+ public function clearOrderBy()
91
+ {
92
+ $this->orderBy = array();
93
+ return $this;
94
+ }
95
+
96
+ public function getOrderBy()
97
+ {
98
+ return $this->orderBy;
99
+ }
100
+
101
+ public function addFrom($fromDataSet)
102
+ {
103
+ $this->from[] = $fromDataSet;
104
+ return $this;
105
+ }
106
+
107
+ public function clearFrom()
108
+ {
109
+ $this->from = array();
110
+ return $this;
111
+ }
112
+
113
+ public function getFrom()
114
+ {
115
+ return $this->from;
116
+ }
117
+
118
+ /**
119
+ * Gets the value of limit.
120
+ *
121
+ * @return mixed
122
+ */
123
+ public function getLimit()
124
+ {
125
+ return $this->limit;
126
+ }
127
+
128
+ /**
129
+ * Sets the value of limit.
130
+ *
131
+ * @param mixed $limit the limit
132
+ *
133
+ * @return self
134
+ */
135
+ public function setLimit($limit)
136
+ {
137
+ $this->limit = $limit;
138
+
139
+ return $this;
140
+ }
141
+
142
+ /**
143
+ * Gets the value of offset.
144
+ *
145
+ * @return mixed
146
+ */
147
+ public function getOffset()
148
+ {
149
+ return $this->offset;
150
+ }
151
+
152
+ /**
153
+ * Sets the value of offset.
154
+ *
155
+ * @param mixed $offset the offset
156
+ *
157
+ * @return self
158
+ */
159
+ public function setOffset($offset)
160
+ {
161
+ $this->offset = $offset;
162
+
163
+ return $this;
164
+ }
165
+
166
+ public function addSearchCondition($value)
167
+ {
168
+ $this->searchCondition = $value;
169
+ return $this;
170
+ }
171
+
172
+ public function getSearchCondition()
173
+ {
174
+ return $this->searchCondition;
175
+ }
176
+
177
+ public function hasMetaJoin()
178
+ {
179
+ return $this->meta_join;
180
+ }
181
+
182
+ public function addMetaJoin()
183
+ {
184
+ $this->meta_join = true;
185
+ return $this;
186
+ }
187
+ }
classes/Sensors/Content.php CHANGED
@@ -9,6 +9,7 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
9
  add_action('admin_init', array($this, 'EventWordpressInit'));
10
  }
11
  add_action('transition_post_status', array($this, 'EventPostChanged'), 10, 3);
 
12
  add_action('delete_post', array($this, 'EventPostDeleted'), 10, 1);
13
  add_action('wp_trash_post', array($this, 'EventPostTrashed'), 10, 1);
14
  add_action('untrash_post', array($this, 'EventPostUntrashed'));
@@ -112,7 +113,6 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
112
  } else {
113
  // Handle update post events
114
  $changes = 0
115
- + $this->CheckDateChange($this->_OldPost, $post)
116
  + $this->CheckAuthorChange($this->_OldPost, $post)
117
  + $this->CheckStatusChange($this->_OldPost, $post)
118
  + $this->CheckParentChange($this->_OldPost, $post)
@@ -124,10 +124,6 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
124
  if (!$changes) {
125
  $changes = $this->CheckPermalinkChange($this->_OldLink, get_permalink($post->ID), $post);
126
  }
127
- if (!$changes) {
128
- $changes = $this->CheckModificationChange($this->_OldPost, $post);
129
- }
130
-
131
  }
132
  }
133
  }
@@ -276,10 +272,15 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
276
  protected function CheckReviewPendingChange($oldpost, $newpost)
277
  {
278
  if ($oldpost->post_status == 'pending') {
 
 
 
 
279
  $this->plugin->alerts->Trigger(2072, array(
280
  'PostID' => $oldpost->ID,
281
  'PostType' => $oldpost->post_type,
282
- 'PostTitle' => $oldpost->post_title
 
283
  ));
284
  return 1;
285
  }
@@ -450,37 +451,44 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
450
  }
451
  }
452
 
453
- protected function CheckModificationChange($oldpost, $newpost)
454
  {
455
- $contentChanged = $oldpost->post_content != $newpost->post_content; // TODO what about excerpts?
456
-
457
- if ($oldpost->post_modified != $newpost->post_modified) {
458
- $event = 0;
459
- // @see http://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters
460
- switch ($oldpost->post_status) { // TODO or should this be $newpost?
461
- case 'draft':
462
- if ($contentChanged) {
463
- $event = $this->GetEventTypeForPostType($newpost, 2068, 2069, 2070);
464
- } else {
465
- $event = $this->GetEventTypeForPostType($newpost, 2003, 2007, 2032);
466
- }
467
- break;
468
- case 'publish':
469
- if ($contentChanged) {
470
- $event = $this->GetEventTypeForPostType($newpost, 2065, 2066, 2067);
471
- } else {
472
- $event = $this->GetEventTypeForPostType($newpost, 2002, 2006, 2031);
 
 
 
 
 
 
 
 
 
473
  }
474
- break;
475
- }
476
- if ($event) {
477
- $this->plugin->alerts->Trigger($event, array(
478
- 'PostID' => $oldpost->ID,
479
- 'PostType' => $oldpost->post_type,
480
- 'PostTitle' => $oldpost->post_title,
481
- 'PostUrl' => get_permalink($oldpost->ID), // TODO or should this be $newpost?
482
- ));
483
- return 1;
484
  }
485
  }
486
  }
@@ -526,4 +534,13 @@ class WSAL_Sensors_Content extends WSAL_AbstractSensor
526
  return false;
527
  }
528
  }
 
 
 
 
 
 
 
 
 
529
  }
9
  add_action('admin_init', array($this, 'EventWordpressInit'));
10
  }
11
  add_action('transition_post_status', array($this, 'EventPostChanged'), 10, 3);
12
+ add_action('post_updated', array($this, 'CheckModificationChange'), 10, 3);
13
  add_action('delete_post', array($this, 'EventPostDeleted'), 10, 1);
14
  add_action('wp_trash_post', array($this, 'EventPostTrashed'), 10, 1);
15
  add_action('untrash_post', array($this, 'EventPostUntrashed'));
113
  } else {
114
  // Handle update post events
115
  $changes = 0
 
116
  + $this->CheckAuthorChange($this->_OldPost, $post)
117
  + $this->CheckStatusChange($this->_OldPost, $post)
118
  + $this->CheckParentChange($this->_OldPost, $post)
124
  if (!$changes) {
125
  $changes = $this->CheckPermalinkChange($this->_OldLink, get_permalink($post->ID), $post);
126
  }
 
 
 
 
127
  }
128
  }
129
  }
272
  protected function CheckReviewPendingChange($oldpost, $newpost)
273
  {
274
  if ($oldpost->post_status == 'pending') {
275
+ $revisions = wp_get_post_revisions($newpost->ID, ARRAY_A);
276
+ if (!empty($revisions)) {
277
+ $revision = array_shift($revisions);
278
+ }
279
  $this->plugin->alerts->Trigger(2072, array(
280
  'PostID' => $oldpost->ID,
281
  'PostType' => $oldpost->post_type,
282
+ 'PostTitle' => $oldpost->post_title,
283
+ 'RevisionLink' => (!empty($revision)) ? $this->getRevisionLink($revision->ID) : null
284
  ));
285
  return 1;
286
  }
451
  }
452
  }
453
 
454
+ public function CheckModificationChange($post_ID, $newpost, $oldpost)
455
  {
456
+ $changes = 0 + $this->CheckDateChange($oldpost, $newpost);
457
+ if (!$changes) {
458
+ $contentChanged = $oldpost->post_content != $newpost->post_content; // TODO what about excerpts?
459
+
460
+ if ($oldpost->post_modified != $newpost->post_modified) {
461
+ $event = 0;
462
+ // @see http://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters
463
+ switch ($oldpost->post_status) { // TODO or should this be $newpost?
464
+ case 'draft':
465
+ if ($contentChanged) {
466
+ $event = $this->GetEventTypeForPostType($newpost, 2068, 2069, 2070);
467
+ } else {
468
+ $event = $this->GetEventTypeForPostType($newpost, 2003, 2007, 2032);
469
+ }
470
+ break;
471
+ case 'publish':
472
+ if ($contentChanged) {
473
+ $event = $this->GetEventTypeForPostType($newpost, 2065, 2066, 2067);
474
+ } else {
475
+ $event = $this->GetEventTypeForPostType($newpost, 2002, 2006, 2031);
476
+ }
477
+ break;
478
+ }
479
+ if ($event) {
480
+ $revisions = wp_get_post_revisions($post_ID, ARRAY_A);
481
+ if (!empty($revisions)) {
482
+ $revision = array_shift($revisions);
483
  }
484
+ $this->plugin->alerts->Trigger($event, array(
485
+ 'PostID' => $post_ID,
486
+ 'PostType' => $oldpost->post_type,
487
+ 'PostTitle' => $oldpost->post_title,
488
+ 'PostUrl' => get_permalink($post_ID), // TODO or should this be $newpost?
489
+ 'RevisionLink' => (!empty($revision)) ? $this->getRevisionLink($revision->ID) : null
490
+ ));
491
+ }
 
 
492
  }
493
  }
494
  }
534
  return false;
535
  }
536
  }
537
+
538
+ private function getRevisionLink($revision_id)
539
+ {
540
+ if (!empty($revision_id)) {
541
+ return admin_url('revision.php?revision='.$revision_id);
542
+ } else {
543
+ return null;
544
+ }
545
+ }
546
  }
classes/Sensors/Database.php CHANGED
@@ -1,130 +1,130 @@
1
- <?php
2
-
3
- class WSAL_Sensors_Database extends WSAL_AbstractSensor {
4
-
5
- public function HookEvents() {
6
- add_action('dbdelta_queries', array($this, 'EventDBDeltaQuery'));
7
- add_action('query', array($this, 'EventDropQuery'));
8
- }
9
-
10
- public function EventDropQuery($query) {
11
- $table_names = array();
12
- $str = explode(" ", $query);
13
-
14
- if (preg_match("|DROP TABLE ([^ ]*)|", $query)) {
15
- if (!empty($str[4])) {
16
- array_push($table_names, $str[4]);
17
- } else {
18
- array_push($table_names, $str[2]);
19
- }
20
- $actype = basename($_SERVER['SCRIPT_NAME'], '.php');
21
- $alertOptions = $this->GetActionType($actype);
22
- }
23
-
24
- if (!empty($table_names)) {
25
- $event_code = $this->GetEventQueryType($actype, "delete");
26
- $alertOptions["TableNames"] = implode(",", $table_names);
27
- $this->plugin->alerts->Trigger($event_code, $alertOptions);
28
- }
29
- return $query;
30
- }
31
-
32
- public function EventDBDeltaQuery($queries) {
33
-
34
- $typeQueries = array(
35
- "create" => array(),
36
- "update" => array(),
37
- "delete" => array()
38
- );
39
- global $wpdb;
40
-
41
- foreach($queries as $qry) {
42
- $str = explode(" ", $qry);
43
- if (preg_match("|CREATE TABLE ([^ ]*)|", $qry)) {
44
- if ($wpdb->get_var("SHOW TABLES LIKE '" . $str[2] . "'") != $str[2]) {
45
- //some plugins keep trying to create tables even when they already exist- would result in too many alerts
46
- array_push($typeQueries['create'], $str[2]);
47
- }
48
- } else if (preg_match("|ALTER TABLE ([^ ]*)|", $qry)) {
49
- array_push($typeQueries['update'], $str[2]);
50
- } else if (preg_match("|DROP TABLE ([^ ]*)|", $qry)) {
51
- if (!empty($str[4])) {
52
- array_push($typeQueries['delete'], $str[4]);
53
- } else {
54
- array_push($typeQueries['delete'], $str[2]);
55
- }
56
- }
57
- }
58
-
59
- if (!empty($typeQueries["create"]) || !empty($typeQueries["update"]) || !empty($typeQueries["delete"])) {
60
- $actype = basename($_SERVER['SCRIPT_NAME'], '.php');
61
- $alertOptions = $this->GetActionType($actype);
62
-
63
-
64
- foreach($typeQueries as $queryType => $tableNames) {
65
- if (!empty($tableNames)) {
66
- $event_code = $this->GetEventQueryType($actype, $queryType);
67
- $alertOptions["TableNames"] = implode(",", $tableNames);
68
- $this->plugin->alerts->Trigger($event_code, $alertOptions);
69
- }
70
- }
71
- }
72
-
73
- return $queries;
74
- }
75
-
76
- protected function GetEventQueryType($type_action, $type_query) {
77
- switch($type_action){
78
- case 'plugins':
79
- if ($type_query == 'create') return 5010;
80
- else if ($type_query == 'update') return 5011;
81
- else if ($type_query == 'delete') return 5012;
82
- case 'themes':
83
- if ($type_query == 'create') return 5013;
84
- else if ($type_query == 'update') return 5014;
85
- else if ($type_query == 'delete') return 5015;
86
- default:
87
- if ($type_query == 'create') return 5016;
88
- else if ($type_query == 'update') return 5017;
89
- else if ($type_query == 'delete') return 5018;
90
- }
91
- }
92
-
93
- protected function GetActionType($actype) {
94
- $is_themes = $actype == 'themes';
95
- $is_plugins = $actype == 'plugins';
96
- //Action Plugin Component
97
- $alertOptions = array();
98
- if ($is_plugins) {
99
- if (isset($_REQUEST['plugin'])) {
100
- $pluginFile = $_REQUEST['plugin'];
101
- } else {
102
- $pluginFile = $_REQUEST['checked'][0];
103
- }
104
- $pluginName = basename($pluginFile, '.php');
105
- $pluginName = str_replace(array('_', '-', ' '), ' ', $pluginName);
106
- $pluginName = ucwords($pluginName);
107
- $alertOptions["Plugin"] = (object)array(
108
- 'Name' => $pluginName,
109
- );
110
- //Action Theme Component
111
- } else if ($is_themes) {
112
- if (isset($_REQUEST['theme'])) {
113
- $themeName = $_REQUEST['theme'];
114
- } else {
115
- $themeName = $_REQUEST['checked'][0];
116
- }
117
- $themeName = str_replace(array('_', '-', ' '), ' ', $themeName);
118
- $themeName = ucwords($themeName);
119
- $alertOptions["Theme"] = (object)array(
120
- 'Name' => $themeName,
121
- );
122
- //Action Unknown Component
123
- } else {
124
- $alertOptions["Component"] = "Unknown";
125
- }
126
-
127
- return $alertOptions;
128
- }
129
-
130
- }
1
+ <?php
2
+
3
+ class WSAL_Sensors_Database extends WSAL_AbstractSensor {
4
+
5
+ public function HookEvents() {
6
+ add_action('dbdelta_queries', array($this, 'EventDBDeltaQuery'));
7
+ add_action('query', array($this, 'EventDropQuery'));
8
+ }
9
+
10
+ public function EventDropQuery($query) {
11
+ $table_names = array();
12
+ $str = explode(" ", $query);
13
+
14
+ if (preg_match("|DROP TABLE ([^ ]*)|", $query)) {
15
+ if (!empty($str[4])) {
16
+ array_push($table_names, $str[4]);
17
+ } else {
18
+ array_push($table_names, $str[2]);
19
+ }
20
+ $actype = basename($_SERVER['SCRIPT_NAME'], '.php');
21
+ $alertOptions = $this->GetActionType($actype);
22
+ }
23
+
24
+ if (!empty($table_names)) {
25
+ $event_code = $this->GetEventQueryType($actype, "delete");
26
+ $alertOptions["TableNames"] = implode(",", $table_names);
27
+ $this->plugin->alerts->Trigger($event_code, $alertOptions);
28
+ }
29
+ return $query;
30
+ }
31
+
32
+ public function EventDBDeltaQuery($queries) {
33
+
34
+ $typeQueries = array(
35
+ "create" => array(),
36
+ "update" => array(),
37
+ "delete" => array()
38
+ );
39
+ global $wpdb;
40
+
41
+ foreach($queries as $qry) {
42
+ $str = explode(" ", $qry);
43
+ if (preg_match("|CREATE TABLE ([^ ]*)|", $qry)) {
44
+ if ($wpdb->get_var("SHOW TABLES LIKE '" . $str[2] . "'") != $str[2]) {
45
+ //some plugins keep trying to create tables even when they already exist- would result in too many alerts
46
+ array_push($typeQueries['create'], $str[2]);
47
+ }
48
+ } else if (preg_match("|ALTER TABLE ([^ ]*)|", $qry)) {
49
+ array_push($typeQueries['update'], $str[2]);
50
+ } else if (preg_match("|DROP TABLE ([^ ]*)|", $qry)) {
51
+ if (!empty($str[4])) {
52
+ array_push($typeQueries['delete'], $str[4]);
53
+ } else {
54
+ array_push($typeQueries['delete'], $str[2]);
55
+ }
56
+ }
57
+ }
58
+
59
+ if (!empty($typeQueries["create"]) || !empty($typeQueries["update"]) || !empty($typeQueries["delete"])) {
60
+ $actype = basename($_SERVER['SCRIPT_NAME'], '.php');
61
+ $alertOptions = $this->GetActionType($actype);
62
+
63
+
64
+ foreach($typeQueries as $queryType => $tableNames) {
65
+ if (!empty($tableNames)) {
66
+ $event_code = $this->GetEventQueryType($actype, $queryType);
67
+ $alertOptions["TableNames"] = implode(",", $tableNames);
68
+ $this->plugin->alerts->Trigger($event_code, $alertOptions);
69
+ }
70
+ }
71
+ }
72
+
73
+ return $queries;
74
+ }
75
+
76
+ protected function GetEventQueryType($type_action, $type_query) {
77
+ switch($type_action){
78
+ case 'plugins':
79
+ if ($type_query == 'create') return 5010;
80
+ else if ($type_query == 'update') return 5011;
81
+ else if ($type_query == 'delete') return 5012;
82
+ case 'themes':
83
+ if ($type_query == 'create') return 5013;
84
+ else if ($type_query == 'update') return 5014;
85
+ else if ($type_query == 'delete') return 5015;
86
+ default:
87
+ if ($type_query == 'create') return 5016;
88
+ else if ($type_query == 'update') return 5017;
89
+ else if ($type_query == 'delete') return 5018;
90
+ }
91
+ }
92
+
93
+ protected function GetActionType($actype) {
94
+ $is_themes = $actype == 'themes';
95
+ $is_plugins = $actype == 'plugins';
96
+ //Action Plugin Component
97
+ $alertOptions = array();
98
+ if ($is_plugins) {
99
+ if (isset($_REQUEST['plugin'])) {
100
+ $pluginFile = $_REQUEST['plugin'];
101
+ } else {
102
+ $pluginFile = $_REQUEST['checked'][0];
103
+ }
104
+ $pluginName = basename($pluginFile, '.php');
105
+ $pluginName = str_replace(array('_', '-', ' '), ' ', $pluginName);
106
+ $pluginName = ucwords($pluginName);
107
+ $alertOptions["Plugin"] = (object)array(
108
+ 'Name' => $pluginName,
109
+ );
110
+ //Action Theme Component
111
+ } else if ($is_themes) {
112
+ if (isset($_REQUEST['theme'])) {
113
+ $themeName = $_REQUEST['theme'];
114
+ } else {
115
+ $themeName = $_REQUEST['checked'][0];
116
+ }
117
+ $themeName = str_replace(array('_', '-', ' '), ' ', $themeName);
118
+ $themeName = ucwords($themeName);
119
+ $alertOptions["Theme"] = (object)array(
120
+ 'Name' => $themeName,
121
+ );
122
+ //Action Unknown Component
123
+ } else {
124
+ $alertOptions["Component"] = "Unknown";
125
+ }
126
+
127
+ return $alertOptions;
128
+ }
129
+
130
+ }
classes/Settings.php CHANGED
@@ -591,9 +591,16 @@ class WSAL_Settings {
591
 
592
  public function GetColumns(){
593
  $columns = array('alert_code' => '1', 'type' => '1', 'date' => '1', 'username' => '1', 'source_ip' => '1', 'message' => '1');
 
 
 
 
594
  $selected = $this->GetColumnsSelected();
595
  if (!empty($selected)) {
596
  $columns = array('alert_code' => '0', 'type' => '0', 'date' => '0', 'username' => '0', 'source_ip' => '0', 'message' => '0');
 
 
 
597
  $selected = (array)json_decode($selected);
598
  $columns = array_merge($columns, $selected);
599
  return $columns;
591
 
592
  public function GetColumns(){
593
  $columns = array('alert_code' => '1', 'type' => '1', 'date' => '1', 'username' => '1', 'source_ip' => '1', 'message' => '1');
594
+ if ($this->_plugin->IsMultisite()) {
595
+ $columns = array_slice($columns, 0, 5, true) + array('site' => '1') + array_slice($columns, 5, null, true);
596
+ }
597
+ error_log(print_r($columns, true));
598
  $selected = $this->GetColumnsSelected();
599
  if (!empty($selected)) {
600
  $columns = array('alert_code' => '0', 'type' => '0', 'date' => '0', 'username' => '0', 'source_ip' => '0', 'message' => '0');
601
+ if ($this->_plugin->IsMultisite()) {
602
+ $columns = array_slice($columns, 0, 5, true) + array('site' => '0') + array_slice($columns, 5, null, true);
603
+ }
604
  $selected = (array)json_decode($selected);
605
  $columns = array_merge($columns, $selected);
606
  return $columns;
classes/Views/Settings.php CHANGED
@@ -353,8 +353,8 @@ class WSAL_Views_Settings extends WSAL_AbstractView {
353
  <?php $columns = $this->_plugin->settings->GetColumns(); ?>
354
  <?php foreach ($columns as $key => $value) { ?>
355
  <label for="columns">
356
- <input type="checkbox" name="Columns[<?=$key?>]" id="<?=$key?>" class="sel-columns" style="margin-top: 2px;" <?php if ($value == '1') echo 'checked="checked"'; ?> value="1">
357
- <span><?=ucwords(str_replace("_", " ", $key))?></span>
358
  </label>
359
  <br/>
360
  <?php } ?>
@@ -439,7 +439,7 @@ viewer though the plugin will still record such information in the database.', '
439
  </td>
440
  </tr>
441
  <tr>
442
- <th><label for="DeleteData"><?php _e('Remove Data on Unistall', 'wp-security-audit-log'); ?></label></th>
443
  <td>
444
  <fieldset>
445
  <label for="DeleteData">
353
  <?php $columns = $this->_plugin->settings->GetColumns(); ?>
354
  <?php foreach ($columns as $key => $value) { ?>
355
  <label for="columns">
356
+ <input type="checkbox" name="Columns[<?php echo $key; ?>]" id="<?php echo $key; ?>" class="sel-columns" style="margin-top: 2px;" <?php if ($value == '1') echo 'checked="checked"'; ?> value="1">
357
+ <span><?php echo ucwords(str_replace("_", " ", $key)); ?></span>
358
  </label>
359
  <br/>
360
  <?php } ?>
439
  </td>
440
  </tr>
441
  <tr>
442
+ <th><label for="DeleteData"><?php _e('Remove Data on Uninstall', 'wp-security-audit-log'); ?></label></th>
443
  <td>
444
  <fieldset>
445
  <label for="DeleteData">
css/install-error.css CHANGED
@@ -1,41 +1,41 @@
1
- .warn-icon-tri {
2
- top: 5px;
3
- left: 5px;
4
- position: absolute;
5
- border-left: 16px solid #FFF;
6
- border-right: 16px solid #FFF;
7
- border-bottom: 28px solid #C33;
8
- height: 3px;
9
- width: 4px
10
- }
11
-
12
- .warn-icon-chr {
13
- top: 8px;
14
- left: 18px;
15
- position: absolute;
16
- color: #FFF;
17
- font: 26px Georgia;
18
- }
19
-
20
- .warn-icon-cir {
21
- top: 2px;
22
- left: 0px;
23
- position: absolute;
24
- overflow: hidden;
25
- border: 6px solid #FFF;
26
- border-radius: 32px;
27
- width: 34px;
28
- height: 34px;
29
- }
30
-
31
- .warn-wrap {
32
- position: relative;
33
- color: #A00;
34
- font: 14px Arial;
35
- padding: 6px 48px;
36
- }
37
-
38
- .warn-wrap a,
39
- .warn-wrap a:hover {
40
- color: #F56;
41
- }
1
+ .warn-icon-tri {
2
+ top: 5px;
3
+ left: 5px;
4
+ position: absolute;
5
+ border-left: 16px solid #FFF;
6
+ border-right: 16px solid #FFF;
7
+ border-bottom: 28px solid #C33;
8
+ height: 3px;
9
+ width: 4px
10
+ }
11
+
12
+ .warn-icon-chr {
13
+ top: 8px;
14
+ left: 18px;
15
+ position: absolute;
16
+ color: #FFF;
17
+ font: 26px Georgia;
18
+ }
19
+
20
+ .warn-icon-cir {
21
+ top: 2px;
22
+ left: 0px;
23
+ position: absolute;
24
+ overflow: hidden;
25
+ border: 6px solid #FFF;
26
+ border-radius: 32px;
27
+ width: 34px;
28
+ height: 34px;
29
+ }
30
+
31
+ .warn-wrap {
32
+ position: relative;
33
+ color: #A00;
34
+ font: 14px Arial;
35
+ padding: 6px 48px;
36
+ }
37
+
38
+ .warn-wrap a,
39
+ .warn-wrap a:hover {
40
+ color: #F56;
41
+ }
css/settings.css CHANGED
@@ -1,71 +1,71 @@
1
- #audit-log-settings {
2
- padding-right: 256px;
3
- position: relative;
4
- }
5
-
6
- #audit-log-adverts {
7
- position: absolute;
8
- top: 3px;
9
- right: 3px;
10
- overflow: hidden;
11
- }
12
-
13
- #audit-log-adverts a {
14
- display: block;
15
- text-decoration: none;
16
- margin: 4px 0;
17
- }
18
-
19
- .sectoken-user,
20
- .sectoken-role,
21
- .sectoken-other {
22
- display: inline-block;
23
- border-width: 1px;
24
- border-style: solid;
25
- padding: 2px 4px;
26
- margin: 2px 0 0 2px;
27
- border-radius: 3px;
28
- cursor: default;
29
- }
30
- .sectoken-other {
31
- display: table;
32
- border-collapse: separate;
33
- }
34
-
35
- .sectoken-user a,
36
- .sectoken-role a,
37
- .sectoken-other a {
38
- text-decoration: none;
39
- font-size: 12px;
40
- font-weight: bold;
41
- color: #FFF;
42
- margin-left: 2px;
43
- background: #BBB;
44
- border-radius: 25px;
45
- height: 14px;
46
- display: inline-block;
47
- width: 14px;
48
- text-align: center;
49
- line-height: 16px;
50
- }
51
-
52
- .sectoken-user a:hover,
53
- .sectoken-role a:hover,
54
- .sectoken-other a:hover {
55
- background: #FB9;
56
- }
57
-
58
- .sectoken-user { background: #EFF; border-color: #5BE; }
59
- .sectoken-role { background: #EFE; border-color: #5B5; }
60
- .sectoken-other { background: #FFE; border-color: #ED5; }
61
- .sectoken-del { background: #FEE; border-color: #EBB; }
62
-
63
- .wsal-tab {
64
- margin-top: 0px;
65
- }
66
- .wsal-tab th {
67
- padding-left: 20px;
68
- }
69
- .wsal-tab td {
70
- padding-left: 20px;
71
  }
1
+ #audit-log-settings {
2
+ padding-right: 256px;
3
+ position: relative;
4
+ }
5
+
6
+ #audit-log-adverts {
7
+ position: absolute;
8
+ top: 3px;
9
+ right: 3px;
10
+ overflow: hidden;
11
+ }
12
+
13
+ #audit-log-adverts a {
14
+ display: block;
15
+ text-decoration: none;
16
+ margin: 4px 0;
17
+ }
18
+
19
+ .sectoken-user,
20
+ .sectoken-role,
21
+ .sectoken-other {
22
+ display: inline-block;
23
+ border-width: 1px;
24
+ border-style: solid;
25
+ padding: 2px 4px;
26
+ margin: 2px 0 0 2px;
27
+ border-radius: 3px;
28
+ cursor: default;
29
+ }
30
+ .sectoken-other {
31
+ display: table;
32
+ border-collapse: separate;
33
+ }
34
+
35
+ .sectoken-user a,
36
+ .sectoken-role a,
37
+ .sectoken-other a {
38
+ text-decoration: none;
39
+ font-size: 12px;
40
+ font-weight: bold;
41
+ color: #FFF;
42
+ margin-left: 2px;
43
+ background: #BBB;
44
+ border-radius: 25px;
45
+ height: 14px;
46
+ display: inline-block;
47
+ width: 14px;
48
+ text-align: center;
49
+ line-height: 16px;
50
+ }
51
+
52
+ .sectoken-user a:hover,
53
+ .sectoken-role a:hover,
54
+ .sectoken-other a:hover {
55
+ background: #FB9;
56
+ }
57
+
58
+ .sectoken-user { background: #EFF; border-color: #5BE; }
59
+ .sectoken-role { background: #EFE; border-color: #5B5; }
60
+ .sectoken-other { background: #FFE; border-color: #ED5; }
61
+ .sectoken-del { background: #FEE; border-color: #EBB; }
62
+
63
+ .wsal-tab {
64
+ margin-top: 0px;
65
+ }
66
+ .wsal-tab th {
67
+ padding-left: 20px;
68
+ }
69
+ .wsal-tab td {
70
+ padding-left: 20px;
71
  }
defaults.php CHANGED
@@ -67,9 +67,9 @@ function wsaldefaults_wsal_init(WpSecurityAuditLog $wsal){
67
  array(2054, E_NOTICE, __('User updates a custom field value for a post', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
68
  array(2055, E_NOTICE, __('User deletes a custom field from a post', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
69
  array(2062, E_NOTICE, __('User updates a custom field name for a post', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
70
- array(2065, E_WARNING, __('User modifies content for a published post', 'wp-security-audit-log'), __('Modified the content of published post %PostTitle%', 'wp-security-audit-log')),
71
- array(2068, E_NOTICE, __('User modifies content for a draft post', 'wp-security-audit-log'), __('Modified the content of draft post %PostTitle%', 'wp-security-audit-log')),
72
- array(2072, E_NOTICE, __('User modifies content of a post', 'wp-security-audit-log'), __('Modified the content of post %PostTitle% which is submitted for review', 'wp-security-audit-log')),
73
  array(2073, E_NOTICE, __('User submitted a post for review', 'wp-security-audit-log'), __('Submitted blog post %PostTitle% for review. Blog post ID is %PostID%', 'wp-security-audit-log')),
74
  ),
75
  __('Pages', 'wp-security-audit-log') => array(
@@ -91,8 +91,8 @@ function wsaldefaults_wsal_init(WpSecurityAuditLog $wsal){
91
  array(2060, E_NOTICE, __('User updates a custom field value for a page', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
92
  array(2061, E_NOTICE, __('User deletes a custom field from a page', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
93
  array(2064, E_NOTICE, __('User updates a custom field name for a page', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
94
- array(2066, E_WARNING, __('User modifies content for a published page', 'wp-security-audit-log'), __('Modified the content of published page %PostTitle%', 'wp-security-audit-log')),
95
- array(2069, E_NOTICE, __('User modifies content for a draft page', 'wp-security-audit-log'), __('Modified the content of draft page %PostTitle%', 'wp-security-audit-log')),
96
  ),
97
  __('Custom Posts', 'wp-security-audit-log') => array(
98
  array(2029, E_NOTICE, __('User created a new post with custom post type and saved it as draft', 'wp-security-audit-log'), __('Created a new custom post called %PostTitle% of type %PostType%. Post ID is %PostID%', 'wp-security-audit-log')),
@@ -112,8 +112,8 @@ function wsaldefaults_wsal_init(WpSecurityAuditLog $wsal){
112
  array(2057, E_NOTICE, __('User updates a custom field for a custom post', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
113
  array(2058, E_NOTICE, __('User deletes a custom field from a custom post', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
114
  array(2063, E_NOTICE, __('User updates a custom field name for a custom post', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
115
- array(2067, E_WARNING, __('User modifies content for a published custom post', 'wp-security-audit-log'), __('Modified the content of published custom post type %PostTitle%', 'wp-security-audit-log')),
116
- array(2070, E_NOTICE, __('User modifies content for a draft custom post', 'wp-security-audit-log'), __('Modified the content of draft custom post type %PostTitle%', 'wp-security-audit-log')),
117
  ),
118
  __('Widgets', 'wp-security-audit-log') => array(
119
  array(2042, E_CRITICAL, __('User added a new widget', 'wp-security-audit-log'), __('Added a new %WidgetName% widget in %Sidebar%', 'wp-security-audit-log')),
67
  array(2054, E_NOTICE, __('User updates a custom field value for a post', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
68
  array(2055, E_NOTICE, __('User deletes a custom field from a post', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
69
  array(2062, E_NOTICE, __('User updates a custom field name for a post', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in post %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
70
+ array(2065, E_WARNING, __('User modifies content for a published post', 'wp-security-audit-log'), __('Modified the content of published post %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
71
+ array(2068, E_NOTICE, __('User modifies content for a draft post', 'wp-security-audit-log'), __('Modified the content of draft post %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
72
+ array(2072, E_NOTICE, __('User modifies content of a post', 'wp-security-audit-log'), __('Modified the content of post %PostTitle% which is submitted for review.'.'%RevisionLink%', 'wp-security-audit-log')),
73
  array(2073, E_NOTICE, __('User submitted a post for review', 'wp-security-audit-log'), __('Submitted blog post %PostTitle% for review. Blog post ID is %PostID%', 'wp-security-audit-log')),
74
  ),
75
  __('Pages', 'wp-security-audit-log') => array(
91
  array(2060, E_NOTICE, __('User updates a custom field value for a page', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
92
  array(2061, E_NOTICE, __('User deletes a custom field from a page', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
93
  array(2064, E_NOTICE, __('User updates a custom field name for a page', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in page %PostTitle%'.'%MetaLink%', 'wp-security-audit-log')),
94
+ array(2066, E_WARNING, __('User modifies content for a published page', 'wp-security-audit-log'), __('Modified the content of published page %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
95
+ array(2069, E_NOTICE, __('User modifies content for a draft page', 'wp-security-audit-log'), __('Modified the content of draft page %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
96
  ),
97
  __('Custom Posts', 'wp-security-audit-log') => array(
98
  array(2029, E_NOTICE, __('User created a new post with custom post type and saved it as draft', 'wp-security-audit-log'), __('Created a new custom post called %PostTitle% of type %PostType%. Post ID is %PostID%', 'wp-security-audit-log')),
112
  array(2057, E_NOTICE, __('User updates a custom field for a custom post', 'wp-security-audit-log'), __('Modified the value of custom field %MetaKey% from %MetaValueOld% to %MetaValueNew% in custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
113
  array(2058, E_NOTICE, __('User deletes a custom field from a custom post', 'wp-security-audit-log'), __('Deleted custom field %MetaKey% with id %MetaID% from custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
114
  array(2063, E_NOTICE, __('User updates a custom field name for a custom post', 'wp-security-audit-log'), __('Changed the custom field name from %MetaKeyOld% to %MetaKeyNew% in custom post %PostTitle% of type %PostType%'.'%MetaLink%', 'wp-security-audit-log')),
115
+ array(2067, E_WARNING, __('User modifies content for a published custom post', 'wp-security-audit-log'), __('Modified the content of published custom post type %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
116
+ array(2070, E_NOTICE, __('User modifies content for a draft custom post', 'wp-security-audit-log'), __('Modified the content of draft custom post type %PostTitle%.'.'%RevisionLink%', 'wp-security-audit-log')),
117
  ),
118
  __('Widgets', 'wp-security-audit-log') => array(
119
  array(2042, E_CRITICAL, __('User added a new widget', 'wp-security-audit-log'), __('Added a new %WidgetName% widget in %Sidebar%', 'wp-security-audit-log')),
js/auditlog.js CHANGED
@@ -1,150 +1,150 @@
1
- var WsalData;
2
-
3
- window['WsalAuditLogRefreshed'] = function(){
4
- // fix pagination links causing form params to get lost
5
- jQuery('span.pagination-links a').click(function(ev){
6
- ev.preventDefault();
7
- var deparam = function(url){
8
- var obj = {};
9
- var pairs = url.split('&');
10
- for(var i in pairs){
11
- var split = pairs[i].split('=');
12
- obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
13
- }
14
- return obj;
15
- };
16
- var paged = deparam(this.href).paged;
17
- if (typeof paged === 'undefined') paged = 1;
18
- jQuery('#audit-log-viewer').append(
19
- jQuery('<input type="hidden" name="paged"/>').val(paged)
20
- ).submit();
21
- });
22
- };
23
-
24
- function WsalAuditLogInit(_WsalData){
25
- WsalData = _WsalData;
26
- var WsalTkn = WsalData.autorefresh.token;
27
-
28
- // list refresher
29
- var WsalAjx = null;
30
- var WsalChk = function(){
31
- if(WsalAjx)WsalAjx.abort();
32
- WsalAjx = jQuery.post(WsalData.ajaxurl, {
33
- action: 'AjaxRefresh',
34
- logcount: WsalTkn
35
- }, function(data){
36
- WsalAjx = null;
37
- if(data && data !== 'false'){
38
- WsalTkn = data;
39
- jQuery('#audit-log-viewer').load(
40
- location.href + ' #audit-log-viewer-content',
41
- window['WsalAuditLogRefreshed']
42
- );
43
- }
44
- WsalChk();
45
- });
46
- };
47
- if(WsalData.autorefresh.enabled){
48
- setInterval(WsalChk, 40000);
49
- WsalChk();
50
- }
51
-
52
- WsalSsasInit();
53
- }
54
-
55
- var WsalIppsPrev;
56
-
57
- function WsalIppsFocus(value){
58
- WsalIppsPrev = value;
59
- }
60
-
61
- function WsalIppsChange(value){
62
- if(value === ''){
63
- value = window.prompt(WsalData.tr8n.numofitems, WsalIppsPrev);
64
- if(value === null || value === WsalIppsPrev)return this.value = WsalIppsPrev; // operation canceled
65
- }
66
- jQuery('select.wsal-ipps').attr('disabled', true);
67
- jQuery.post(WsalData.ajaxurl, {
68
- action: 'AjaxSetIpp',
69
- count: value
70
- }, function(){
71
- location.reload();
72
- });
73
- }
74
-
75
- function WsalSsasInit(){
76
- var SsasAjx = null;
77
- var SsasInps = jQuery("input.wsal-ssas");
78
- SsasInps.after('<div class="wsal-ssas-dd" style="display: none;"/>');
79
- SsasInps.click(function(){
80
- jQuery(this).select();
81
- });
82
- window['WsalAuditLogRefreshed']();
83
- SsasInps.keyup(function(){
84
- var SsasInp = jQuery(this);
85
- var SsasDiv = SsasInp.next();
86
- var SsasVal = SsasInp.val();
87
- if(SsasAjx)SsasAjx.abort();
88
- SsasInp.removeClass('loading');
89
-
90
- // do a new search
91
- if(SsasInp.attr('data-oldvalue') !== SsasVal && SsasVal.length > 2){
92
- SsasInp.addClass('loading');
93
- SsasAjx = jQuery.post(WsalData.ajaxurl, {
94
- action: 'AjaxSearchSite',
95
- search: SsasVal
96
- }, function(data){
97
- if(SsasAjx)SsasAjx = null;
98
- SsasInp.removeClass('loading');
99
- SsasDiv.hide();
100
- SsasDiv.html('');
101
- if(data && data.length){
102
- var SsasReg = new RegExp(SsasVal.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'), 'gi');
103
- for (var i = 0; i < data.length; i++){
104
- var link = jQuery('<a href="javascript:;" onclick="WsalSsasChange(' + data[i].blog_id + ')"/>')
105
- .text(data[i].blogname + ' (' + data[i].domain + ')');
106
- link.html(link.text().replace(SsasReg, '<u>$&</u>'));
107
- SsasDiv.append(link);
108
- }
109
- }else{
110
- SsasDiv.append(jQuery('<span/>').text(WsalData.tr8n.searchnone));
111
- }
112
- SsasDiv.prepend(jQuery('<a href="javascript:;" onclick="WsalSsasChange(0)" class="allsites"/>').text(WsalData.tr8n.searchback));
113
- SsasDiv.show();
114
- }, 'json');
115
- SsasInp.attr('data-oldvalue', SsasVal);
116
- }
117
-
118
- // handle keys
119
- });
120
- SsasInps.blur(function(){
121
- setTimeout(function(){
122
- var SsasInp = jQuery(this);
123
- var SsasDiv = SsasInp.next();
124
- SsasInp.attr('data-oldvalue', '');
125
- SsasDiv.hide();
126
- }, 200);
127
- });
128
- }
129
-
130
- function WsalSsasChange(value){
131
- jQuery('div.wsal-ssas-dd').hide();
132
- jQuery('input.wsal-ssas').attr('disabled', true);
133
- jQuery('#wsal-cbid').val(value);
134
- jQuery('#audit-log-viewer').submit();
135
- }
136
-
137
- function WsalDisableCustom(link, meta_key){
138
- var nfe = jQuery(this).parents('div:first');
139
- jQuery(link).hide();
140
- jQuery.ajax({
141
- type: 'POST',
142
- url: ajaxurl,
143
- async: false,
144
- data: { action: 'AjaxDisableCustomField', notice: meta_key },
145
- success: function(data) {
146
- var notice = jQuery('<div class="updated" data-notice-name="notifications-extension"></div>').html(data);
147
- jQuery("h2:first").after(notice);
148
- }
149
- });
150
  }
1
+ var WsalData;
2
+
3
+ window['WsalAuditLogRefreshed'] = function(){
4
+ // fix pagination links causing form params to get lost
5
+ jQuery('span.pagination-links a').click(function(ev){
6
+ ev.preventDefault();
7
+ var deparam = function(url){
8
+ var obj = {};
9
+ var pairs = url.split('&');
10
+ for(var i in pairs){
11
+ var split = pairs[i].split('=');
12
+ obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
13
+ }
14
+ return obj;
15
+ };
16
+ var paged = deparam(this.href).paged;
17
+ if (typeof paged === 'undefined') paged = 1;
18
+ jQuery('#audit-log-viewer').append(
19
+ jQuery('<input type="hidden" name="paged"/>').val(paged)
20
+ ).submit();
21
+ });
22
+ };
23
+
24
+ function WsalAuditLogInit(_WsalData){
25
+ WsalData = _WsalData;
26
+ var WsalTkn = WsalData.autorefresh.token;
27
+
28
+ // list refresher
29
+ var WsalAjx = null;
30
+ var WsalChk = function(){
31
+ if(WsalAjx)WsalAjx.abort();
32
+ WsalAjx = jQuery.post(WsalData.ajaxurl, {
33
+ action: 'AjaxRefresh',
34
+ logcount: WsalTkn
35
+ }, function(data){
36
+ WsalAjx = null;
37
+ if(data && data !== 'false'){
38
+ WsalTkn = data;
39
+ jQuery('#audit-log-viewer').load(
40
+ location.href + ' #audit-log-viewer-content',
41
+ window['WsalAuditLogRefreshed']
42
+ );
43
+ }
44
+ WsalChk();
45
+ });
46
+ };
47
+ if(WsalData.autorefresh.enabled){
48
+ setInterval(WsalChk, 40000);
49
+ WsalChk();
50
+ }
51
+
52
+ WsalSsasInit();
53
+ }
54
+
55
+ var WsalIppsPrev;
56
+
57
+ function WsalIppsFocus(value){
58
+ WsalIppsPrev = value;
59
+ }
60
+
61
+ function WsalIppsChange(value){
62
+ if(value === ''){
63
+ value = window.prompt(WsalData.tr8n.numofitems, WsalIppsPrev);
64
+ if(value === null || value === WsalIppsPrev)return this.value = WsalIppsPrev; // operation canceled
65
+ }
66
+ jQuery('select.wsal-ipps').attr('disabled', true);
67
+ jQuery.post(WsalData.ajaxurl, {
68
+ action: 'AjaxSetIpp',
69
+ count: value
70
+ }, function(){
71
+ location.reload();
72
+ });
73
+ }
74
+
75
+ function WsalSsasInit(){
76
+ var SsasAjx = null;
77
+ var SsasInps = jQuery("input.wsal-ssas");
78
+ SsasInps.after('<div class="wsal-ssas-dd" style="display: none;"/>');
79
+ SsasInps.click(function(){
80
+ jQuery(this).select();
81
+ });
82
+ window['WsalAuditLogRefreshed']();
83
+ SsasInps.keyup(function(){
84
+ var SsasInp = jQuery(this);
85
+ var SsasDiv = SsasInp.next();
86
+ var SsasVal = SsasInp.val();
87
+ if(SsasAjx)SsasAjx.abort();
88
+ SsasInp.removeClass('loading');
89
+
90
+ // do a new search
91
+ if(SsasInp.attr('data-oldvalue') !== SsasVal && SsasVal.length > 2){
92
+ SsasInp.addClass('loading');
93
+ SsasAjx = jQuery.post(WsalData.ajaxurl, {
94
+ action: 'AjaxSearchSite',
95
+ search: SsasVal
96
+ }, function(data){
97
+ if(SsasAjx)SsasAjx = null;
98
+ SsasInp.removeClass('loading');
99
+ SsasDiv.hide();
100
+ SsasDiv.html('');
101
+ if(data && data.length){
102
+ var SsasReg = new RegExp(SsasVal.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'), 'gi');
103
+ for (var i = 0; i < data.length; i++){
104
+ var link = jQuery('<a href="javascript:;" onclick="WsalSsasChange(' + data[i].blog_id + ')"/>')
105
+ .text(data[i].blogname + ' (' + data[i].domain + ')');
106
+ link.html(link.text().replace(SsasReg, '<u>$&</u>'));
107
+ SsasDiv.append(link);
108
+ }
109
+ }else{
110
+ SsasDiv.append(jQuery('<span/>').text(WsalData.tr8n.searchnone));
111
+ }
112
+ SsasDiv.prepend(jQuery('<a href="javascript:;" onclick="WsalSsasChange(0)" class="allsites"/>').text(WsalData.tr8n.searchback));
113
+ SsasDiv.show();
114
+ }, 'json');
115
+ SsasInp.attr('data-oldvalue', SsasVal);
116
+ }
117
+
118
+ // handle keys
119
+ });
120
+ SsasInps.blur(function(){
121
+ setTimeout(function(){
122
+ var SsasInp = jQuery(this);
123
+ var SsasDiv = SsasInp.next();
124
+ SsasInp.attr('data-oldvalue', '');
125
+ SsasDiv.hide();
126
+ }, 200);
127
+ });
128
+ }
129
+
130
+ function WsalSsasChange(value){
131
+ jQuery('div.wsal-ssas-dd').hide();
132
+ jQuery('input.wsal-ssas').attr('disabled', true);
133
+ jQuery('#wsal-cbid').val(value);
134
+ jQuery('#audit-log-viewer').submit();
135
+ }
136
+
137
+ function WsalDisableCustom(link, meta_key){
138
+ var nfe = jQuery(this).parents('div:first');
139
+ jQuery(link).hide();
140
+ jQuery.ajax({
141
+ type: 'POST',
142
+ url: ajaxurl,
143
+ async: false,
144
+ data: { action: 'AjaxDisableCustomField', notice: meta_key },
145
+ success: function(data) {
146
+ var notice = jQuery('<div class="updated" data-notice-name="notifications-extension"></div>').html(data);
147
+ jQuery("h2:first").after(notice);
148
+ }
149
+ });
150
  }
js/common.js CHANGED
@@ -1,14 +1,14 @@
1
-
2
- jQuery(document).ready(function(){
3
- jQuery('a.wsal-dismiss-notification').click(function(){
4
- var nfe = jQuery(this).parents('div:first');
5
- var nfn = nfe.attr('data-notice-name');
6
- jQuery.ajax({
7
- type: 'POST',
8
- url: ajaxurl,
9
- async: false,
10
- data: { action: 'AjaxDismissNotice', notice: nfn }
11
- });
12
- nfe.fadeOut();
13
- });
14
- });
1
+
2
+ jQuery(document).ready(function(){
3
+ jQuery('a.wsal-dismiss-notification').click(function(){
4
+ var nfe = jQuery(this).parents('div:first');
5
+ var nfn = nfe.attr('data-notice-name');
6
+ jQuery.ajax({
7
+ type: 'POST',
8
+ url: ajaxurl,
9
+ async: false,
10
+ data: { action: 'AjaxDismissNotice', notice: nfn }
11
+ });
12
+ nfe.fadeOut();
13
+ });
14
+ });
js/nice_r.js CHANGED
@@ -1,12 +1,12 @@
1
- function nice_r_toggle(pfx, id){
2
- var el = document.getElementById(pfx+'_v'+id);
3
- if(el){
4
- if(el.style.display==='block'){
5
- el.style.display = 'none';
6
- document.getElementById(pfx+'_a'+id).innerHTML = '&#9658;';
7
- }else{
8
- el.style.display = 'block';
9
- document.getElementById(pfx+'_a'+id).innerHTML = '&#9660;';
10
- }
11
- }
12
  }
1
+ function nice_r_toggle(pfx, id){
2
+ var el = document.getElementById(pfx+'_v'+id);
3
+ if(el){
4
+ if(el.style.display==='block'){
5
+ el.style.display = 'none';
6
+ document.getElementById(pfx+'_a'+id).innerHTML = '&#9658;';
7
+ }else{
8
+ el.style.display = 'block';
9
+ document.getElementById(pfx+'_a'+id).innerHTML = '&#9660;';
10
+ }
11
+ }
12
  }
js/settings.js CHANGED
@@ -1,73 +1,73 @@
1
- jQuery(document).ready(function(){
2
- var RemoveSecToken = function(){
3
- var $this = jQuery(this).parents('span:first');
4
- $this.addClass('sectoken-del').fadeOut('fast', function(){
5
- $this.remove();
6
- });
7
- };
8
-
9
- jQuery('#ViewerQueryBox, #EditorQueryBox, #ExRoleQueryBox, #ExUserQueryBox, #CustomQueryBox, #IpAddrQueryBox').keydown(function(event){
10
- if(event.keyCode === 13) {
11
- var type = jQuery(this).attr('id').substr(0, 6);
12
- jQuery('#'+type+'QueryAdd').click();
13
- return false;
14
- }
15
- });
16
-
17
- jQuery('#ViewerQueryAdd, #EditorQueryAdd, #ExRoleQueryAdd, #ExUserQueryAdd, #CustomQueryAdd, #IpAddrQueryAdd').click(function(){
18
- var type = jQuery(this).attr('id').substr(0, 6);
19
- var value = jQuery.trim(jQuery('#'+type+'QueryBox').val());
20
- var existing = jQuery('#'+type+'List input').filter(function() { return this.value === value; });
21
-
22
- if(!value || existing.length)return; // if value is empty or already used, stop here
23
-
24
- jQuery('#'+type+'QueryBox, #'+type+'QueryAdd').attr('disabled', true);
25
- jQuery.post(jQuery('#ajaxurl').val(), {action: 'AjaxCheckSecurityToken', token: value}, function(data){
26
- jQuery('#'+type+'QueryBox, #'+type+'QueryAdd').attr('disabled', false);
27
- if (type != 'Custom' && type != 'IpAddr') {
28
- if(data === 'other') {
29
- alert('The specified token is not a user nor a role!');
30
- jQuery('#'+type+'QueryBox').val('');
31
- return;
32
- }
33
- }
34
- jQuery('#'+type+'QueryBox').val('');
35
- jQuery('#'+type+'List').append(jQuery('<span class="sectoken-'+data+'"/>').text(value).append(
36
- jQuery('<input type="hidden" name="'+type+'s[]"/>').val(value),
37
- jQuery('<a href="javascript:;" title="Remove">&times;</a>').click(RemoveSecToken)
38
- ));
39
- });
40
- });
41
-
42
- jQuery('#ViewerList>span>a, #EditorList>span>a, #ExRoleList>span>a, #ExUserList>span>a, #CustomList>span>a, #IpAddrList>span>a').click(RemoveSecToken);
43
-
44
- jQuery('#RestrictAdmins').change(function(){
45
- var user = jQuery('#RestrictAdminsDefaultUser').val();
46
- var fltr = function() { return this.value === user; };
47
- if (this.checked && jQuery('#EditorList input').filter(fltr).length === 0) {
48
- jQuery('#EditorList').append(
49
- jQuery('<span class="sectoken-user"/>').text(user)
50
- .prepend(jQuery('<input type="hidden" name="Editors[]"/>').val(user))
51
- .append(jQuery('<a href="javascript:;" title="Remove">&times;</a>').click(RemoveSecToken))
52
- );
53
- } else {
54
- jQuery('#EditorList').children().remove();
55
- }
56
- });
57
-
58
-
59
- var usersUrl = ajaxurl + "?action=AjaxGetAllUsers";
60
- jQuery("#ExUserQueryBox").autocomplete({
61
- source: usersUrl,
62
- minLength:1
63
- });
64
-
65
- var rolesUrl = ajaxurl + "?action=AjaxGetAllRoles";
66
- jQuery("#ExRoleQueryBox").autocomplete({
67
- source: rolesUrl,
68
- minLength:1
69
- });
70
-
71
- });
72
-
73
-
1
+ jQuery(document).ready(function(){
2
+ var RemoveSecToken = function(){
3
+ var $this = jQuery(this).parents('span:first');
4
+ $this.addClass('sectoken-del').fadeOut('fast', function(){
5
+ $this.remove();
6
+ });
7
+ };
8
+
9
+ jQuery('#ViewerQueryBox, #EditorQueryBox, #ExRoleQueryBox, #ExUserQueryBox, #CustomQueryBox, #IpAddrQueryBox').keydown(function(event){
10
+ if(event.keyCode === 13) {
11
+ var type = jQuery(this).attr('id').substr(0, 6);
12
+ jQuery('#'+type+'QueryAdd').click();
13
+ return false;
14
+ }
15
+ });
16
+
17
+ jQuery('#ViewerQueryAdd, #EditorQueryAdd, #ExRoleQueryAdd, #ExUserQueryAdd, #CustomQueryAdd, #IpAddrQueryAdd').click(function(){
18
+ var type = jQuery(this).attr('id').substr(0, 6);
19
+ var value = jQuery.trim(jQuery('#'+type+'QueryBox').val());
20
+ var existing = jQuery('#'+type+'List input').filter(function() { return this.value === value; });
21
+
22
+ if(!value || existing.length)return; // if value is empty or already used, stop here
23
+
24
+ jQuery('#'+type+'QueryBox, #'+type+'QueryAdd').attr('disabled', true);
25
+ jQuery.post(jQuery('#ajaxurl').val(), {action: 'AjaxCheckSecurityToken', token: value}, function(data){
26
+ jQuery('#'+type+'QueryBox, #'+type+'QueryAdd').attr('disabled', false);
27
+ if (type != 'Custom' && type != 'IpAddr') {
28
+ if(data === 'other') {
29
+ alert('The specified token is not a user nor a role!');
30
+ jQuery('#'+type+'QueryBox').val('');
31
+ return;
32
+ }
33
+ }
34
+ jQuery('#'+type+'QueryBox').val('');
35
+ jQuery('#'+type+'List').append(jQuery('<span class="sectoken-'+data+'"/>').text(value).append(
36
+ jQuery('<input type="hidden" name="'+type+'s[]"/>').val(value),
37
+ jQuery('<a href="javascript:;" title="Remove">&times;</a>').click(RemoveSecToken)
38
+ ));
39
+ });
40
+ });
41
+
42
+ jQuery('#ViewerList>span>a, #EditorList>span>a, #ExRoleList>span>a, #ExUserList>span>a, #CustomList>span>a, #IpAddrList>span>a').click(RemoveSecToken);
43
+
44
+ jQuery('#RestrictAdmins').change(function(){
45
+ var user = jQuery('#RestrictAdminsDefaultUser').val();
46
+ var fltr = function() { return this.value === user; };
47
+ if (this.checked && jQuery('#EditorList input').filter(fltr).length === 0) {
48
+ jQuery('#EditorList').append(
49
+ jQuery('<span class="sectoken-user"/>').text(user)
50
+ .prepend(jQuery('<input type="hidden" name="Editors[]"/>').val(user))
51
+ .append(jQuery('<a href="javascript:;" title="Remove">&times;</a>').click(RemoveSecToken))
52
+ );
53
+ } else {
54
+ jQuery('#EditorList').children().remove();
55
+ }
56
+ });
57
+
58
+
59
+ var usersUrl = ajaxurl + "?action=AjaxGetAllUsers";
60
+ jQuery("#ExUserQueryBox").autocomplete({
61
+ source: usersUrl,
62
+ minLength:1
63
+ });
64
+
65
+ var rolesUrl = ajaxurl + "?action=AjaxGetAllRoles";
66
+ jQuery("#ExRoleQueryBox").autocomplete({
67
+ source: rolesUrl,
68
+ minLength:1
69
+ });
70
+
71
+ });
72
+
73
+
readme.txt CHANGED
@@ -6,14 +6,16 @@ License: GPLv3
6
  License URI: http://www.gnu.org/licenses/gpl.html
7
  Tags: wordpress security plugin, wordpress security audit log, audit log, wordpress log, event log wordpress, wordpress user tracking, wordpress activity log, wordpress audit, security event log, audit trail, security audit trail, wordpress security alerts, wordpress monitor, wordpress security monitor, wordpress admin, wordpress admin monitoring, analytics, activity, admin, multisite, wordpress multisite, actions, dashboard, log, notification, wordpress monitoring, email notification, wordpress email alerts, tracking, user tracking, user activity report
8
  Requires at least: 3.6
9
- Tested up to: 4.3
10
- Stable tag: 2.1.1
11
 
12
  Keep an audit log of all changes and under the hood WordPress activity to ensure productivity and thwart possible WordPress hacker attacks.
13
 
14
  == Description ==
15
  Keep an audit log of everything that is happening on your WordPress and [WordPress multisite](http://www.wpsecurityauditlog.com/documentation/wordpress-multisite-plugin-features-support/) with WP Security Audit Log to ensure user productivity and identify WordPress security issues before they become a security problem. WP Security Audit Log, WordPress' most comprehensive user monitoring and audit log plugin already helps thousands of WordPress administrators, owners and security professionals ensure the security of their websites and blogs. Ensure the security of your WordPress too by installing WP Security Audit Log. The community's favourite WordPress user monitoring monitoring and security auditing plugin is developed by WordPress Security Consultants and Professionals [WP White Security](http://www.wpwhitesecurity.com/).
16
 
 
 
17
  > <strong>Free and Premium Support</strong><br>
18
  >
19
  > WP White Security provides support for WP Security Audit Log plugin on the WordPress forums for free, though please note that it is free support hence it is not always possible to answer all questions on a timely manner, although we do try.
@@ -81,13 +83,10 @@ WP Security Audit Log is the first tracking and audit WordPress security monitor
81
  For more information about the features for WordPress Multisite network installation refer to [WP Security Audit Log Features for WordPress Multisite](http://www.wpsecurityauditlog.com/documentation/wordpress-multisite-plugin-features-support/)
82
 
83
  = WordPress Security Audit Log in your Language! =
84
- We need help translating the plugin and the WordPress Security Events. If you're good at translating, please drop us an email on plugins@wpwhitesecurity.com.
85
 
86
  * Italian translation by [Leonardo Musumeci](http://leonardomusumeci.net/)
87
  * German translation by [Mourad Louha](http://excel-translator.de)
88
- * Romanian translations by [Artmotion Secure Servers](http://www.artmotion.eu)
89
- * Serbo-Croatian by [Andrijana Nikolic](http://webhostinggeeks.com/)
90
- * Spanish translation by Andrew Kurtis
91
 
92
  = WordPress & PHP Errors Monitoring Tools =
93
  Plugins and themes customizations are most probably the norm of the day on large WordPress websites, not to mention the installation of new plugins and components. With WP Security Audit Log now it is easier than ever before to monitor your plugins', theme's and other code behaviour, it will generate a alert when a PHP error, warning, exception or shutdown is detected. It is also possible to log all HTTP GET and POST requests that are reaching your WordPress installation to a log file with WP Security Audit Log. Simply enable the PHP Errors monitoring or logging from the plugins settings.
@@ -99,6 +98,8 @@ WP Security Audit Log plugin also has a number of features that make WordPress a
99
 
100
  * Realtime Audit Log viewer to watch user activity as it happens without any delays
101
  * Built-in support for reverse proxies and web application firewalls [more information](http://www.wpsecurityauditlog.com/documentation/automatically-retrieve-originating-wordpress-user-ip-address/)
 
 
102
  * Limit who can view the security alerts by users and roles
103
  * Limit who can manage the plugin by users and roles
104
  * Configurable WordPress dashboard widget highlighting the most recent critical activity
@@ -110,15 +111,23 @@ WP Security Audit Log plugin also has a number of features that make WordPress a
110
 
111
  = As Featured On: =
112
 
113
- * [WP Mayor](http://www.wpmayor.com/wp-security-audit-log-plugin-review-user-activity-logging-wordpress/)
114
  * [ManageWP Plugins of the month](https://managewp.com/free-wordpress-plugins-june-2014)
 
 
115
  * [Pagely](https://pagely.com/blog/2015/01/log-wordpress-dashboard-activity-improved-security-auditing/)
116
  * [Design Wall](http://www.designwall.com/blog/10-wordpress-multisite-plugins-you-shouldnt-live-without/)
 
117
  * [WPLift](http://wplift.com/wordpress-event-tracking)
118
  * [Tourqe News](http://torquemag.io/5-awesome-wordpress-plugins-you-may-not-have-heard-of/)
119
- * [BlogVault](https://blogvault.net/wp-security-audit-log-plugin-review/)
120
- * [MyWPExpert](http://www.mywpexpert.com/wp-security-audit-log/)
121
  * [Shout Me Loud](http://www.shoutmeloud.com/how-to-monitor-user-activities-wordpress-dashboard.html)
 
 
 
 
 
 
 
122
 
123
  = Related Links and Documentation =
124
  For more information and to get started with WordPress Security, check out the following:
@@ -189,9 +198,17 @@ Yes. To exclude an IP address you can specify it in the Excluded Objects section
189
  5. The Enable/Disable Alerts settings node from where Administrators can disable or enable WordPress security alerts.
190
  6. The Audit Log Viewer of a Super Admin in a WordPress multisite network installation with the Site selection drop down menu.
191
  7. If there are more than 15 sites in a multisite, an auto complete site search shows up instead of the drop down menu (see [screenshots](https://wordpress.org/plugins/wp-security-audit-log/screenshots/) for reference)
 
192
 
193
  == Changelog ==
194
 
 
 
 
 
 
 
 
195
  = 2.1.1 (2015-10-08) =
196
  * **New WordPress Security Alerts**
197
  * 2072: User modifies a post that is submitted for review
6
  License URI: http://www.gnu.org/licenses/gpl.html
7
  Tags: wordpress security plugin, wordpress security audit log, audit log, wordpress log, event log wordpress, wordpress user tracking, wordpress activity log, wordpress audit, security event log, audit trail, security audit trail, wordpress security alerts, wordpress monitor, wordpress security monitor, wordpress admin, wordpress admin monitoring, analytics, activity, admin, multisite, wordpress multisite, actions, dashboard, log, notification, wordpress monitoring, email notification, wordpress email alerts, tracking, user tracking, user activity report
8
  Requires at least: 3.6
9
+ Tested up to: 4.3.1
10
+ Stable tag: 2.2
11
 
12
  Keep an audit log of all changes and under the hood WordPress activity to ensure productivity and thwart possible WordPress hacker attacks.
13
 
14
  == Description ==
15
  Keep an audit log of everything that is happening on your WordPress and [WordPress multisite](http://www.wpsecurityauditlog.com/documentation/wordpress-multisite-plugin-features-support/) with WP Security Audit Log to ensure user productivity and identify WordPress security issues before they become a security problem. WP Security Audit Log, WordPress' most comprehensive user monitoring and audit log plugin already helps thousands of WordPress administrators, owners and security professionals ensure the security of their websites and blogs. Ensure the security of your WordPress too by installing WP Security Audit Log. The community's favourite WordPress user monitoring monitoring and security auditing plugin is developed by WordPress Security Consultants and Professionals [WP White Security](http://www.wpwhitesecurity.com/).
16
 
17
+ [youtube https://www.youtube.com/watch?v=1nopATCS-CQ]
18
+
19
  > <strong>Free and Premium Support</strong><br>
20
  >
21
  > WP White Security provides support for WP Security Audit Log plugin on the WordPress forums for free, though please note that it is free support hence it is not always possible to answer all questions on a timely manner, although we do try.
83
  For more information about the features for WordPress Multisite network installation refer to [WP Security Audit Log Features for WordPress Multisite](http://www.wpsecurityauditlog.com/documentation/wordpress-multisite-plugin-features-support/)
84
 
85
  = WordPress Security Audit Log in your Language! =
86
+ We need help translating the plugin and the WordPress Security Alerts. If you would like to translate this plugin visit the [WordPress translate Project](https://translate.wordpress.org/) for more information on how to translate the plugin. If you already know how translations work, [start translating WP Security Audit Log now](https://translate.wordpress.org/projects/wp-plugins/wp-security-audit-log) and contact us on plugins@wpwhitesecurity.com for a free license of all add-ons.
87
 
88
  * Italian translation by [Leonardo Musumeci](http://leonardomusumeci.net/)
89
  * German translation by [Mourad Louha](http://excel-translator.de)
 
 
 
90
 
91
  = WordPress & PHP Errors Monitoring Tools =
92
  Plugins and themes customizations are most probably the norm of the day on large WordPress websites, not to mention the installation of new plugins and components. With WP Security Audit Log now it is easier than ever before to monitor your plugins', theme's and other code behaviour, it will generate a alert when a PHP error, warning, exception or shutdown is detected. It is also possible to log all HTTP GET and POST requests that are reaching your WordPress installation to a log file with WP Security Audit Log. Simply enable the PHP Errors monitoring or logging from the plugins settings.
98
 
99
  * Realtime Audit Log viewer to watch user activity as it happens without any delays
100
  * Built-in support for reverse proxies and web application firewalls [more information](http://www.wpsecurityauditlog.com/documentation/automatically-retrieve-originating-wordpress-user-ip-address/)
101
+ * Allows you to see what actually changed when the content of posts, pages and custom post types is changed
102
+ * Integrated with WhatIsMyIpAddress.com so you to get all information about a source IP with just a mouse click
103
  * Limit who can view the security alerts by users and roles
104
  * Limit who can manage the plugin by users and roles
105
  * Configurable WordPress dashboard widget highlighting the most recent critical activity
111
 
112
  = As Featured On: =
113
 
114
+ * [WPKube](http://www.wpkube.com/improve-wordpress-security-wp-security-audit-log/)
115
  * [ManageWP Plugins of the month](https://managewp.com/free-wordpress-plugins-june-2014)
116
+ * [MyWPExpert](http://www.mywpexpert.com/wp-security-audit-log/)
117
+ * [BlogVault](https://blogvault.net/wp-security-audit-log-plugin-review/)
118
  * [Pagely](https://pagely.com/blog/2015/01/log-wordpress-dashboard-activity-improved-security-auditing/)
119
  * [Design Wall](http://www.designwall.com/blog/10-wordpress-multisite-plugins-you-shouldnt-live-without/)
120
+ * [WP Mayor](http://www.wpmayor.com/wp-security-audit-log-plugin-review-user-activity-logging-wordpress/)
121
  * [WPLift](http://wplift.com/wordpress-event-tracking)
122
  * [Tourqe News](http://torquemag.io/5-awesome-wordpress-plugins-you-may-not-have-heard-of/)
 
 
123
  * [Shout Me Loud](http://www.shoutmeloud.com/how-to-monitor-user-activities-wordpress-dashboard.html)
124
+ * [The Darknet](http://www.darknet.org.uk/2015/10/wp-security-audit-log-a-complete-audit-log-plugin-for-wordpress/)
125
+
126
+ = WordPress Security Audit Log in your Language! =
127
+ We need help translating the plugin and the WordPress Security Alerts. Please visit the [WordPress Translate Project](https://translate.wordpress.org/projects/wp-plugins/wp-security-audit-log) to translate the plugin and drop us an email on support@wpwhitesecurity.com to get mentioned in the list of translators below.
128
+
129
+ * Italian translation by [Leonardo Musumeci](http://leonardomusumeci.net/)
130
+ * German translation by [Mourad Louha](http://excel-translator.de)
131
 
132
  = Related Links and Documentation =
133
  For more information and to get started with WordPress Security, check out the following:
198
  5. The Enable/Disable Alerts settings node from where Administrators can disable or enable WordPress security alerts.
199
  6. The Audit Log Viewer of a Super Admin in a WordPress multisite network installation with the Site selection drop down menu.
200
  7. If there are more than 15 sites in a multisite, an auto complete site search shows up instead of the drop down menu (see [screenshots](https://wordpress.org/plugins/wp-security-audit-log/screenshots/) for reference)
201
+ 8. WP Security Audit Log is integrated with the built-in revision system of WordPress, thus allowing you to see what content changes users make on your WordPress posts, pages and custom post types. For more information read [Keep Record of All WordPress Content Changes with WP Security Audit Log Plugin](http://www.wpsecurityauditlog.com/wordpress-user-monitoring-plugin-releases/record-all-wordpress-content-changes-wp-security-audit-log-plugin/)
202
 
203
  == Changelog ==
204
 
205
+ = 2.2 (2015-11-10) =
206
+ * **New Features**
207
+ * Aded the revision link in content change security alerts allowing you to see the actual content changes that took place on posts, pages and custom post types. [Learn More](http://www.wpsecurityauditlog.com/wordpress-user-monitoring-plugin-releases/record-all-wordpress-content-changes-wp-security-audit-log-plugin/)
208
+
209
+ * **Bug Fixes**
210
+ * Fixed an issue where user was allowed to disable all columns in Audit Log Viewer [Support ticket](https://wordpress.org/support/topic/audit-log-columns-selection-is-empty). Fix recommendation by Bates College.
211
+
212
  = 2.1.1 (2015-10-08) =
213
  * **New WordPress Security Alerts**
214
  * 2072: User modifies a post that is submitted for review
wp-security-audit-log.php CHANGED
@@ -4,7 +4,7 @@ Plugin Name: WP Security Audit Log
4
  Plugin URI: http://www.wpsecurityauditlog.com/
5
  Description: Identify WordPress security issues before they become a problem. Keep track of everything happening on your WordPress including WordPress users activity. Similar to Windows Event Log and Linux Syslog, WP Security Audit Log generates a security alert for everything that happens on your WordPress blogs and websites. Use the Audit Log Viewer included in the plugin to see all the security alerts.
6
  Author: WP White Security
7
- Version: 2.1.1
8
  Text Domain: wp-security-audit-log
9
  Author URI: http://www.wpsecurityauditlog.com/
10
  License: GPL2
4
  Plugin URI: http://www.wpsecurityauditlog.com/
5
  Description: Identify WordPress security issues before they become a problem. Keep track of everything happening on your WordPress including WordPress users activity. Similar to Windows Event Log and Linux Syslog, WP Security Audit Log generates a security alert for everything that happens on your WordPress blogs and websites. Use the Audit Log Viewer included in the plugin to see all the security alerts.
6
  Author: WP White Security
7
+ Version: 2.2
8
  Text Domain: wp-security-audit-log
9
  Author URI: http://www.wpsecurityauditlog.com/
10
  License: GPL2