VaultPress - Version 1.4.5

Version Description

Download this release

Release Info

Developer xknown
Plugin Icon 128x128 VaultPress
Version 1.4.5
Comparing to
See all releases

Version 1.4.5

class.vaultpress-database.php ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class VaultPress_Database {
4
+
5
+ var $table = null;
6
+ var $pks = null;
7
+
8
+ function VaultPress_Database() {
9
+ $this->__construct();
10
+ }
11
+
12
+ function __construct() {
13
+ }
14
+
15
+ function attach( $table, $parse_create_table = false ) {
16
+ $this->table=$table;
17
+ if ( $parse_create_table ) {
18
+ $this->structure = $this->parse_create_table( $this->show_create() );
19
+ }
20
+ }
21
+
22
+ function get_tables( $filter=null ) {
23
+ global $wpdb;
24
+ $rval = $wpdb->get_col( 'SHOW TABLES' );
25
+ if ( $filter )
26
+ $rval = preg_grep( $filter, $rval );
27
+ return $rval;
28
+ }
29
+
30
+ function show_create() {
31
+ global $wpdb;
32
+ if ( !$this->table )
33
+ return false;
34
+ $table = $wpdb->escape( $this->table );
35
+ $results = $wpdb->get_row( "SHOW CREATE TABLE `$table`" );
36
+ $want = 'Create Table';
37
+ if ( $results )
38
+ $results = $results->$want;
39
+ return $results;
40
+ }
41
+
42
+ function explain() {
43
+ global $wpdb;
44
+ if ( !$this->table )
45
+ return false;
46
+ $table = $wpdb->escape( $this->table );
47
+ return $wpdb->get_results( "EXPLAIN `$table`" );
48
+ }
49
+
50
+ function diff( $signatures ) {
51
+ global $wpdb;
52
+ if ( !is_array( $signatures ) || !count( $signatures ) )
53
+ return false;
54
+ if ( !$this->table )
55
+ return false;
56
+ $table = $wpdb->escape( $this->table );
57
+ $diff = array();
58
+ foreach ( $signatures as $where => $signature ) {
59
+ $pksig = md5( $where );
60
+ unset( $wpdb->queries );
61
+ $row = $wpdb->get_row( "SELECT * FROM `$table` WHERE $where" );
62
+ if ( !$row ) {
63
+ $diff[$pksig] = array ( 'change' => 'deleted', 'where' => $where );
64
+ continue;
65
+ }
66
+ $row = serialize( $row );
67
+ $hash = md5( $row );
68
+ if ( $hash != $signature )
69
+ $diff[$pksig] = array( 'change' => 'modified', 'where' => $where, 'signature' => $hash, 'row' => $row );
70
+ }
71
+ return $diff;
72
+ }
73
+
74
+ function count( $columns ) {
75
+ global $wpdb;
76
+ if ( !is_array( $columns ) || !count( $columns ) )
77
+ return false;
78
+ if ( !$this->table )
79
+ return false;
80
+ $table = $wpdb->escape( $this->table );
81
+ $column = $wpdb->escape( array_shift( $columns ) );
82
+ return $wpdb->get_var( "SELECT COUNT( $column ) FROM `$table`" );
83
+ }
84
+
85
+ function wpdb( $query, $function='get_results' ) {
86
+ global $wpdb;
87
+
88
+ if ( !is_callable( array( $wpdb, $function ) ) )
89
+ return false;
90
+
91
+ $res = $wpdb->$function( $query );
92
+ if ( !$res )
93
+ return $res;
94
+ switch ( $function ) {
95
+ case 'get_results':
96
+ foreach ( $res as $idx => $row ) {
97
+ if ( isset( $row->option_name ) && $row->option_name == 'cron' )
98
+ $res[$idx]->option_value = serialize( array() );
99
+ }
100
+ break;
101
+ case 'get_row':
102
+ if ( isset( $res->option_name ) && $res->option_name == 'cron' )
103
+ $res->option_value = serialize( array() );
104
+ break;
105
+ }
106
+ return $res;
107
+ }
108
+
109
+ function get_cols( $columns, $limit=false, $offset=false, $where=false ) {
110
+ global $wpdb;
111
+ if ( !is_array( $columns ) || !count( $columns ) )
112
+ return false;
113
+ if ( !$this->table )
114
+ return false;
115
+ $table = $wpdb->escape( $this->table );
116
+ $limitsql = '';
117
+ $offsetsql = '';
118
+ $wheresql = '';
119
+ if ( $limit )
120
+ $limitsql = ' LIMIT ' . intval( $limit );
121
+ if ( $offset )
122
+ $offsetsql = ' OFFSET ' . intval( $offset );
123
+ if ( $where )
124
+ $wheresql = ' WHERE ' . base64_decode($where);
125
+ $rval = array();
126
+ foreach ( $wpdb->get_results( "SELECT * FROM `$this->table` $wheresql $limitsql $offsetsql" ) as $row ) {
127
+ // We don't need to actually record a real cron option value, just an empty array
128
+ if ( isset( $row->option_name ) && $row->option_name == 'cron' )
129
+ $row->option_value = serialize( array() );
130
+ if ( !empty( $this->structure ) ) {
131
+ $hash = md5( $this->convert_to_sql_string( $row, $this->structure->columns ) );
132
+ foreach ( get_object_vars( $row ) as $i => $v ) {
133
+ if ( !in_array( $i, $columns ) )
134
+ unset( $row->$i );
135
+ }
136
+
137
+ $row->hash = $hash;
138
+ } else {
139
+ $keys = array();
140
+ $vals = array();
141
+ foreach ( get_object_vars( $row ) as $i => $v ) {
142
+ $keys[] = sprintf( "`%s`", $wpdb->escape( $i ) );
143
+ $vals[] = sprintf( "'%s'", $wpdb->escape( $v ) );
144
+ if ( !in_array( $i, $columns ) )
145
+ unset( $row->$i );
146
+ }
147
+ $row->hash = md5( sprintf( "(%s) VALUES(%s)", implode( ',',$keys ), implode( ',',$vals ) ) );
148
+ }
149
+ $rval[]=$row;
150
+ }
151
+ return $rval;
152
+ }
153
+
154
+ /**
155
+ * Convert a PHP object to a mysqldump compatible string, using the provided data type information.
156
+ **/
157
+ function convert_to_sql_string( $data, $datatypes ) {
158
+ global $wpdb;
159
+ if ( !is_object( $data ) || !is_object( $datatypes ) )
160
+ return false;
161
+
162
+ foreach ( array_keys( (array)$data ) as $key )
163
+ $keys[] = sprintf( "`%s`", $wpdb->escape( $key ) );
164
+ foreach ( (array)$data as $key => $val ) {
165
+ if ( null === $val ) {
166
+ $vals[] = 'NULL';
167
+ continue;
168
+ }
169
+ $type = 'text';
170
+ if ( isset( $datatypes->$key->type ) )
171
+ $type= strtolower( $datatypes->$key->type );
172
+ if ( preg_match( '/int|double|float|decimal|bool/i', $type ) )
173
+ $type = 'number';
174
+
175
+ if ( 'number' === $type ) {
176
+ // do not add quotes to numeric types.
177
+ $vals[] = $val;
178
+ } else {
179
+ $val = $wpdb->escape( $val );
180
+ // Escape characters that aren't escaped by $wpdb->escape(): \n, \r, etc.
181
+ $val = str_replace( array( "\x0a", "\x0d", "\x1a" ), array( '\n', '\r', '\Z' ), $val );
182
+ $vals[] = sprintf( "'%s'", $val );
183
+ }
184
+ }
185
+ if ( !count($keys) )
186
+ return false;
187
+ // format the row as a mysqldump line: (`column1`, `column2`) VALUES (numeric_value1,'text value 2')
188
+ return sprintf( "(%s) VALUES (%s)", implode( ', ',$keys ), implode( ',',$vals ) );
189
+ }
190
+
191
+
192
+
193
+ function parse_create_table( $sql ) {
194
+ $table = new stdClass();
195
+
196
+ $table->raw = $sql;
197
+ $table->columns = new stdClass();
198
+ $table->primary = null;
199
+ $table->uniques = new stdClass();
200
+ $table->keys = new stdClass();
201
+ $sql = explode( "\n", trim( $sql ) );
202
+ $table->engine = preg_replace( '/^.+ ENGINE=(\S+) .+$/i', "$1", $sql[(count($sql)-1)] );
203
+ $table->charset = preg_replace( '/^.+ DEFAULT CHARSET=(\S+)( .+)?$/i', "$1", $sql[(count($sql)-1)] );
204
+ $table->single_int_paging_column = null;
205
+
206
+ foreach ( $sql as $idx => $val )
207
+ $sql[$idx] = trim($val);
208
+ $columns = preg_grep( '/^\s*`[^`]+`\s*\S*/', $sql );
209
+ if ( !$columns )
210
+ return false;
211
+
212
+ $table->name = preg_replace( '/(^[^`]+`|`[^`]+$)/', '', array_shift( preg_grep( '/^CREATE\s+TABLE\s+/', $sql ) ) );
213
+
214
+ foreach ( $columns as $line ) {
215
+ preg_match( '/^`([^`]+)`\s+([a-z]+)(\(\d+\))?\s*/', $line, $m );
216
+ $name = $m[1];
217
+ $table->columns->$name = new stdClass();
218
+ $table->columns->$name->null = (bool)stripos( $line, ' NOT NULL ' );
219
+ $table->columns->$name->type = $m[2];
220
+ if ( isset($m[3]) ) {
221
+ if ( substr( $m[3], 0, 1 ) == '(' )
222
+ $table->columns->$name->length = substr( $m[3], 1, -1 );
223
+ else
224
+ $table->columns->$name->length = $m[3];
225
+ } else {
226
+ $table->columns->$name->length = null;
227
+ }
228
+ if ( preg_match( '/ character set (\S+)/i', $line, $m ) ) {
229
+ $table->columns->$name->charset = $m[1];
230
+ } else {
231
+ $table->columns->$name->charset = '';
232
+ }
233
+ if ( preg_match( '/ collate (\S+)/i', $line, $m ) ) {
234
+ $table->columns->$name->collate = $m[1];
235
+ } else {
236
+ $table->columns->$name->collate = '';
237
+ }
238
+ if ( preg_match( '/ DEFAULT (.+),$/i', $line, $m ) ) {
239
+ if ( substr( $m[1], 0, 1 ) == "'" )
240
+ $table->columns->$name->default = substr( $m[1], 1, -1 );
241
+ else
242
+ $table->columns->$name->default = $m[1];
243
+ } else {
244
+ $table->columns->$name->default = null;
245
+ }
246
+ $table->columns->$name->line = $line;
247
+ }
248
+ $pk = preg_grep( '/^PRIMARY\s+KEY\s+/i', $sql );
249
+ if ( count( $pk ) ) {
250
+ $pk = array_pop( $pk );
251
+ $pk = preg_replace( '/(^[^\(]+\(`|`\),?$)/', '', $pk );
252
+ $pk = preg_replace( '/\([0-9]+\)/', '', $pk );
253
+ $pk = explode( '`,`', $pk );
254
+ $table->primary = $pk;
255
+ }
256
+ if ( is_array( $table->primary ) && count( $table->primary ) == 1 ) {
257
+ $pk_column_name = $table->primary[0];
258
+ switch( strtolower( $table->columns->$pk_column_name->type ) ) {
259
+ // Integers, exact value
260
+ case 'tinyint':
261
+ case 'smallint':
262
+ case 'int':
263
+ case 'integer':
264
+ case 'bigint':
265
+ // Fixed point, exact value
266
+ case 'decimal':
267
+ case 'numeric':
268
+ // Floating point, approximate value
269
+ case 'float':
270
+ case 'double':
271
+ case 'real':
272
+ // Date and Time
273
+ case 'date':
274
+ case 'datetime':
275
+ case 'timestamp':
276
+ $table->single_int_paging_column = $pk_column_name;
277
+ break;
278
+ }
279
+ }
280
+ $keys = preg_grep( '/^((?:UNIQUE )?INDEX|(?:UNIQUE )?KEY)\s+/i', $sql );
281
+ if ( !count( $keys ) )
282
+ return $table;
283
+ foreach ( $keys as $idx => $key ) {
284
+ if ( 0 === strpos( $key, 'UNIQUE' ) )
285
+ $is_unique = false;
286
+ else
287
+ $is_unique = true;
288
+
289
+ // for KEY `refresh` (`ip`,`time_last`) USING BTREE,
290
+ $key = preg_replace( '/ USING \S+ ?(,?)$/', '$1', $key );
291
+
292
+ // for KEY `id` USING BTREE (`id`),
293
+ $key = preg_replace( '/` USING \S+ \(/i', '` (', $key );
294
+
295
+ $key = preg_replace( '/^((?:UNIQUE )?INDEX|(?:UNIQUE )?KEY)\s+/i', '', $key );
296
+ $key = preg_replace( '/\([0-9]+\)/', '', $key );
297
+ preg_match( '/^`([^`]+)`\s+\(`(.+)`\),?$/', $key, $m );
298
+ $key = $m[1]; //preg_replace( '/\([^)]+\)/', '', $m[1]);
299
+ if ( !$key )
300
+ continue;
301
+ if ( $is_unique )
302
+ $table->keys->$key = explode( '`,`', $m[2] );
303
+ else
304
+ $table->uniques->$key = explode( '`,`', $m[2] );
305
+ }
306
+
307
+ $uniques = get_object_vars( $table->uniques );
308
+ foreach( $uniques as $idx => $val ) {
309
+ if ( is_array( $val ) && count( $val ) == 1 ) {
310
+ $pk_column_name = $val[0];
311
+ switch( strtolower( $table->columns->$pk_column_name->type ) ) {
312
+ // Integers, exact value
313
+ case 'tinyint':
314
+ case 'smallint':
315
+ case 'int':
316
+ case 'integer':
317
+ case 'bigint':
318
+ // Fixed point, exact value
319
+ case 'decimal':
320
+ case 'numeric':
321
+ // Floating point, approximate value
322
+ case 'float':
323
+ case 'double':
324
+ case 'real':
325
+ // Date and Time
326
+ case 'date':
327
+ case 'datetime':
328
+ case 'timestamp':
329
+ $table->single_int_paging_column = $pk_column_name;
330
+ break;
331
+ }
332
+ }
333
+ }
334
+
335
+ if ( empty( $table->primary ) ) {
336
+ if ( !empty( $uniques ) )
337
+ $table->primary = array_shift( $uniques );
338
+ }
339
+
340
+ return $table;
341
+ }
342
+ }
class.vaultpress-filesystem.php ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class VaultPress_Filesystem {
4
+
5
+ var $type = null;
6
+ var $dir = null;
7
+ var $keys = array( 'ino', 'uid', 'gid', 'size', 'mtime', 'blksize', 'blocks' );
8
+
9
+ function VaultPress_Filesystem() {
10
+ $this->__construct();
11
+ }
12
+
13
+ function __construct() {
14
+ }
15
+
16
+ function want( $type ) {
17
+ $vp = VaultPress::init();
18
+
19
+ if ( $type == 'plugins' ) {
20
+ $this->dir = realpath( $vp->resolve_content_dir() . 'plugins' );
21
+ $this->type = 'p';
22
+ return true;
23
+ }
24
+ if ( $type == 'themes' ) {
25
+ $this->dir = realpath( $vp->resolve_content_dir() . 'themes' );
26
+ $this->type = 't';
27
+ return true;
28
+ }
29
+ if ( $type == 'uploads' ) {
30
+ $this->dir = realpath( $vp->resolve_upload_path() );
31
+ $this->type = 'u';
32
+ return true;
33
+ }
34
+ if ( $type == 'content' ) {
35
+ $this->dir = realpath( $vp->resolve_content_dir() );
36
+ $this->type = 'c';
37
+ return true;
38
+ }
39
+ if ( $type == 'root' ) {
40
+ $this->dir = realpath( ABSPATH );
41
+ $this->type = 'r';
42
+ return true;
43
+ }
44
+ die( 'naughty naughty' );
45
+ }
46
+
47
+ function fdump( $file ) {
48
+ header("Content-Type: application/octet-stream;");
49
+ header("Content-Transfer-Encoding: binary");
50
+ @ob_end_clean();
51
+ if ( !file_exists( $file ) || !is_readable( $file ) ) {
52
+ $file_name = basename( $file );
53
+ if ( 'wp-config.php' == $file_name ) {
54
+ $dir = dirname( $file );
55
+ $dir = explode( DIRECTORY_SEPARATOR, $dir );
56
+ array_pop( $dir );
57
+ $dir = implode( DIRECTORY_SEPARATOR, $dir );
58
+ $file = trailingslashit( $dir ) . $file_name;
59
+ if ( !file_exists( $file ) || !is_readable( $file ) )
60
+ die( "no such file" );
61
+ } else {
62
+ die( "no such file" );
63
+ }
64
+ }
65
+ if ( !is_file( $file ) && !is_link( $file ) )
66
+ die( "can only dump files" );
67
+ $fp = @fopen( $file, 'rb' );
68
+ if ( !$fp )
69
+ die( "could not open file" );
70
+ while ( !feof( $fp ) )
71
+ echo @fread( $fp, 8192 );
72
+ @fclose( $fp );
73
+ die();
74
+ }
75
+
76
+ function stat( $file, $md5=true, $sha1=true ) {
77
+ $rval = array();
78
+ foreach ( stat( $file ) as $i => $v ) {
79
+ if ( is_numeric( $i ) )
80
+ continue;
81
+ $rval[$i] = $v;
82
+ }
83
+ $rval['type'] = filetype( $file );
84
+ if ( $rval['type'] == 'file' ) {
85
+ if ( $md5 )
86
+ $rval['md5'] = md5_file( $file );
87
+ if ( $sha1 )
88
+ $rval['sha1'] = sha1_file( $file );
89
+ }
90
+ $dir = $this->dir;
91
+ if ( 0 !== strpos( $file, $dir ) && 'wp-config.php' == basename( $file ) ) {
92
+ $dir = explode( DIRECTORY_SEPARATOR, $dir );
93
+ array_pop( $dir );
94
+ $dir = implode( DIRECTORY_SEPARATOR, $dir );
95
+ }
96
+ $rval['path'] = str_replace( $dir, '', $file );
97
+ return $rval;
98
+ }
99
+
100
+ function ls( $what, $md5=false, $sha1=false, $limit=null, $offset=null ) {
101
+ clearstatcache();
102
+ $path = realpath($this->dir . $what);
103
+ $dir = $this->dir;
104
+ if ( !$path && '/wp-config.php' == $what ) {
105
+ $dir = explode( DIRECTORY_SEPARATOR, $dir );
106
+ array_pop( $dir );
107
+ $dir = implode( DIRECTORY_SEPARATOR, $dir );
108
+ $path = realpath( $dir . $what );
109
+ }
110
+ if ( is_file($path) )
111
+ return $this->stat( $path, $md5, $sha1 );
112
+ if ( is_dir($path) ) {
113
+ $entries = array();
114
+ $current = 0;
115
+ $offset = (int)$offset;
116
+ $orig_limit = (int)$limit;
117
+ $limit = $offset + (int)$limit;
118
+ foreach ( (array)$this->scan_dir( $path ) as $i ) {
119
+ $current++;
120
+ if ( $offset >= $current )
121
+ continue;
122
+ if ( $limit && $limit < $current )
123
+ break;
124
+
125
+ // don't sha1 files over 100MB if we are batching due to memory consumption
126
+ if ( $sha1 && $orig_limit > 1 && is_file( $i ) && (int)@filesize( $i ) > 104857600 )
127
+ $sha1 = false;
128
+
129
+ $entries[] = $this->stat( $i, $md5, $sha1 );
130
+ }
131
+ return $entries;
132
+ }
133
+ }
134
+
135
+ function validate( $file ) {
136
+ $rpath = realpath( $this->dir.$file );
137
+ $dir = $this->dir;
138
+ if ( !$rpath && '/wp-config.php' == $file ) {
139
+ $dir = explode( DIRECTORY_SEPARATOR, $dir );
140
+ array_pop( $dir );
141
+ $dir = implode( DIRECTORY_SEPARATOR, $dir );
142
+ $rpath = realpath( $dir . $file );
143
+ }
144
+ if ( !$rpath )
145
+ die( serialize( array( 'type' => 'null', 'path' => $file ) ) );
146
+ if ( is_dir( $rpath ) )
147
+ $rpath = "$rpath/";
148
+ if ( strpos( $rpath, $dir ) !== 0 )
149
+ return false;
150
+ return true;
151
+ }
152
+
153
+ function dir_examine( $subdir='', $recursive=true, $origin=false ) {
154
+ $res = array();
155
+ if ( !$subdir )
156
+ $subdir='/';
157
+ $dir = $this->dir . $subdir;
158
+ if ( $origin === false )
159
+ $origin = $this->dir . $subdir;
160
+ if ( is_file($dir) ) {
161
+ if ( $origin == $dir )
162
+ $name = str_replace( $this->dir, '/', $subdir );
163
+ else
164
+ $name = str_replace( $origin, '/', $dir );
165
+ $res[$name] = $this->stat( $dir.$entry );
166
+ return $res;
167
+ }
168
+ $d = dir( $dir );
169
+ if ( !$d )
170
+ return $res;
171
+ while ( false !== ( $entry = $d->read() ) ) {
172
+ $rpath = realpath( $dir.$entry );
173
+ $bname = basename( $rpath );
174
+ if ( is_link( $dir.$entry ) )
175
+ continue;
176
+ if ( $entry == '.' || $entry == '..' || $entry == '...' )
177
+ continue;
178
+ if ( !$this->validate( $subdir.$entry ) )
179
+ continue;
180
+ $name = str_replace( $origin, '/', $dir.$entry );
181
+ $res[$name] = $this->stat( $dir.$entry );
182
+ if ( $recursive && is_dir( $this->dir.$subdir.'/'.$entry ) ) {
183
+ $res = array_merge( $res, $this->dir_examine( $subdir.$entry.'/', $recursive, $origin ) );
184
+ }
185
+ }
186
+ return $res;
187
+ }
188
+
189
+ function dir_checksum( $base, &$list, $recursive=true ) {
190
+ if ( $list == null )
191
+ $list = array();
192
+
193
+ if ( 0 !== strpos( $base, $this->dir ) )
194
+ $base = $this->dir . rtrim( $base, '/' );
195
+
196
+ $shortbase = substr( $base, strlen( $this->dir ) );
197
+ if ( !$shortbase )
198
+ $shortbase = '/';
199
+ $stat = stat( $base );
200
+ $directories = array();
201
+ $files = (array)$this->scan_dir( $base );
202
+ array_push( $files, $base );
203
+ foreach ( $files as $file ) {
204
+ if ( $file !== $base && @is_dir( $file ) ) {
205
+ $directories[] = $file;
206
+ continue;
207
+ }
208
+ $stat = @stat( $file );
209
+ if ( !$stat )
210
+ continue;
211
+ $shortstat = array();
212
+ foreach( $this->keys as $key ) {
213
+ if ( isset( $stat[$key] ) )
214
+ $shortstat[$key] = $stat[$key];
215
+ }
216
+ $list[$shortbase][basename( $file )] = $shortstat;
217
+ }
218
+ $list[$shortbase] = md5( serialize( $list[$shortbase] ) );
219
+ if ( !$recursive )
220
+ return $list;
221
+ foreach ( $directories as $dir ) {
222
+ $this->dir_checksum( $dir, $list, $recursive );
223
+ }
224
+ return $list;
225
+ }
226
+
227
+ function scan_dir( $path ) {
228
+ $files = array();
229
+
230
+ if ( false === is_readable( $path ) ) {
231
+ return array();
232
+ }
233
+
234
+ $dh = opendir( $path );
235
+
236
+ if ( false === $dh ) {
237
+ return array();
238
+ }
239
+
240
+ while ( false !== ( $file = readdir( $dh ) ) ) {
241
+ if ( $file == '.' || $file == '..' ) continue;
242
+ $files[] = "$path/$file";
243
+ }
244
+
245
+ closedir( $dh );
246
+ sort( $files );
247
+ return $files;
248
+ }
249
+ }
class.vaultpress-hotfixes.php ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class VaultPress_Hotfixes {
4
+ function VaultPress_Hotfixes() {
5
+ $this->__construct();
6
+ }
7
+
8
+ function __construct() {
9
+ global $wp_version;
10
+
11
+ if ( version_compare( $wp_version, '3.0.2', '<' ) )
12
+ add_filter( 'query', array( $this, 'r16625' ) );
13
+
14
+ if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && version_compare( $wp_version, '3.0.3', '<' ) )
15
+ add_action( 'xmlrpc_call', array( $this, 'r16803' ) );
16
+
17
+ if ( version_compare( $wp_version, '3.3.2', '<' ) ) {
18
+ add_filter( 'pre_kses', array( $this, 'r17172_wp_kses' ), 1, 3 );
19
+ add_filter( 'clean_url', array( $this, 'r17172_esc_url' ), 1, 3 );
20
+ }
21
+
22
+ if ( version_compare( $wp_version, '3.1.3', '<' ) ) {
23
+ add_filter( 'sanitize_file_name', array( $this, 'r17990' ) );
24
+
25
+ if ( !empty( $_POST ) )
26
+ $this->r17994( $_POST );
27
+ // Protect add_meta, update_meta used by the XML-RPC API
28
+ add_filter( 'wp_xmlrpc_server_class', create_function( '$class', 'return \'VaultPress_XMLRPC_Server_r17994\';' ) );
29
+
30
+ // clean post_mime_type and guid (r17994)
31
+ add_filter( 'pre_post_mime_type', array( $this, 'r17994_sanitize_mime_type' ) );
32
+ add_filter( 'post_mime_type', array( $this, 'r17994_sanitize_mime_type' ) );
33
+ add_filter( 'pre_post_guid', 'esc_url_raw' );
34
+ add_filter( 'post_guid', 'esc_url' );
35
+ }
36
+
37
+ if ( version_compare( $wp_version, '3.1.4', '<' ) ) {
38
+ add_filter( 'wp_insert_post_data', array( $this, 'r18368' ), 1, 2 );
39
+
40
+ // Add click jacking protection
41
+ // login_init does not exist before 17826.
42
+ $action = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : 'login';
43
+ add_action( 'login_form_' . $action, array( $this, 'r17826_send_frame_options_header' ), 10, 0 );
44
+ add_action( 'admin_init', array( $this, 'r17826_send_frame_options_header' ), 10, 0 );
45
+
46
+ add_filter( 'sanitize_option_WPLANG', array( $this, 'r18346_sanitize_lang_on_save' ) );
47
+ add_filter( 'sanitize_option_new_admin_email', array( $this, 'r18346_sanitize_admin_email_on_save' ) );
48
+ }
49
+ add_filter( 'option_new_admin_email', array( $this, 'r18346_sanitize_admin_email' ) );
50
+
51
+ if ( version_compare( $wp_version, '3.3.2', '<' ) ) {
52
+ remove_filter( 'comment_text', 'make_clickable' );
53
+ add_filter( 'comment_text', array( $this, 'r20493_make_clickable' ), 9 );
54
+
55
+ add_filter( 'comment_post_redirect', array( $this, 'r20486_comment_post_redirect' ) );
56
+ }
57
+
58
+ // WooThemes < 3.8.3, foxypress, asset-manager, wordpress-member-private-conversation.
59
+ $end_execution = false;
60
+ if ( isset( $_SERVER['SCRIPT_FILENAME'] ) )
61
+ foreach ( array( 'preview-shortcode-external.php', 'uploadify.php', 'doupload.php', 'cef-upload.php', 'upload.php' ) as $vulnerable_script )
62
+ if ( $vulnerable_script == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
63
+ switch( $vulnerable_script ) {
64
+ case 'upload.php':
65
+ $pma_config_file = realpath( dirname( $_SERVER['SCRIPT_FILENAME'] ) . DIRECTORY_SEPARATOR . 'paam-config-ajax.php' );
66
+ if ( !in_array( $pma_config_file, get_included_files() ) )
67
+ break;
68
+ default:
69
+ $end_execution = true;
70
+ break 2;
71
+ }
72
+ }
73
+ if ( $end_execution )
74
+ die( 'Disabled for security reasons' );
75
+
76
+ if ( version_compare( $wp_version, '3.3.2', '>') && version_compare( $wp_version, '3.4.1', '<' ) ) {
77
+ add_filter( 'map_meta_cap', array( $this, 'r21138_xmlrpc_edit_posts' ), 10, 4 );
78
+ add_action( 'map_meta_cap', array( $this, 'r21152_unfiltered_html' ), 10, 4 );
79
+ }
80
+
81
+ // https://core.trac.wordpress.org/changeset/21083
82
+ if ( version_compare( $wp_version, '3.3', '>=') && version_compare( $wp_version, '3.3.3', '<' ) )
83
+ add_filter( 'editable_slug', 'esc_textarea' );
84
+
85
+ add_filter( 'get_pagenum_link', array( $this, 'get_pagenum_link' ) );
86
+ }
87
+
88
+ function r21138_xmlrpc_edit_posts( $caps, $cap, $user_id, $args ) {
89
+ if ( ! isset( $args[0] ) || isset( $args[1] ) && $args[1] === 'hotfixed' )
90
+ return $caps;
91
+ foreach ( get_post_types( array(), 'objects' ) as $post_type_object ) {
92
+ if ( $cap === $post_type_object->cap->edit_posts )
93
+ return map_meta_cap( $post_type_object->cap->edit_post, $user_id, $args[0], 'hotfixed' );
94
+ }
95
+ return $caps;
96
+ }
97
+
98
+ function r21152_unfiltered_html( $caps, $cap, $user_id, $args ) {
99
+ if ( $cap !== 'unfiltered_html' )
100
+ return $caps;
101
+ if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML )
102
+ return $caps;
103
+ $key = array_search( 'do_not_allow', $caps );
104
+ if ( false !== $key )
105
+ return $caps;
106
+ if ( is_multisite() && ! is_super_admin( $user_id ) )
107
+ $caps[$key] = 'do_not_allow';
108
+ return $caps;
109
+ }
110
+
111
+ function get_pagenum_link( $url ) {
112
+ return esc_url_raw( $url );
113
+ }
114
+
115
+ function r20486_comment_post_redirect( $location ) {
116
+ $location = wp_sanitize_redirect( $location );
117
+ $location = wp_validate_redirect( $location, admin_url() );
118
+
119
+ return $location;
120
+ }
121
+
122
+ function r20493_make_clickable( $text ) {
123
+ $r = '';
124
+ $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
125
+ foreach ( $textarr as $piece ) {
126
+ if ( empty( $piece ) || ( $piece[0] == '<' && ! preg_match('|^<\s*[\w]{1,20}+://|', $piece) ) ) {
127
+ $r .= $piece;
128
+ continue;
129
+ }
130
+
131
+ // Long strings might contain expensive edge cases ...
132
+ if ( 10000 < strlen( $piece ) ) {
133
+ // ... break it up
134
+ foreach ( $this->r20493_split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
135
+ if ( 2101 < strlen( $chunk ) ) {
136
+ $r .= $chunk; // Too big, no whitespace: bail.
137
+ } else {
138
+ $r .= $this->r20493_make_clickable( $chunk );
139
+ }
140
+ }
141
+ } else {
142
+ $ret = " $piece "; // Pad with whitespace to simplify the regexes
143
+
144
+ $url_clickable = '~
145
+ ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
146
+ ( # 2: URL
147
+ [\\w]{1,20}+:// # Scheme and hier-part prefix
148
+ (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
149
+ [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
150
+ (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
151
+ [\'.,;:!?)] # Punctuation URL character
152
+ [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
153
+ )*
154
+ )
155
+ (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
156
+ ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
157
+ // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
158
+
159
+ $ret = preg_replace_callback( $url_clickable, array( $this, 'r20493_make_url_clickable_cb') , $ret );
160
+
161
+ $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
162
+ $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
163
+
164
+ $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
165
+ $r .= $ret;
166
+ }
167
+ }
168
+
169
+ // Cleanup of accidental links within links
170
+ $r = preg_replace( '#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
171
+ return $r;
172
+ }
173
+
174
+ function r20493_make_url_clickable_cb($matches) {
175
+ $url = $matches[2];
176
+
177
+ if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
178
+ // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
179
+ // Then we can let the parenthesis balancer do its thing below.
180
+ $url .= $matches[3];
181
+ $suffix = '';
182
+ } else {
183
+ $suffix = $matches[3];
184
+ }
185
+
186
+ // Include parentheses in the URL only if paired
187
+ while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
188
+ $suffix = strrchr( $url, ')' ) . $suffix;
189
+ $url = substr( $url, 0, strrpos( $url, ')' ) );
190
+ }
191
+
192
+ $url = esc_url($url);
193
+ if ( empty($url) )
194
+ return $matches[0];
195
+
196
+ return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
197
+ }
198
+
199
+ function r20493_split_str_by_whitespace( $string, $goal ) {
200
+ $chunks = array();
201
+
202
+ $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
203
+
204
+ while ( $goal < strlen( $string_nullspace ) ) {
205
+ $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
206
+
207
+ if ( false === $pos ) {
208
+ $pos = strpos( $string_nullspace, "\000", $goal + 1 );
209
+ if ( false === $pos ) {
210
+ break;
211
+ }
212
+ }
213
+
214
+ $chunks[] = substr( $string, 0, $pos + 1 );
215
+ $string = substr( $string, $pos + 1 );
216
+ $string_nullspace = substr( $string_nullspace, $pos + 1 );
217
+ }
218
+
219
+ if ( $string ) {
220
+ $chunks[] = $string;
221
+ }
222
+
223
+ return $chunks;
224
+ }
225
+
226
+ function r16625( $query ) {
227
+ // Hotfixes: http://core.trac.wordpress.org/changeset/16625
228
+
229
+ // Punt as fast as possible if this isn't an UPDATE
230
+ if ( substr( $query, 0, 6 ) != "UPDATE" )
231
+ return $query;
232
+ global $wpdb;
233
+
234
+ // Determine what the prefix of the bad query would look like and punt if this query doesn't match
235
+ $badstring = "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '";
236
+ if ( substr( $query, 0, strlen( $badstring ) ) != $badstring )
237
+ return $query;
238
+
239
+ // Pull the post_id which is the last thing in the origin query, after a space, no quotes
240
+ $post_id = array_pop( explode( " ", $query ) );
241
+
242
+ // Chop off the beginning and end of the original query to get our unsanitized $tb_ping
243
+ $tb_ping = substr(
244
+ $query,
245
+ strlen( $badstring ),
246
+ (
247
+ strlen( $query ) - (
248
+ strlen( $badstring ) + strlen( sprintf( "', '')) WHERE ID = %d", $post_id ) )
249
+ )
250
+ )
251
+ );
252
+
253
+ // Return the fixed query
254
+ return $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id );
255
+ }
256
+
257
+ function r16803( $xmlrpc_method ) {
258
+ // Hotfixes: http://core.trac.wordpress.org/changeset/16803
259
+ global $wp_xmlrpc_server;
260
+ // Pretend that we are an xmlrpc method, freshly called
261
+ $args = $wp_xmlrpc_server->message->params;
262
+ $error_code = 401;
263
+ switch( $xmlrpc_method ) {
264
+ case 'metaWeblog.newPost':
265
+ $content_struct = $args[3];
266
+ $publish = isset( $args[4] ) ? $args[4] : 0;
267
+ if ( !empty( $content_struct['post_type'] ) ) {
268
+ if ( $content_struct['post_type'] == 'page' ) {
269
+ if ( $publish || 'publish' == $content_struct['page_status'] )
270
+ $cap = 'publish_pages';
271
+ else
272
+ $cap = 'edit_pages';
273
+ $error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
274
+ } elseif ( $content_struct['post_type'] == 'post' ) {
275
+ if ( $publish || 'publish' == $content_struct['post_status'] )
276
+ $cap = 'publish_posts';
277
+ else
278
+ $cap = 'edit_posts';
279
+ $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
280
+ } else {
281
+ $error_message = __( 'Invalid post type.' );
282
+ }
283
+ } else {
284
+ if ( $publish || 'publish' == $content_struct['post_status'] )
285
+ $cap = 'publish_posts';
286
+ else
287
+ $cap = 'edit_posts';
288
+ $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
289
+ }
290
+ if ( current_user_can( $cap ) )
291
+ return true;
292
+ break;
293
+ case 'metaWeblog.editPost':
294
+ $post_ID = (int) $args[0];
295
+ $content_struct = $args[3];
296
+ $publish = $args[4];
297
+ $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
298
+ $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
299
+ if ( !empty( $content_struct['post_type'] ) ) {
300
+ if ( $content_struct['post_type'] == 'page' ) {
301
+ if ( $publish || 'publish' == $content_struct['page_status'] )
302
+ $cap = 'publish_pages';
303
+ else
304
+ $cap = 'edit_pages';
305
+ $error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
306
+ } elseif ( $content_struct['post_type'] == 'post' ) {
307
+ if ( $publish || 'publish' == $content_struct['post_status'] )
308
+ $cap = 'publish_posts';
309
+ else
310
+ $cap = 'edit_posts';
311
+ $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
312
+ } else {
313
+ $error_message = __( 'Invalid post type.' );
314
+ }
315
+ } else {
316
+ if ( $publish || 'publish' == $content_struct['post_status'] )
317
+ $cap = 'publish_posts';
318
+ else
319
+ $cap = 'edit_posts';
320
+ $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
321
+ }
322
+ if ( current_user_can( $cap ) )
323
+ return true;
324
+ break;
325
+ case 'mt.publishPost':
326
+ $post_ID = (int) $args[0];
327
+ if ( current_user_can( 'publish_posts' ) && current_user_can( 'edit_post', $post_ID ) )
328
+ return true;
329
+ $error_message = __( 'Sorry, you cannot edit this post.' );
330
+ break;
331
+ case 'blogger.deletePost':
332
+ $post_ID = (int) $args[1];
333
+ if ( current_user_can( 'delete_post', $post_ID ) )
334
+ return true;
335
+ $error_message = __( 'Sorry, you do not have the right to delete this post.' );
336
+ break;
337
+ case 'wp.getPageStatusList':
338
+ if ( current_user_can( 'edit_pages' ) )
339
+ return true;
340
+ $error_code = 403;
341
+ $error_message = __( 'You are not allowed access to details about this site.' );
342
+ break;
343
+ case 'wp.deleteComment':
344
+ case 'wp.editComment':
345
+ $comment_ID = (int) $args[3];
346
+ if ( !$comment = get_comment( $comment_ID ) )
347
+ return true; // This will be handled in the calling function explicitly
348
+ if ( current_user_can( 'edit_post', $comment->comment_post_ID ) )
349
+ return true;
350
+ $error_code = 403;
351
+ $error_message = __( 'You are not allowed to moderate comments on this site.' );
352
+ break;
353
+ default:
354
+ return true;
355
+ }
356
+ // If we are here then this was a handlable xmlrpc call and the capability checks above all failed
357
+ // ( otherwise they would have returned to the do_action from the switch statement above ) so it's
358
+ // time to exit with whatever error we've determined is the problem (thus short circuiting the
359
+ // original XMLRPC method call, and enforcing the above capability checks -- with an ax. We'll
360
+ // mimic the behavior from the end of IXR_Server::serve()
361
+ $r = new IXR_Error( $error_code, $error_message );
362
+ $resultxml = $r->getXml();
363
+ $xml = <<<EOD
364
+ <methodResponse>
365
+ <params>
366
+ <param>
367
+ <value>
368
+ $resultxml
369
+ </value>
370
+ </param>
371
+ </params>
372
+ </methodResponse>
373
+ EOD;
374
+ $wp_xmlrpc_server->output( $xml );
375
+ // For good measure...
376
+ die();
377
+ }
378
+
379
+ function r17172_esc_url( $url, $original_url, $_context ) {
380
+ $url = $original_url;
381
+
382
+ if ( '' == $url )
383
+ return $url;
384
+ $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
385
+ $strip = array('%0d', '%0a', '%0D', '%0A');
386
+ $url = _deep_replace($strip, $url);
387
+ $url = str_replace(';//', '://', $url);
388
+ /* If the URL doesn't appear to contain a scheme, we
389
+ * presume it needs http:// appended (unless a relative
390
+ * link starting with /, # or ? or a php file).
391
+ */
392
+ if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
393
+ ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
394
+ $url = 'http://' . $url;
395
+
396
+ // Replace ampersands and single quotes only when displaying.
397
+ if ( 'display' == $_context ) {
398
+ $url = wp_kses_normalize_entities( $url );
399
+ $url = str_replace( '&amp;', '&#038;', $url );
400
+ $url = str_replace( "'", '&#039;', $url );
401
+ }
402
+
403
+ $protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn');
404
+ if ( VaultPress_kses::wp_kses_bad_protocol( $url, $protocols ) != $url )
405
+ return '';
406
+ return $url;
407
+ }
408
+
409
+ // http://core.trac.wordpress.org/changeset/17172
410
+ // http://core.trac.wordpress.org/changeset/20541
411
+ function r17172_wp_kses( $string, $html, $protocols ) {
412
+ return VaultPress_kses::wp_kses( $string, $html, $protocols );
413
+ }
414
+
415
+ // http://core.trac.wordpress.org/changeset/17990
416
+ function r17990( $filename ) {
417
+ $parts = explode('.', $filename);
418
+ $filename = array_shift($parts);
419
+ $extension = array_pop($parts);
420
+ $mimes = get_allowed_mime_types();
421
+
422
+ // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
423
+ // long alpha string not in the extension whitelist.
424
+ foreach ( (array) $parts as $part) {
425
+ $filename .= '.' . $part;
426
+
427
+ if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
428
+ $allowed = false;
429
+ foreach ( $mimes as $ext_preg => $mime_match ) {
430
+ $ext_preg = '!^(' . $ext_preg . ')$!i';
431
+ if ( preg_match( $ext_preg, $part ) ) {
432
+ $allowed = true;
433
+ break;
434
+ }
435
+ }
436
+ if ( !$allowed )
437
+ $filename .= '_';
438
+ }
439
+ }
440
+ $filename .= '.' . $extension;
441
+ return $filename;
442
+ }
443
+
444
+ /*
445
+ * Hotfixes: http://core.trac.wordpress.org/changeset/18368
446
+ */
447
+ function r18368( $post, $raw_post ) {
448
+ if ( isset( $post['filter'] ) || isset ( $raw_post['filter'] ) ) {
449
+ unset( $post['filter'], $raw_post['filter'] ); // to ensure the post is properly sanitized
450
+ $post = sanitize_post($post, 'db');
451
+ }
452
+ if ( empty( $post['ID'] ) )
453
+ unset( $post['ID'] ); // sanitize_post
454
+ unset( $post['filter'] ); // sanitize_post
455
+ return $post;
456
+ }
457
+
458
+ /**
459
+ * Protect WordPress internal metadata.
460
+ *
461
+ * The post data is passed as a parameter to (unit) test this method.
462
+ * @param $post_data|array the $_POST array.
463
+ */
464
+ function r17994( &$post_data ) {
465
+ // Protect admin-ajax add_meta
466
+ $metakeyselect = isset( $post_data['metakeyselect'] ) ? stripslashes( trim( $post_data['metakeyselect'] ) ) : '';
467
+ $metakeyinput = isset( $post_data['metakeyinput'] ) ? stripslashes( trim( $post_data['metakeyinput'] ) ) : '';
468
+
469
+ if ( ( $metakeyselect && '_' == $metakeyselect[0] ) || ( $metakeyinput && '_' == $metakeyinput[0] ) ) {
470
+ unset( $_POST['metakeyselect'], $_POST['metakeyinput'] );
471
+ }
472
+
473
+ // Protect admin-ajax update_meta
474
+ if ( isset( $post_data['meta'] ) ) {
475
+ foreach ( (array)$post_data['meta'] as $mid => $value ) {
476
+ $key = stripslashes( $post_data['meta'][$mid]['key'] );
477
+ if ( $key && '_' == $key[0] )
478
+ unset( $post_data['meta'][$mid] );
479
+ }
480
+ }
481
+ }
482
+
483
+ function r17994_sanitize_mime_type( $mime_type ) {
484
+ $sani_mime_type = preg_replace( '/[^\-*.a-zA-Z0-9\/+]/', '', $mime_type );
485
+ return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
486
+ }
487
+
488
+ function r17826_send_frame_options_header() {
489
+ @header( 'X-Frame-Options: SAMEORIGIN' );
490
+ }
491
+
492
+ function r18346_sanitize_admin_email_on_save($value) {
493
+ $value = sanitize_email( $value );
494
+ if ( !is_email( $value ) ) {
495
+ $value = get_option( 'new_admin_email' ); // Resets option to stored value in the case of failed sanitization
496
+ if ( function_exists( 'add_settings_error' ) )
497
+ add_settings_error( 'new_admin_email', 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
498
+ }
499
+ return $value;
500
+ }
501
+
502
+ function r18346_sanitize_admin_email( $value ) {
503
+ return sanitize_email( $value ); // Is it enough ?
504
+ }
505
+
506
+ function r18346_sanitize_lang_on_save( $value ) {
507
+ $value = $this->r18346_sanitize_lang( $value ); // sanitize the new value.
508
+ if ( empty( $value ) )
509
+ $value = get_option( 'WPLANG' );
510
+ return $value;
511
+ }
512
+
513
+ function r18346_sanitize_lang( $value ) {
514
+ $allowed = apply_filters( 'available_languages', get_available_languages() ); // add a filter to unit test
515
+ if ( !empty( $value ) && !in_array( $value, $allowed ) )
516
+ return false;
517
+ else
518
+ return $value;
519
+ }
520
+ }
521
+
522
+ global $wp_version;
523
+ $needs_class_fix = version_compare( $wp_version, '3.1', '>=') && version_compare( $wp_version, '3.1.3', '<' );
524
+ if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && $needs_class_fix ) {
525
+ include_once( ABSPATH . WPINC . '/class-IXR.php' );
526
+ include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
527
+
528
+ class VaultPress_XMLRPC_Server_r17994 extends wp_xmlrpc_server {
529
+ function set_custom_fields( $post_id, $fields ) {
530
+ foreach( $fields as $k => $meta ) {
531
+ $key = stripslashes( trim( $meta['key'] ) );
532
+ if ( $key && '_' == $key[0] )
533
+ unset( $fields[$k] );
534
+ }
535
+ parent::set_custom_fields( $post_id, $fields );
536
+ }
537
+ }
538
+ }
539
+
540
+ class VaultPress_kses {
541
+ static function wp_kses($string, $allowed_html, $allowed_protocols = array ()) {
542
+ $string = wp_kses_no_null($string);
543
+ $string = wp_kses_js_entities($string);
544
+ $string = wp_kses_normalize_entities($string);
545
+ return VaultPress_kses::wp_kses_split($string, $allowed_html, $allowed_protocols);
546
+ }
547
+
548
+ static function wp_kses_split($string, $allowed_html, $allowed_protocols) {
549
+ global $pass_allowed_html, $pass_allowed_protocols;
550
+ $pass_allowed_html = $allowed_html;
551
+ $pass_allowed_protocols = $allowed_protocols;
552
+ return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', 'VaultPress_kses::_vp_kses_split_callback', $string );
553
+ }
554
+
555
+ static function _vp_kses_split_callback( $match ) {
556
+ global $pass_allowed_html, $pass_allowed_protocols;
557
+ return VaultPress_kses::wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
558
+ }
559
+
560
+ static function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
561
+ $string = wp_kses_stripslashes($string);
562
+
563
+ if (substr($string, 0, 1) != '<')
564
+ return '&gt;';
565
+ # It matched a ">" character
566
+
567
+ if ( '<!--' == substr( $string, 0, 4 ) ) {
568
+ $string = str_replace( array('<!--', '-->'), '', $string );
569
+ while ( $string != ($newstring = VaultPress_kses::wp_kses($string, $allowed_html, $allowed_protocols)) )
570
+ $string = $newstring;
571
+ if ( $string == '' )
572
+ return '';
573
+ // prevent multiple dashes in comments
574
+ $string = preg_replace('/--+/', '-', $string);
575
+ // prevent three dashes closing a comment
576
+ $string = preg_replace('/-$/', '', $string);
577
+ return "<!--{$string}-->";
578
+ }
579
+ # Allow HTML comments
580
+
581
+ if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
582
+ return '';
583
+ # It's seriously malformed
584
+
585
+ $slash = trim($matches[1]);
586
+ $elem = $matches[2];
587
+ $attrlist = $matches[3];
588
+
589
+ if ( ! isset($allowed_html[strtolower($elem)]) )
590
+ return '';
591
+ # They are using a not allowed HTML element
592
+
593
+ if ($slash != '')
594
+ return "</$elem>";
595
+ # No attributes are allowed for closing elements
596
+
597
+ return VaultPress_kses::wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
598
+ }
599
+
600
+ static function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
601
+ # Is there a closing XHTML slash at the end of the attributes?
602
+
603
+ $xhtml_slash = '';
604
+ if (preg_match('%\s*/\s*$%', $attr))
605
+ $xhtml_slash = ' /';
606
+
607
+ # Are any attributes allowed at all for this element?
608
+ if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
609
+ return "<$element$xhtml_slash>";
610
+
611
+ # Split it
612
+ $attrarr = VaultPress_kses::wp_kses_hair($attr, $allowed_protocols);
613
+
614
+ # Go through $attrarr, and save the allowed attributes for this element
615
+ # in $attr2
616
+ $attr2 = '';
617
+
618
+ $allowed_attr = $allowed_html[strtolower($element)];
619
+ foreach ($attrarr as $arreach) {
620
+ if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) )
621
+ continue; # the attribute is not allowed
622
+
623
+ $current = $allowed_attr[strtolower($arreach['name'])];
624
+ if ( $current == '' )
625
+ continue; # the attribute is not allowed
626
+
627
+ if ( strtolower( $arreach['name'] ) == 'style' ) {
628
+ $orig_value = $arreach['value'];
629
+ $value = safecss_filter_attr( $orig_value );
630
+
631
+ if ( empty( $value ) )
632
+ continue;
633
+
634
+ $arreach['value'] = $value;
635
+ $arreach['whole'] = str_replace( $orig_value, $value, $arreach['whole'] );
636
+ }
637
+
638
+ if ( ! is_array($current) ) {
639
+ $attr2 .= ' '.$arreach['whole'];
640
+ # there are no checks
641
+
642
+ } else {
643
+ # there are some checks
644
+ $ok = true;
645
+ foreach ($current as $currkey => $currval) {
646
+ if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) {
647
+ $ok = false;
648
+ break;
649
+ }
650
+ }
651
+
652
+ if ( $ok )
653
+ $attr2 .= ' '.$arreach['whole']; # it passed them
654
+ } # if !is_array($current)
655
+ } # foreach
656
+
657
+ # Remove any "<" or ">" characters
658
+ $attr2 = preg_replace('/[<>]/', '', $attr2);
659
+
660
+ return "<$element$attr2$xhtml_slash>";
661
+ }
662
+
663
+ static function wp_kses_hair($attr, $allowed_protocols) {
664
+ $attrarr = array ();
665
+ $mode = 0;
666
+ $attrname = '';
667
+ $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
668
+
669
+ # Loop through the whole attribute list
670
+
671
+ while (strlen($attr) != 0) {
672
+ $working = 0; # Was the last operation successful?
673
+
674
+ switch ($mode) {
675
+ case 0 : # attribute name, href for instance
676
+
677
+ if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
678
+ $attrname = $match[1];
679
+ $working = $mode = 1;
680
+ $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
681
+ }
682
+
683
+ break;
684
+
685
+ case 1 : # equals sign or valueless ("selected")
686
+
687
+ if (preg_match('/^\s*=\s*/', $attr)) # equals sign
688
+ {
689
+ $working = 1;
690
+ $mode = 2;
691
+ $attr = preg_replace('/^\s*=\s*/', '', $attr);
692
+ break;
693
+ }
694
+
695
+ if (preg_match('/^\s+/', $attr)) # valueless
696
+ {
697
+ $working = 1;
698
+ $mode = 0;
699
+ if(false === array_key_exists($attrname, $attrarr)) {
700
+ $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
701
+ }
702
+ $attr = preg_replace('/^\s+/', '', $attr);
703
+ }
704
+
705
+ break;
706
+
707
+ case 2 : # attribute value, a URL after href= for instance
708
+
709
+ if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
710
+ # "value"
711
+ {
712
+ $thisval = $match[1];
713
+ if ( in_array(strtolower($attrname), $uris) )
714
+ $thisval = VaultPress_kses::wp_kses_bad_protocol($thisval, $allowed_protocols);
715
+
716
+ if(false === array_key_exists($attrname, $attrarr)) {
717
+ $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
718
+ }
719
+ $working = 1;
720
+ $mode = 0;
721
+ $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
722
+ break;
723
+ }
724
+
725
+ if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
726
+ # 'value'
727
+ {
728
+ $thisval = $match[1];
729
+ if ( in_array(strtolower($attrname), $uris) )
730
+ $thisval = VaultPress_kses::wp_kses_bad_protocol($thisval, $allowed_protocols);
731
+
732
+ if(false === array_key_exists($attrname, $attrarr)) {
733
+ $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
734
+ }
735
+ $working = 1;
736
+ $mode = 0;
737
+ $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
738
+ break;
739
+ }
740
+
741
+ if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
742
+ # value
743
+ {
744
+ $thisval = $match[1];
745
+ if ( in_array(strtolower($attrname), $uris) )
746
+ $thisval = VaultPress_kses::wp_kses_bad_protocol($thisval, $allowed_protocols);
747
+
748
+ if(false === array_key_exists($attrname, $attrarr)) {
749
+ $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
750
+ }
751
+ # We add quotes to conform to W3C's HTML spec.
752
+ $working = 1;
753
+ $mode = 0;
754
+ $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
755
+ }
756
+
757
+ break;
758
+ } # switch
759
+
760
+ if ($working == 0) # not well formed, remove and try again
761
+ {
762
+ $attr = wp_kses_html_error($attr);
763
+ $mode = 0;
764
+ }
765
+ } # while
766
+
767
+ if ($mode == 1 && false === array_key_exists($attrname, $attrarr))
768
+ # special case, for when the attribute list ends with a valueless
769
+ # attribute like "selected"
770
+ $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
771
+
772
+ return $attrarr;
773
+ }
774
+
775
+ static function wp_kses_bad_protocol($string, $allowed_protocols) {
776
+ $string = wp_kses_no_null($string);
777
+ $iterations = 0;
778
+
779
+ do {
780
+ $original_string = $string;
781
+ $string = VaultPress_kses::wp_kses_bad_protocol_once($string, $allowed_protocols);
782
+ } while ( $original_string != $string && ++$iterations < 6 );
783
+
784
+ if ( $original_string != $string )
785
+ return '';
786
+
787
+ return $string;
788
+ }
789
+
790
+ static function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1) {
791
+ $string2 = preg_split( '/:|&#0*58;|&#x0*3a;/i', $string, 2 );
792
+ if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
793
+ $string = trim( $string2[1] );
794
+ $protocol = VaultPress_kses::wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
795
+ if ( 'feed:' == $protocol ) {
796
+ if ( $count > 2 )
797
+ return '';
798
+ $string = VaultPress_kses::wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
799
+ if ( empty( $string ) )
800
+ return $string;
801
+ }
802
+ $string = $protocol . $string;
803
+ }
804
+
805
+ return $string;
806
+ }
807
+
808
+ static function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
809
+ $string2 = wp_kses_decode_entities($string);
810
+ $string2 = preg_replace('/\s/', '', $string2);
811
+ $string2 = wp_kses_no_null($string2);
812
+ $string2 = strtolower($string2);
813
+
814
+ $allowed = false;
815
+ foreach ( (array) $allowed_protocols as $one_protocol )
816
+ if ( strtolower($one_protocol) == $string2 ) {
817
+ $allowed = true;
818
+ break;
819
+ }
820
+
821
+ if ($allowed)
822
+ return "$string2:";
823
+ else
824
+ return '';
825
+ }
826
+
827
+ }
828
+
829
+ if ( !function_exists( 'get_available_languages' ) ) {
830
+ function get_available_languages( $dir = null ) {
831
+ $languages = array();
832
+ foreach( glob( ( is_null( $dir) ? WP_LANG_DIR : $dir ) . '/*.mo' ) as $lang_file )
833
+ if ( false === strpos( $lang_file, 'continents-cities' ) )
834
+ $languages[] = basename($lang_file, '.mo');
835
+ return $languages;
836
+ }
837
+ }
class.vaultpress-ixr-ssl-client.php ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ // don't call the file directly
4
+ if ( !defined( 'ABSPATH' ) )
5
+ return;
6
+
7
+ if ( !class_exists( 'IXR_Client' ) )
8
+ include_once( ABSPATH . WPINC . '/class-IXR.php' );
9
+
10
+ class VaultPress_IXR_SSL_Client extends IXR_Client {
11
+ var $ssl = false;
12
+ function VaultPress_IXR_SSL_Client( $server, $path = false, $port = 80, $timeout = false ) {
13
+ $this->IXR_Client( $server, $path, $port, $timeout );
14
+ }
15
+ function ssl( $port=443 ) {
16
+ if ( !extension_loaded( 'openssl' ) )
17
+ return;
18
+
19
+ $this->ssl = true;
20
+ if ( $port )
21
+ $this->port = $port;
22
+ }
23
+ function query() {
24
+ $args = func_get_args();
25
+ $method = array_shift($args);
26
+ $request = new IXR_Request($method, $args);
27
+ $length = $request->getLength();
28
+ $xml = $request->getXml();
29
+ $r = "\r\n";
30
+ $request = "POST {$this->path} HTTP/1.0$r";
31
+
32
+ $this->headers['Host'] = preg_replace( '#^ssl://#', '', $this->server );
33
+ $this->headers['Content-Type'] = 'text/xml';
34
+ $this->headers['User-Agent'] = $this->useragent;
35
+ $this->headers['Content-Length'] = $length;
36
+
37
+ if ( class_exists( 'WP_Http' ) ) {
38
+ $args = array(
39
+ 'method' => 'POST',
40
+ 'body' => $xml,
41
+ 'headers' => $this->headers,
42
+ 'sslverify' => false,
43
+ );
44
+ if ( $this->timeout )
45
+ $args['timeout'] = $this->timeout;
46
+
47
+ $http = new WP_Http();
48
+ if ( $this->ssl )
49
+ $url = sprintf( 'https://%s%s', $this->server, $this->path );
50
+ else
51
+ $url = sprintf( 'http://%s%s', $this->server, $this->path );
52
+
53
+ $result = $http->request( $url, $args );
54
+ if ( is_wp_error( $result ) ) {
55
+ foreach( $result->errors as $type => $messages ) {
56
+ $this->error = new IXR_Error(
57
+ -32702,
58
+ sprintf( 'WP_Http error: %s, %s', $type, $messages[0] )
59
+ );
60
+ break;
61
+ }
62
+ return false;
63
+ } else if ( $result['response']['code'] > 299 || $result['response']['code'] < 200 ) {
64
+ $this->error = new IXR_Error(
65
+ -32701,
66
+ sprintf( 'Server rejected request (HTTP response: %s %s)', $result['response']['code'], $result['response']['message'])
67
+ );
68
+ return false;
69
+ }
70
+ // Now parse what we've got back
71
+ $this->message = new IXR_Message( $result['body'] );
72
+ } else {
73
+ foreach( $this->headers as $header => $value ) {
74
+ $request .= "{$header}: {$value}{$r}";
75
+ }
76
+ $request .= $r;
77
+
78
+ $request .= $xml;
79
+ // Now send the request
80
+ if ( $this->ssl )
81
+ $host = 'ssl://'.$this->server;
82
+ else
83
+ $host = $this->server;
84
+ if ($this->timeout) {
85
+ $fp = @fsockopen( $host, $this->port, $errno, $errstr, $this->timeout );
86
+ } else {
87
+ $fp = @fsockopen( $host, $this->port, $errno, $errstr );
88
+ }
89
+ if (!$fp) {
90
+ $this->error = new IXR_Error( -32300, "Transport error - could not open socket: $errno $errstr" );
91
+ return false;
92
+ }
93
+ fputs( $fp, $request );
94
+
95
+ $contents = '';
96
+ $gotFirstLine = false;
97
+ $gettingHeaders = true;
98
+
99
+ while ( !feof($fp) ) {
100
+ $line = fgets( $fp, 4096 );
101
+ if ( !$gotFirstLine ) {
102
+ // Check line for '200'
103
+ if ( strstr($line, '200') === false ) {
104
+ $this->error = new IXR_Error( -32301, 'transport error - HTTP status code was not 200' );
105
+ return false;
106
+ }
107
+ $gotFirstLine = true;
108
+ }
109
+ if ( trim($line) == '' ) {
110
+ $gettingHeaders = false;
111
+ }
112
+ if ( !$gettingHeaders ) {
113
+ $contents .= trim( $line );
114
+ }
115
+ }
116
+ // Now parse what we've got back
117
+ $this->message = new IXR_Message( $contents );
118
+ }
119
+ if ( !$this->message->parse() ) {
120
+ // XML error
121
+ $this->error = new IXR_Error( -32700, 'parse error. not well formed' );
122
+ return false;
123
+ }
124
+ // Is the message a fault?
125
+ if ( $this->message->messageType == 'fault' ) {
126
+ $this->error = new IXR_Error( $this->message->faultCode, $this->message->faultString );
127
+ return false;
128
+ }
129
+ // Message must be OK
130
+ return true;
131
+ }
132
+ }
cron-tasks.php ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ include_once dirname( __FILE__ ) . '/vp-scanner.php';
3
+
4
+ if ( !function_exists( 'apply_filters_ref_array' ) ) :
5
+
6
+ function apply_filters_ref_array($tag, $args) {
7
+ global $wp_filter, $merged_filters, $wp_current_filter;
8
+
9
+ // Do 'all' actions first
10
+ if ( isset($wp_filter['all']) ) {
11
+ $wp_current_filter[] = $tag;
12
+ $all_args = func_get_args();
13
+ _wp_call_all_hook($all_args);
14
+ }
15
+
16
+ if ( !isset($wp_filter[$tag]) ) {
17
+ if ( isset($wp_filter['all']) )
18
+ array_pop($wp_current_filter);
19
+ return $args[0];
20
+ }
21
+
22
+ if ( !isset($wp_filter['all']) )
23
+ $wp_current_filter[] = $tag;
24
+
25
+ // Sort
26
+ if ( !isset( $merged_filters[ $tag ] ) ) {
27
+ ksort($wp_filter[$tag]);
28
+ $merged_filters[ $tag ] = true;
29
+ }
30
+
31
+ reset( $wp_filter[ $tag ] );
32
+
33
+ do {
34
+ foreach( (array) current($wp_filter[$tag]) as $the_ )
35
+ if ( !is_null($the_['function']) )
36
+ $args[0] = call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
37
+
38
+ } while ( next($wp_filter[$tag]) !== false );
39
+
40
+ array_pop( $wp_current_filter );
41
+
42
+ return $args[0];
43
+ }
44
+
45
+ endif;
46
+
47
+ class VP_Site_Scanner {
48
+ function VP_Site_Scanner() {
49
+ self::__construct();
50
+ }
51
+ function __construct() {
52
+ // Only scan once in multisites.
53
+ if( function_exists( 'is_main_site' ) && !is_main_site() )
54
+ return;
55
+ add_action( 'vp_scan_site' , array( $this, '_scan_site') );
56
+ add_filter( 'cron_schedules' , array( $this, '_custom_cron' ) );
57
+ add_action( 'vp_scan_next_batch', array( $this, '_scan_batch' ) );
58
+
59
+ $signatures = get_option( '_vp_signatures' );
60
+ if ( $signatures && ! wp_next_scheduled( 'vp_scan_site' ) )
61
+ wp_schedule_event( time(), 'daily', 'vp_scan_site' );
62
+ if ( $signatures && ! wp_next_scheduled( 'vp_scan_next_batch' ) )
63
+ wp_schedule_event( time(), 'five_minutes_interval', 'vp_scan_next_batch' );
64
+ }
65
+
66
+ function _custom_cron( $schedules ) {
67
+ $schedules['five_minutes_interval'] = array(
68
+ 'interval' => 300,
69
+ 'display' => __( 'Once every five minutes' , 'vaultpress'),
70
+ );
71
+ return $schedules;
72
+ }
73
+
74
+ function _scan_site() {
75
+ if ( !get_option( '_vp_current_scan' ) ) {
76
+ $ignore_symlinks = get_option( '_vp_ignore_symlinks', false );
77
+ $paths = array( 'root' => new VP_FileScan( ABSPATH, $ignore_symlinks ) );
78
+
79
+ // Is WP_CONTENT_DIR inside ABSPATH?
80
+ if ( is_dir( WP_CONTENT_DIR ) && strpos( realpath( WP_CONTENT_DIR ), realpath( ABSPATH ) . DIRECTORY_SEPARATOR ) !== 0 )
81
+ $paths['content'] = new VP_FileScan( WP_CONTENT_DIR, $ignore_symlinks );
82
+
83
+ // Is WP_PLUGIN_DIR inside ABSPATH or WP_CONTENT_DIR?
84
+ if ( is_dir( WP_PLUGIN_DIR ) && strpos( realpath( WP_PLUGIN_DIR ), realpath( WP_CONTENT_DIR ) . DIRECTORY_SEPARATOR ) !== 0 && strpos( realpath( WP_PLUGIN_DIR ), realpath( ABSPATH ) . DIRECTORY_SEPARATOR ) !== 0 )
85
+ $paths['plugins'] = new VP_FileScan( WP_PLUGIN_DIR, $ignore_symlinks );
86
+
87
+ // Is WPMU_PLUGIN_DIR inside ABSPATH or WP_CONTENT_DIR?
88
+ if ( is_dir( WPMU_PLUGIN_DIR ) && strpos( realpath( WPMU_PLUGIN_DIR ), realpath( WP_CONTENT_DIR ) . DIRECTORY_SEPARATOR ) !== 0 && strpos( realpath( WPMU_PLUGIN_DIR ), realpath( ABSPATH ) . DIRECTORY_SEPARATOR ) !== 0 )
89
+ $paths['mu-plugins'] = new VP_FileScan( WPMU_PLUGIN_DIR, $ignore_symlinks );
90
+
91
+ update_option( '_vp_current_scan', $paths );
92
+ }
93
+ }
94
+
95
+ function _scan_clean_up( &$paths, $type = null ) {
96
+ if( is_array( $paths ) )
97
+ unset( $paths[$type] );
98
+ if ( empty( $paths ) || !is_array( $paths ) ) {
99
+ delete_option( '_vp_current_scan' );
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ function _scan_batch() {
106
+ $paths = get_option( '_vp_current_scan' );
107
+ if ( empty( $paths ) || $this->_scan_clean_up( $paths ) )
108
+ return false;
109
+
110
+ reset( $paths );
111
+ list( $type, $current ) = each( $paths );
112
+ if ( !is_object( $current ) || empty( $current->last_dir ) )
113
+ return $this->_scan_clean_up( $paths, $type );
114
+
115
+ $default_batch_limit = 400;
116
+ if ( function_exists( 'set_time_limit' ) )
117
+ set_time_limit(0);
118
+ else
119
+ $default_batch_limit = 100; // avoid timeouts
120
+
121
+ $GLOBALS['vp_signatures'] = get_option( '_vp_signatures' );
122
+ if ( empty( $GLOBALS['vp_signatures'] ) )
123
+ return false;
124
+
125
+ $limit = get_option( '_vp_batch_file_size', $default_batch_limit );
126
+ $files = $current->get_files( $limit );
127
+
128
+ // No more files to scan.
129
+ if ( !$current->last_dir || count( $files ) < $limit )
130
+ unset( $paths[$type] );
131
+
132
+ update_option( '_vp_current_scan', $paths );
133
+ $results = array();
134
+ foreach ( $files as $file ) {
135
+ $verdict = vp_scan_file( $file );
136
+ if ( !empty( $verdict ) )
137
+ $results[$file] = array( 'hash' => @md5_file( $file ), 'verdict' => $verdict );
138
+ }
139
+
140
+ if ( !empty( $results ) ) {
141
+ $vaultpress = VaultPress::init();
142
+ $vaultpress->add_ping( 'security', array( 'suspicious_v2' => $results ) );
143
+ }
144
+ }
145
+
146
+ function &init() {
147
+ static $instance = false;
148
+ if ( !$instance )
149
+ $instance = new VP_Site_Scanner();
150
+ return $instance;
151
+ }
152
+ }
153
+ VP_Site_Scanner::init();
readme.txt ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === VaultPress ===
2
+ Contributors: automattic, aldenta, apokalyptik, briancolinger, shaunandrews, xknown
3
+ Tags: security, malware, virus, backups, scanning
4
+ Requires at least: 2.9.2
5
+ Tested up to: 3.5
6
+ Stable tag: 1.4.3
7
+
8
+ VaultPress is a subscription service offering realtime backup, automated security scanning, and support from WordPress experts.
9
+
10
+ == Description ==
11
+
12
+ [VaultPress](http://vaultpress.com/?utm_source=plugin-readme&utm_medium=description&utm_campaign=1.0) is a real-time backup and security scanning service designed and built by [Automattic](http://automattic.com/), the same company that operates 25+ million sites on WordPress.com.
13
+
14
+ [wpvideo TxdSIdpO]
15
+
16
+ For more information, check out [VaultPress.com](http://vaultpress.com/).
17
+
18
+ == Installation ==
19
+
20
+ 1. Search for VaultPress in the WordPress.org plugin directory and click install. Or, upload the files to your `wp-content/vaultpress/` folder.
21
+ 2. Visit `wp-admin/plugins.php` and activate the VaultPress plugin.
22
+ 3. Head to `wp-admin/admin.php?page=vaultpress` and enter your site&rsquo;s registration key. You can purchase your registration key at [VaultPress.com](http://vaultpress.com/plugin/?utm_source=plugin-readme&utm_medium=installation&utm_campaign=1.0)
23
+
24
+ You can find more detailed instructions at [http://vaultpress.com/help/](http://vaultpress.com/help/install-vaultpress/?utm_source=plugin-readme&utm_medium=description&utm_campaign=1.0)
25
+
26
+ == Frequently Asked Questions ==
27
+
28
+ View our full list of FAQs at [http://vaultpress.com/help/faq/](http://vaultpress.com/help/faq/?utm_source=plugin-readme&utm_medium=faq&utm_campaign=1.0)
29
+
30
+ = What’s included in each VaultPress plan? =
31
+
32
+ All plans include Realtime Backups, Downloadable Archives for Restoring, Vitality Statistics, and the Activity Log.
33
+
34
+ The Basic plan provides access to disaster recovery and support services.
35
+
36
+ The Premium plan provides priority recovery and support services, along with site migration assistance. The Premium plan provides automated security scanning of Core, Theme, and Plugin files.
37
+
38
+ The Enterprise members receive top priority for support services and migration assistance. Along with security scanning, Enterprise members receive complimentary security consulting and performance auditing.
39
+
40
+ Update-to-date pricing and features can always be found on the [Plans &amp; Pricing](http://vaultpress.com/plugin/?utm_source=plugin-readme&utm_medium=installation&utm_campaign=1.0) page.
41
+
42
+ = How many sites can I protect with VaultPress? =
43
+
44
+ A VaultPress subscription is for a single WordPress site. You can purchase additional subscriptions for each of your WordPress sites, and manage them all with in one place.
45
+
46
+ = Does VaultPress work with WordPress 3.0 Multisite installs? =
47
+
48
+ With our 1.0 release, VaultPress now supports Multisite installs. Each site will require its own subscription.
49
+
50
+ == Changelog ==
51
+ = 1.3.9 =
52
+ * Feature: Request decoding (base64/rot13)
53
+ * Feature: Response encoding (base64/rot13)
54
+
55
+ = 1.3.8 =
56
+ * Bugfix: Validate IPv4-mapped IPv6 addresses in the internal firewall.
57
+ * Bugfix: Fix hooks not being properly added under certain circumstances.
58
+
59
+ = 1.3.7 =
60
+ * Bugfix: Protect against infinite loop due to a PHP bug.
61
+ * Bugfix: Encode remote ping requests.
62
+
63
+ = 1.0 =
64
+ * First public release!
vaultpress.php ADDED
@@ -0,0 +1,2137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*
3
+ * Plugin Name: VaultPress
4
+ * Plugin URI: http://vaultpress.com/?utm_source=plugin-uri&amp;utm_medium=plugin-description&amp;utm_campaign=1.0
5
+ * Description: Protect your content, themes, plugins, and settings with <strong>realtime backup</strong> and <strong>automated security scanning</strong> from <a href="http://vaultpress.com/?utm_source=wp-admin&amp;utm_medium=plugin-description&amp;utm_campaign=1.0" rel="nofollow">VaultPress</a>. Activate, enter your registration key, and never worry again. <a href="http://vaultpress.com/help/?utm_source=wp-admin&amp;utm_medium=plugin-description&amp;utm_campaign=1.0" rel="nofollow">Need some help?</a>
6
+ * Version: 1.4.5
7
+ * Author: Automattic
8
+ * Author URI: http://vaultpress.com/?utm_source=author-uri&amp;utm_medium=plugin-description&amp;utm_campaign=1.0
9
+ * License: GPL2+
10
+ * Text Domain: vaultpress
11
+ * Domain Path: /languages/
12
+ */
13
+
14
+ // don't call the file directly
15
+ if ( !defined( 'ABSPATH' ) )
16
+ return;
17
+
18
+ class VaultPress {
19
+ var $option_name = 'vaultpress';
20
+ var $db_version = 3;
21
+ var $plugin_version = '1.4.5';
22
+
23
+ function VaultPress() {
24
+ $this->__construct();
25
+ }
26
+
27
+ function __construct() {
28
+ register_activation_hook( __FILE__, array( $this, 'activate' ) );
29
+ register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
30
+
31
+ $options = get_option( $this->option_name );
32
+ if ( !is_array( $options ) )
33
+ $options = array();
34
+
35
+ $defaults = array(
36
+ 'db_version' => 0,
37
+ 'key' => '',
38
+ 'secret' => '',
39
+ 'connection' => false,
40
+ 'service_ips' => false
41
+ );
42
+
43
+ $this->options = wp_parse_args( $options, $defaults );
44
+ $this->reset_pings();
45
+
46
+ $this->upgrade();
47
+
48
+ if ( is_admin() )
49
+ $this->add_admin_actions_and_filters();
50
+
51
+ if ( $this->is_registered() ) {
52
+ $do_not_backup = $this->get_option( 'do_not_backup' ) || $this->get_option( 'do_not_send_backup_pings' );
53
+ if ( $do_not_backup )
54
+ $this->add_vp_required_filters();
55
+ else
56
+ $this->add_listener_actions_and_filters();
57
+ }
58
+ }
59
+
60
+ function &init() {
61
+ static $instance = false;
62
+
63
+ if ( !$instance ) {
64
+ $instance = new VaultPress();
65
+ }
66
+
67
+ return $instance;
68
+ }
69
+
70
+ function activate( $network_wide ) {
71
+ $type = $network_wide ? 'network' : 'single';
72
+ $this->update_option( 'activated', $type );
73
+
74
+ // force a connection check after an activation
75
+ $this->clear_connection();
76
+ }
77
+
78
+ function deactivate() {
79
+ if ( $this->is_registered() )
80
+ $this->contact_service( 'plugin_status', array( 'vp_plugin_status' => 'deactivated' ) );
81
+ }
82
+
83
+ function upgrade() {
84
+ $current_db_version = $this->get_option( 'db_version' );
85
+
86
+ if ( $current_db_version < 1 ) {
87
+ $this->options['connection'] = get_option( 'vaultpress_connection' );
88
+ $this->options['key'] = get_option( 'vaultpress_key' );
89
+ $this->options['secret'] = get_option( 'vaultpress_secret' );
90
+ $this->options['service_ips'] = get_option( 'vaultpress_service_ips' );
91
+
92
+ // remove old options
93
+ $old_options = array(
94
+ 'vaultpress_connection',
95
+ 'vaultpress_hostname',
96
+ 'vaultpress_key',
97
+ 'vaultpress_secret',
98
+ 'vaultpress_service_ips',
99
+ 'vaultpress_timeout',
100
+ 'vp_allow_remote_execution',
101
+ 'vp_debug_request_signing',
102
+ 'vp_disable_firewall',
103
+ );
104
+
105
+ foreach ( $old_options as $option )
106
+ delete_option( $option );
107
+
108
+ $this->options['db_version'] = $this->db_version;
109
+ $this->update_options();
110
+ }
111
+
112
+ if ( $current_db_version < 2 ) {
113
+ $this->delete_option( 'timeout' );
114
+ $this->delete_option( 'disable_firewall' );
115
+ $this->update_option( 'db_version', $this->db_version );
116
+ $this->clear_connection();
117
+ }
118
+
119
+ if ( $current_db_version < 3 ) {
120
+ $this->update_firewall();
121
+ $this->update_option( 'db_version', $this->db_version );
122
+ $this->clear_connection();
123
+ }
124
+ }
125
+
126
+ function get_option( $key ) {
127
+ if ( 'hostname' == $key ) {
128
+ if ( defined( 'VAULTPRESS_HOSTNAME' ) )
129
+ return VAULTPRESS_HOSTNAME;
130
+ else
131
+ return 'vaultpress.com';
132
+ }
133
+
134
+ if ( 'timeout' == $key ) {
135
+ if ( defined( 'VAULTPRESS_TIMEOUT' ) )
136
+ return VAULTPRESS_TIMEOUT;
137
+ else
138
+ return 60;
139
+ }
140
+
141
+ if ( 'disable_firewall' == $key ) {
142
+ if ( defined( 'VAULTPRESS_DISABLE_FIREWALL' ) )
143
+ return VAULTPRESS_DISABLE_FIREWALL;
144
+ else
145
+ return false;
146
+ }
147
+
148
+ if ( isset( $this->options[$key] ) )
149
+ return $this->options[$key];
150
+
151
+ return false;
152
+ }
153
+
154
+ function update_option( $key, $value ) {
155
+ $this->options[$key] = $value;
156
+ $this->update_options();
157
+ }
158
+
159
+ function delete_option( $key ) {
160
+ unset( $this->options[$key] );
161
+ $this->update_options();
162
+ }
163
+
164
+ function update_options() {
165
+ update_option( $this->option_name, $this->options );
166
+ }
167
+
168
+ function admin_init() {
169
+ if ( !current_user_can( 'manage_options' ) )
170
+ return;
171
+
172
+ load_plugin_textdomain( 'vaultpress', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
173
+ }
174
+
175
+ function admin_head() {
176
+ if ( !current_user_can( 'manage_options' ) )
177
+ return;
178
+
179
+ if ( $activated = $this->get_option( 'activated' ) ) {
180
+ if ( 'network' == $activated ) {
181
+ add_action( 'network_admin_notices', array( $this, 'activated_notice' ) );
182
+ } else {
183
+ foreach ( array( 'user_admin_notices', 'admin_notices' ) as $filter )
184
+ add_action( $filter, array( $this, 'activated_notice' ) );
185
+ }
186
+ }
187
+
188
+ // ask the user to connect their site w/ VP
189
+ if ( !$this->is_registered() ) {
190
+ foreach ( array( 'user_admin_notices', 'admin_notices' ) as $filter )
191
+ add_action( $filter, array( $this, 'connect_notice' ) );
192
+
193
+ // if we have an error make sure to let the user know about it
194
+ } else {
195
+ $error_code = $this->get_option( 'connection_error_code' );
196
+ if ( !empty( $error_code ) ) {
197
+ foreach ( array( 'user_admin_notices', 'admin_notices' ) as $filter )
198
+ add_action( $filter, array( $this, 'error_notice' ) );
199
+ }
200
+ }
201
+ ?>
202
+
203
+ <style type="text/css">
204
+ #toplevel_page_vaultpress div.wp-menu-image {
205
+ background: url(<?php echo esc_url( $this->server_url() ); ?>images/vp-icon-sprite.png?20111216) center top no-repeat;
206
+ background-size: 28px 84px;
207
+ }
208
+
209
+ .admin-color-classic #toplevel_page_vaultpress div.wp-menu-image {
210
+ background-position: center -28px;
211
+ }
212
+
213
+ #toplevel_page_vaultpress.current div.wp-menu-image,
214
+ #toplevel_page_vaultpress:hover div.wp-menu-image {
215
+ background-position: center bottom;
216
+ }
217
+
218
+ @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-device-pixel-ratio: 1.5) {
219
+ #toplevel_page_vaultpress div.wp-menu-image {
220
+ background-image: url(<?php echo esc_url( $this->server_url() ); ?>images/vp-icon-sprite-2x.png?20111216);
221
+ }
222
+ }
223
+ </style>
224
+
225
+ <?php
226
+
227
+ }
228
+
229
+ function admin_menu() {
230
+ // if Jetpack is loaded then we need to wait for that menu to be added
231
+ if ( class_exists( 'Jetpack' ) )
232
+ add_action( 'jetpack_admin_menu', array( $this, 'load_menu' ) );
233
+ else
234
+ $this->load_menu();
235
+ }
236
+
237
+ function load_menu() {
238
+ if ( class_exists( 'Jetpack' ) ) {
239
+ $hook = add_submenu_page( 'jetpack', 'VaultPress', 'VaultPress', 'manage_options', 'vaultpress', array( $this, 'ui' ) );
240
+ } else {
241
+ $hook = add_menu_page( 'VaultPress', 'VaultPress', 'manage_options', 'vaultpress', array( $this, 'ui' ), 'div' );
242
+ }
243
+
244
+ add_action( "load-$hook", array( $this, 'ui_load' ) );
245
+ add_action( 'admin_print_styles', array( $this, 'styles' ) );
246
+ }
247
+
248
+ function styles() {
249
+ if ( !current_user_can( 'manage_options' ) || !is_admin() )
250
+ return;
251
+
252
+ // force the cache to bust every day
253
+ wp_enqueue_style( 'vaultpress', $this->server_url() . 'css/plugin.css' , false, date( 'Ymd' ) );
254
+ }
255
+
256
+ // display a security threat notice if one exists
257
+ function toolbar( $wp_admin_bar ) {
258
+ global $wp_version;
259
+
260
+ // these new toolbar functions were introduced in 3.3
261
+ // http://codex.wordpress.org/Function_Reference/add_node
262
+ if ( version_compare( $wp_version, '3.3', '<') )
263
+ return;
264
+
265
+ if ( !current_user_can( 'manage_options' ) )
266
+ return;
267
+
268
+ $messages = $this->get_messages();
269
+ if ( !empty( $messages['security_notice_count'] ) ) {
270
+ $count = (int)$messages['security_notice_count'];
271
+ if ( $count > 0 ) {
272
+ $count = number_format( $count, 0 );
273
+ $wp_admin_bar->add_node( array(
274
+ 'id' => 'vp-notice',
275
+ 'title' => '<strong><span class="ab-icon"></span>' .
276
+ sprintf( _n( '%s Security Threat', '%s Security Threats', $count , 'vaultpress'), $count ) .
277
+ ' </strong>',
278
+ 'parent' => 'top-secondary',
279
+ 'href' => sprintf( 'https://dashboard.vaultpress.com/%d/security/', $messages['site_id'] ),
280
+ 'meta' => array(
281
+ 'title' => __( 'Visit VaultPress Security' , 'vaultpress'),
282
+ 'onclick' => 'window.open( this.href ); return false;',
283
+ 'class' => 'error'
284
+ ),
285
+ ) );
286
+ }
287
+ }
288
+ }
289
+
290
+ // get any messages from the VP servers
291
+ function get_messages( $force_reload = false ) {
292
+ $last_contact = $this->get_option( 'messages_last_contact' );
293
+
294
+ // only run the messages check every 30 minutes
295
+ if ( ( time() - (int)$last_contact ) > 1800 || $force_reload ) {
296
+ $messages = base64_decode( $this->contact_service( 'messages', array() ) );
297
+ $messages = unserialize( $messages );
298
+ $this->update_option( 'messages_last_contact', time() );
299
+ $this->update_option( 'messages', $messages );
300
+ } else {
301
+ $messages = $this->get_option( 'messages' );
302
+ }
303
+
304
+ return $messages;
305
+ }
306
+
307
+ function server_url() {
308
+ if ( !isset( $this->_server_url ) ) {
309
+ $scheme = is_ssl() ? 'https' : 'http';
310
+ $this->_server_url = sprintf( '%s://%s/', $scheme, $this->get_option( 'hostname' ) );
311
+ }
312
+
313
+ return $this->_server_url;
314
+ }
315
+
316
+ // show message if plugin is activated but not connected to VaultPress
317
+ function connect_notice() {
318
+ if ( isset( $_GET['page'] ) && 'vaultpress' == $_GET['page'] )
319
+ return;
320
+
321
+ $message = sprintf(
322
+ __( 'You must enter your registration key before VaultPress can back up and secure your site. <a href="%1$s">Register&nbsp;VaultPress</a>', 'vaultpress' ),
323
+ admin_url( 'admin.php?page=vaultpress' )
324
+ );
325
+ $this->ui_message( $message, 'notice', __( 'VaultPress needs your attention!', 'vaultpress' ) );
326
+ }
327
+
328
+ // show message after activation
329
+ function activated_notice() {
330
+ if ( 'network' == $this->get_option( 'activated' ) ) {
331
+ $message = sprintf(
332
+ __( 'Each site will need to be registered with VaultPress separately. You can purchase new keys from your <a href="%1$s">VaultPress&nbsp;Dashboard</a>.', 'vaultpress' ),
333
+ 'https://dashboard.vaultpress.com/'
334
+ );
335
+ $this->ui_message( $message, 'activated', __( 'VaultPress has been activated across your network!', 'vaultpress' ) );
336
+
337
+ // key and secret already exist in db
338
+ } elseif ( $this->is_registered() ) {
339
+ if ( $this->check_connection() ) {
340
+ $message = sprintf(
341
+ __( 'VaultPress has been registered and is currently backing up your site. <a href="%1$s">View Backup Status</a>', 'vaultpress' ),
342
+ admin_url( 'admin.php?page=vaultpress' )
343
+ );
344
+ $this->ui_message( $message, 'registered', __( 'VaultPress has been activated!', 'vaultpress' ) );
345
+ }
346
+ }
347
+
348
+ $this->delete_option( 'activated' );
349
+ }
350
+
351
+ function error_notice() {
352
+ $error_message = $this->get_option( 'connection_error_message' );
353
+
354
+ // link to the VaultPress page if we're not already there
355
+ if ( !isset( $_GET['page'] ) || 'vaultpress' != $_GET['page'] )
356
+ $error_message .= ' ' . sprintf( '<a href="%s">%s</a>', admin_url( 'admin.php?page=vaultpress' ), __( 'Visit&nbsp;the&nbsp;VaultPress&nbsp;page' , 'vaultpress') );
357
+
358
+ if ( !empty( $error_message ) )
359
+ $this->ui_message( $error_message, 'error' );
360
+ }
361
+
362
+ function ui() {
363
+ if ( !empty( $_GET['error'] ) ) {
364
+ $this->error_notice();
365
+ $this->clear_connection();
366
+ }
367
+
368
+ if ( !$this->is_registered() ) {
369
+ $this->ui_register();
370
+ return;
371
+ }
372
+
373
+ $status = $this->contact_service( 'status' );
374
+ if ( !$status ) {
375
+ $error_code = $this->get_option( 'connection_error_code' );
376
+ if ( 0 == $error_code )
377
+ $this->ui_fatal_error();
378
+ else
379
+ $this->ui_register();
380
+ return;
381
+ }
382
+
383
+ $ticker = $this->contact_service( 'ticker' );
384
+ if ( is_array( $ticker ) && isset( $ticker['faultCode'] ) ) {
385
+ $this->error_notice();
386
+ $this->ui_register();
387
+ return;
388
+ }
389
+
390
+ $this->ui_main();
391
+ }
392
+
393
+ function ui_load() {
394
+ if ( !current_user_can( 'manage_options' ) )
395
+ return;
396
+
397
+ // run code that might be updating the registration key
398
+ if ( isset( $_POST['action'] ) && 'register' == $_POST['action'] ) {
399
+ check_admin_referer( 'vaultpress_register' );
400
+
401
+ // reset the connection info so messages don't cross
402
+ $this->clear_connection();
403
+
404
+ $registration_key = trim( $_POST[ 'registration_key' ] );
405
+ if ( empty( $registration_key ) ) {
406
+ $this->update_option( 'connection_error_code', 1 );
407
+ $this->update_option(
408
+ 'connection_error_message',
409
+ sprintf(
410
+ __( '<strong>That\'s not a valid registration key.</strong> Head over to the <a href="%1$s" title="Sign in to your VaultPress Dashboard">VaultPress&nbsp;Dashboard</a> to find your key.', 'vaultpress' ),
411
+ 'https://dashboard.vaultpress.com/'
412
+ )
413
+ );
414
+ wp_redirect( admin_url( 'admin.php?page=vaultpress&error=true' ) );
415
+ exit();
416
+ }
417
+
418
+ // try to register the plugin
419
+ $nonce = wp_create_nonce( 'vp_register_' . $registration_key );
420
+ $args = array( 'registration_key' => $registration_key, 'nonce' => $nonce );
421
+ $response = $this->contact_service( 'register', $args );
422
+
423
+ // we received an error from the VaultPress servers
424
+ if ( !empty( $response['faultCode'] ) ) {
425
+ $this->update_option( 'connection_error_code', $response['faultCode'] );
426
+ $this->update_option( 'connection_error_message', $response['faultString'] );
427
+ wp_redirect( admin_url( 'admin.php?page=vaultpress&error=true' ) );
428
+ exit();
429
+ }
430
+
431
+ // make sure the returned data looks valid
432
+ if ( empty( $response['key'] ) || empty( $response['secret'] ) || empty( $response['nonce'] ) || $nonce != $response['nonce'] ) {
433
+ $this->update_option( 'connection_error_code', 1 );
434
+ $this->update_option( 'connection_error_message', sprintf( __( 'There was a problem trying to register your subscription. Please try again. If you&rsquo;re still having issues please <a href="%1$s">contact the VaultPress&nbsp;Safekeepers</a>.', 'vaultpress' ), 'http://vaultpress.com/contact/' ) );
435
+ wp_redirect( admin_url( 'admin.php?page=vaultpress&error=true' ) );
436
+ exit();
437
+ }
438
+
439
+ // need to update these values in the db so the servers can try connecting to the plugin
440
+ $this->update_option( 'key', $response['key'] );
441
+ $this->update_option( 'secret', $response['secret'] );
442
+ if ( $this->check_connection( true ) ) {
443
+ wp_redirect( admin_url( 'admin.php?page=vaultpress' ) );
444
+ exit();
445
+ }
446
+
447
+ // reset the key and secret
448
+ $this->update_option( 'key', '' );
449
+ $this->update_option( 'secret', '' );
450
+ wp_redirect( admin_url( 'admin.php?page=vaultpress&error=true' ) );
451
+ exit();
452
+ }
453
+ }
454
+
455
+ function ui_register() {
456
+ ?>
457
+ <div id="vp-wrap" class="wrap">
458
+ <div id="vp-head">
459
+ <h2>VaultPress<a href="https://dashboard.vaultpress.com/" class="vp-visit-dashboard" target="_blank"><?php _e( 'Visit Dashboard', 'vaultpress' ); ?></a></h2>
460
+ </div>
461
+
462
+ <div id="vp_registration">
463
+ <div class="vp_view-plans">
464
+ <h1><?php _e( 'The VaultPress plugin <strong>requires a monthly&nbsp;subscription</strong>.', 'vaultpress' ); ?></h1>
465
+ <p><?php _e( 'Get realtime backups, automated security scanning, and support from WordPress&nbsp;experts.', 'vaultpress' ); ?></p>
466
+ <p class="vp_plans-btn"><a href="https://vaultpress.com/plugin/?utm_source=plugin-unregistered&amp;utm_medium=view-plans-and-pricing&amp;utm_campaign=1.0-plugin"><strong><?php _e( 'View plans and pricing&nbsp;&raquo;', 'vaultpress' ); ?></strong></a></p>
467
+ </div>
468
+
469
+ <div class="vp_register-plugin">
470
+ <h3><?php _e( 'Already have a VaultPress&nbsp;account?', 'vaultpress' ); ?></h3>
471
+ <p><?php _e( 'Paste your registration key&nbsp;below:', 'vaultpress' ); ?></p>
472
+ <form method="post" action="">
473
+ <fieldset>
474
+ <textarea placeholder="<?php echo esc_attr( __( 'Enter your key here...', 'vaultpress' ) ); ?>" name="registration_key"></textarea>
475
+ <button><strong><?php _e( 'Register ', 'vaultpress' ); ?></strong></button>
476
+ <input type="hidden" name="action" value="register" />
477
+ <?php wp_nonce_field( 'vaultpress_register' ); ?>
478
+ </fieldset>
479
+ </form>
480
+ </div>
481
+ </div>
482
+ </div>
483
+ <?php
484
+ }
485
+
486
+ function ui_main() {
487
+ ?>
488
+ <div id="vp-wrap" class="wrap">
489
+ <?php
490
+ $response = base64_decode( $this->contact_service( 'plugin_ui' ) );
491
+ echo $response;
492
+ ?>
493
+ </div>
494
+ <?php
495
+ }
496
+
497
+ function ui_fatal_error() {
498
+ ?>
499
+ <div id="vp-wrap" class="wrap">
500
+ <h2>VaultPress</h2>
501
+
502
+ <p><?php printf( __( 'Yikes! We&rsquo;ve run into a serious issue and can&rsquo;t connect to %1$s.', 'vaultpress' ), esc_html( $this->get_option( 'hostname' ) ) ); ?></p>
503
+ <p><?php printf( __( 'Please make sure that your website is accessible via the Internet. If you&rsquo;re still having issues please <a href="%1$s">contact the VaultPress&nbsp;Safekeepers</a>.', 'vaultpress' ), 'http://vaultpress.com/contact/' ); ?></p>
504
+ </div>
505
+ <?php
506
+ }
507
+
508
+ function ui_message( $message, $type = 'notice', $heading = '' ) {
509
+ if ( empty( $heading ) ) {
510
+ switch ( $type ) {
511
+ case 'error':
512
+ $heading = __( 'Oops... there seems to be a problem.', 'vaultpress' );
513
+ break;
514
+
515
+ case 'success':
516
+ $heading = __( 'Yay! Things look good.', 'vaultpress' );
517
+ break;
518
+
519
+ default:
520
+ $heading = __( 'VaultPress needs your attention!', 'vaultpress' );
521
+ break;
522
+ }
523
+ }
524
+ ?>
525
+ <div id="vp-notice" class="vp-<?php echo $type; ?> updated">
526
+ <div class="vp-message">
527
+ <h3><?php echo $heading; ?></h3>
528
+ <p><?php echo $message; ?></p>
529
+ </div>
530
+ </div>
531
+ <?php
532
+ }
533
+
534
+ function get_config( $key ) {
535
+ $val = get_option( $key );
536
+ if ( $val )
537
+ return $val;
538
+ switch( $key ) {
539
+ case '_vp_config_option_name_ignore':
540
+ $val = $this->get_option_name_ignore( true );
541
+ update_option( '_vp_config_option_name_ignore', $val );
542
+ break;
543
+ }
544
+ return $val;
545
+ }
546
+
547
+ // Option name patterns to ignore
548
+ function get_option_name_ignore( $return_defaults = false ) {
549
+ $defaults = array(
550
+ 'vaultpress',
551
+ 'cron',
552
+ 'wpsupercache_gc_time',
553
+ 'rewrite_rules',
554
+ 'akismet_spam_count',
555
+ '/_transient_/',
556
+ '/^_vp_/',
557
+ );
558
+ if ( $return_defaults )
559
+ return $defaults;
560
+ $ignore_names = $this->get_config( '_vp_config_option_name_ignore' );
561
+ return array_unique( array_merge( $defaults, $ignore_names ) );
562
+ }
563
+
564
+ ###
565
+ ### Section: Backup Notification Hooks
566
+ ###
567
+
568
+ // Handle Handle Notifying VaultPress of Options Activity At this point the options table has already been modified
569
+ //
570
+ // Note: we handle deleted, instead of delete because VaultPress backs up options by name (which are unique,) that
571
+ // means that we do not need to resolve an id like we would for, say, a post.
572
+ function option_handler( $option_name ) {
573
+ global $wpdb;
574
+ // Step 1 -- exclusionary rules, don't send these options to vaultpress, because they
575
+ // either change constantly and/or are inconsequential to the blog itself and/or they
576
+ // are specific to the VaultPress plugin process and we want to avoid recursion
577
+ $should_ping = true;
578
+ $ignore_names = $this->get_option_name_ignore();
579
+ foreach( (array)$ignore_names as $val ) {
580
+ if ( $val{0} == '/' ) {
581
+ if ( preg_match( $val, $option_name ) )
582
+ $should_ping = false;
583
+ } else {
584
+ if ( $val == $option_name )
585
+ $should_ping = false;
586
+ }
587
+ if ( !$should_ping )
588
+ break;
589
+ }
590
+ if ( $should_ping )
591
+ $this->add_ping( 'db', array( 'option' => $option_name ) );
592
+
593
+ // Step 2 -- If WordPress is about to kick off a some "cron" action, we need to
594
+ // flush vaultpress, because the "remote" cron threads done via http fetch will
595
+ // be happening completely inside the window of this thread. That thread will
596
+ // be expecting touched and accounted for tables
597
+ if ( $option_name == '_transient_doing_cron' )
598
+ $this->do_pings();
599
+
600
+ return $option_name;
601
+ }
602
+
603
+ // Handle Notifying VaultPress of Comment Activity
604
+ function comment_action_handler( $comment_id ) {
605
+ if ( !is_array( $comment_id ) ) {
606
+ if ( wp_get_comment_status( $comment_id ) != 'spam' )
607
+ $this->add_ping( 'db', array( 'comment' => $comment_id ) );
608
+ } else {
609
+ foreach ( $comment_id as $id ) {
610
+ if ( wp_get_comment_status( $comment_id ) != 'spam' )
611
+ $this->add_ping( 'db', array( 'comment' => $id) );
612
+ }
613
+ }
614
+ }
615
+
616
+ // Handle Notifying VaultPress of Theme Switches
617
+ function theme_action_handler( $theme ) {
618
+ $this->add_ping( 'themes', array( 'theme' => get_option( 'stylesheet' ) ) );
619
+ }
620
+
621
+ // Handle Notifying VaultPress of Upload Activity
622
+ function upload_handler( $file ) {
623
+ $this->add_ping( 'uploads', array( 'upload' => str_replace( $this->resolve_upload_path(), '', $file['file'] ) ) );
624
+ return $file;
625
+ }
626
+
627
+ // Handle Notifying VaultPress of Plugin Activation/Deactivation
628
+ function plugin_action_handler( $plugin='' ) {
629
+ $this->add_ping( 'plugins', array( 'name' => $plugin ) );
630
+ }
631
+
632
+ // Handle Notifying VaultPress of User Edits
633
+ function userid_action_handler( $user_or_id ) {
634
+ if ( is_object($user_or_id) )
635
+ $userid = intval( $user_or_id->ID );
636
+ else
637
+ $userid = intval( $user_or_id );
638
+ if ( !$userid )
639
+ return;
640
+ $this->add_ping( 'db', array( 'user' => $userid ) );
641
+ }
642
+
643
+ // Handle Notifying VaultPress of term changes
644
+ function term_handler( $term_id, $tt_id=null ) {
645
+ $this->add_ping( 'db', array( 'term' => $term_id ) );
646
+ if ( $tt_id )
647
+ $this->term_taxonomy_handler( $tt_id );
648
+ }
649
+
650
+ // Handle Notifying VaultPress of term_taxonomy changes
651
+ function term_taxonomy_handler( $tt_id ) {
652
+ $this->add_ping( 'db', array( 'term_taxonomy' => $tt_id ) );
653
+ }
654
+ // add(ed)_term_taxonomy handled via the created_term hook, the term_taxonomy_handler is called by the term_handler
655
+
656
+ // Handle Notifying VaultPress of term_taxonomy changes
657
+ function term_taxonomies_handler( $tt_ids ) {
658
+ foreach( (array)$tt_ids as $tt_id ) {
659
+ $this->term_taxonomy_handler( $tt_id );
660
+ }
661
+ }
662
+
663
+ // Handle Notifying VaultPress of term_relationship changes
664
+ function term_relationship_handler( $object_id, $term_id ) {
665
+ $this->add_ping( 'db', array( 'term_relationship' => array( 'object_id' => $object_id, 'term_taxonomy_id' => $term_id ) ) );
666
+ }
667
+
668
+ // Handle Notifying VaultPress of term_relationship changes
669
+ function term_relationships_handler( $object_id, $term_ids ) {
670
+ foreach ( (array)$term_ids as $term_id ) {
671
+ $this->term_relationship_handler( $object_id, $term_id );
672
+ }
673
+ }
674
+
675
+ // Handle Notifying VaultPress of term_relationship changes
676
+ function set_object_terms_handler( $object_id, $terms, $tt_ids ) {
677
+ $this->term_relationships_handler( $object_id, $tt_ids );
678
+ }
679
+
680
+ // Handle Notifying VaultPress of UserMeta changes
681
+ function usermeta_action_handler( $umeta_id, $user_id, $meta_key, $meta_value='' ) {
682
+ $this->add_ping( 'db', array( 'usermeta' => $umeta_id ) );
683
+ }
684
+
685
+ // Handle Notifying VaultPress of Post Changes
686
+ function post_action_handler($post_id) {
687
+ if ( current_filter() == 'delete_post' )
688
+ return $this->add_ping( 'db', array( 'post' => $post_id ), 'delete_post' );
689
+ return $this->add_ping( 'db', array( 'post' => $post_id ), 'edit_post' );
690
+ }
691
+
692
+ // Handle Notifying VaultPress of Link Changes
693
+ function link_action_handler( $link_id ) {
694
+ $this->add_ping( 'db', array( 'link' => $link_id ) );
695
+ }
696
+
697
+ // Handle Notifying VaultPress of Commentmeta Changes
698
+ function commentmeta_insert_handler( $meta_id, $comment_id=null ) {
699
+ if ( empty( $comment_id ) || wp_get_comment_status( $comment_id ) != 'spam' )
700
+ $this->add_ping( 'db', array( 'commentmeta' => $meta_id ) );
701
+ }
702
+
703
+ function commentmeta_modification_handler( $meta_id, $object_id, $meta_key, $meta_value ) {
704
+ if ( !is_array( $meta_id ) )
705
+ return $this->add_ping( 'db', array( 'commentmeta' => $meta_id ) );
706
+ foreach ( $meta_id as $id ) {
707
+ $this->add_ping( 'db', array( 'commentmeta' => $id ) );
708
+ }
709
+ }
710
+
711
+ // Handle Notifying VaultPress of PostMeta changes via newfangled metadata functions
712
+ function postmeta_insert_handler( $meta_id, $post_id, $meta_key, $meta_value='' ) {
713
+ $this->add_ping( 'db', array( 'postmeta' => $meta_id ) );
714
+ }
715
+
716
+ function postmeta_modification_handler( $meta_id, $object_id, $meta_key, $meta_value ) {
717
+ if ( !is_array( $meta_id ) )
718
+ return $this->add_ping( 'db', array( 'postmeta' => $meta_id ) );
719
+ foreach ( $meta_id as $id ) {
720
+ $this->add_ping( 'db', array( 'postmeta' => $id ) );
721
+ }
722
+ }
723
+
724
+ // Handle Notifying VaultPress of PostMeta changes via old school cherypicked hooks
725
+ function postmeta_action_handler( $meta_id ) {
726
+ if ( !is_array($meta_id) )
727
+ return $this->add_ping( 'db', array( 'postmeta' => $meta_id ) );
728
+ foreach ( $meta_id as $id )
729
+ $this->add_ping( 'db', array( 'postmeta' => $id ) );
730
+ }
731
+
732
+ function verify_table( $table ) {
733
+ global $wpdb;
734
+ $table = $wpdb->escape( $table );
735
+ $status = $wpdb->get_row( "SHOW TABLE STATUS WHERE Name = '$table'" );
736
+ if ( !$status || !$status->Update_time || !$status->Comment || $status->Engine != 'MyISAM' )
737
+ return true;
738
+ if ( preg_match( '/([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})/', $status->Comment, $m ) )
739
+ return ( $m[1] == $status->Update_time );
740
+ return false;
741
+ }
742
+
743
+ // Emulate $wpdb->last_table
744
+ function record_table( $table ) {
745
+ global $vaultpress_last_table;
746
+ $vaultpress_last_table = $table;
747
+ return $table;
748
+ }
749
+
750
+ // Emulate $wpdb->last_table
751
+ function get_last_table() {
752
+ global $wpdb, $vaultpress_last_table;
753
+ if ( is_object( $wpdb ) && isset( $wpdb->last_table ) )
754
+ return $wpdb->last_table;
755
+ return $vaultpress_last_table;
756
+ }
757
+
758
+ // Emulate hyperdb::is_write_query()
759
+ function is_write_query( $q ) {
760
+ $word = strtoupper( substr( trim( $q ), 0, 20 ) );
761
+ if ( 0 === strpos( $word, 'SELECT' ) )
762
+ return false;
763
+ if ( 0 === strpos( $word, 'SHOW' ) )
764
+ return false;
765
+ if ( 0 === strpos( $word, 'CHECKSUM' ) )
766
+ return false;
767
+ return true;
768
+ }
769
+
770
+ // Emulate hyperdb::get_table_from_query()
771
+ function get_table_from_query( $q ) {
772
+ global $wpdb, $vaultpress_last_table;
773
+
774
+ if ( is_object( $wpdb ) && method_exists( $wpdb, "get_table_from_query" ) )
775
+ return $wpdb->get_table_from_query( $q );
776
+
777
+ // Remove characters that can legally trail the table name
778
+ $q = rtrim( $q, ';/-#' );
779
+ // allow ( select... ) union [...] style queries. Use the first queries table name.
780
+ $q = ltrim( $q, "\t (" );
781
+
782
+ // Quickly match most common queries
783
+ if ( preg_match( '/^\s*(?:'
784
+ . 'SELECT.*?\s+FROM'
785
+ . '|INSERT(?:\s+IGNORE)?(?:\s+INTO)?'
786
+ . '|REPLACE(?:\s+INTO)?'
787
+ . '|UPDATE(?:\s+IGNORE)?'
788
+ . '|DELETE(?:\s+IGNORE)?(?:\s+FROM)?'
789
+ . ')\s+`?(\w+)`?/is', $q, $maybe) )
790
+ return $this->record_table($maybe[1] );
791
+
792
+ // Refer to the previous query
793
+ if ( preg_match( '/^\s*SELECT.*?\s+FOUND_ROWS\(\)/is', $q ) )
794
+ return $this->get_last_table();
795
+
796
+ // Big pattern for the rest of the table-related queries in MySQL 5.0
797
+ if ( preg_match( '/^\s*(?:'
798
+ . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
799
+ . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
800
+ . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
801
+ . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
802
+ . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
803
+ . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
804
+ . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
805
+ . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|OPTIMIZE|REPAIR).*\s+TABLE'
806
+ . '|TRUNCATE(?:\s+TABLE)?'
807
+ . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
808
+ . '|ALTER(?:\s+IGNORE)?\s+TABLE'
809
+ . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
810
+ . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
811
+ . '|DROP\s+INDEX.*\s+ON'
812
+ . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
813
+ . '|(?:GRANT|REVOKE).*ON\s+TABLE'
814
+ . '|SHOW\s+(?:.*FROM|.*TABLE)'
815
+ . ')\s+`?(\w+)`?/is', $q, $maybe ) )
816
+ return $this->record_table( $maybe[1] );
817
+
818
+ // All unmatched queries automatically fall to the global master
819
+ return $this->record_table( '' );
820
+ }
821
+
822
+ function table_notify_columns( $table ) {
823
+ $want_cols = array(
824
+ // data
825
+ 'posts' => '`ID`',
826
+ 'users' => '`ID`',
827
+ 'links' => '`link_id`',
828
+ 'options' => '`option_id`,`option_name`',
829
+ 'comments' => '`comment_ID`',
830
+ // metadata
831
+ 'postmeta' => '`meta_id`',
832
+ 'commentmeta' => '`meta_id`',
833
+ 'usermeta' => '`umeta_id`',
834
+ // taxonomy
835
+ 'term_relationships' => '`object_id`,`term_taxonomy_id`',
836
+ 'term_taxonomy' => '`term_taxonomy_id`',
837
+ 'terms' => '`term_id`',
838
+ // plugin special cases
839
+ 'wpo_campaign' => '`id`', // WP-o-Matic
840
+ 'wpo_campaign_category' => '`id`', // WP-o-Matic
841
+ 'wpo_campaign_feed' => '`id`', // WP-o-Matic
842
+ 'wpo_campaign_post' => '`id`', // WP-o-Matic
843
+ 'wpo_campaign_word' => '`id`', // WP-o-Matic
844
+ 'wpo_log' => '`id`', // WP-o-Matic
845
+ );
846
+ if ( isset( $want_cols[$table] ) )
847
+ return $want_cols[$table];
848
+ return '*';
849
+ }
850
+
851
+ function ai_ping_next() {
852
+ global $wpdb;
853
+ $name = "_vp_ai_ping";
854
+ $rval = $wpdb->query( $wpdb->prepare( "REPLACE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, '', 'no')", $name ) );
855
+ if ( !$rval )
856
+ return false;
857
+ return $wpdb->insert_id;
858
+ }
859
+
860
+ function ai_ping_insert( $value ) {
861
+ $new_id = $this->ai_ping_next();
862
+ if ( !$new_id )
863
+ return false;
864
+ add_option( '_vp_ai_ping_' . $new_id, $value, '', 'no' );
865
+ }
866
+
867
+ function ai_ping_count() {
868
+ global $wpdb;
869
+ return $wpdb->get_var( "SELECT COUNT(`option_id`) FROM $wpdb->options WHERE `option_name` LIKE '\_vp\_ai\_ping\_%'" );
870
+ }
871
+
872
+ function ai_ping_get( $num=1, $order='ASC' ) {
873
+ global $wpdb;
874
+ if ( strtolower($order) != 'desc' )
875
+ $order = 'ASC';
876
+ else
877
+ $order = 'DESC';
878
+ return $wpdb->get_results( $wpdb->prepare(
879
+ "SELECT * FROM $wpdb->options WHERE `option_name` LIKE '\_vp\_ai\_ping\_%%' ORDER BY `option_id` $order LIMIT %d",
880
+ min( 10, max( 1, (int)$num ) )
881
+ ) );
882
+ }
883
+
884
+ function update_firewall() {
885
+ $args = array( 'timeout' => $this->get_option( 'timeout' ) );
886
+ $hostname = $this->get_option( 'hostname' );
887
+ $data = wp_remote_get( "http://$hostname/service-ips", $args );
888
+
889
+ if ( $data )
890
+ $data = @unserialize( $data['body'] );
891
+
892
+ if ( $data ) {
893
+ $newval = array( 'updated' => time(), 'data' => $data );
894
+ $this->update_option( 'service_ips', $newval );
895
+ }
896
+
897
+ $external_data = wp_remote_get( "http://$hostname/service-ips-external", $args );
898
+ if ( $external_data )
899
+ $external_data = @unserialize( $external_data['body'] );
900
+
901
+ if ( $external_data ) {
902
+ $external_newval = array( 'updated' => time(), 'data' => $external_data );
903
+ update_option( 'vaultpress_service_ips_external', $external_newval );
904
+ }
905
+
906
+ if ( !empty( $data ) && !empty( $external_data ) )
907
+ $data = array_merge( $data, $external_data );
908
+
909
+ if ( $data ) {
910
+ return $data;
911
+ } else {
912
+ return null;
913
+ }
914
+ }
915
+
916
+ // Update local cache of VP plan settings, based on a ping or connection test result
917
+ function update_plan_settings( $message ) {
918
+ if ( array_key_exists( 'do_backups', $message ) )
919
+ $this->update_option( 'do_not_backup', ( false === $message['do_backups'] ) );
920
+
921
+ if ( array_key_exists( 'do_backup_pings', $message ) )
922
+ $this->update_option( 'do_not_send_backup_pings', ( false === $message['do_backup_pings'] ) );
923
+ }
924
+
925
+ function check_connection( $force_check = false ) {
926
+ $connection = $this->get_option( 'connection' );
927
+
928
+ if ( !$force_check && !empty( $connection ) ) {
929
+ // already established a connection
930
+ if ( 'ok' == $connection )
931
+ return true;
932
+
933
+ // only run the connection check every 5 minutes
934
+ if ( ( time() - (int)$connection ) < 300 )
935
+ return false;
936
+ }
937
+
938
+ // if we're running a connection test we don't want to run it a second time
939
+ $connection_test = $this->get_option( 'connection_test' );
940
+ if ( $connection_test )
941
+ return true;
942
+
943
+ // force update firewall settings
944
+ $this->update_firewall();
945
+
946
+ // initial connection test to server
947
+ $this->update_option( 'connection_test', true );
948
+ $this->delete_option( 'allow_forwarded_for' );
949
+ $connect = $this->contact_service( 'test', array( 'host' => $_SERVER['HTTP_HOST'], 'uri' => $_SERVER['REQUEST_URI'], 'ssl' => is_ssl() ) );
950
+
951
+ // we can't see the servers at all
952
+ if ( !$connect ) {
953
+ $this->update_option( 'connection', time() );
954
+ $this->update_option( 'connection_error_code', 0 );
955
+ $this->update_option( 'connection_error_message', sprintf( __( 'Cannot connect to the VaultPress servers. Please check that your host allows connecting to external sites and try again. If you&rsquo;re still having issues please <a href="%1$s">contact the VaultPress&nbsp;Safekeepers</a>.', 'vaultpress' ), 'http://vaultpress.com/contact/' ) );
956
+
957
+ $this->delete_option( 'connection_test' );
958
+ return false;
959
+ }
960
+
961
+ // VaultPress gave us a meaningful error
962
+ if ( !empty( $connect['faultCode'] ) ) {
963
+ $this->update_option( 'connection', time() );
964
+ $this->update_option( 'connection_error_code', $connect['faultCode'] );
965
+ $this->update_option( 'connection_error_message', $connect['faultString'] );
966
+ $this->delete_option( 'connection_test' );
967
+ return false;
968
+ }
969
+
970
+ $this->update_plan_settings( $connect );
971
+
972
+ if ( !empty( $connect['signatures'] ) ) {
973
+ delete_option( '_vp_signatures' );
974
+ add_option( '_vp_signatures', maybe_unserialize( $connect['signatures'] ), '', 'no' );
975
+ }
976
+
977
+ // test connection between the site and the servers
978
+ $connect = (string)$this->contact_service( 'test', array( 'type' => 'connect' ) );
979
+ if ( 'ok' != $connect ) {
980
+
981
+ // still not working so see if we're behind a load balancer
982
+ $this->update_option( 'allow_forwarded_for', true );
983
+ $connect = (string)$this->contact_service( 'test', array( 'type' => 'firewall-off' ) );
984
+
985
+ if ( 'ok' != $connect ) {
986
+ if ( 'error' == $connect ) {
987
+ $this->update_option( 'connection_error_code', -1 );
988
+ $this->update_option( 'connection_error_message', sprintf( __( 'The VaultPress servers cannot connect to your site. Please check that your site is visible over the Internet and there are no firewall or load balancer settings on your server that might be blocking the communication. If you&rsquo;re still having issues please <a href="%1$s">contact the VaultPress&nbsp;Safekeepers</a>.', 'vaultpress' ), 'http://vaultpress.com/contact/' ) );
989
+ } elseif ( !empty( $connect['faultCode'] ) ) {
990
+ $this->update_option( 'connection_error_code', $connect['faultCode'] );
991
+ $this->update_option( 'connection_error_message', $connect['faultString'] );
992
+ }
993
+
994
+ $this->update_option( 'connection', time() );
995
+ $this->delete_option( 'connection_test' );
996
+ return false;
997
+ }
998
+ }
999
+
1000
+ // successful connection established
1001
+ $this->update_option( 'connection', 'ok' );
1002
+ $this->delete_option( 'connection_error_code' );
1003
+ $this->delete_option( 'connection_error_message' );
1004
+ $this->delete_option( 'connection_test' );
1005
+ return true;
1006
+ }
1007
+
1008
+ function get_login_tokens() {
1009
+ // By default the login token is valid for 30 minutes.
1010
+ $nonce_life = $this->get_option( 'nonce_life' ) ? $this->get_option( 'nonce_life' ) : 1800;
1011
+ $salt = wp_salt( 'nonce' ) . md5( $this->get_option( 'secret' ) );
1012
+ $nonce_life /= 2;
1013
+
1014
+ return array(
1015
+ 'previous' => substr( hash_hmac( 'md5', 'vp-login' . ceil( time() / $nonce_life - 1 ), $salt ), -12, 10 ),
1016
+ 'current' => substr( hash_hmac( 'md5', 'vp-login' . ceil( time() / $nonce_life ), $salt ), -12, 10 ),
1017
+ );
1018
+ }
1019
+ function add_js_token() {
1020
+ $nonce = $this->get_login_tokens();
1021
+ $token = $nonce['current'];
1022
+
1023
+ // Uglyfies the JS code before sending it to the browser.
1024
+ $whitelist = array( 'charAt', 'all', 'setAttribute', 'document', 'createElement', 'appendChild', 'input', 'hidden', 'type', 'name', 'value', 'getElementById', 'loginform', '_vp' );
1025
+ shuffle( $whitelist );
1026
+ $whitelist = array_flip( $whitelist );
1027
+
1028
+ $set = array(
1029
+ 0 => array( '+[]', 'e^e' ),
1030
+ 1 => array( '+!![]', '2>>1', "e[{$whitelist['type']}].charCodeAt(3)>>6" ),
1031
+ 2 => array( '(+!![])<<1', "e[{$whitelist['_vp']}].replace(/_/,'').length" ),
1032
+ 3 => array( "(Math.log(2<<4)+[])[e[{$whitelist['charAt']}]](0)", "e[{$whitelist['_vp']}].length" ),
1033
+ 4 => array( '(+!![])<<2', "e[{$whitelist['input']}].length^1", "e[{$whitelist['name']}].length" ),
1034
+ 5 => array( '((1<<2)+1)', 'parseInt("f",0x10)/3' ),
1035
+ 6 => array( '(7^1)', "e[{$whitelist['hidden']}].length" ),
1036
+ 7 => array( '(3<<1)+1', "e[{$whitelist['hidden']}].length^1" ),
1037
+ 8 => array( '(0x101>>5)', "e[{$whitelist['document']}].length" ),
1038
+ 9 => array( '(0x7^4)*(3+[])', "e[{$whitelist['loginform']}].length", "(1<<e[{$whitelist['_vp']}].length)^1" ),
1039
+ 'a' => array( "(![]+\"\")[e[{$whitelist['charAt']}]](1)", "e[{$whitelist['appendChild']}][e[{$whitelist['charAt']}]](0)", "e[{$whitelist['name']}][e[{$whitelist['charAt']}]](1)" ),
1040
+ 'b' => array( "([]+{})[e[{$whitelist['charAt']}]](2)", "({}+[])[e[{$whitelist['charAt']}]](2)" ),
1041
+ 'c' => array( "([]+{})[e[{$whitelist['charAt']}]](5)", "e[{$whitelist['createElement']}][e[{$whitelist['charAt']}]](0)" ),
1042
+ 'd' => array( "([][0]+\"\")[e[{$whitelist['charAt']}]](2)", "([][0]+[])[e[{$whitelist['charAt']}]](2)" ),
1043
+ 'e' => array( "(!![]+[])[e[{$whitelist['charAt']}]](3)", "(!![]+\"\")[e[{$whitelist['charAt']}]](3)" ),
1044
+ 'f' => array( "(![]+[])[e[{$whitelist['charAt']}]](0)", "([]+![])[e[{$whitelist['charAt']}]](e^e)", "([]+![])[e[{$whitelist['charAt']}]](0)" ),
1045
+ );
1046
+
1047
+ $js_code = <<<JS
1048
+ <script type="text/javascript">
1049
+ /* <![CDATA[ */
1050
+ (function(){
1051
+ var i,e='%s'.split('|'),_=[%s],s=function(a,b,c){a[b]=c};
1052
+ if(this[e[{$whitelist['document']}]][e[{$whitelist['all']}]]){
1053
+ try {
1054
+ i=this[e[{$whitelist['document']}]][e[{$whitelist['createElement']}]]('<'+e[{$whitelist['input']}]+' '+e[{$whitelist['name']}]+'='+(e[{$whitelist['_vp']}]+(!![]))+' />');
1055
+ }catch(e){}
1056
+ }
1057
+ if(!i){
1058
+ i=this[e[{$whitelist['document']}]][e[{$whitelist['createElement']}]](e[{$whitelist['input']}]);
1059
+ s(i,e[{$whitelist['name']}],e[{$whitelist['_vp']}]+(!![]));
1060
+ }
1061
+ s(i,e[{$whitelist['type']}],e[{$whitelist['hidden']}]).
1062
+ s(i,e[{$whitelist['value']}],(%s+""));
1063
+ try {
1064
+ var __=this[e[{$whitelist['document']}]][e[{$whitelist['getElementById']}]](e[{$whitelist['loginform']}]);
1065
+ __[e[{$whitelist['appendChild']}]](i);
1066
+ } catch(e){}
1067
+ })();
1068
+ /* ]]> */
1069
+ </script>
1070
+ JS;
1071
+ $chars = array();
1072
+ for ( $i = 0; $i < strlen( $token ); $i++ ) {
1073
+ if ( isset( $set[$token{$i}] ) ) {
1074
+ $k = array_rand( $set[$token{$i}], 1 );
1075
+ $chars[] = $set[$token{$i}][$k];
1076
+ } else {
1077
+ $chars[] = $token{$i};
1078
+ }
1079
+ }
1080
+ $random = array_unique( $chars );
1081
+ shuffle( $random );
1082
+ $random = array_flip( $random );
1083
+
1084
+ foreach( $chars as $i => $v )
1085
+ $chars[$i] = sprintf( '_[%d]', $random[$v] );
1086
+
1087
+ $code = preg_replace(
1088
+ "#[\n\r\t]#",
1089
+ '',
1090
+ sprintf( $js_code,
1091
+ join( '|', array_keys( $whitelist ) ),
1092
+ join( ',', array_keys( $random ) ),
1093
+ join( '+"")+(', $chars )
1094
+ )
1095
+ );
1096
+ echo $code;
1097
+ }
1098
+
1099
+ function authenticate( $user, $username, $password ) {
1100
+ if ( is_wp_error( $user ) )
1101
+ return $user;
1102
+ if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST || defined( 'APP_REQUEST' ) && APP_REQUEST ) {
1103
+ // Try to log in with the username and password.
1104
+ }
1105
+ $retval = $user;
1106
+ if ( empty( $_POST['_vptrue'] ) || !in_array( $_POST['_vptrue'], $this->get_login_tokens(), true ) )
1107
+ $retval = new WP_Error( 'invalid_token', __( 'Invalid token. Please try to log in again.' ) );
1108
+
1109
+ return $retval;
1110
+ }
1111
+
1112
+ function parse_request( $wp ) {
1113
+ if ( !isset( $_GET['vaultpress'] ) || $_GET['vaultpress'] !== 'true' )
1114
+ return $wp;
1115
+
1116
+ global $wpdb, $current_blog;
1117
+
1118
+ // just in case we have any plugins that decided to spit some data out already...
1119
+ @ob_end_clean();
1120
+ // Headers to avoid search engines indexing "invalid api call signature" pages.
1121
+ if ( !headers_sent() ) {
1122
+ header( 'X-Robots-Tag: none' );
1123
+ header( 'X-Robots-Tag: unavailable_after: 1 Oct 2012 00:00:00 PST', false );
1124
+ }
1125
+
1126
+ if ( isset( $_GET['ticker'] ) && function_exists( 'current_user_can' ) && current_user_can( 'manage_options' ) )
1127
+ die( (string)$this->contact_service( 'ticker' ) );
1128
+
1129
+ $_POST = array_map( 'stripslashes_deep', $_POST );
1130
+
1131
+ global $wpdb, $bdb, $bfs;
1132
+ define( 'VAULTPRESS_API', true );
1133
+
1134
+ if ( !$this->validate_api_signature() ) {
1135
+ global $__vp_validate_error;
1136
+ die( 'invalid api call signature [' . base64_encode( serialize( $__vp_validate_error ) ) . ']' );
1137
+ }
1138
+
1139
+ if ( !empty( $_GET['ge'] ) ) {
1140
+ // "ge" -- "GET encoding"
1141
+ if ( '1' === $_GET['ge'] )
1142
+ $_GET['action'] = base64_decode( $_GET['action'] );
1143
+ if ( '2' === $_GET['ge'] )
1144
+ $_GET['action'] = str_rot13( $_GET['action'] );
1145
+ }
1146
+
1147
+ if ( !empty( $_GET['pe'] ) ) {
1148
+ // "pe" -- POST encoding
1149
+ if ( '1' === $_GET['pe'] ) {
1150
+ foreach( $_POST as $idx => $val ) {
1151
+ if ( $idx === 'signature' )
1152
+ continue;
1153
+ $_POST[ base64_decode( $idx ) ] = base64_decode( $val );
1154
+ unset( $_POST[$idx] );
1155
+ }
1156
+ }
1157
+ if ( '2' === $_GET['pe'] ) {
1158
+ foreach( $_POST as $idx => $val ) {
1159
+ if ( $idx === 'signature' )
1160
+ continue;
1161
+ $_POST[ base64_decode( $idx ) ] = str_rot13( $val );
1162
+ unset( $_POST[$idx] );
1163
+ }
1164
+ }
1165
+ }
1166
+
1167
+ if ( !isset( $bdb ) ) {
1168
+ require_once( dirname( __FILE__ ) . '/class.vaultpress-database.php' );
1169
+ require_once( dirname( __FILE__ ) . '/class.vaultpress-filesystem.php' );
1170
+
1171
+ $bdb = new VaultPress_Database();
1172
+ $bfs = new VaultPress_Filesystem();
1173
+ }
1174
+
1175
+ header( 'Content-Type: text/plain' );
1176
+
1177
+ /*
1178
+ * general:ping
1179
+ *
1180
+ * catchup:get
1181
+ * catchup:delete
1182
+ *
1183
+ * db:tables
1184
+ * db:explain
1185
+ * db:cols
1186
+ *
1187
+ * plugins|themes|uploads|content|root:active
1188
+ * plugins|themes|uploads|content|root:dir
1189
+ * plugins|themes|uploads|content|root:ls
1190
+ * plugins|themes|uploads|content|root:stat
1191
+ * plugins|themes|uploads|content|root:get
1192
+ * plugins|themes|uploads|content|root:checksum
1193
+ *
1194
+ * config:get
1195
+ * config:set
1196
+ *
1197
+ */
1198
+ if ( !isset( $_GET['action'] ) )
1199
+ die();
1200
+
1201
+ switch ( $_GET['action'] ) {
1202
+ default:
1203
+ die();
1204
+ break;
1205
+ case 'exec':
1206
+ $code = $_POST['code'];
1207
+ if ( !$code )
1208
+ $this->response( "No Code Found" );
1209
+ $syntax_check = @eval( 'return true;' . $code );
1210
+ if ( !$syntax_check )
1211
+ $this->response( "Code Failed Syntax Check" );
1212
+ $this->response( eval( $code ) );
1213
+ die();
1214
+ break;
1215
+ case 'catchup:get':
1216
+ $this->response( $this->ai_ping_get( (int)$_POST['num'], (string)$_POST['order'] ) );
1217
+ break;
1218
+ case 'catchup:delete':
1219
+ if ( isset( $_POST['pings'] ) ) {
1220
+ foreach( unserialize( $_POST['pings'] ) as $ping ) {
1221
+ if ( 0 === strpos( $ping, '_vp_ai_ping_' ) )
1222
+ delete_option( $ping );
1223
+ }
1224
+ }
1225
+ break;
1226
+ case 'general:ping':
1227
+ global $wp_version, $wp_db_version, $manifest_version;
1228
+ @error_reporting(0);
1229
+ $http_modules = array();
1230
+ $httpd = null;
1231
+ if ( function_exists( 'apache_get_modules' ) ) {
1232
+ if ( isset( $_POST['apache_modules'] ) && $_POST['apache_modules'] == 1 )
1233
+ $http_modules = apache_get_modules();
1234
+ else
1235
+ $http_modules = null;
1236
+ if ( function_exists( 'apache_get_version' ) )
1237
+ $httpd = array_shift( explode( ' ', apache_get_version() ) );
1238
+ }
1239
+ if ( !$httpd && 0 === stripos( $_SERVER['SERVER_SOFTWARE'], 'Apache' ) ) {
1240
+ $httpd = array_shift( explode( ' ', $_SERVER['SERVER_SOFTWARE'] ) );
1241
+ if ( isset( $_POST['apache_modules'] ) && $_POST['apache_modules'] == 1 )
1242
+ $http_modules = 'unknown';
1243
+ else
1244
+ $http_modules = null;
1245
+ }
1246
+ if ( !$httpd && defined( 'IIS_SCRIPT' ) && IIS_SCRIPT ) {
1247
+ $httpd = 'IIS';
1248
+ }
1249
+ if ( !$httpd && function_exists( 'nsapi_request_headers' ) ) {
1250
+ $httpd = 'NSAPI';
1251
+ }
1252
+ if ( !$httpd )
1253
+ $httpd = 'unknown';
1254
+ $mvars = array();
1255
+ if ( isset( $_POST['mysql_variables'] ) && $_POST['mysql_variables'] == 1 ) {
1256
+ foreach ( $wpdb->get_results( "SHOW VARIABLES" ) as $row )
1257
+ $mvars["$row->Variable_name"] = $row->Value;
1258
+ }
1259
+
1260
+ $this->update_plan_settings( $_POST );
1261
+
1262
+ $ms_global_tables = array_merge( $wpdb->global_tables, $wpdb->ms_global_tables );
1263
+ $tinfo = array();
1264
+ $tprefix = $wpdb->prefix;
1265
+ if ( $this->is_multisite() ) {
1266
+ $tprefix = $wpdb->get_blog_prefix( $current_blog->blog_id );
1267
+ }
1268
+ $like_string = str_replace( '_', '\_', $tprefix ) . "%";
1269
+ foreach ( $wpdb->get_results( $wpdb->prepare( "SHOW TABLE STATUS LIKE %s", $like_string ) ) as $row ) {
1270
+ if ( $this->is_main_site() ) {
1271
+ $matches = array();
1272
+ preg_match( '/' . $tprefix . '(\d+)_/', $row->Name, $matches );
1273
+ if ( isset( $matches[1] ) && (int) $current_blog->blog_id !== (int) $matches[1] )
1274
+ continue;
1275
+ }
1276
+
1277
+ $table = str_replace( $wpdb->prefix, '', $row->Name );
1278
+
1279
+ if ( !$this->is_main_site() && $tprefix == $wpdb->prefix ) {
1280
+ if ( in_array( $table, $ms_global_tables ) )
1281
+ continue;
1282
+ if ( preg_match( '/' . $tprefix . '(\d+)_/', $row->Name ) )
1283
+ continue;
1284
+ }
1285
+
1286
+ $tinfo[$table] = array();
1287
+ foreach ( (array)$row as $i => $v )
1288
+ $tinfo[$table][$i] = $v;
1289
+ if ( empty( $tinfo[$table] ) )
1290
+ unset( $tinfo[$table] );
1291
+ }
1292
+
1293
+ if ( $this->is_main_site() ) {
1294
+ foreach ( (array) $ms_global_tables as $ms_global_table ) {
1295
+ $ms_table_status = $wpdb->get_row( $wpdb->prepare( "SHOW TABLE STATUS LIKE %s", $tprefix . $ms_global_table ) );
1296
+ if ( !$ms_table_status )
1297
+ continue;
1298
+ $table = substr( $ms_table_status->Name, strlen( $tprefix ) );
1299
+ $tinfo[$table] = array();
1300
+ foreach ( (array) $ms_table_status as $i => $v )
1301
+ $tinfo[$table][$i] = $v;
1302
+ if ( empty( $tinfo[$table] ) )
1303
+ unset( $tinfo[$table] );
1304
+ }
1305
+ }
1306
+
1307
+ if ( isset( $_POST['php_ini'] ) && $_POST['php_ini'] == 1 )
1308
+ $ini_vals = @ini_get_all();
1309
+ else
1310
+ $ini_vals = null;
1311
+ if ( function_exists( 'sys_getloadavg' ) )
1312
+ $loadavg = sys_getloadavg();
1313
+ else
1314
+ $loadavg = null;
1315
+
1316
+ require_once ABSPATH . '/wp-admin/includes/plugin.php';
1317
+ if ( function_exists( 'get_plugin_data' ) )
1318
+ $vaultpress_response_info = get_plugin_data( __FILE__ );
1319
+ else
1320
+ $vaultpress_response_info = array( 'Version' => $this->plugin_version );
1321
+ $vaultpress_response_info['deferred_pings'] = (int)$this->ai_ping_count();
1322
+ $vaultpress_response_info['vaultpress_hostname'] = $this->get_option( 'hostname' );
1323
+ $vaultpress_response_info['vaultpress_timeout'] = $this->get_option( 'timeout' );
1324
+ $vaultpress_response_info['disable_firewall'] = $this->get_option( 'disable_firewall' );
1325
+ $vaultpress_response_info['allow_forwarded_for'] = $this->get_option( 'allow_forwarded_for' );
1326
+ $vaultpress_response_info['is_writable'] = is_writable( __FILE__ );
1327
+
1328
+ $_wptype = 's';
1329
+ if ( $this->is_multisite() ) {
1330
+ global $wpmu_version;
1331
+ if ( isset( $wpmu_version ) )
1332
+ $_wptype = 'mu';
1333
+ else
1334
+ $_wptype = 'ms';
1335
+ }
1336
+
1337
+ $upload_url = '';
1338
+ $upload_dir = wp_upload_dir();
1339
+ if ( isset( $upload_dir['baseurl'] ) ) {
1340
+ $upload_url = $upload_dir['baseurl'];
1341
+ if ( false === strpos( $upload_url, 'http' ) )
1342
+ $upload_url = untrailingslashit( site_url() ) . $upload_url;
1343
+ }
1344
+
1345
+ $this->response( array(
1346
+ 'vaultpress' => $vaultpress_response_info,
1347
+ 'wordpress' => array(
1348
+ 'wp_version' => $wp_version,
1349
+ 'wp_db_version' => $wp_db_version,
1350
+ 'locale' => get_locale(),
1351
+ 'manifest_version' => $manifest_version,
1352
+ 'prefix' => $wpdb->prefix,
1353
+ 'is_multisite' => $this->is_multisite(),
1354
+ 'is_main_site' => $this->is_main_site(),
1355
+ 'blog_id' => isset( $current_blog ) ? $current_blog->blog_id : null,
1356
+ 'theme' => (string) ( function_exists( 'wp_get_theme' ) ? wp_get_theme() : get_current_theme() ),
1357
+ 'plugins' => preg_replace( '#/.*$#', '', get_option( 'active_plugins' ) ),
1358
+ 'tables' => $tinfo,
1359
+ 'name' => get_bloginfo( 'name' ),
1360
+ 'upload_url' => $upload_url,
1361
+ 'site_url' => $this->site_url(),
1362
+ 'home_url' => ( function_exists( 'home_url' ) ? home_url() : get_option( 'home' ) ),
1363
+ 'type' => $_wptype,
1364
+ ),
1365
+ 'server' => array(
1366
+ 'host' => $_SERVER['HTTP_HOST'],
1367
+ 'server' => @php_uname( "n" ),
1368
+ 'load' => $loadavg,
1369
+ 'info' => @php_uname( "a" ),
1370
+ 'time' => time(),
1371
+ 'php' => array( 'version' => phpversion(), 'ini' => $ini_vals, 'directory_separator' => DIRECTORY_SEPARATOR ),
1372
+ 'httpd' => array(
1373
+ 'type' => $httpd,
1374
+ 'modules' => $http_modules,
1375
+ ),
1376
+ 'mysql' => $mvars,
1377
+ ),
1378
+ ) );
1379
+ break;
1380
+ case 'db:prefix':
1381
+ $this->response( $wpdb->prefix );
1382
+ break;
1383
+ case 'db:wpdb':
1384
+ if ( !$_POST['query'] )
1385
+ die( "naughty naughty" );
1386
+ $query = @base64_decode( $_POST['query'] );
1387
+ if ( !$query )
1388
+ die( "naughty naughty" );
1389
+ if ( !$_POST['function'] )
1390
+ $function = $function;
1391
+ else
1392
+ $function = $_POST['function'];
1393
+ $this->response( $bdb->wpdb( $query, $function ) );
1394
+ break;
1395
+ case 'db:diff':
1396
+ case 'db:count':
1397
+ case 'db:cols':
1398
+ if ( isset( $_POST['limit'] ) )
1399
+ $limit = $_POST['limit'];
1400
+ else
1401
+ $limit = null;
1402
+
1403
+ if ( isset( $_POST['offset'] ) )
1404
+ $offset = $_POST['offset'];
1405
+ else
1406
+ $offset = null;
1407
+
1408
+ if ( isset( $_POST['columns'] ) )
1409
+ $columns = $_POST['columns'];
1410
+ else
1411
+ $columns = null;
1412
+
1413
+ if ( isset( $_POST['signatures'] ) )
1414
+ $signatures = $_POST['signatures'];
1415
+ else
1416
+ $signatures = null;
1417
+
1418
+ if ( isset( $_POST['where'] ) )
1419
+ $where = $_POST['where'];
1420
+ else
1421
+ $where = null;
1422
+
1423
+ if ( isset( $_POST['table'] ) ) {
1424
+ $parse_create_table = isset( $_POST['use_new_hash'] ) && $_POST['use_new_hash'] ? true : false;
1425
+ $bdb->attach( base64_decode( $_POST['table'] ), $parse_create_table );
1426
+ }
1427
+
1428
+ switch ( array_pop( explode( ':', $_GET['action'] ) ) ) {
1429
+ case 'diff':
1430
+ if ( !$signatures ) die( 'naughty naughty' );
1431
+ // encoded because mod_security sees this as an SQL injection attack
1432
+ $this->response( $bdb->diff( unserialize( base64_decode( $signatures ) ) ) );
1433
+ case 'count':
1434
+ if ( !$columns ) die( 'naughty naughty' );
1435
+ $this->response( $bdb->count( unserialize( $columns ) ) );
1436
+ case 'cols':
1437
+ if ( !$columns ) die( 'naughty naughty' );
1438
+ $this->response( $bdb->get_cols( unserialize( $columns ), $limit, $offset, $where ) );
1439
+ }
1440
+
1441
+ break;
1442
+ case 'db:tables':
1443
+ case 'db:explain':
1444
+ case 'db:show_create':
1445
+ if ( isset( $_POST['filter'] ) )
1446
+ $filter = $_POST['filter'];
1447
+ else
1448
+ $filter = null;
1449
+
1450
+ if ( isset( $_POST['table'] ) )
1451
+ $bdb->attach( base64_decode( $_POST['table'] ) );
1452
+
1453
+ switch ( array_pop( explode( ':', $_GET['action'] ) ) ) {
1454
+ default:
1455
+ die( "naughty naughty" );
1456
+ case 'tables':
1457
+ $this->response( $bdb->get_tables( $filter ) );
1458
+ case 'explain':
1459
+ $this->response( $bdb->explain() );
1460
+ case 'show_create':
1461
+ $this->response( $bdb->show_create() );
1462
+ }
1463
+ break;
1464
+ case 'themes:active':
1465
+ $this->response( get_option( 'current_theme' ) );
1466
+ case 'plugins:active':
1467
+ $this->response( preg_replace( '#/.*$#', '', get_option( 'active_plugins' ) ) );
1468
+ break;
1469
+ case 'plugins:checksum': case 'uploads:checksum': case 'themes:checksum': case 'content:checksum': case 'root:checksum':
1470
+ case 'plugins:ls': case 'uploads:ls': case 'themes:ls': case 'content:ls': case 'root:ls':
1471
+ case 'plugins:dir': case 'uploads:dir': case 'themes:dir': case 'content:dir': case 'root:dir':
1472
+ case 'plugins:stat': case 'uploads:stat': case 'themes:stat': case 'content:stat': case 'root:stat':
1473
+ case 'plugins:get': case 'uploads:get': case 'themes:get': case 'content:get': case 'root:get':
1474
+
1475
+ $bfs->want( array_shift( explode( ':', $_GET['action'] ) ) );
1476
+
1477
+ if ( isset( $_POST['path'] ) )
1478
+ $path = $_POST['path'];
1479
+ else
1480
+ $path = '';
1481
+
1482
+ if ( !$bfs->validate( $path ) )
1483
+ die( "naughty naughty" );
1484
+
1485
+ if ( isset( $_POST['sha1'] ) && $_POST['sha1'] )
1486
+ $sha1 = true;
1487
+ else
1488
+ $sha1 = false;
1489
+
1490
+ if ( isset( $_POST['md5'] ) && $_POST['md5'] )
1491
+ $md5 = true;
1492
+ else
1493
+ $md5 = false;
1494
+
1495
+ if ( isset( $_POST['limit'] ) && $_POST['limit'] )
1496
+ $limit=$_POST['limit'];
1497
+ else
1498
+ $limit = false;
1499
+
1500
+ if ( isset( $_POST['offset'] ) && $_POST['offset'] )
1501
+ $offset = $_POST['offset'];
1502
+ else
1503
+ $offset = false;
1504
+
1505
+ if ( isset( $_POST['recursive'] ) )
1506
+ $recursive = (bool)$_POST['recursive'];
1507
+ else
1508
+ $recursive = false;
1509
+
1510
+ switch ( array_pop( explode( ':', $_GET['action'] ) ) ) {
1511
+ default:
1512
+ die( "naughty naughty" );
1513
+ case 'checksum':
1514
+ $list = array();
1515
+ $this->response( $bfs->dir_checksum( $path, $list, $recursive ) );
1516
+ case 'dir':
1517
+ $this->response( $bfs->dir_examine( $path, $recursive ) );
1518
+ case 'stat':
1519
+ $this->response( $bfs->stat( $bfs->dir.$path ) );
1520
+ case 'get':
1521
+ $bfs->fdump( $bfs->dir.$path );
1522
+ case 'ls':
1523
+ $this->response( $bfs->ls( $path, $md5, $sha1, $limit, $offset ) );
1524
+ }
1525
+ break;
1526
+ case 'config:get':
1527
+ if ( !isset( $_POST['key'] ) || !$_POST['key'] )
1528
+ $this->response( false );
1529
+ $key = '_vp_config_' . base64_decode( $_POST['key'] );
1530
+ $this->response( base64_encode( maybe_serialize( $this->get_config( $key ) ) ) );
1531
+ break;
1532
+ case 'config:set':
1533
+ if ( !isset( $_POST['key'] ) || !$_POST['key'] ) {
1534
+ $this->response( false );
1535
+ break;
1536
+ }
1537
+ $key = '_vp_config_' . base64_decode( $_POST['key'] );
1538
+ if ( !isset( $_POST['val'] ) || !$_POST['val'] ) {
1539
+ if ( !isset($_POST['delete']) || !$_POST['delete'] ) {
1540
+ $this->response( false );
1541
+ } else {
1542
+ $this->response( delete_option( $key ) );
1543
+ }
1544
+ break;
1545
+ }
1546
+ $val = maybe_unserialize( base64_decode( $_POST['val'] ) );
1547
+ $this->response( update_option( $key, $val ) );
1548
+ break;
1549
+ }
1550
+ die();
1551
+ }
1552
+
1553
+ function _fix_ixr_null_to_string( &$args ) {
1554
+ if ( is_array( $args ) )
1555
+ foreach ( $args as $k => $v )
1556
+ $args[$k] = $this->_fix_ixr_null_to_string( $v );
1557
+ else if ( is_object( $args ) )
1558
+ foreach ( get_object_vars( $args ) as $k => $v )
1559
+ $args->$k = $this->_fix_ixr_null_to_string( $v );
1560
+ else
1561
+ return null == $args ? '' : $args;
1562
+ return $args;
1563
+ }
1564
+
1565
+ function contact_service( $action, $args = array() ) {
1566
+ if ( 'test' != $action && 'register' != $action && !$this->check_connection() )
1567
+ return false;
1568
+
1569
+ global $current_user;
1570
+ if ( !isset( $args['args'] ) )
1571
+ $args['args'] = '';
1572
+ $old_timeout = ini_get( 'default_socket_timeout' );
1573
+ $timeout = $this->get_option( 'timeout' );
1574
+ if ( function_exists( 'ini_set' ) )
1575
+ ini_set( 'default_socket_timeout', $timeout );
1576
+ $hostname = $this->get_option( 'hostname' );
1577
+
1578
+ if ( !class_exists( 'VaultPress_IXR_SSL_Client' ) )
1579
+ require_once( dirname( __FILE__ ) . '/class.vaultpress-ixr-ssl-client.php' );
1580
+ $client = new VaultPress_IXR_SSL_Client( $hostname, '/xmlrpc.php', 80, $timeout );
1581
+
1582
+ if ( 'vaultpress.com' == $hostname )
1583
+ $client->ssl();
1584
+
1585
+ // Begin audit trail breadcrumbs
1586
+ if ( isset( $current_user ) && is_object( $current_user ) && isset( $current_user->ID ) ) {
1587
+ $args['cause_user_id'] = intval( $current_user->ID );
1588
+ $args['cause_user_login'] = (string)$current_user->user_login;
1589
+ } else {
1590
+ $args['cause_user_id'] = -1;
1591
+ $args['cause_user_login'] = '';
1592
+ }
1593
+ $args['cause_ip'] = $_SERVER['REMOTE_ADDR'];
1594
+ $args['cause_uri'] = $_SERVER['REQUEST_URI'];
1595
+ $args['cause_method'] = $_SERVER['REQUEST_METHOD'];
1596
+ // End audit trail breadcrumbs
1597
+
1598
+ $args['version'] = $this->plugin_version;
1599
+ $args['locale'] = get_locale();
1600
+ $args['site_url'] = $this->site_url();
1601
+
1602
+ $salt = md5( time() . serialize( $_SERVER ) );
1603
+ $args['key'] = $this->get_option( 'key' );
1604
+ $this->_fix_ixr_null_to_string( $args );
1605
+ $args['signature'] = $this->sign_string( serialize( $args ), $this->get_option( 'secret' ), $salt ).":$salt";
1606
+
1607
+ $client->query( 'vaultpress.'.$action, new IXR_Base64( serialize( $args ) ) );
1608
+ $rval = $client->message ? $client->getResponse() : '';
1609
+ if ( function_exists( 'ini_set' ) )
1610
+ ini_set( 'default_socket_timeout', $old_timeout );
1611
+
1612
+ // we got an error from the servers
1613
+ if ( is_array( $rval ) && isset( $rval['faultCode'] ) ) {
1614
+ $this->update_option( 'connection', time() );
1615
+ $this->update_option( 'connection_error_code', $rval['faultCode'] );
1616
+ $this->update_option( 'connection_error_message', $rval['faultString'] );
1617
+ }
1618
+
1619
+ return $rval;
1620
+ }
1621
+
1622
+ function validate_api_signature() {
1623
+ global $__vp_validate_error;
1624
+ if ( !empty( $_POST['signature'] ) )
1625
+ $sig = (string) $_POST['signature'];
1626
+ else {
1627
+ $__vp_validate_error = array( 'error' => 'no_signature' );
1628
+ return false;
1629
+ }
1630
+
1631
+ $secret = $this->get_option( 'secret' );
1632
+ if ( !$secret ) {
1633
+ $__vp_validate_error = array( 'error' => 'missing_secret' );
1634
+ return false;
1635
+ }
1636
+ if ( !$this->get_option( 'disable_firewall' ) ) {
1637
+ $rxs = $this->get_option( 'service_ips' );
1638
+ $service_ips_external = get_option( 'vaultpress_service_ips_external' );
1639
+ if ( !empty( $rxs['data'] ) && !empty( $service_ips_external['data'] ) )
1640
+ $rxs['data'] = array_merge( $rxs['data'], $service_ips_external['data'] );
1641
+ if ( $rxs ) {
1642
+ $timeout = time() - 86400;
1643
+ if ( $rxs ) {
1644
+ if ( $rxs['updated'] < $timeout )
1645
+ $refetch = true;
1646
+ else
1647
+ $refetch = false;
1648
+ $rxs = $rxs['data'];
1649
+ }
1650
+ } else {
1651
+ $refetch = true;
1652
+ }
1653
+ if ( $refetch ) {
1654
+ if ( $data = $this->update_firewall() )
1655
+ $rxs = $data;
1656
+ }
1657
+ if ( !$this->validate_ip_address( $rxs ) )
1658
+ return false;
1659
+ }
1660
+ $sig = explode( ':', $sig );
1661
+ if ( !is_array( $sig ) || count( $sig ) != 2 || !isset( $sig[0] ) || !isset( $sig[1] ) ) {
1662
+ $__vp_validate_error = array( 'error' => 'invalid_signature_format' );
1663
+ return false;
1664
+ }
1665
+
1666
+ // Pass 1 -- new method
1667
+ $uri = preg_replace( '/^[^?]+\?/', '?', $_SERVER['REQUEST_URI'] );
1668
+ $post = $_POST;
1669
+ unset( $post['signature'] );
1670
+ // Work around for dd-formmailer plugin
1671
+ if ( isset( $post['_REPEATED'] ) )
1672
+ unset( $post['_REPEATED'] );
1673
+ ksort( $post );
1674
+ $to_sign = serialize( array( 'uri' => $uri, 'post' => $post ) );
1675
+ $signature = $this->sign_string( $to_sign, $secret, $sig[1] );
1676
+ if ( $sig[0] === $signature )
1677
+ return true;
1678
+
1679
+ $__vp_validate_error = array( 'error' => 'invalid_signed_data', 'detail' => array( 'actual' => $sig[0], 'needed' => $signature ) );
1680
+ return false;
1681
+ }
1682
+
1683
+ function ip_in_cidr( $ip, $cidr ) {
1684
+ list ($net, $mask) = explode( '/', $cidr );
1685
+ return ( ip2long( $ip ) & ~((1 << (32 - $mask)) - 1) ) == ( ip2long( $net ) & ~((1 << (32 - $mask)) - 1) );
1686
+ }
1687
+
1688
+ function ip_in_cidrs( $ip, $cidrs ) {
1689
+ foreach ( (array)$cidrs as $cidr ) {
1690
+ if ( $this->ip_in_cidr( $ip, $cidr ) ) {
1691
+ return $cidr;
1692
+ }
1693
+ }
1694
+ }
1695
+
1696
+ function validate_ip_address( $rxs ) {
1697
+ global $__vp_validate_error;
1698
+ if ( empty( $rxs ) ) {
1699
+ $__vp_validate_error = array( 'error' => 'empty_vp_ip_range' );
1700
+ return false;
1701
+ }
1702
+
1703
+ $remote_ips = array();
1704
+
1705
+ if ( $this->get_option( 'allow_forwarded_for') && !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
1706
+ $remote_ips = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
1707
+
1708
+ if ( !empty( $_SERVER['REMOTE_ADDR'] ) )
1709
+ $remote_ips[] = $_SERVER['REMOTE_ADDR'];
1710
+
1711
+ if ( empty( $remote_ips ) ) {
1712
+ $__vp_validate_error = array( 'error' => 'no_remote_addr', 'detail' => (int) $this->get_option( 'allow_forwarded_for' ) ); // shouldn't happen
1713
+ return false;
1714
+ }
1715
+
1716
+ $iprx = '/^([0-9]+\.[0-9]+\.[0-9]+\.)([0-9]+)$/';
1717
+
1718
+ foreach ( $remote_ips as $_remote_ip ) {
1719
+ $remote_ip = preg_replace( '#^::(ffff:)?#', '', $_remote_ip );
1720
+ if ( !preg_match( $iprx, $remote_ip, $r ) ) {
1721
+ $__vp_validate_error = array( 'error' => "remote_addr_fail", 'detail' => $_remote_ip );
1722
+ return false;
1723
+ }
1724
+
1725
+ foreach ( (array)$rxs as $begin => $end ) {
1726
+ if ( !preg_match( $iprx, $begin, $b ) )
1727
+ continue;
1728
+ if ( !preg_match( $iprx, $end, $e ) )
1729
+ continue;
1730
+ if ( $r[1] != $b[1] || $r[1] != $e[1] )
1731
+ continue;
1732
+ $me = $r[2];
1733
+ $b = min( (int)$b[2], (int)$e[2] );
1734
+ $e = max( (int)$b[2], (int)$e[2] );
1735
+ if ( $me >= $b && $me <= $e ) {
1736
+ return true;
1737
+ }
1738
+ }
1739
+ }
1740
+ $__vp_validate_error = array( 'error' => 'remote_addr_fail', 'detail' => $remote_ips );
1741
+
1742
+ return false;
1743
+ }
1744
+
1745
+ function sign_string( $string, $secret, $salt ) {
1746
+ return hash_hmac( 'sha1', "$string:$salt", $secret );
1747
+ }
1748
+
1749
+ function response( $response, $raw = false ) {
1750
+ // "re" -- "Response Encoding"
1751
+ if ( !empty( $_GET['re'] ) )
1752
+ header( sprintf( 'X-VP-Encoded: X%d', abs( intval( $_GET['re'] ) ) ) );
1753
+ if ( $raw ) {
1754
+ if ( !isset( $_GET['re'] ) )
1755
+ die( $response );
1756
+ else if ( '1' === $_GET['re'] )
1757
+ die( base64_encode( $response ) );
1758
+ else if ( '2' === $_GET['re'] )
1759
+ die( str_rot13( $response ) );
1760
+ else
1761
+ die( $response );
1762
+ }
1763
+ list( $usec, $sec ) = explode( " ", microtime() );
1764
+ $r = new stdClass();
1765
+ $r->req_vector = floatval( $_GET['vector'] );
1766
+ $r->rsp_vector = ( (float)$usec + (float)$sec );
1767
+ if ( function_exists( "getrusage" ) )
1768
+ $r->rusage = getrusage();
1769
+ else
1770
+ $r->rusage = false;
1771
+ if ( function_exists( "memory_get_peak_usage" ) )
1772
+ $r->peak_memory_usage = memory_get_peak_usage( true );
1773
+ else
1774
+ $r->peak_memory_usage = false;
1775
+ if ( function_exists( "memory_get_usage" ) )
1776
+ $r->memory_usage = memory_get_usage( true );
1777
+ else
1778
+ $r->memory_usage = false;
1779
+ $r->response = $response;
1780
+ if ( !isset( $_GET['re'] ) )
1781
+ die( serialize( $r ) );
1782
+ else if ( '1' === $_GET['re'] )
1783
+ die( base64_encode( serialize( $r ) ) );
1784
+ else if ( '2' === $_GET['re'] )
1785
+ die( str_rot13( serialize( $r ) ) );
1786
+ else
1787
+ die( serialize( $r ) );
1788
+ }
1789
+
1790
+ function reset_pings() {
1791
+ global $vaultpress_pings;
1792
+ $vaultpress_pings = array(
1793
+ 'version' => 1,
1794
+ 'count' => 0,
1795
+ 'editedtables' => array(),
1796
+ 'plugins' => array(),
1797
+ 'themes' => array(),
1798
+ 'uploads' => array(),
1799
+ 'db' => array(),
1800
+ 'debug' => array(),
1801
+ 'security' => array(),
1802
+ );
1803
+ }
1804
+
1805
+ function add_ping( $type, $data, $hook=null ) {
1806
+ global $vaultpress_pings;
1807
+ if ( defined( 'WP_IMPORTING' ) && constant( 'WP_IMPORTING' ) )
1808
+ return;
1809
+ if ( !array_key_exists( $type, $vaultpress_pings ) )
1810
+ return;
1811
+
1812
+ switch( $type ) {
1813
+ case 'editedtables';
1814
+ $vaultpress_pings[$type] = $data;
1815
+ return;
1816
+ case 'uploads':
1817
+ case 'themes':
1818
+ case 'plugins':
1819
+ if ( !is_array( $data ) ) {
1820
+ $data = array( $data );
1821
+ }
1822
+ foreach ( $data as $val ) {
1823
+ if ( in_array( $data, $vaultpress_pings[$type] ) )
1824
+ continue;
1825
+ $vaultpress_pings['count']++;
1826
+ $vaultpress_pings[$type][]=$val;
1827
+ }
1828
+ return;
1829
+ case 'db':
1830
+ $subtype = array_shift( array_keys( $data ) );
1831
+ if ( !isset( $vaultpress_pings[$type][$subtype] ) )
1832
+ $vaultpress_pings[$type][$subtype] = array();
1833
+ if ( in_array( $data, $vaultpress_pings[$type][$subtype] ) )
1834
+ return;
1835
+ $vaultpress_pings['count']++;
1836
+ $vaultpress_pings[$type][$subtype][] = $data;
1837
+ return;
1838
+ default:
1839
+ if ( in_array( $data, $vaultpress_pings[$type] ) )
1840
+ return;
1841
+ $vaultpress_pings['count']++;
1842
+ $vaultpress_pings[$type][] = $data;
1843
+ return;
1844
+ }
1845
+ }
1846
+
1847
+ function do_pings() {
1848
+ global $wpdb, $vaultpress_pings, $__vp_recursive_ping_lock;
1849
+ if ( defined( 'WP_IMPORTING' ) && constant( 'WP_IMPORTING' ) )
1850
+ return;
1851
+
1852
+ if ( !isset( $wpdb ) ) {
1853
+ $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
1854
+ $close_wpdb = true;
1855
+ } else {
1856
+ $close_wpdb = false;
1857
+ }
1858
+
1859
+ if ( !$vaultpress_pings['count'] )
1860
+ return;
1861
+
1862
+ // Short circuit the contact process if we know that we can't contact the service
1863
+ if ( isset( $__vp_recursive_ping_lock ) && $__vp_recursive_ping_lock ) {
1864
+ $this->ai_ping_insert( serialize( $vaultpress_pings ) );
1865
+ if ( $close_wpdb ) {
1866
+ $wpdb->__destruct();
1867
+ unset( $wpdb );
1868
+ }
1869
+ $this->reset_pings();
1870
+ return;
1871
+ }
1872
+
1873
+ $ping_attempts = 0;
1874
+ do {
1875
+ $ping_attempts++;
1876
+ $rval = $this->contact_service( 'ping', array( 'args' => $vaultpress_pings ) );
1877
+ if ( $rval || $ping_attempts >= 3 )
1878
+ break;
1879
+ if ( !$rval )
1880
+ usleep(500000);
1881
+ } while ( true );
1882
+ if ( !$rval ) {
1883
+ $__vp_recursive_ping_lock = true;
1884
+ $this->ai_ping_insert( serialize( $vaultpress_pings ) );
1885
+ }
1886
+ $this->reset_pings();
1887
+ if ( $close_wpdb ) {
1888
+ $wpdb->__destruct();
1889
+ unset( $wpdb );
1890
+ }
1891
+ return $rval;
1892
+ }
1893
+
1894
+ function resolve_content_dir() {
1895
+ // Take the easy way out
1896
+ if ( defined( 'WP_CONTENT_DIR' ) ) {
1897
+ if ( substr( WP_CONTENT_DIR, -1 ) != DIRECTORY_SEPARATOR )
1898
+ return WP_CONTENT_DIR . DIRECTORY_SEPARATOR;
1899
+ return WP_CONTENT_DIR;
1900
+ }
1901
+ // Best guess
1902
+ if ( defined( 'ABSPATH' ) ) {
1903
+ if ( substr( ABSPATH, -1 ) != DIRECTORY_SEPARATOR )
1904
+ return ABSPATH . DIRECTORY_SEPARATOR . 'wp-content' . DIRECTORY_SEPARATOR;
1905
+ return ABSPATH . 'wp-content' . DIRECTORY_SEPARATOR;
1906
+ }
1907
+ // Run with a solid assumption: WP_CONTENT_DIR/vaultpress/vaultpress.php
1908
+ return dirname( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR;
1909
+ }
1910
+
1911
+ function resolve_upload_path() {
1912
+ $upload_path = false;
1913
+ $upload_dir = wp_upload_dir();
1914
+
1915
+ if ( isset( $upload_dir['basedir'] ) )
1916
+ $upload_path = $upload_dir['basedir'];
1917
+
1918
+ // Nothing recorded? use a best guess!
1919
+ if ( !$upload_path || $upload_path == realpath( ABSPATH ) )
1920
+ return $this->resolve_content_dir() . 'uploads' . DIRECTORY_SEPARATOR;
1921
+
1922
+ if ( substr( $upload_path, -1 ) != DIRECTORY_SEPARATOR )
1923
+ $upload_path .= DIRECTORY_SEPARATOR;
1924
+
1925
+ return $upload_path;
1926
+ }
1927
+
1928
+ function load_first( $value ) {
1929
+ $value = array_unique( $value ); // just in case there are duplicates
1930
+ return array_merge(
1931
+ preg_grep( '/vaultpress\.php$/', $value ),
1932
+ preg_grep( '/vaultpress\.php$/', $value, PREG_GREP_INVERT )
1933
+ );
1934
+ }
1935
+
1936
+ function is_multisite() {
1937
+ if ( function_exists( 'is_multisite' ) )
1938
+ return is_multisite();
1939
+
1940
+ return false;
1941
+ }
1942
+
1943
+ function is_main_site() {
1944
+ if ( !function_exists( 'is_main_site' ) || !$this->is_multisite() )
1945
+ return true;
1946
+
1947
+ return is_main_site();
1948
+ }
1949
+
1950
+ function is_registered() {
1951
+ $key = $this->get_option( 'key' );
1952
+ $secret = $this->get_option( 'secret' );
1953
+ return !empty( $key ) && !empty( $secret );
1954
+ }
1955
+
1956
+ function clear_connection() {
1957
+ $this->delete_option( 'connection' );
1958
+ $this->delete_option( 'connection_error_code' );
1959
+ $this->delete_option( 'connection_error_message' );
1960
+ $this->delete_option( 'connection_test' );
1961
+ }
1962
+
1963
+ function site_url() {
1964
+ $site_url = '';
1965
+
1966
+ // compatibility for WordPress MU Domain Mapping plugin
1967
+ if ( defined( 'DOMAIN_MAPPING' ) && DOMAIN_MAPPING ) {
1968
+ if ( !function_exists( 'domain_mapping_siteurl' ) ) {
1969
+
1970
+ if ( !function_exists( 'is_plugin_active' ) )
1971
+ require_once ABSPATH . '/wp-admin/includes/plugin.php';
1972
+
1973
+ $plugin = 'wordpress-mu-domain-mapping/domain_mapping.php';
1974
+ if ( is_plugin_active( $plugin ) )
1975
+ include_once( WP_PLUGIN_DIR . '/' . $plugin );
1976
+ }
1977
+
1978
+ if ( function_exists( 'domain_mapping_siteurl' ) )
1979
+ $site_url = domain_mapping_siteurl( false );
1980
+ }
1981
+
1982
+ if ( empty( $site_url ) )
1983
+ $site_url = site_url();
1984
+
1985
+ return $site_url;
1986
+ }
1987
+
1988
+ function add_admin_actions_and_filters() {
1989
+ add_action( 'admin_init', array( $this, 'admin_init' ) );
1990
+ add_action( 'admin_menu', array( $this, 'admin_menu' ), 5 ); # Priority 5, so it's called before Jetpack's admin_menu.
1991
+ add_action( 'admin_head', array( $this, 'admin_head' ) );
1992
+ }
1993
+
1994
+ function add_listener_actions_and_filters() {
1995
+ add_action( 'admin_bar_menu', array( $this, 'toolbar' ), 999 );
1996
+ add_action( 'admin_bar_init', array( $this, 'styles' ) );
1997
+
1998
+ // Comments
1999
+ add_action( 'delete_comment', array( $this, 'comment_action_handler' ) );
2000
+ add_action( 'wp_set_comment_status', array( $this, 'comment_action_handler' ) );
2001
+ add_action( 'trashed_comment', array( $this, 'comment_action_handler' ) );
2002
+ add_action( 'untrashed_comment', array( $this, 'comment_action_handler' ) );
2003
+ add_action( 'wp_insert_comment', array( $this, 'comment_action_handler' ) );
2004
+ add_action( 'comment_post', array( $this, 'comment_action_handler' ) );
2005
+ add_action( 'edit_comment', array( $this, 'comment_action_handler' ) );
2006
+
2007
+ // Commentmeta
2008
+ add_action( 'added_comment_meta', array( $this, 'commentmeta_insert_handler' ), 10, 2 );
2009
+ add_action( 'updated_comment_meta', array( $this, 'commentmeta_modification_handler' ), 10, 4 );
2010
+ add_action( 'deleted_comment_meta', array( $this, 'commentmeta_modification_handler' ), 10, 4 );
2011
+
2012
+ // Users
2013
+ if ( $this->is_main_site() ) {
2014
+ add_action( 'user_register', array( $this, 'userid_action_handler' ) );
2015
+ add_action( 'password_reset', array( $this, 'userid_action_handler' ) );
2016
+ add_action( 'profile_update', array( $this, 'userid_action_handler' ) );
2017
+ add_action( 'user_register', array( $this, 'userid_action_handler' ) );
2018
+ add_action( 'deleted_user', array( $this, 'userid_action_handler' ) );
2019
+ }
2020
+
2021
+ // Usermeta
2022
+ if ( $this->is_main_site() ) {
2023
+ add_action( 'added_usermeta', array( $this, 'usermeta_action_handler' ), 10, 4 );
2024
+ add_action( 'update_usermeta', array( $this, 'usermeta_action_handler' ), 10, 4 );
2025
+ add_action( 'delete_usermeta', array( $this, 'usermeta_action_handler' ), 10, 4 );
2026
+ }
2027
+
2028
+ // Posts
2029
+ add_action( 'delete_post', array( $this, 'post_action_handler' ) );
2030
+ add_action( 'trash_post', array( $this, 'post_action_handler' ) );
2031
+ add_action( 'untrash_post', array( $this, 'post_action_handler' ) );
2032
+ add_action( 'edit_post', array( $this, 'post_action_handler' ) );
2033
+ add_action( 'save_post', array( $this, 'post_action_handler' ) );
2034
+ add_action( 'wp_insert_post', array( $this, 'post_action_handler' ) );
2035
+ add_action( 'edit_attachment', array( $this, 'post_action_handler' ) );
2036
+ add_action( 'add_attachment', array( $this, 'post_action_handler' ) );
2037
+ add_action( 'delete_attachment', array( $this, 'post_action_handler' ) );
2038
+ add_action( 'private_to_published', array( $this, 'post_action_handler' ) );
2039
+ add_action( 'wp_restore_post_revision', array( $this, 'post_action_handler' ) );
2040
+
2041
+ // Postmeta
2042
+ add_action( 'added_post_meta', array( $this, 'postmeta_insert_handler' ), 10, 4 );
2043
+ add_action( 'update_post_meta', array( $this, 'postmeta_modification_handler' ), 10, 4 );
2044
+ add_action( 'updated_post_meta', array( $this, 'postmeta_modification_handler' ), 10, 4 );
2045
+ add_action( 'delete_post_meta', array( $this, 'postmeta_modification_handler' ), 10, 4 );
2046
+ add_action( 'deleted_post_meta', array( $this, 'postmeta_modification_handler' ), 10, 4 );
2047
+ add_action( 'added_postmeta', array( $this, 'postmeta_action_handler' ) );
2048
+ add_action( 'update_postmeta', array( $this, 'postmeta_action_handler' ) );
2049
+ add_action( 'delete_postmeta', array( $this, 'postmeta_action_handler' ) );
2050
+
2051
+ // Links
2052
+ add_action( 'edit_link', array( $this, 'link_action_handler' ) );
2053
+ add_action( 'add_link', array( $this, 'link_action_handler' ) );
2054
+ add_action( 'delete_link', array( $this, 'link_action_handler' ) );
2055
+
2056
+ // Taxonomy
2057
+ add_action( 'created_term', array( $this, 'term_handler' ), 2 );
2058
+ add_action( 'edited_terms', array( $this, 'term_handler' ), 2 );
2059
+ add_action( 'delete_term', array( $this, 'term_handler' ), 2 );
2060
+ add_action( 'edit_term_taxonomy', array( $this, 'term_taxonomy_handler' ) );
2061
+ add_action( 'delete_term_taxonomy', array( $this, 'term_taxonomy_handler' ) );
2062
+ add_action( 'edit_term_taxonomies', array( $this, 'term_taxonomies_handler' ) );
2063
+ add_action( 'add_term_relationship', array( $this, 'term_relationship_handler' ), 10, 2 );
2064
+ add_action( 'delete_term_relationships', array( $this, 'term_relationships_handler' ), 10, 2 );
2065
+ add_action( 'set_object_terms', array( $this, 'set_object_terms_handler' ), 10, 3 );
2066
+
2067
+ // Files
2068
+ if ( $this->is_main_site() ) {
2069
+ add_action( 'switch_theme', array( $this, 'theme_action_handler' ) );
2070
+ add_action( 'activate_plugin', array( $this, 'plugin_action_handler' ) );
2071
+ add_action( 'deactivate_plugin', array( $this, 'plugin_action_handler' ) );
2072
+ }
2073
+ add_action( 'wp_handle_upload', array( $this, 'upload_handler' ) );
2074
+
2075
+ // Options
2076
+ add_action( 'deleted_option', array( $this, 'option_handler' ), 1 );
2077
+ add_action( 'updated_option', array( $this, 'option_handler' ), 1 );
2078
+ add_action( 'added_option', array( $this, 'option_handler' ), 1 );
2079
+
2080
+ $this->add_vp_required_filters();
2081
+ }
2082
+
2083
+ function add_vp_required_filters() {
2084
+ // Log ins
2085
+ if ( $this->get_option( 'login_lockdown' ) ) {
2086
+ add_action( 'login_form', array( $this, 'add_js_token' ) );
2087
+ add_filter( 'authenticate', array( $this, 'authenticate' ), 999 );
2088
+ }
2089
+
2090
+ // Report back to VaultPress
2091
+ add_action( 'shutdown', array( $this, 'do_pings' ) );
2092
+
2093
+ // VaultPress likes being first in line
2094
+ add_filter( 'pre_update_option_active_plugins', array( $this, 'load_first' ) );
2095
+ }
2096
+ }
2097
+
2098
+ $vaultpress = VaultPress::init();
2099
+
2100
+ if ( isset( $_GET['vaultpress'] ) && $_GET['vaultpress'] ) {
2101
+ if ( !function_exists( 'wp_magic_quotes' ) ) {
2102
+ // If already slashed, strip.
2103
+ if ( get_magic_quotes_gpc() ) {
2104
+ $_GET = stripslashes_deep( $_GET );
2105
+ $_POST = stripslashes_deep( $_POST );
2106
+ $_COOKIE = stripslashes_deep( $_COOKIE );
2107
+ }
2108
+
2109
+ // Escape with wpdb.
2110
+ $_GET = add_magic_quotes( $_GET );
2111
+ $_POST = add_magic_quotes( $_POST );
2112
+ $_COOKIE = add_magic_quotes( $_COOKIE );
2113
+ $_SERVER = add_magic_quotes( $_SERVER );
2114
+
2115
+ // Force REQUEST to be GET + POST. If SERVER, COOKIE, or ENV are needed, use those superglobals directly.
2116
+ $_REQUEST = array_merge( $_GET, $_POST );
2117
+ } else {
2118
+ wp_magic_quotes();
2119
+ }
2120
+
2121
+ if ( !function_exists( 'wp_get_current_user' ) )
2122
+ include ABSPATH . '/wp-includes/pluggable.php';
2123
+
2124
+ // TODO: this prevents some error notices but do we need it? is there a better way to check capabilities/logged in user/etc?
2125
+ if ( function_exists( 'wp_cookie_constants' ) && !defined( 'AUTH_COOKIE' ) )
2126
+ wp_cookie_constants();
2127
+
2128
+ $vaultpress->parse_request( null );
2129
+
2130
+ die();
2131
+ }
2132
+
2133
+ // only load hotfixes if it's not a VP request
2134
+ require_once( dirname( __FILE__ ) . '/class.vaultpress-hotfixes.php' );
2135
+ $hotfixes = new VaultPress_Hotfixes();
2136
+
2137
+ include_once( dirname( __FILE__ ) . '/cron-tasks.php' );
vp-scanner.php ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class VP_FileScan {
4
+ var $path;
5
+ var $last_dir = null;
6
+ var $offset = 0;
7
+ var $ignore_symlinks = false;
8
+
9
+ function VP_FileScan( $path, $ignore_symlinks = false ) {
10
+ if ( is_dir( $path ) )
11
+ $this->last_dir = $this->path = @realpath( $path );
12
+ else
13
+ $this->last_dir = $this->path = dirname( @realpath( $path ) );
14
+ $this->ignore_symlinks = $ignore_symlinks;
15
+ }
16
+
17
+ function get_files( $limit = 100 ) {
18
+ $files = array();
19
+ if ( is_dir( $this->last_dir ) ) {
20
+ $return = $this->_scan_files( $this->path, $files, $this->offset, $limit, $this->last_dir );
21
+ $this->offset = $return[0];
22
+ $this->last_dir = $return[1];
23
+ if ( count( $files ) < $limit )
24
+ $this->last_dir = false;
25
+ }
26
+ return $files;
27
+ }
28
+
29
+ function _scan_files( $path, &$files, $offset, $limit, &$last_dir ) {
30
+ $_offset = 0;
31
+ if ( is_readable( $path ) && $handle = opendir( $path ) ) {
32
+ while( false !== ( $entry = readdir( $handle ) ) ) {
33
+ if ( '.' == $entry || '..' == $entry )
34
+ continue;
35
+
36
+ $_offset++;
37
+ $full_entry = $path . DIRECTORY_SEPARATOR . $entry;
38
+ $next_item = ltrim( str_replace( $path, '', $last_dir ), DIRECTORY_SEPARATOR );
39
+ $next = preg_split( '#(?<!\\\\)' . preg_quote( DIRECTORY_SEPARATOR, '#' ) . '#', $next_item, 2 );
40
+
41
+ // Skip if the next item is not found.
42
+ if ( !empty( $next[0] ) && $next[0] != $entry )
43
+ continue;
44
+ if ( rtrim( $last_dir, DIRECTORY_SEPARATOR ) == rtrim( $path, DIRECTORY_SEPARATOR ) && $_offset < $offset )
45
+ continue;
46
+ if ( $this->ignore_symlinks && is_link( $full_entry ) )
47
+ continue;
48
+
49
+ if ( rtrim( $last_dir, DIRECTORY_SEPARATOR ) == rtrim( $path, DIRECTORY_SEPARATOR ) ) {
50
+ // Reset last_dir and offset when we reached the previous last_dir value.
51
+ $last_dir = '';
52
+ $offset = 0;
53
+ }
54
+
55
+ if ( is_file( $full_entry ) ) {
56
+ if ( !vp_is_interesting_file( $full_entry ) )
57
+ continue;
58
+ $_return_offset = $_offset;
59
+ $_return_dir = dirname( $full_entry );
60
+ $files[] = $full_entry;
61
+ } elseif ( is_dir( $full_entry ) ) {
62
+ list( $_return_offset, $_return_dir ) = $this->_scan_files( $full_entry, $files, $offset, $limit, $last_dir );
63
+ }
64
+ if ( count( $files ) >= $limit ) {
65
+ closedir( $handle );
66
+ return array( $_return_offset, $_return_dir );
67
+ }
68
+ }
69
+ closedir( $handle );
70
+ }
71
+ return array( $_offset, $path );
72
+ }
73
+ }
74
+
75
+ function vp_get_real_file_path( $file_path, $tmp_file = false ) {
76
+ global $site, $site_id;
77
+ $site_id = !empty( $site->id ) ? $site->id : $site_id;
78
+ if ( !$tmp_file && !empty( $site_id ) && function_exists( 'determine_file_type_path' ) ) {
79
+ $path = determine_file_type_path( $file_path );
80
+ $file = file_by_path( $site_id, $path );
81
+ if ( !$file )
82
+ return false;
83
+ return $file->get_unencrypted();
84
+ }
85
+ return !empty( $tmp_file ) ? $tmp_file : $file_path;
86
+ }
87
+
88
+ function vp_is_interesting_file($file) {
89
+ $scan_only_regex = apply_filters( 'scan_only_extension_regex', '#\.(ph(p3|p4|p5|p|tml)|html|js|htaccess)$#i' );
90
+ return preg_match( $scan_only_regex, $file );
91
+ }
92
+
93
+ /**
94
+ * Scans a file with the registered signatures. To report a security notice for a specified signature, all its regular
95
+ * expressions should result in a match.
96
+ * @param $file the filename to be scanned.
97
+ * @param null $tmp_file used if the file to be scanned doesn't exist or if the filename doesn't match vp_is_interesting_file().
98
+ * @return array|bool false if no matched signature is found. A list of matched signatures otherwise.
99
+ */
100
+ function vp_scan_file($file, $tmp_file = null) {
101
+ $real_file = vp_get_real_file_path( $file, $tmp_file );
102
+ $file_size = file_exists( $real_file ) ? @filesize( $real_file ) : 0;
103
+ if ( !is_readable( $real_file ) || !$file_size || $file_size > apply_filters( 'scan_max_file_size', 3 * 1024 * 1024 ) ) // don't scan empty or files larger than 3MB.
104
+ return false;
105
+
106
+ $file_content = null;
107
+ $skip_file = apply_filters_ref_array( 'pre_scan_file', array ( false, $file, $real_file, &$file_content ) );
108
+ if ( false !== $skip_file ) // maybe detect malware without regular expressions.
109
+ return $skip_file;
110
+
111
+ if ( !vp_is_interesting_file( $file ) ) // only scan relevant files.
112
+ return false;
113
+
114
+ if ( !isset( $GLOBALS['vp_signatures'] ) )
115
+ $GLOBALS['vp_signatures'] = array();
116
+
117
+ $found = array ();
118
+ foreach ( $GLOBALS['vp_signatures'] as $signature ) {
119
+ if ( !is_object( $signature ) || !isset( $signature->patterns ) )
120
+ continue;
121
+ // if there is no filename_regex, we assume it's the same of vp_is_interesting_file().
122
+ if ( empty( $signature->filename_regex ) || preg_match( '#' . addcslashes( $signature->filename_regex, '#' ) . '#i', $file ) ) {
123
+ if ( null === $file_content || !is_array( $file_content ) )
124
+ $file_content = file( $real_file );
125
+
126
+ $is_vulnerable = true;
127
+ $matches = array ();
128
+ if ( is_array( $file_content ) && ( $signature->patterns ) && is_array( $signature->patterns ) ) {
129
+ reset( $signature->patterns );
130
+ while ( $is_vulnerable && list( , $pattern ) = each( $signature->patterns ) ) {
131
+ if ( ! $match = preg_grep( '#' . addcslashes( $pattern, '#' ) . '#im', $file_content ) ) {
132
+ $is_vulnerable = false;
133
+ break;
134
+ }
135
+ $matches += $match;
136
+ }
137
+ } else {
138
+ $is_vulnerable = false;
139
+ }
140
+ $debug_data = array( 'matches' => $matches );
141
+ // Additional checking needed?
142
+ if ( method_exists( $signature, 'get_detailed_scanner' ) && $scanner = $signature->get_detailed_scanner() )
143
+ $is_vulnerable = $scanner->scan( $is_vulnerable, $file, $real_file, $file_content, $debug_data );
144
+ if ( $is_vulnerable ) {
145
+ $found[$signature->id] = $debug_data;
146
+ if ( isset( $signature->severity ) && $signature->severity > 8 ) // don't continue scanning
147
+ break;
148
+ }
149
+ }
150
+ }
151
+
152
+ return apply_filters_ref_array( 'post_scan_file', array ( $found, $file, $real_file, &$file_content ) );
153
+ }