ManageWP Worker - Version 3.9.6

Version Description

= * Improved dashboard performance * Fixed bug with W3TC, we hope it is fully comptabile now * Improved backup feature * Various other fixes and improvements

Download this release

Release Info

Developer freediver
Plugin Icon 128x128 ManageWP Worker
Version 3.9.6
Comparing to
See all releases

Code changes from version 3.9.5 to 3.9.6

Files changed (18) hide show
  1. api.php +37 -37
  2. backup.class.php +1361 -1241
  3. comment.class.php +42 -42
  4. core.class.php +437 -437
  5. helper.class.php +427 -403
  6. init.php +630 -599
  7. installer.class.php +451 -450
  8. lib/dropbox.php +144 -144
  9. lib/s3.php +909 -909
  10. link.class.php +38 -38
  11. plugins/cleanup/cleanup.php +175 -175
  12. plugins/extra_html_example/extra_html_example.php +17 -17
  13. plugins/search/search.php +129 -129
  14. post.class.php +339 -339
  15. readme.txt +149 -143
  16. stats.class.php +430 -430
  17. user.class.php +52 -52
  18. version +1 -1
api.php CHANGED
@@ -1,38 +1,38 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * api.php
5
- *
6
- * ManageWP addons api
7
- *
8
- * Copyright (c) 2011 Prelovac Media
9
- * www.prelovac.com
10
- **************************************************************/
11
-
12
- function mmb_add_action($action = false, $callback = false)
13
- {
14
- if (!$action || !$callback)
15
- return false;
16
-
17
- global $mmb_actions;
18
- mmb_function_exists($callback);
19
-
20
- if (isset($mmb_actions[$action]))
21
- wp_die('Cannot redeclare ManageWP action "' . $action . '".');
22
-
23
- $mmb_actions[$action] = $callback;
24
- }
25
-
26
- function mmb_function_exists($callback)
27
- {
28
- global $mwp_core;
29
- if (count($callback) === 2) {
30
- if (!method_exists($callback[0], $callback[1]))
31
- wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Class ' . get_class($callback[0]) . ' does not contain <b>"' . $callback[1] . '"</b> function</p>', '', '50%'));
32
- } else {
33
- if (!function_exists($callback))
34
- wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Function <b>"' . $callback . '"</b> does not exists.</p>', '', '50%'));
35
- }
36
- }
37
-
38
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * api.php
5
+ *
6
+ * ManageWP addons api
7
+ *
8
+ * Copyright (c) 2011 Prelovac Media
9
+ * www.prelovac.com
10
+ **************************************************************/
11
+
12
+ function mmb_add_action($action = false, $callback = false)
13
+ {
14
+ if (!$action || !$callback)
15
+ return false;
16
+
17
+ global $mmb_actions;
18
+ mmb_function_exists($callback);
19
+
20
+ if (isset($mmb_actions[$action]))
21
+ wp_die('Cannot redeclare ManageWP action "' . $action . '".');
22
+
23
+ $mmb_actions[$action] = $callback;
24
+ }
25
+
26
+ function mmb_function_exists($callback)
27
+ {
28
+ global $mwp_core;
29
+ if (count($callback) === 2) {
30
+ if (!method_exists($callback[0], $callback[1]))
31
+ wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Class ' . get_class($callback[0]) . ' does not contain <b>"' . $callback[1] . '"</b> function</p>', '', '50%'));
32
+ } else {
33
+ if (!function_exists($callback))
34
+ wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Function <b>"' . $callback . '"</b> does not exists.</p>', '', '50%'));
35
+ }
36
+ }
37
+
38
  ?>
backup.class.php CHANGED
@@ -1,1242 +1,1362 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * backup.class.php
5
- *
6
- * Manage Backups
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Backup extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- parent::__construct();
18
- }
19
-
20
- function get_backup_settings()
21
- {
22
- $backup_settings = get_option('mwp_backup_tasks');
23
- if(!empty($backup_settings))
24
- return $backup_settings;
25
- else
26
- return false;
27
- }
28
-
29
- function set_backup_task($params)
30
- {
31
- //$params => [$task_name, $args, $error]
32
- if(!empty($params)){
33
- extract($params);
34
-
35
- $before = $this->get_backup_settings();
36
- if(!$before || empty($before))
37
- $before = array();
38
-
39
- if(isset($args['remove'])){
40
- unset($before[$task_name]);
41
- $return = array('removed' => true);
42
- } else {
43
- $args['account_info'] = $account_info;
44
- $before[$task_name]['task_args'] = $args;
45
-
46
- if(!empty($args['schedule']))
47
- $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'],$args['schedule']);
48
-
49
- $return = $before[$task_name];
50
- }
51
-
52
- if($error){
53
- $before[$task_name]['task_results'][count($before[$task_name]['task_results'])] = array('error' => $error);
54
- }
55
- update_option('mwp_backup_tasks',$before);
56
-
57
- if($task_name == 'Backup Now'){
58
- $result = $this->backup($args, $task_name);
59
- $backup_settings = $this->get_backup_settings();
60
- if(is_array($result) && array_key_exists('error',$result)){
61
- $return = $result;
62
- } else {
63
- $return = $backup_settings[$task_name];
64
- }
65
- }
66
- return $return;
67
- }
68
- return false;
69
- }
70
-
71
- //Cron check
72
- function check_backup_tasks()
73
- {
74
- $settings = $this->get_backup_settings();
75
- if(is_array($settings) && !empty($settings)){
76
- foreach($settings as $task_name => $setting){
77
- if($setting['task_args']['next'] && $setting['task_args']['next'] < time()){
78
- $result = $this->backup($setting['task_args'], $task_name);
79
-
80
- if(is_array($result) && array_key_exists('error', $result)){
81
- $error = $result['error'];
82
- } else {
83
- $error = '';
84
- }
85
-
86
- //Update task with next schedule and possible error
87
- $this->set_backup_task(array('task_name' => $task_name, 'args' => $settings[$task_name]['task_args'], 'error' => $error)); //Update
88
- break;
89
- }
90
- }
91
- }
92
-
93
- }
94
-
95
-
96
-
97
- /*
98
- * If Task Name not set then it's manual backup
99
- * Backup args:
100
- * type -> db, full
101
- * what -> daily, weekly, monthly
102
- * account_info -> ftp, amazons3, dropbox
103
- * exclude-> array of paths to exclude from backup
104
- */
105
-
106
- function backup($args, $task_name = false){
107
- if(!$args || empty($args))
108
- return false;
109
-
110
- extract($args); //extract settings
111
-
112
-
113
- //try increase memory limit
114
- @ini_set('memory_limit', '1000M');
115
- @set_time_limit(600); //ten minutes
116
-
117
- //Remove old backup(s)
118
- if($type == 'manual'){
119
- $old = get_option('mwp_manual_backup');
120
- if($old['file_path'] && file_exists($old['file_path']))
121
- @unlink($old['file_path']);
122
- } else {
123
- $this->remove_old_backups($task_name);
124
- }
125
-
126
- $sec_string = md5('mmb-worker');
127
- $file = "/$sec_string/mwp_backups";
128
- $new_file_path = WP_CONTENT_DIR . $file;
129
-
130
- if (!file_exists($new_file_path)) {
131
- if (!mkdir($new_file_path, 0755, true))
132
- return array(
133
- 'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
134
- );
135
- }
136
-
137
- @file_put_contents($new_file_path . '/index.php', ''); //safe
138
- //Delete possible breaked previous backups - don't need it anymore (works only for previous wrokers)
139
- foreach (glob($new_file_path."/*.zip") as $filename) {
140
- $short = basename($filename);
141
- preg_match('/^wp\-content(.*)/Ui',$short,$matches);
142
- if($matches)
143
- @unlink($filename);
144
- }
145
-
146
- //Prepare .zip file name
147
- $site_name = $this->remove_http(get_bloginfo('url'));
148
- $site_name = str_replace(array(
149
- "_",
150
- "/"
151
- ), array(
152
- "",
153
- "-"
154
- ), $site_name);
155
-
156
- $hash = md5(time());
157
- $label = $type ? $type : 'manual';
158
- $backup_file = $new_file_path . '/' . $site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') .'_'.$hash. '.zip';
159
- $backup_url = WP_CONTENT_URL . $file . '/' . $site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') .'_'.$hash. '.zip';
160
-
161
-
162
- //What to backup - db or full
163
- if (trim($what) == 'db') {
164
- //take database backup
165
-
166
- $db_result = $this->backup_db();
167
- if(!$db_result){
168
- return array('error' => 'Failed to extract database.');
169
- }
170
- else
171
- {
172
- if ($this->mmb_exec('which zip')) {
173
- $command = "zip $backup_file -j $db_result";
174
- ob_start();
175
- $result = $this->mmb_exec($command);
176
- ob_get_clean();
177
- } else {
178
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
179
- $archive = new PclZip($backup_file);
180
- $result = $archive->add($db_result, PCLZIP_OPT_REMOVE_ALL_PATH);
181
-
182
- }
183
-
184
- @unlink($db_result);
185
- if(!$result)
186
- return array(
187
- 'error' => 'Failed to zip database.'
188
- );
189
- }
190
- }
191
- elseif (trim($what) == 'full') {
192
- $content_backup = $this->backup_full($backup_file,$exclude);
193
- if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
194
- return array(
195
- 'error' => $content_backup['error']
196
- );
197
- }
198
- }
199
-
200
- //Update backup info
201
- if($task_name){
202
- //backup task (scheduled)
203
- $backup_settings = $this->get_backup_settings();
204
- $paths = array();
205
- $size = ceil(filesize($backup_file) / 1024);
206
-
207
- if($size > 1000){
208
- $paths['size'] = ceil($size / 1024).'Mb';
209
- } else {
210
- $paths['size'] = $size.'kb';
211
- }
212
- $paths['time'] = time();
213
-
214
- if(!$backup_settings[$task_name]['task_args']['del_host_file']){
215
- $paths['server'] = array('file_path' => $backup_file, 'file_url' => $backup_url);
216
- }
217
-
218
- if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_ftp'])) {
219
- $paths['ftp'] = basename($backup_url);
220
- }
221
-
222
- if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
223
- $paths['amazons3'] = basename($backup_url);
224
- }
225
-
226
- if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
227
- $paths['dropbox'] = basename($backup_url);
228
- }
229
-
230
- if($backup_settings[$task_name]['task_args']['email_backup']) {
231
- $paths['email'] = $backup_settings[$task_name]['task_args']['email_backup'];
232
- }
233
-
234
- $temp = $backup_settings[$task_name]['task_results'];
235
- $temp['temp'] = $paths;
236
- $backup_settings[$task_name]['task_results'] = array_values($temp);
237
- update_option ('mwp_backup_tasks',$backup_settings);
238
- }
239
- else
240
- {
241
- //manual - predefined backup used for cloning
242
- $manual_backup = $args;
243
- $manual_backup ['file_path'] = $backup_file;
244
- $manual_backup ['file_url'] = $backup_url;
245
- update_option('mwp_manual_backup', $manual_backup);
246
- }
247
-
248
- //Additional: Table optimize, email, ftp, amazon_s3, dropbox...
249
- if(isset($optimize_tables) && !empty($optimize_tables)){
250
- $this->optimize_tables();
251
- }
252
-
253
- if(isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])){
254
- $account_info['mwp_ftp']['backup_file'] = $backup_file;
255
- $this->ftp_backup($account_info['mwp_ftp']);
256
- }
257
-
258
- if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])){
259
- $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
260
- $this->amazons3_backup($account_info['mwp_amazon_s3']);
261
- }
262
-
263
- if(isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])){
264
- $account_info['mwp_dropbox']['backup_file'] = $backup_file;
265
- $this->dropbox_backup($account_info['mwp_dropbox']);
266
- }
267
-
268
- if(isset($email_backup) && is_email($email_backup)){
269
- $mail_args = array(
270
- 'email' => $email_backup,
271
- 'task_name' => $task_name,
272
- 'file_path' => $backup_file
273
- );
274
- $this->email_backup($mail_args);
275
- }
276
-
277
- if($del_host_file){
278
- @unlink($backup_file);
279
- }
280
-
281
- return $backup_url; //Return url to backup file (we need return only for manual backup)
282
- }
283
-
284
- function backup_full($path, $exclude = array())
285
- {
286
- $db_result = $this->backup_db();
287
- if(!$db_result)
288
- return array('error' => 'Failed to backup database.');
289
- $sec_string = md5('mmb-worker');
290
- $remove = "wp-content/$sec_string/mwp_backups";
291
-
292
- if ($this->mmb_exec('which zip')) {
293
- chdir(ABSPATH);
294
-
295
- //exclude paths
296
- if(empty($exclude)){
297
- $exclude[0] = $remove;
298
- } else {
299
- $exclude[count($exclude)] = $remove;
300
- }
301
-
302
- $exclude_data = "-x";
303
- foreach($exclude as $data){
304
- $exclude_data .= " '$data/*'";
305
- }
306
-
307
- $command = "zip -r $path './' $exclude_data";
308
- ob_start();
309
- $result = $this->mmb_exec($command);
310
- ob_get_clean();
311
- @unlink($db_result);
312
-
313
- if($result){
314
- return true;
315
- }
316
- else{
317
- return array('error' => 'Failed to backup site.');
318
- }
319
-
320
- }
321
- else { //php zip
322
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
323
- $archive = new PclZip($path);
324
- $result = $archive->add(ABSPATH, PCLZIP_OPT_REMOVE_PATH, ABSPATH);
325
- $exclude_data = array();
326
- if(!empty($exclude) && $result){
327
- $exclude_data = array();
328
- foreach($exclude as $data){
329
- $exclude_data [] = $data.'/';
330
- }
331
-
332
- }
333
- $exclude_data[] = $remove.'/';
334
- $result = $archive->delete(PCLZIP_OPT_BY_NAME, $exclude_data);
335
-
336
- @unlink($db_result);
337
- if ($result) {
338
- return true;
339
- }
340
- else {
341
- if($archive->error_code == '-10'){
342
- return array('error' => 'Failed to zip backup. Try increasing memory limit and/or free space on your server.');
343
- }
344
- else{
345
- return array('error' => 'Failed to backup site. Try to enable Zip on your server.');
346
- }
347
- }
348
- }
349
- }
350
-
351
-
352
- function backup_db()
353
- {
354
- $db_folder = ABSPATH.'mwp_db/';
355
- if (!file_exists($db_folder)) {
356
- if (!mkdir($db_folder, 0755, true))
357
- return array(
358
- 'error' => 'Error creating database backup folder. Make sure you have write permission to your site root folder.'
359
- );
360
- }
361
-
362
- $file = $db_folder . DB_NAME . '.sql';
363
- $mysqldump = $this->check_mysqldump();
364
- if (is_array($mysqldump)) {
365
- $result = $this->backup_db_dump($file,$mysqldump);
366
-
367
- } else {
368
- $result = $this->backup_db_php($file);
369
- }
370
- return $result;
371
- }
372
-
373
- function backup_db_dump($file,$mysqldump)
374
- {
375
- global $wpdb;
376
- $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
377
- $command = $brace . $mysqldump['mysqldump'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
378
-
379
- ob_start();
380
- $result = $this->mmb_exec($command);
381
- ob_get_clean();
382
- if (!$result) {
383
- $result = $this->backup_db_php($file);
384
- return $result;
385
- }
386
-
387
- if (filesize($file) == 0 || !is_file($file) || !$result) {
388
- @unlink($file);
389
- return false;
390
- } else {
391
- return $file;
392
- }
393
- }
394
-
395
- function backup_db_php($file)
396
- {
397
- global $wpdb;
398
- $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
399
- foreach ($tables as $table) {
400
- //drop existing table
401
- $dump_data = "DROP TABLE IF EXISTS $table[0];";
402
- //create table
403
- $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
404
- $dump_data .= "\n\n" . $create_table[1] . ";\n\n";
405
-
406
- $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
407
- if ($count > 100)
408
- $count = ceil($count / 100) - 1;
409
- else
410
- $count = 1;
411
- for ($i = 0; $i < $count; $i++) {
412
- $low_limit = $i * 100;
413
- $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
414
- $rows = $wpdb->get_results($qry, ARRAY_A);
415
- if (is_array($rows)) {
416
- foreach ($rows as $row) {
417
- //insert single row
418
- $dump_data .= "INSERT INTO $table[0] VALUES(";
419
- $num_values = count($row);
420
- $j = 1;
421
- foreach ($row as $value) {
422
- $value = addslashes($value);
423
- $value = preg_replace("/\n/Ui", "\\n", $value);
424
- $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
425
- $j++;
426
- unset($value);
427
- }
428
- $dump_data .= ");\n";
429
- }
430
- }
431
- }
432
- $dump_data .= "\n\n\n";
433
-
434
- unset($rows);
435
- file_put_contents($file, $dump_data, FILE_APPEND);
436
- unset($dump_data);
437
- }
438
-
439
- if (filesize($file) == 0 || !is_file($file)) {
440
- @unlink($file);
441
- return false;
442
- }
443
-
444
- return $file;
445
-
446
- }
447
-
448
- function restore($args)
449
- {
450
- global $wpdb;
451
- if(empty($args)) {return false;}
452
-
453
- extract($args);
454
- @ini_set('memory_limit', '300M');
455
- @set_time_limit(300);
456
-
457
- $unlink_file = true; //Delete file after restore
458
-
459
- //Detect source
460
- if($backup_url){
461
- //This is for clone (overwrite)
462
- include_once ABSPATH . 'wp-admin/includes/file.php';
463
- $backup_file = download_url($backup_url);
464
- if(is_wp_error($backup_file)){
465
- return array(
466
- 'error' => $backup_file->get_error_message()
467
- );
468
- }
469
- $what = 'full';
470
- } else {
471
- $tasks = $this->get_backup_settings();
472
- $task = $tasks[$task_name];
473
- if(isset($task['task_results'][$result_id]['server'])) {
474
- $backup_file = $task['task_results'][$result_id]['server']['file_path'];
475
- $unlink_file = false; //Don't delete file if stored on server
476
- }elseif(isset($task['task_results'][$result_id]['ftp'])){
477
- $ftp_file = $task['task_results'][$result_id]['ftp'];
478
- $args = $task['task_args']['account_info']['mwp_ftp'];
479
- $args['backup_file'] = $ftp_file;
480
- $backup_file = $this->get_ftp_backup($args);
481
- if($backup_file == false){
482
- return array(
483
- 'error' => 'Failed to download file from FTP'
484
- );
485
- }
486
- }elseif(isset($task['task_results'][$result_id]['amazons3'])){
487
- $amazons3_file = $task['task_results'][$result_id]['amazons3'];
488
- $args = $task['task_args']['account_info']['mwp_amazon_s3'];
489
- $args['backup_file'] = $ftp_file;
490
- $backup_file = $this->get_amazons3_backup($args);
491
- if($backup_file == false){
492
- return array(
493
- 'error' => 'Failed to download file from Amazon S3'
494
- );
495
- }
496
- }
497
-
498
- $what = $tasks[$task_name]['task_args']['what'];
499
- }
500
-
501
- if ($backup_file && file_exists($backup_file)) {
502
-
503
- if($overwrite) {
504
- //Keep old db credentials before overwrite
505
- if(!rename(ABSPATH.'wp-config.php',ABSPATH.'mwp-temp-wp-config.php')){
506
- return array('error' => 'Error creating wp-config. Please check your write permisions.');
507
- }
508
-
509
- $db_host = DB_HOST;
510
- $db_user = DB_USER;
511
- $db_password = DB_PASSWORD;
512
- $home = get_option('home');
513
- $site_url = get_option('site_url');
514
- }
515
-
516
- if ($this->mmb_exec('which unzip')) {
517
- if($what == 'db')
518
- chdir(ABSPATH.'mwp_db/');
519
- else {
520
- chdir(ABSPATH);
521
- }
522
- $command = "unzip -o $backup_file";
523
- ob_start();
524
- $result = $this->mmb_exec($command);
525
- ob_get_clean();
526
-
527
- } else {
528
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
529
- $archive = new PclZip($backup_file);
530
- if($what == 'db'){
531
- $result = $archive->extract(PCLZIP_OPT_PATH, ABSPATH.'mwp_db/');
532
- } else {
533
- $result = $archive->extract(PCLZIP_OPT_PATH, ABSPATH);
534
- }
535
- }
536
-
537
- if($unlink_file){
538
- @unlink($backup_file);
539
- }
540
-
541
- if (!$result) {
542
- return array(
543
- 'error' => 'Error extracting backup file.'
544
- );
545
- }
546
-
547
- $db_result = $this->restore_db();
548
-
549
- if (!$db_result) {
550
- return array(
551
- 'error' => 'Error restoring database.'
552
- );
553
- }
554
-
555
-
556
-
557
- } else {
558
- return array(
559
- 'error' => 'Error restoring. Cannot find backup file.'
560
- );
561
- }
562
-
563
- //Replace options and content urls
564
- if($overwrite){
565
- //Get New Table prefix
566
- $new_table_prefix = trim($this->get_table_prefix());
567
-
568
- //Retrieve old wp_config
569
- @unlink(ABSPATH.'wp-config.php');
570
-
571
- //Replace table prefix
572
- $lines = file(ABSPATH.'mwp-temp-wp-config.php');
573
- foreach ($lines as $line) {
574
- if (strstr($line, '$table_prefix')) {
575
- $line = '$table_prefix = "'.$new_table_prefix.'";'.PHP_EOL;
576
- }
577
- file_put_contents(ABSPATH.'wp-config.php', $line, FILE_APPEND);
578
- }
579
-
580
- @unlink(ABSPATH.'mwp-temp-wp-config.php');
581
-
582
- //Replace options
583
- $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
584
- $old = $wpdb->get_var($wpdb->prepare($query));
585
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'home'";
586
- $wpdb->query($wpdb->prepare($query));
587
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'siteurl'";
588
- $wpdb->query($wpdb->prepare($query));
589
- //Replace content urls
590
- $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, '$old','$home') WHERE post_content REGEXP 'src=\"(.*)$old(.*)\"' OR post_content REGEXP 'href=\"(.*)$old(.*)\"'";
591
- $wpdb->query($wpdb->prepare($query));
592
- }
593
-
594
- return true;
595
- }
596
-
597
- function restore_db()
598
- {
599
- global $wpdb;
600
- $mysqldump = $this->check_mysqldump();
601
- $file_path = ABSPATH.'mwp_db';
602
- $file_name = glob($file_path . '/*.sql');
603
- $file_name = $file_name[0];
604
-
605
- if(is_array($mysqldump)) {
606
- $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
607
- $command = $brace . $mysqldump['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
608
-
609
- ob_start();
610
- $result = $this->mmb_exec($command);
611
- ob_get_clean();
612
- if (!$result) {
613
- //try php
614
- $this->restore_db_php($file_name);
615
- }
616
-
617
- } else {
618
- $this->restore_db_php($file_name);
619
- }
620
-
621
- @unlink($file_name);
622
- return true;
623
- }
624
-
625
- function restore_db_php($file_name)
626
- {
627
- $current_query = '';
628
- // Read in entire file
629
- $lines = file($file_name);
630
- // Loop through each line
631
- foreach ($lines as $line) {
632
- // Skip it if it's a comment
633
- if (substr($line, 0, 2) == '--' || $line == '')
634
- continue;
635
-
636
- // Add this line to the current query
637
- $current_query .= $line;
638
- // If it has a semicolon at the end, it's the end of the query
639
- if (substr(trim($line), -1, 1) == ';') {
640
- // Perform the query
641
- $result = $wpdb->query($current_query);
642
- if ($result === false)
643
- return FALSE;
644
- // Reset temp variable to empty
645
- $current_query = '';
646
- }
647
- }
648
-
649
- @unlink($file_name);
650
- return true;
651
- }
652
-
653
- function get_table_prefix()
654
- {
655
- $lines = file(ABSPATH.'wp-config.php');
656
- foreach ($lines as $line) {
657
- if (strstr($line, '$table_prefix')) {
658
- $pattern = "/(\'|\")[^(\'|\")]*/";
659
- preg_match($pattern, $line, $matches);
660
- $prefix = substr($matches[0], 1);
661
- return $prefix;
662
- break;
663
- }
664
- }
665
- return 'wp_'; //default
666
- }
667
-
668
- function optimize_tables()
669
- {
670
- global $wpdb;
671
- $query = 'SHOW TABLE STATUS FROM '. DB_NAME;
672
- $tables = $wpdb->get_results($wpdb->prepare($query),ARRAY_A);
673
- foreach ($tables as $table) {
674
- if(in_array($table['Engine'], array('MyISAM', 'ISAM', 'HEAP', 'MEMORY', 'ARCHIVE')))
675
- $table_string .= $table['Name'] . ",";
676
- elseif($table['Engine'] == 'InnoDB'){
677
- $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
678
- }
679
- }
680
-
681
- $table_string = rtrim($table_string);
682
- $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
683
-
684
- return $optimize ? true : false;
685
- }
686
-
687
- ### Function: Auto Detect MYSQL and MYSQL Dump Paths
688
- function check_mysqldump()
689
- {
690
- global $wpdb;
691
- $paths = array(
692
- 'mysq' => '',
693
- 'mysqldump' => ''
694
- );
695
- if (substr(PHP_OS, 0, 3) == 'WIN') {
696
- $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
697
- if ($mysql_install) {
698
- $install_path = str_replace('\\', '/', $mysql_install->Value);
699
- $paths['mysql'] = $install_path . 'bin/mysql.exe';
700
- $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
701
- } else {
702
- $paths['mysql'] = 'mysql.exe';
703
- $paths['mysqldump'] = 'mysqldump.exe';
704
- }
705
- } else {
706
- if ($this->check_sys()) {
707
- $paths['mysql'] = $this->mmb_exec('which mysql',true);
708
- $paths['mysqldump'] = $this->mmb_exec('which mysqldump',true);
709
- } else {
710
- $paths['mysql'] = 'mysql';
711
- $paths['mysqldump'] = 'mysqldump';
712
- }
713
- }
714
-
715
- if (!@file_exists(stripslashes($paths['mysqldump']))) {
716
- return false;
717
- }
718
- if (!@file_exists(stripslashes($paths['mysql']))) {
719
- return false;
720
- }
721
-
722
- return $paths;
723
- }
724
-
725
- //Check if exec, system, passthru functions exist
726
- function check_sys()
727
- {
728
- if (function_exists('exec'))
729
- return 'exec';
730
-
731
- if (function_exists('system'))
732
- return 'system';
733
-
734
- if (function_exists('passhtru'))
735
- return 'passthru';
736
-
737
- return false;
738
-
739
- }
740
-
741
- function mmb_exec($command,$string = false)
742
- {
743
- if($command == '')
744
- return false;
745
-
746
- if (function_exists('exec'))
747
- {
748
- $log = @exec($command,$output,$return);
749
-
750
- if($string) return $log;
751
- return $return ? false : true;
752
- }
753
- elseif(function_exists('system')){
754
- $log = @system($command,$return);
755
-
756
- if($string) return $log;
757
- return $return ? false : true;
758
- }
759
- elseif (function_exists('passthru')){
760
- $log = passthru($command,$return);
761
-
762
- return $return ? false : true;
763
- }
764
- else {
765
- return false;
766
- }
767
- }
768
-
769
- function check_backup_compat()
770
- {
771
- $reqs = array();
772
- if ( strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0 ) {
773
- $reqs['Server OS']['status'] = 'Linux (or compatible)';
774
- $reqs['Server OS']['pass'] = true;
775
- } else {
776
- $reqs['Server OS']['status'] = 'Windows';
777
- $reqs['Server OS']['pass'] = false;
778
- $pass = false;
779
- }
780
- $reqs['PHP Version']['status'] = phpversion();
781
- if ( (float) phpversion() >= 5.1 ) {
782
- $reqs['PHP Version']['pass'] = true;
783
- } else {
784
- $reqs['PHP Version']['pass'] = false;
785
- $pass = false;
786
- }
787
-
788
-
789
- if(is_writable(WP_CONTENT_DIR))
790
- {
791
- $reqs['Backup Folder']['status'] = "writable";
792
- $reqs['Backup Folder']['pass'] = true;
793
- }
794
- else
795
- {
796
- $reqs['Backup Folder']['status'] = "not writable";
797
- $reqs['Backup Folder']['pass'] = false;
798
- }
799
-
800
- $sec_string = md5('mmb-worker');
801
- $file = "/$sec_string/mwp_backups";
802
- $file_path = WP_CONTENT_DIR . $file;
803
- $reqs['Backup Folder']['status'].= ' ('.$file_path.')';
804
-
805
- if($func = $this->check_sys())
806
- {
807
- $reqs['Execute Function']['status'] =$func;
808
- $reqs['Execute Function']['pass'] = true;
809
- }
810
- else
811
- {
812
- $reqs['Execute Function']['status'] = "not found";
813
- $reqs['Execute Function']['info'] = "(will try with PHP)";
814
- $reqs['Execute Function']['pass'] = false;
815
- }
816
-
817
- if($this->mmb_exec('which zip'))
818
- {
819
- $reqs['Zip']['status'] = "enabled";
820
- $reqs['Zip']['pass'] = true;
821
- }
822
- else
823
- {
824
- $reqs['Zip']['status'] = "not found";
825
- $reqs['Zip']['info'] = "(will try with PHP pclZip class)";
826
- $reqs['Zip']['pass'] = false;
827
- }
828
-
829
- if($this->mmb_exec('which unzip'))
830
- {
831
- $reqs['Unzip']['status'] = "enabled";
832
- $reqs['Unzip']['pass'] = true;
833
- }
834
- else
835
- {
836
- $reqs['Unzip']['status'] = "not found";
837
- $reqs['Unzip']['info'] = "(will try with PHP pclZip class)";
838
- $reqs['Unzip']['pass'] = false;
839
- }
840
- if(is_array($this->check_mysqldump()))
841
- {
842
- $reqs['MySQL Dump']['status'] = "enabled";
843
- $reqs['MySQL Dump']['pass'] = true;
844
- }
845
- else
846
- {
847
- $reqs['MySQL Dump']['status'] = "not found";
848
- $reqs['MySQL Dump']['info'] = "(will try PHP)";
849
- $reqs['MySQL Dump']['pass'] = false;
850
- }
851
-
852
-
853
-
854
- return $reqs;
855
- }
856
-
857
- function email_backup($args)
858
- {
859
- $email = $args['email'];
860
- $backup_file = $args['file_path'];
861
- $task_name = isset($args['task_name']) ? $args['task_name'].' on ' : '';
862
- if(file_exists($backup_file) && $email)
863
- {
864
- $attachments = array($backup_file);
865
- $headers = 'From: ManageWP <no-reply@managewp.com>' . "\r\n";
866
- $subject = "ManageWP Backup - ".$task_name . date('F jS, y H:s');
867
- ob_start();
868
- wp_mail($email, $subject, $subject, $headers, $attachments);
869
- ob_end_clean();
870
-
871
- }
872
-
873
- }
874
-
875
- function ftp_backup($args){
876
- extract($args);
877
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
878
-
879
- if($ftp_ssl && function_exists('ftp_ssl_connect')){
880
- $conn_id = ftp_ssl_connect($ftp_hostname);
881
- }else if (function_exists('ftp_connect')){
882
- $conn_id = ftp_connect($ftp_hostname);
883
- if ($conn_id===false){
884
- $this->_log("ftp failed to connect");
885
- }
886
- }
887
- else {
888
- $this->_log("ftp not supported");
889
- }
890
-
891
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
892
- if ($login === false ) {
893
- $this->_log("failed to login");
894
- } else {
895
- $this->_log("connected to ftp");
896
- }
897
-
898
- @ftp_mkdir($conn_id, $ftp_remote_folder);
899
-
900
- $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
901
- if ($upload === false) {
902
- $this->_log("not uploaded to ftp");
903
- } else {
904
- $this->_log("ftp uploaded successfuly");
905
- }
906
- ftp_close($conn_id);
907
-
908
- }
909
-
910
- function remove_ftp_backup($args)
911
- {
912
- extract($args);
913
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
914
- if($ftp_ssl && function_exists('ftp_ssl_connect')){
915
- $conn_id = ftp_ssl_connect($ftp_hostname);
916
- $this->_log("sftp failed to connect");
917
- }else if (function_exists('ftp_connect')){
918
- $conn_id = ftp_connect($ftp_hostname);
919
- if ($conn_id===false){
920
- $this->_log("ftp failed to connect");
921
- }
922
- }
923
- else {
924
- $this->_log("ftp not supported");
925
- }
926
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
927
- if ($login === false ) {
928
- $this->_log("failed to connect");
929
- } else {
930
- $this->_log("connected");
931
- }
932
-
933
- $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
934
- if ($delete === false) {
935
- $this->_log("not deleted");
936
- } else {
937
- $this->_log("deleted successfuly");
938
- }
939
- ftp_close($conn_id);
940
-
941
- }
942
-
943
- function get_ftp_backup($args){
944
- extract($args);
945
- //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
946
- if($ftp_ssl && function_exists('ftp_ssl_connect')){
947
- $conn_id = ftp_ssl_connect($ftp_hostname);
948
- $this->_log("sftp failed to connect");
949
- }else if (function_exists('ftp_connect')){
950
- $conn_id = ftp_connect($ftp_hostname);
951
- if ($conn_id===false){
952
- return false;
953
- }
954
- }
955
- else {
956
- $this->_log("ftp not supported");
957
- }
958
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
959
- if ($login === false ) {
960
- return false;
961
- } else {
962
- $this->_log("connected");
963
- }
964
-
965
- $temp = ABSPATH.'mwp_temp_backup.zip';
966
- $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
967
- if ($get === false) {
968
- return false;
969
- } else {
970
- $this->_log("download successfuly");
971
- }
972
- ftp_close($conn_id);
973
-
974
- return $temp;
975
- }
976
-
977
- function dropbox_backup($args)
978
- {
979
- require_once('lib/dropbox.php');
980
- extract($args);
981
-
982
- //$email, $password, $backup_file, $destination
983
- try{
984
- $uploader = new DropboxUploader($dropbox_username, $dropbox_password);
985
- $uploader->upload($backup_file, $dropbox_destination);
986
- } catch (Exception $e){
987
- $this->_log($e->getMessage());
988
- }
989
- }
990
-
991
- function amazons3_backup($args)
992
- {
993
- require_once('lib/s3.php');
994
- extract($args);
995
-
996
- $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
997
-
998
- $s3->putBucket( $as3_bucket, S3::ACL_PUBLIC_READ );
999
-
1000
- if ( $s3->putObjectFile( $backup_file, $as3_bucket, $as3_directory .'/'. basename($backup_file), S3::ACL_PRIVATE) ) {
1001
- return array('success' => 'ok');
1002
- } else {
1003
- return array('success' => 'error');
1004
- }
1005
-
1006
- }
1007
-
1008
- function remove_amazons3_backup($args)
1009
- {
1010
- require_once('lib/s3.php');
1011
- extract($args);
1012
- $this->_log("delete");
1013
- $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
1014
- $s3->deleteObject($as3_bucket,$as3_directory.'/'. $backup_file);
1015
- }
1016
-
1017
- function get_amazons3_backup($args)
1018
- {
1019
- require_once('lib/s3.php');
1020
- extract($args);
1021
- $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
1022
- $s3->deleteObject($as3_bucket,$as3_directory.'/'. $backup_file);
1023
- $s3->getObject($as3_bucket, $as3_directory.'/'. $backup_file, $temp);
1024
- $temp = ABSPATH.'mwp_temp_backup.zip';
1025
- return $temp;
1026
- }
1027
-
1028
- function schedule_next($type,$schedule)
1029
- {
1030
-
1031
- $schedule = explode("|", $schedule);
1032
- if(empty($schedule))
1033
- return false;
1034
- switch($type){
1035
-
1036
- case 'daily':
1037
-
1038
- if($schedule[1]) { $delay_time = $schedule[1] * 60;}
1039
-
1040
- $current_hour = date("H");
1041
- $schedule_hour = $schedule[0];
1042
- if($current_hour >= $schedule_hour)
1043
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+1, date("Y"));
1044
- else
1045
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1046
- break;
1047
-
1048
-
1049
- case 'weekly':
1050
- if($schedule[2]) { $delay_time = $schedule[2] * 60;}
1051
- $current_weekday = date('w');
1052
- $schedule_weekday = $schedule[1];
1053
- $current_hour = date("H");
1054
- $schedule_hour = $schedule[0];
1055
-
1056
- if($current_weekday > $schedule_weekday)
1057
- $weekday_offset = 7 - ($week_day - $task_schedule[1]);
1058
- else
1059
- $weekday_offset = $schedule_weekday - $current_weekday;
1060
-
1061
-
1062
- if(!$weekday_offset){ //today is scheduled weekday
1063
- if($current_hour >= $schedule_hour)
1064
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+7, date("Y"));
1065
- else
1066
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1067
- } else {
1068
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+ $weekday_offset, date("Y"));
1069
- }
1070
-
1071
- break;
1072
-
1073
- case 'monthly':
1074
- if($schedule[2]) { $delay_time = $schedule[2] * 60;}
1075
- $current_monthday = date('j');
1076
- $schedule_monthday = $schedule[1];
1077
- $current_hour = date("H");
1078
- $schedule_hour = $schedule[0];
1079
-
1080
- if($current_monthday > $schedule_monthday){
1081
- $time = mktime($schedule_hour, 0, 0, date("m")+1, $schedule_monthday, date("Y"));
1082
- } else if($current_monthday < $schedule_monthday) {
1083
-
1084
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1085
- }
1086
- else if($current_monthday == $schedule_monthday) {
1087
- if($current_hour >= $schedule_hour)
1088
- $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
1089
- else
1090
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1091
- break;
1092
- }
1093
-
1094
- break;
1095
- default: break;
1096
- }
1097
-
1098
- if($delay_time) {$time += $delay_time; }
1099
-
1100
- return $time;
1101
-
1102
- }
1103
-
1104
- //Parse task arguments for info on master
1105
- function get_backup_stats()
1106
- {
1107
- $stats = array();
1108
- $tasks = get_option('mwp_backup_tasks');
1109
- if(is_array($tasks) && !empty($tasks)) {
1110
- foreach($tasks as $task_name => $info)
1111
- {
1112
- $stats[$task_name] = $info['task_results'];
1113
- }
1114
- }
1115
- return $stats;
1116
- }
1117
-
1118
- function remove_old_backups($task_name){
1119
- $backups = $this->get_backup_settings();
1120
- if(count($backups[$task_name]['task_results']) >= $backups[$task_name]['task_args']['limit']) {
1121
- // ? how many to remove
1122
- $remove_num = (count($backups[$task_name]['task_results']) - $backups[$task_name]['task_args']['limit']) + 1;
1123
-
1124
- for($i = 0; $i < $remove_num; $i++){
1125
- if(!isset($backups[$task_name]['task_results'][$i]['error'])) {
1126
-
1127
- //Remove from the server
1128
- if(isset($backups[$task_name]['task_results'][$i]['server'])){
1129
- @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
1130
- }
1131
-
1132
- //Remove from ftp
1133
- if(isset($backups[$task_name]['task_results'][$i]['ftp'])){
1134
- $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
1135
- $args = $backups[$task_name]['task_args']['account_info']['mwp_ftp'];
1136
- $args['backup_file'] = $ftp_file;
1137
- $this->remove_ftp_backup($args);
1138
- }
1139
-
1140
- if(isset($backups[$task_name]['task_results'][$i]['amazons3'])){
1141
- $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
1142
- $args = $backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
1143
- $args['backup_file'] = $amazons3_file;
1144
- $this->remove_amazons3_backup($args);
1145
- }
1146
-
1147
- if(isset($backups[$task_name]['task_results'][$i]['dropbox'])){
1148
-
1149
- }
1150
-
1151
- }
1152
- //Remove database backup info
1153
- unset($backups[$task_name]['task_results'][$i]);
1154
- update_option('mwp_backup_tasks',$backups);
1155
-
1156
- }//end foreach
1157
- }
1158
- }
1159
-
1160
- /**
1161
- * Delete specified backup
1162
- * Args: $task_name, $result_id
1163
- */
1164
-
1165
- function delete_backup($args){
1166
- if(empty($args))
1167
- return false;
1168
- extract($args);
1169
-
1170
- $tasks = $this->get_backup_settings();
1171
- $task = $tasks[$task_name];
1172
- $backups = $task['task_results'];
1173
- $backup = $backups[$result_id];
1174
-
1175
- if(isset($backup['server'])){
1176
- @unlink($backup['server']['file_path']);
1177
- }
1178
-
1179
- //Remove from ftp
1180
- if(isset($backup['ftp'])){
1181
- $ftp_file = $backup['ftp'];
1182
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_ftp'];
1183
- $args['backup_file'] = $ftp_file;
1184
- $this->remove_ftp_backup($args);
1185
- }
1186
-
1187
- if(isset($backup['amazons3'])){
1188
- $amazons3_file = $backup['amazons3'];
1189
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
1190
- $args['backup_file'] = $amazons3_file;
1191
- $this->remove_amazons3_backup($args);
1192
- }
1193
-
1194
- if(isset($backup['dropbox'])){
1195
-
1196
- }
1197
-
1198
- unset($backups[$result_id]);
1199
-
1200
- if(count($backups)){
1201
- $tasks[$task_name]['task_results'] = $backups;
1202
- } else {
1203
- unset($tasks[$task_name]['task_results']);
1204
- }
1205
-
1206
- update_option('mwp_backup_tasks',$tasks);
1207
- return true;
1208
-
1209
- }
1210
-
1211
- function cleanup()
1212
- {
1213
- $tasks = $this->get_backup_settings();
1214
- $backup_folder = WP_CONTENT_DIR.'/'.md5('mmb-worker').'/mwp_backups/';
1215
- $files = glob($backup_folder."*.*");
1216
- if(count($files)){
1217
- $results = array();
1218
- if(count($tasks)){
1219
- foreach($tasks as $task){
1220
- if(isset($task['task_results']) && count($task['task_results'])) {
1221
- foreach($task['task_results'] as $backup) {
1222
- if(isset($backup['server'])) {
1223
- $results[] = $backup['server']['file_path'];
1224
- }
1225
- }
1226
- }
1227
- }
1228
- }
1229
-
1230
- $num_deleted = 0;
1231
- foreach($files as $file){
1232
- if(!in_array($file,$results)) {
1233
- @unlink($file);
1234
- $num_deleted++;
1235
- }
1236
- }
1237
- }
1238
- }
1239
-
1240
- }
1241
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1242
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * backup.class.php
5
+ *
6
+ * Manage Backups
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Backup extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ parent::__construct();
18
+ }
19
+
20
+ function get_backup_settings()
21
+ {
22
+ $backup_settings = get_option('mwp_backup_tasks');
23
+ if(!empty($backup_settings))
24
+ return $backup_settings;
25
+ else
26
+ return false;
27
+ }
28
+
29
+ function set_backup_task($params)
30
+ {
31
+ //$params => [$task_name, $args, $error]
32
+ if(!empty($params)){
33
+ extract($params);
34
+
35
+ $before = $this->get_backup_settings();
36
+ if(!$before || empty($before))
37
+ $before = array();
38
+
39
+ if(isset($args['remove'])){
40
+ unset($before[$task_name]);
41
+ $return = array('removed' => true);
42
+ } else {
43
+ $args['account_info'] = $account_info;
44
+ $before[$task_name]['task_args'] = $args;
45
+
46
+ if(!empty($args['schedule']))
47
+ $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'],$args['schedule']);
48
+
49
+ $return = $before[$task_name];
50
+ }
51
+
52
+ if($error){
53
+ $before[$task_name]['task_results'][count($before[$task_name]['task_results'])] = array('error' => $error);
54
+ }
55
+ update_option('mwp_backup_tasks',$before);
56
+
57
+ if($task_name == 'Backup Now'){
58
+ $result = $this->backup($args, $task_name);
59
+ $backup_settings = $this->get_backup_settings();
60
+ if(is_array($result) && array_key_exists('error',$result)){
61
+ $return = $result;
62
+ } else {
63
+ $return = $backup_settings[$task_name];
64
+ }
65
+ }
66
+ return $return;
67
+ }
68
+ return false;
69
+ }
70
+
71
+ //Cron check
72
+ function check_backup_tasks()
73
+ {
74
+ $settings = $this->get_backup_settings();
75
+ if(is_array($settings) && !empty($settings)){
76
+ foreach($settings as $task_name => $setting){
77
+ if($setting['task_args']['next'] && $setting['task_args']['next'] < time()){
78
+ $result = $this->backup($setting['task_args'], $task_name);
79
+
80
+ if(is_array($result) && array_key_exists('error', $result)){
81
+ $error = $result['error'];
82
+ } else {
83
+ $error = '';
84
+ }
85
+
86
+ //Update task with next schedule and possible error
87
+ $this->set_backup_task(array('task_name' => $task_name, 'args' => $settings[$task_name]['task_args'], 'error' => $error)); //Update
88
+ break;
89
+ }
90
+ }
91
+ }
92
+
93
+ }
94
+
95
+
96
+
97
+ /*
98
+ * If Task Name not set then it's manual backup
99
+ * Backup args:
100
+ * type -> db, full
101
+ * what -> daily, weekly, monthly
102
+ * account_info -> ftp, amazons3, dropbox
103
+ * exclude-> array of paths to exclude from backup
104
+ */
105
+
106
+ function backup($args, $task_name = false){
107
+
108
+ if(!$args || empty($args))
109
+ return false;
110
+
111
+
112
+
113
+ extract($args); //extract settings
114
+
115
+
116
+ //try increase memory limit
117
+ @ini_set('memory_limit', '1000M');
118
+ @set_time_limit(600); //ten minutes
119
+
120
+ //Remove old backup(s)
121
+ if($type == 'manual'){
122
+ $old = get_option('mwp_manual_backup');
123
+ if($old['file_path'] && file_exists($old['file_path']))
124
+ @unlink($old['file_path']);
125
+ } else {
126
+ $this->remove_old_backups($task_name);
127
+ }
128
+
129
+ $sec_string = md5('mmb-worker');
130
+ $file = "/$sec_string/mwp_backups";
131
+ $new_file_path = WP_CONTENT_DIR . $file;
132
+
133
+ if (!file_exists($new_file_path)) {
134
+ if (!mkdir($new_file_path, 0755, true))
135
+ return array(
136
+ 'error' => 'Permission denied, make sure you have write permission to wp-content folder.'
137
+ );
138
+ }
139
+
140
+ @file_put_contents($new_file_path . '/index.php', ''); //safe
141
+ //Delete possible breaked previous backups - don't need it anymore (works only for previous wrokers)
142
+ foreach (glob($new_file_path."/*.zip") as $filename) {
143
+ $short = basename($filename);
144
+ preg_match('/^wp\-content(.*)/Ui',$short,$matches);
145
+ if($matches)
146
+ @unlink($filename);
147
+ }
148
+
149
+ //Prepare .zip file name
150
+ $site_name = $this->remove_http(get_bloginfo('url'));
151
+ $site_name = str_replace(array(
152
+ "_",
153
+ "/"
154
+ ), array(
155
+ "",
156
+ "-"
157
+ ), $site_name);
158
+
159
+ $hash = md5(time());
160
+ $label = $type ? $type : 'manual';
161
+ $backup_file = $new_file_path . '/' . $site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') .'_'.$hash. '.zip';
162
+ $backup_url = WP_CONTENT_URL . $file . '/' . $site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') .'_'.$hash. '.zip';
163
+
164
+
165
+ //What to backup - db or full
166
+ if (trim($what) == 'db') {
167
+ //take database backup
168
+
169
+ $db_result = $this->backup_db();
170
+ if($db_result == false){
171
+ return array('error' => 'Failed to backup database.');
172
+ }
173
+ else if(is_array($db_result) && isset($db_result['error']))
174
+ {
175
+ return array('error' => $db_result['error']);
176
+
177
+ }else
178
+ {
179
+ if ($this->mmb_exec('which zip')) {
180
+ chdir(WP_CONTENT_DIR);
181
+ $command = "zip -r $backup_file 'mwp_db'";
182
+ $this->_log($command);
183
+ ob_start();
184
+ $result = $this->mmb_exec($command);
185
+ ob_get_clean();
186
+ } else {
187
+ require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
188
+ $archive = new PclZip($backup_file);
189
+ $result = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, WP_CONTENT_DIR);
190
+ }
191
+
192
+ @unlink($db_result);
193
+ if(!$result)
194
+ return array(
195
+ 'error' => 'Failed to zip database.'
196
+ );
197
+ }
198
+ }
199
+ elseif (trim($what) == 'full') {
200
+ $content_backup = $this->backup_full($backup_file,$exclude);
201
+ if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
202
+ return array(
203
+ 'error' => $content_backup['error']
204
+ );
205
+ }
206
+ }
207
+
208
+ //Update backup info
209
+ if($task_name){
210
+ //backup task (scheduled)
211
+ $backup_settings = $this->get_backup_settings();
212
+ $paths = array();
213
+ $size = ceil(filesize($backup_file) / 1024);
214
+
215
+ if($size > 1000){
216
+ $paths['size'] = ceil($size / 1024).'Mb';
217
+ } else {
218
+ $paths['size'] = $size.'kb';
219
+ }
220
+ $paths['time'] = time();
221
+
222
+ if($task_name != 'Backup Now') {
223
+ if(!$backup_settings[$task_name]['task_args']['del_host_file']){
224
+ $paths['server'] = array('file_path' => $backup_file, 'file_url' => $backup_url);
225
+ }
226
+ } else
227
+ {
228
+ $paths['server'] = array('file_path' => $backup_file, 'file_url' => $backup_url);
229
+ }
230
+
231
+ if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_ftp'])) {
232
+ $paths['ftp'] = basename($backup_url);
233
+ }
234
+
235
+ if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
236
+ $paths['amazons3'] = basename($backup_url);
237
+ }
238
+
239
+ if(isset($backup_settings[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
240
+ $paths['dropbox'] = basename($backup_url);
241
+ }
242
+
243
+ if($backup_settings[$task_name]['task_args']['email_backup']) {
244
+ $paths['email'] = $backup_settings[$task_name]['task_args']['email_backup'];
245
+ }
246
+
247
+ $temp = $backup_settings[$task_name]['task_results'];
248
+ $temp['temp'] = $paths;
249
+ $backup_settings[$task_name]['task_results'] = array_values($temp);
250
+ update_option ('mwp_backup_tasks',$backup_settings);
251
+ }
252
+ else
253
+ {
254
+ //manual - predefined backup used for cloning
255
+ $manual_backup = $args;
256
+ $manual_backup ['file_path'] = $backup_file;
257
+ $manual_backup ['file_url'] = $backup_url;
258
+ update_option('mwp_manual_backup', $manual_backup);
259
+ }
260
+
261
+
262
+ //Additional: Email, ftp, amazon_s3, dropbox...
263
+ if(isset($optimize_tables) && !empty($optimize_tables)){
264
+ $this->optimize_tables();
265
+ }
266
+
267
+ if($task_name != 'Backup Now'){
268
+ if(isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])){
269
+ $account_info['mwp_ftp']['backup_file'] = $backup_file;
270
+ $this->ftp_backup($account_info['mwp_ftp']);
271
+ }
272
+
273
+ if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])){
274
+ $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
275
+ $this->amazons3_backup($account_info['mwp_amazon_s3']);
276
+ }
277
+
278
+ if(isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])){
279
+ $account_info['mwp_dropbox']['backup_file'] = $backup_file;
280
+ $this->dropbox_backup($account_info['mwp_dropbox']);
281
+ }
282
+
283
+ if(isset($email_backup) && is_email($email_backup)){
284
+ $mail_args = array(
285
+ 'email' => $email_backup,
286
+ 'task_name' => $task_name,
287
+ 'file_path' => $backup_file
288
+ );
289
+ $this->email_backup($mail_args);
290
+ }
291
+
292
+ if($del_host_file){
293
+ @unlink($backup_file);
294
+ }
295
+
296
+ } //end additional
297
+
298
+ return $backup_url; //Return url to backup file (we need return only for manual backup)
299
+ }
300
+
301
+ function backup_full($backup_file, $exclude = array())
302
+ {
303
+ $db_result = $this->backup_db();
304
+ if($db_result == false){
305
+ return array('error' => 'Failed to backup database.');
306
+ }else if(is_array($db_result) && isset($db_result['error'])){
307
+ return array('error' => $db_result['error']);
308
+ }
309
+
310
+ $sec_string = md5('mmb-worker');
311
+ $remove = array("wp-content/$sec_string/mwp_backups","wp-content/mwp_db");
312
+
313
+ if ($this->mmb_exec('which zip')) {
314
+ chdir(ABSPATH);
315
+
316
+ //exclude paths
317
+ $exclude_data = "-x";
318
+ if(!empty($exclude)){
319
+ foreach($exclude as $data){
320
+ if($data)
321
+ $exclude_data .= " '$data/*'";
322
+ }
323
+ }
324
+
325
+ foreach($remove as $data){
326
+ $exclude_data .= " '$data/*'";
327
+ }
328
+
329
+ $command = "zip -r $backup_file './' $exclude_data";
330
+ ob_start();
331
+ $result = $this->mmb_exec($command);
332
+ ob_get_clean();
333
+
334
+ //Add database file
335
+ chdir(WP_CONTENT_DIR);
336
+ $command = "zip -r $backup_file 'mwp_db'";
337
+ ob_start();
338
+ $result = $this->mmb_exec($command);
339
+ ob_get_clean();
340
+
341
+ @unlink($db_result);
342
+
343
+ if($result){
344
+ return true;
345
+ }
346
+ else{
347
+ return array('error' => 'Failed to backup site.');
348
+ }
349
+
350
+ }
351
+ else { //php zip
352
+
353
+ require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
354
+ $archive = new PclZip($backup_file);
355
+ $result = $archive->add(ABSPATH, PCLZIP_OPT_REMOVE_PATH, ABSPATH);
356
+ $result = $archive->add($db_result, PCLZIP_OPT_REMOVE_PATH, WP_CONTENT_DIR);
357
+ $exclude_data = array();
358
+ if(!empty($exclude) && $result){
359
+ $exclude_data = array();
360
+ foreach($exclude as $data){
361
+ if($data)
362
+ $exclude_data [] = $data.'/';
363
+ }
364
+ }
365
+ foreach($remove as $rem){
366
+ $exclude_data[] = $rem.'/';
367
+ }
368
+
369
+ $result = $archive->delete(PCLZIP_OPT_BY_NAME, $exclude_data);
370
+
371
+ @unlink($db_result);
372
+ if ($result) {
373
+ return true;
374
+ }
375
+ else {
376
+ if($archive->error_code == '-10'){
377
+ return array('error' => 'Failed to backup site. Try increasing memory limit and/or free space on your server.');
378
+ }
379
+ else{
380
+ return array('error' => 'Failed to backup site. Try to enable Zip on your server.');
381
+ }
382
+ }
383
+ }
384
+ }
385
+
386
+
387
+ function backup_db()
388
+ {
389
+ $db_folder = ABSPATH.'wp-content/mwp_db/';
390
+ if (!file_exists($db_folder)) {
391
+ if (!mkdir($db_folder, 0755, true))
392
+ return array(
393
+ 'error' => 'Error creating database backup folder. Make sure you have write permissions to your site root folder.'
394
+ );
395
+ }
396
+
397
+ $file = $db_folder . DB_NAME . '.sql';
398
+ $mysqldump = $this->check_mysqldump();
399
+ if (is_array($mysqldump)) {
400
+ $result = $this->backup_db_dump($file,$mysqldump);
401
+
402
+ } else {
403
+ $result = $this->backup_db_php($file);
404
+ }
405
+ return $result;
406
+ }
407
+
408
+ function backup_db_dump($file,$mysqldump)
409
+ {
410
+ global $wpdb;
411
+ $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
412
+ $command = $brace . $mysqldump['mysqldump'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
413
+
414
+ ob_start();
415
+ $result = $this->mmb_exec($command);
416
+ ob_get_clean();
417
+ if (!$result) {
418
+ $result = $this->backup_db_php($file);
419
+ return $result;
420
+ }
421
+
422
+ if (filesize($file) == 0 || !is_file($file) || !$result) {
423
+ @unlink($file);
424
+ return false;
425
+ } else {
426
+ return $file;
427
+ }
428
+ }
429
+
430
+ function backup_db_php($file)
431
+ {
432
+ global $wpdb;
433
+ $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
434
+ foreach ($tables as $table) {
435
+ //drop existing table
436
+ $dump_data = "DROP TABLE IF EXISTS $table[0];";
437
+ //create table
438
+ $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
439
+ $dump_data .= "\n\n" . $create_table[1] . ";\n\n";
440
+
441
+ $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
442
+ if ($count > 100)
443
+ $count = ceil($count / 100) - 1;
444
+ else
445
+ $count = 1;
446
+ for ($i = 0; $i < $count; $i++) {
447
+ $low_limit = $i * 100;
448
+ $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
449
+ $rows = $wpdb->get_results($qry, ARRAY_A);
450
+ if (is_array($rows)) {
451
+ foreach ($rows as $row) {
452
+ //insert single row
453
+ $dump_data .= "INSERT INTO $table[0] VALUES(";
454
+ $num_values = count($row);
455
+ $j = 1;
456
+ foreach ($row as $value) {
457
+ $value = addslashes($value);
458
+ $value = preg_replace("/\n/Ui", "\\n", $value);
459
+ $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
460
+ $j++;
461
+ unset($value);
462
+ }
463
+ $dump_data .= ");\n";
464
+ }
465
+ }
466
+ }
467
+ $dump_data .= "\n\n\n";
468
+
469
+ unset($rows);
470
+ file_put_contents($file, $dump_data, FILE_APPEND);
471
+ unset($dump_data);
472
+ }
473
+
474
+ if (filesize($file) == 0 || !is_file($file)) {
475
+ @unlink($file);
476
+ return false;
477
+ }
478
+
479
+ return $file;
480
+
481
+ }
482
+
483
+ function restore($args)
484
+ {
485
+ global $wpdb;
486
+ if(empty($args)) {return false;}
487
+
488
+ extract($args);
489
+ @ini_set('memory_limit', '300M');
490
+ @set_time_limit(300);
491
+
492
+ $unlink_file = true; //Delete file after restore
493
+
494
+ //Detect source
495
+ if($backup_url){
496
+ //This is for clone (overwrite)
497
+ include_once ABSPATH . 'wp-admin/includes/file.php';
498
+ $backup_file = download_url($backup_url);
499
+ if(is_wp_error($backup_file)){
500
+ return array(
501
+ 'error' => $backup_file->get_error_message()
502
+ );
503
+ }
504
+ $what = 'full';
505
+ } else {
506
+ $tasks = $this->get_backup_settings();
507
+ $task = $tasks[$task_name];
508
+ if(isset($task['task_results'][$result_id]['server'])) {
509
+ $backup_file = $task['task_results'][$result_id]['server']['file_path'];
510
+ $unlink_file = false; //Don't delete file if stored on server
511
+ }elseif(isset($task['task_results'][$result_id]['ftp'])){
512
+ $ftp_file = $task['task_results'][$result_id]['ftp'];
513
+ $args = $task['task_args']['account_info']['mwp_ftp'];
514
+ $args['backup_file'] = $ftp_file;
515
+ $backup_file = $this->get_ftp_backup($args);
516
+ if($backup_file == false){
517
+ return array(
518
+ 'error' => 'Failed to download file from FTP'
519
+ );
520
+ }
521
+ }elseif(isset($task['task_results'][$result_id]['amazons3'])){
522
+ $amazons3_file = $task['task_results'][$result_id]['amazons3'];
523
+ $args = $task['task_args']['account_info']['mwp_amazon_s3'];
524
+ $args['backup_file'] = $ftp_file;
525
+ $backup_file = $this->get_amazons3_backup($args);
526
+ if($backup_file == false){
527
+ return array(
528
+ 'error' => 'Failed to download file from Amazon S3'
529
+ );
530
+ }
531
+ }
532
+
533
+ $what = $tasks[$task_name]['task_args']['what'];
534
+ }
535
+
536
+ if ($backup_file && file_exists($backup_file)) {
537
+
538
+ if($overwrite) {
539
+ //Keep old db credentials before overwrite
540
+ if(!rename(ABSPATH.'wp-config.php',ABSPATH.'mwp-temp-wp-config.php')){
541
+ return array('error' => 'Error creating wp-config. Please check your write permisions.');
542
+ }
543
+
544
+ $db_host = DB_HOST;
545
+ $db_user = DB_USER;
546
+ $db_password = DB_PASSWORD;
547
+ $home = get_option('home');
548
+ $site_url = get_option('site_url');
549
+ }
550
+
551
+ if ($this->mmb_exec('which unzip')) {
552
+
553
+ chdir(ABSPATH);
554
+ $command = "unzip -o $backup_file";
555
+ ob_start();
556
+ $result = $this->mmb_exec($command);
557
+ ob_get_clean();
558
+
559
+ } else {
560
+ require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
561
+ $archive = new PclZip($backup_file);
562
+ $result = $archive->extract(PCLZIP_OPT_PATH, ABSPATH);
563
+ }
564
+
565
+ if($unlink_file){
566
+ @unlink($backup_file);
567
+ }
568
+
569
+ if (!$result) {
570
+ return array(
571
+ 'error' => 'Error extracting backup file.'
572
+ );
573
+ }
574
+
575
+ $db_result = $this->restore_db();
576
+
577
+ if (!$db_result) {
578
+ return array(
579
+ 'error' => 'Error restoring database.'
580
+ );
581
+ }
582
+
583
+
584
+
585
+ } else {
586
+ return array(
587
+ 'error' => 'Error restoring. Cannot find backup file.'
588
+ );
589
+ }
590
+
591
+ //Replace options and content urls
592
+ if($overwrite){
593
+ //Get New Table prefix
594
+ $new_table_prefix = trim($this->get_table_prefix());
595
+
596
+ //Retrieve old wp_config
597
+ @unlink(ABSPATH.'wp-config.php');
598
+
599
+ //Replace table prefix
600
+ $lines = file(ABSPATH.'mwp-temp-wp-config.php');
601
+ foreach ($lines as $line) {
602
+ if (strstr($line, '$table_prefix')) {
603
+ $line = '$table_prefix = "'.$new_table_prefix.'";'.PHP_EOL;
604
+ }
605
+ file_put_contents(ABSPATH.'wp-config.php', $line, FILE_APPEND);
606
+ }
607
+
608
+ @unlink(ABSPATH.'mwp-temp-wp-config.php');
609
+
610
+ //Replace options
611
+ $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
612
+ $old = $wpdb->get_var($wpdb->prepare($query));
613
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'home'";
614
+ $wpdb->query($wpdb->prepare($query));
615
+ $query = "UPDATE " . $new_table_prefix . "options SET option_value = '$home' WHERE option_name = 'siteurl'";
616
+ $wpdb->query($wpdb->prepare($query));
617
+ //Replace content urls
618
+ $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, '$old','$home') WHERE post_content REGEXP 'src=\"(.*)$old(.*)\"' OR post_content REGEXP 'href=\"(.*)$old(.*)\"'";
619
+ $wpdb->query($wpdb->prepare($query));
620
+ }
621
+
622
+ return true;
623
+ }
624
+
625
+ function restore_db()
626
+ {
627
+ global $wpdb;
628
+ $mysqldump = $this->check_mysqldump();
629
+ $file_path = ABSPATH.'mwp_db';
630
+ $file_name = glob($file_path . '/*.sql');
631
+ $file_name = $file_name[0];
632
+
633
+ if(is_array($mysqldump)) {
634
+ $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
635
+ $command = $brace . $mysqldump['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" ' . DB_NAME . ' < ' . $brace . $file_name . $brace;
636
+
637
+ ob_start();
638
+ $result = $this->mmb_exec($command);
639
+ ob_get_clean();
640
+ if (!$result) {
641
+ //try php
642
+ $this->restore_db_php($file_name);
643
+ }
644
+
645
+ } else {
646
+ $this->restore_db_php($file_name);
647
+ }
648
+
649
+ @unlink($file_name);
650
+ return true;
651
+ }
652
+
653
+ function restore_db_php($file_name)
654
+ {
655
+ $current_query = '';
656
+ // Read in entire file
657
+ $lines = file($file_name);
658
+ // Loop through each line
659
+ foreach ($lines as $line) {
660
+ // Skip it if it's a comment
661
+ if (substr($line, 0, 2) == '--' || $line == '')
662
+ continue;
663
+
664
+ // Add this line to the current query
665
+ $current_query .= $line;
666
+ // If it has a semicolon at the end, it's the end of the query
667
+ if (substr(trim($line), -1, 1) == ';') {
668
+ // Perform the query
669
+ $result = $wpdb->query($current_query);
670
+ if ($result === false)
671
+ return FALSE;
672
+ // Reset temp variable to empty
673
+ $current_query = '';
674
+ }
675
+ }
676
+
677
+ @unlink($file_name);
678
+ return true;
679
+ }
680
+
681
+ function get_table_prefix()
682
+ {
683
+ $lines = file(ABSPATH.'wp-config.php');
684
+ foreach ($lines as $line) {
685
+ if (strstr($line, '$table_prefix')) {
686
+ $pattern = "/(\'|\")[^(\'|\")]*/";
687
+ preg_match($pattern, $line, $matches);
688
+ $prefix = substr($matches[0], 1);
689
+ return $prefix;
690
+ break;
691
+ }
692
+ }
693
+ return 'wp_'; //default
694
+ }
695
+
696
+ function optimize_tables()
697
+ {
698
+ global $wpdb;
699
+ $query = 'SHOW TABLE STATUS FROM '. DB_NAME;
700
+ $tables = $wpdb->get_results($wpdb->prepare($query),ARRAY_A);
701
+ foreach ($tables as $table) {
702
+ if(in_array($table['Engine'], array('MyISAM', 'ISAM', 'HEAP', 'MEMORY', 'ARCHIVE')))
703
+ $table_string .= $table['Name'] . ",";
704
+ elseif($table['Engine'] == 'InnoDB'){
705
+ $optimize = $wpdb->query("ALTER TABLE {$table['Name']} ENGINE=InnoDB");
706
+ }
707
+ }
708
+
709
+ $table_string = rtrim($table_string);
710
+ $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
711
+
712
+ return $optimize ? true : false;
713
+ }
714
+
715
+ ### Function: Auto Detect MYSQL and MYSQL Dump Paths
716
+ function check_mysqldump()
717
+ {
718
+ global $wpdb;
719
+ $paths = array(
720
+ 'mysq' => '',
721
+ 'mysqldump' => ''
722
+ );
723
+ if (substr(PHP_OS, 0, 3) == 'WIN') {
724
+ $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
725
+ if ($mysql_install) {
726
+ $install_path = str_replace('\\', '/', $mysql_install->Value);
727
+ $paths['mysql'] = $install_path . 'bin/mysql.exe';
728
+ $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
729
+ } else {
730
+ $paths['mysql'] = 'mysql.exe';
731
+ $paths['mysqldump'] = 'mysqldump.exe';
732
+ }
733
+ } else {
734
+ if ($this->check_sys()) {
735
+ $paths['mysql'] = $this->mmb_exec('which mysql',true);
736
+ $paths['mysqldump'] = $this->mmb_exec('which mysqldump',true);
737
+ } else {
738
+ $paths['mysql'] = 'mysql';
739
+ $paths['mysqldump'] = 'mysqldump';
740
+ }
741
+ }
742
+
743
+ if (!@file_exists(stripslashes($paths['mysqldump']))) {
744
+ return false;
745
+ }
746
+ if (!@file_exists(stripslashes($paths['mysql']))) {
747
+ return false;
748
+ }
749
+
750
+ return $paths;
751
+ }
752
+
753
+ //Check if exec, system, passthru functions exist
754
+ function check_sys()
755
+ {
756
+ if ($this->mmb_function_exists('exec'))
757
+ return 'exec';
758
+
759
+ if ($this->mmb_function_exists('system'))
760
+ return 'system';
761
+
762
+ if ($this->mmb_function_exists('passhtru'))
763
+ return 'passthru';
764
+
765
+ return false;
766
+
767
+ }
768
+
769
+ function mmb_exec($command,$string = false)
770
+ {
771
+ if($command == '')
772
+ return false;
773
+
774
+ if ($this->mmb_function_exists('exec'))
775
+ {
776
+ $log = @exec($command,$output,$return);
777
+
778
+ if($string) return $log;
779
+ return $return ? false : true;
780
+ }
781
+ elseif($this->mmb_function_exists('system')){
782
+ $log = @system($command,$return);
783
+
784
+ if($string) return $log;
785
+ return $return ? false : true;
786
+ }
787
+ elseif ($this->mmb_function_exists('passthru')){
788
+ $log = passthru($command,$return);
789
+
790
+ return $return ? false : true;
791
+ }
792
+ else {
793
+ return false;
794
+ }
795
+ }
796
+
797
+ function check_backup_compat()
798
+ {
799
+ $reqs = array();
800
+ if ( strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0 ) {
801
+ $reqs['Server OS']['status'] = 'Linux (or compatible)';
802
+ $reqs['Server OS']['pass'] = true;
803
+ } else {
804
+ $reqs['Server OS']['status'] = 'Windows';
805
+ $reqs['Server OS']['pass'] = false;
806
+ $pass = false;
807
+ }
808
+ $reqs['PHP Version']['status'] = phpversion();
809
+ if ( (float) phpversion() >= 5.1 ) {
810
+ $reqs['PHP Version']['pass'] = true;
811
+ } else {
812
+ $reqs['PHP Version']['pass'] = false;
813
+ $pass = false;
814
+ }
815
+
816
+
817
+ if(is_writable(WP_CONTENT_DIR))
818
+ {
819
+ $reqs['Backup Folder']['status'] = "writable";
820
+ $reqs['Backup Folder']['pass'] = true;
821
+ }
822
+ else
823
+ {
824
+ $reqs['Backup Folder']['status'] = "not writable";
825
+ $reqs['Backup Folder']['pass'] = false;
826
+ }
827
+
828
+ $sec_string = md5('mmb-worker');
829
+ $file = "/$sec_string/mwp_backups";
830
+ $file_path = WP_CONTENT_DIR . $file;
831
+ $reqs['Backup Folder']['status'].= ' ('.$file_path.')';
832
+
833
+ if($func = $this->check_sys())
834
+ {
835
+ $reqs['Execute Function']['status'] =$func;
836
+ $reqs['Execute Function']['pass'] = true;
837
+ }
838
+ else
839
+ {
840
+ $reqs['Execute Function']['status'] = "not found";
841
+ $reqs['Execute Function']['info'] = "(will try with PHP)";
842
+ $reqs['Execute Function']['pass'] = false;
843
+ }
844
+
845
+ if($this->mmb_exec('which zip'))
846
+ {
847
+ $reqs['Zip']['status'] = "enabled";
848
+ $reqs['Zip']['pass'] = true;
849
+ }
850
+ else
851
+ {
852
+ $reqs['Zip']['status'] = "not found";
853
+ $reqs['Zip']['info'] = "(will try with PHP pclZip class)";
854
+ $reqs['Zip']['pass'] = false;
855
+ }
856
+
857
+ if($this->mmb_exec('which unzip'))
858
+ {
859
+ $reqs['Unzip']['status'] = "enabled";
860
+ $reqs['Unzip']['pass'] = true;
861
+ }
862
+ else
863
+ {
864
+ $reqs['Unzip']['status'] = "not found";
865
+ $reqs['Unzip']['info'] = "(will try with PHP pclZip class)";
866
+ $reqs['Unzip']['pass'] = false;
867
+ }
868
+ if(is_array($this->check_mysqldump()))
869
+ {
870
+ $reqs['MySQL Dump']['status'] = "enabled";
871
+ $reqs['MySQL Dump']['pass'] = true;
872
+ }
873
+ else
874
+ {
875
+ $reqs['MySQL Dump']['status'] = "not found";
876
+ $reqs['MySQL Dump']['info'] = "(will try PHP)";
877
+ $reqs['MySQL Dump']['pass'] = false;
878
+ }
879
+
880
+
881
+
882
+ return $reqs;
883
+ }
884
+
885
+ function email_backup($args)
886
+ {
887
+ $email = $args['email'];
888
+ $backup_file = $args['file_path'];
889
+ $task_name = isset($args['task_name']) ? $args['task_name'].' on ' : '';
890
+ if(file_exists($backup_file) && $email)
891
+ {
892
+
893
+ $attachments = array($backup_file);
894
+ $headers = 'From: ManageWP <no-reply@managewp.com>' . "\r\n";
895
+ $subject = "ManageWP Backup - ".$task_name . date('F jS, G:i');
896
+ ob_start();
897
+ wp_mail($email, $subject, $subject, $headers, $attachments);
898
+ ob_end_clean();
899
+
900
+ }
901
+
902
+ return true;
903
+
904
+ }
905
+
906
+ function ftp_backup($args){
907
+ extract($args);
908
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
909
+
910
+ if($ftp_ssl && function_exists('ftp_ssl_connect')){
911
+ $conn_id = ftp_ssl_connect($ftp_hostname);
912
+ }else if (function_exists('ftp_connect')){
913
+ $conn_id = ftp_connect($ftp_hostname);
914
+ if ($conn_id===false){
915
+ return array('error' => 'Failed to connect to '.$ftp_hostname);
916
+ }
917
+ }
918
+ else {
919
+ return array('error' => 'Your server doesn\'t support FTP');
920
+ }
921
+
922
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
923
+ if ($login === false ) {
924
+ return array('error' => 'FTP login failed for '.$ftp_username.', '.$ftp_password);
925
+ }
926
+
927
+ @ftp_mkdir($conn_id, $ftp_remote_folder);
928
+
929
+ $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
930
+ if ($upload === false) {
931
+ return array('error' => 'Failed to upload file. Please check your specified path.');
932
+ }
933
+
934
+ ftp_close($conn_id);
935
+
936
+ return true;
937
+ }
938
+
939
+ function remove_ftp_backup($args)
940
+ {
941
+ extract($args);
942
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
943
+ if($ftp_ssl && function_exists('ftp_ssl_connect')){
944
+ $conn_id = ftp_ssl_connect($ftp_hostname);
945
+
946
+ }else if (function_exists('ftp_connect')){
947
+ $conn_id = ftp_connect($ftp_hostname);
948
+ if ($conn_id===false){
949
+
950
+ }
951
+ }
952
+ else {
953
+
954
+ }
955
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
956
+ if ($login === false ) {
957
+
958
+ } else {
959
+
960
+ }
961
+
962
+ $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
963
+ if ($delete === false) {
964
+
965
+ } else {
966
+
967
+ }
968
+ ftp_close($conn_id);
969
+
970
+ }
971
+
972
+ function get_ftp_backup($args){
973
+ extract($args);
974
+ //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
975
+ if($ftp_ssl && function_exists('ftp_ssl_connect')){
976
+ $conn_id = ftp_ssl_connect($ftp_hostname);
977
+
978
+ }else if (function_exists('ftp_connect')){
979
+ $conn_id = ftp_connect($ftp_hostname);
980
+ if ($conn_id===false){
981
+ return false;
982
+ }
983
+ }
984
+ else {
985
+
986
+ }
987
+ $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
988
+ if ($login === false ) {
989
+ return false;
990
+ } else {
991
+
992
+ }
993
+
994
+ $temp = ABSPATH.'mwp_temp_backup.zip';
995
+ $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
996
+ if ($get === false) {
997
+ return false;
998
+ } else {
999
+
1000
+ }
1001
+ ftp_close($conn_id);
1002
+
1003
+ return $temp;
1004
+ }
1005
+
1006
+ function dropbox_backup($args)
1007
+ {
1008
+ require_once('lib/dropbox.php');
1009
+ extract($args);
1010
+
1011
+ //$email, $password, $backup_file, $destination
1012
+ try{
1013
+ $uploader = new DropboxUploader($dropbox_username, $dropbox_password);
1014
+ $uploader->upload($backup_file, $dropbox_destination);
1015
+ } catch (Exception $e){
1016
+ return array('error' => $e->getMessage());
1017
+ }
1018
+
1019
+ return true;
1020
+
1021
+ }
1022
+
1023
+ function amazons3_backup($args)
1024
+ {
1025
+ require_once('lib/s3.php');
1026
+ extract($args);
1027
+
1028
+ $start_time = time();
1029
+ $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
1030
+
1031
+ $s3->putBucket( $as3_bucket, S3::ACL_PUBLIC_READ );
1032
+
1033
+ if ( $s3->putObjectFile( $backup_file, $as3_bucket, $as3_directory .'/'. basename($backup_file), S3::ACL_PRIVATE) ) {
1034
+ return true;
1035
+ } else {
1036
+ return array('error' => 'Failed to upload to Amazon S3. Please check your details.');
1037
+ }
1038
+
1039
+ }
1040
+
1041
+ function remove_amazons3_backup($args)
1042
+ {
1043
+ require_once('lib/s3.php');
1044
+ extract($args);
1045
+
1046
+ $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
1047
+ $s3->deleteObject($as3_bucket,$as3_directory.'/'. $backup_file);
1048
+ }
1049
+
1050
+ function get_amazons3_backup($args)
1051
+ {
1052
+ require_once('lib/s3.php');
1053
+ extract($args);
1054
+ $s3 = new S3( $as3_access_key, str_replace(' ', '+', $as3_secure_key));
1055
+ $s3->deleteObject($as3_bucket,$as3_directory.'/'. $backup_file);
1056
+ $s3->getObject($as3_bucket, $as3_directory.'/'. $backup_file, $temp);
1057
+ $temp = ABSPATH.'mwp_temp_backup.zip';
1058
+ return $temp;
1059
+ }
1060
+
1061
+ function schedule_next($type,$schedule)
1062
+ {
1063
+
1064
+ $schedule = explode("|", $schedule);
1065
+ if(empty($schedule))
1066
+ return false;
1067
+ switch($type){
1068
+
1069
+ case 'daily':
1070
+
1071
+ if($schedule[1]) { $delay_time = $schedule[1] * 60;}
1072
+
1073
+ $current_hour = date("H");
1074
+ $schedule_hour = $schedule[0];
1075
+ if($current_hour >= $schedule_hour)
1076
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+1, date("Y"));
1077
+ else
1078
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1079
+ break;
1080
+
1081
+
1082
+ case 'weekly':
1083
+ if($schedule[2]) { $delay_time = $schedule[2] * 60;}
1084
+ $current_weekday = date('w');
1085
+ $schedule_weekday = $schedule[1];
1086
+ $current_hour = date("H");
1087
+ $schedule_hour = $schedule[0];
1088
+
1089
+ if($current_weekday > $schedule_weekday)
1090
+ $weekday_offset = 7 - ($week_day - $task_schedule[1]);
1091
+ else
1092
+ $weekday_offset = $schedule_weekday - $current_weekday;
1093
+
1094
+
1095
+ if(!$weekday_offset){ //today is scheduled weekday
1096
+ if($current_hour >= $schedule_hour)
1097
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+7, date("Y"));
1098
+ else
1099
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
1100
+ } else {
1101
+ $time = mktime($schedule_hour, 0, 0, date("m"), date("d")+ $weekday_offset, date("Y"));
1102
+ }
1103
+
1104
+ break;
1105
+
1106
+ case 'monthly':
1107
+ if($schedule[2]) { $delay_time = $schedule[2] * 60;}
1108
+ $current_monthday = date('j');
1109
+ $schedule_monthday = $schedule[1];
1110
+ $current_hour = date("H");
1111
+ $schedule_hour = $schedule[0];
1112
+
1113
+ if($current_monthday > $schedule_monthday){
1114
+ $time = mktime($schedule_hour, 0, 0, date("m")+1, $schedule_monthday, date("Y"));
1115
+ } else if($current_monthday < $schedule_monthday) {
1116
+
1117
+ $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1118
+ }
1119
+ else if($current_monthday == $schedule_monthday) {
1120
+ if($current_hour >= $schedule_hour)
1121
+ $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
1122
+ else
1123
+ $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
1124
+ break;
1125
+ }
1126
+
1127
+ break;
1128
+ default: break;
1129
+ }
1130
+
1131
+ if($delay_time) {$time += $delay_time; }
1132
+
1133
+ return $time;
1134
+
1135
+ }
1136
+
1137
+ //Parse task arguments for info on master
1138
+ function get_backup_stats()
1139
+ {
1140
+ $stats = array();
1141
+ $tasks = get_option('mwp_backup_tasks');
1142
+ if(is_array($tasks) && !empty($tasks)) {
1143
+ foreach($tasks as $task_name => $info)
1144
+ {
1145
+ $stats[$task_name] = $info['task_results'];
1146
+ }
1147
+ }
1148
+ return $stats;
1149
+ }
1150
+
1151
+ function remove_old_backups($task_name){
1152
+ $backups = $this->get_backup_settings();
1153
+ if(count($backups[$task_name]['task_results']) >= $backups[$task_name]['task_args']['limit']) {
1154
+ // ? how many to remove
1155
+ $remove_num = (count($backups[$task_name]['task_results']) - $backups[$task_name]['task_args']['limit']) + 1;
1156
+
1157
+ for($i = 0; $i < $remove_num; $i++){
1158
+ if(!isset($backups[$task_name]['task_results'][$i]['error'])) {
1159
+
1160
+ //Remove from the server
1161
+ if(isset($backups[$task_name]['task_results'][$i]['server'])){
1162
+ @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
1163
+ }
1164
+
1165
+ //Remove from ftp
1166
+ if(isset($backups[$task_name]['task_results'][$i]['ftp'])){
1167
+ $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
1168
+ $args = $backups[$task_name]['task_args']['account_info']['mwp_ftp'];
1169
+ $args['backup_file'] = $ftp_file;
1170
+ $this->remove_ftp_backup($args);
1171
+ }
1172
+
1173
+ if(isset($backups[$task_name]['task_results'][$i]['amazons3'])){
1174
+ $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
1175
+ $args = $backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
1176
+ $args['backup_file'] = $amazons3_file;
1177
+ $this->remove_amazons3_backup($args);
1178
+ }
1179
+
1180
+ if(isset($backups[$task_name]['task_results'][$i]['dropbox'])){
1181
+
1182
+ }
1183
+
1184
+ }
1185
+ //Remove database backup info
1186
+ unset($backups[$task_name]['task_results'][$i]);
1187
+ update_option('mwp_backup_tasks',$backups);
1188
+
1189
+ }//end foreach
1190
+ }
1191
+ }
1192
+
1193
+ /**
1194
+ * Delete specified backup
1195
+ * Args: $task_name, $result_id
1196
+ */
1197
+
1198
+ function delete_backup($args){
1199
+ if(empty($args))
1200
+ return false;
1201
+ extract($args);
1202
+
1203
+ $tasks = $this->get_backup_settings();
1204
+ $task = $tasks[$task_name];
1205
+ $backups = $task['task_results'];
1206
+ $backup = $backups[$result_id];
1207
+
1208
+ if(isset($backup['server'])){
1209
+ @unlink($backup['server']['file_path']);
1210
+ }
1211
+
1212
+ //Remove from ftp
1213
+ if(isset($backup['ftp'])){
1214
+ $ftp_file = $backup['ftp'];
1215
+ $args = $tasks[$task_name]['task_args']['account_info']['mwp_ftp'];
1216
+ $args['backup_file'] = $ftp_file;
1217
+ $this->remove_ftp_backup($args);
1218
+ }
1219
+
1220
+ if(isset($backup['amazons3'])){
1221
+ $amazons3_file = $backup['amazons3'];
1222
+ $args = $tasks[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
1223
+ $args['backup_file'] = $amazons3_file;
1224
+ $this->remove_amazons3_backup($args);
1225
+ }
1226
+
1227
+ if(isset($backup['dropbox'])){
1228
+
1229
+ }
1230
+
1231
+ unset($backups[$result_id]);
1232
+
1233
+ if(count($backups)){
1234
+ $tasks[$task_name]['task_results'] = $backups;
1235
+ } else {
1236
+ unset($tasks[$task_name]['task_results']);
1237
+ }
1238
+
1239
+ update_option('mwp_backup_tasks',$tasks);
1240
+ return true;
1241
+
1242
+ }
1243
+
1244
+ function cleanup()
1245
+ {
1246
+ $tasks = $this->get_backup_settings();
1247
+ $backup_folder = WP_CONTENT_DIR.'/'.md5('mmb-worker').'/mwp_backups/';
1248
+ $files = glob($backup_folder."*.*");
1249
+ $deleted = array();
1250
+ if(is_array($files) && count($files)){
1251
+ $results = array();
1252
+ if(count($tasks)){
1253
+ foreach($tasks as $task){
1254
+ if(isset($task['task_results']) && count($task['task_results'])) {
1255
+ foreach($task['task_results'] as $backup) {
1256
+ if(isset($backup['server'])) {
1257
+ $results[] = $backup['server']['file_path'];
1258
+ }
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+
1264
+ $num_deleted = 0;
1265
+ foreach($files as $file){
1266
+ if(!in_array($file,$results) && basename($file) != 'index.php') {
1267
+ @unlink($file);
1268
+ $deleted[] = basename($file);
1269
+ $num_deleted++;
1270
+ }
1271
+ }
1272
+ }
1273
+
1274
+ //Failed db files?
1275
+ $db_folder = WP_CONTENT_DIR.'/mwp_db/';
1276
+ $files = glob($db_folder."*.*");
1277
+ if(is_array($files) && count($files)){
1278
+ foreach($files as $file){
1279
+ @unlink($file);
1280
+ }
1281
+ }
1282
+
1283
+ return $deleted;
1284
+ }
1285
+
1286
+
1287
+ function remote_backup_now($args){
1288
+ if(!empty($args))
1289
+ extract($args);
1290
+ $tasks = $this->get_backup_settings();
1291
+ $task = $tasks['Backup Now'];
1292
+
1293
+ if(!empty($task)){
1294
+ extract($task['task_args']);
1295
+ }
1296
+
1297
+ $results = $task['task_results'];
1298
+
1299
+ if(is_array($results) && count($results)){
1300
+ $backup_file = $results[count($results)-1]['server']['file_path'];
1301
+ }
1302
+
1303
+ if($backup_file && file_exists($backup_file)){
1304
+
1305
+ if($email){
1306
+
1307
+ $mail_args = array(
1308
+ 'email' => $email_backup,
1309
+ 'task_name' => 'Backup Now',
1310
+ 'file_path' => $backup_file
1311
+ );
1312
+
1313
+
1314
+
1315
+ $return = $this->email_backup($mail_args);
1316
+
1317
+ //delete from server?
1318
+ if($return == true && $del_host_file){
1319
+ @unlink($backup_file);
1320
+
1321
+ unset($tasks['Backup Now']['task_results'][count($results)-1]['server']);
1322
+ update_option('mwp_backup_tasks',$tasks);
1323
+
1324
+ }
1325
+ } else {
1326
+
1327
+ //FTP, Amazon S3 or Dropbox
1328
+ if(isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])){
1329
+ $account_info['mwp_ftp']['backup_file'] = $backup_file;
1330
+ $return = $this->ftp_backup($account_info['mwp_ftp']);
1331
+ }
1332
+
1333
+ if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])){
1334
+ $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
1335
+ $return = $this->amazons3_backup($account_info['mwp_amazon_s3']);
1336
+ }
1337
+
1338
+ if(isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])){
1339
+ $account_info['mwp_dropbox']['backup_file'] = $backup_file;
1340
+ $return = $this->dropbox_backup($account_info['mwp_dropbox']);
1341
+ }
1342
+
1343
+ if($return == true && $del_host_file && !$email_backup){
1344
+ @unlink($backup_file);
1345
+ unset($tasks['Backup Now']['task_results'][count($results)-1]['server']);
1346
+
1347
+ update_option('mwp_backup_tasks',$tasks);
1348
+ }
1349
+
1350
+ }
1351
+
1352
+ } else {
1353
+ $return = array('error' => 'Backup file not found on your server. Please try again.');
1354
+ }
1355
+
1356
+ return $return;
1357
+
1358
+ }
1359
+
1360
+ }
1361
+
1362
  ?>
comment.class.php CHANGED
@@ -1,43 +1,43 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * post.class.php
5
- *
6
- * Create remote post
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Comment extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- parent::__construct();
18
- }
19
-
20
- function change_status($args)
21
- {
22
-
23
- global $wpdb;
24
- $comment_id = $args['comment_id'];
25
- $status = $args['status'];
26
-
27
- if ( 'approve' == $status )
28
- $status_sql = '1';
29
- elseif ( 'unapprove' == $status )
30
- $status_sql = '0';
31
- elseif ( 'spam' == $status )
32
- $status_sql = 'spam';
33
- elseif ( 'trash' == $status )
34
- $status_sql = 'trash';
35
- $sql = "update ".$wpdb->prefix."comments set comment_approved = '$status_sql' where comment_ID = '$comment_id'";
36
- $success = $wpdb->query($sql);
37
-
38
-
39
- return $success;
40
- }
41
-
42
- }
43
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * post.class.php
5
+ *
6
+ * Create remote post
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Comment extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ parent::__construct();
18
+ }
19
+
20
+ function change_status($args)
21
+ {
22
+
23
+ global $wpdb;
24
+ $comment_id = $args['comment_id'];
25
+ $status = $args['status'];
26
+
27
+ if ( 'approve' == $status )
28
+ $status_sql = '1';
29
+ elseif ( 'unapprove' == $status )
30
+ $status_sql = '0';
31
+ elseif ( 'spam' == $status )
32
+ $status_sql = 'spam';
33
+ elseif ( 'trash' == $status )
34
+ $status_sql = 'trash';
35
+ $sql = "update ".$wpdb->prefix."comments set comment_approved = '$status_sql' where comment_ID = '$comment_id'";
36
+ $success = $wpdb->query($sql);
37
+
38
+
39
+ return $success;
40
+ }
41
+
42
+ }
43
  ?>
core.class.php CHANGED
@@ -1,438 +1,438 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * core.class.php
5
- *
6
- * Upgrade Plugins
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
- class MMB_Core extends MMB_Helper
13
- {
14
- var $name;
15
- var $slug;
16
- var $settings;
17
- var $remote_client;
18
- var $comment_instance;
19
- var $plugin_instance;
20
- var $theme_instance;
21
- var $wp_instance;
22
- var $post_instance;
23
- var $stats_instance;
24
- var $search_instance;
25
- var $links_instance;
26
- var $user_instance;
27
- var $backup_instance;
28
- var $installer_instance;
29
- var $mmb_multisite = false;
30
-
31
-
32
- function __construct()
33
- {
34
- global $mmb_plugin_dir, $wpmu_version, $blog_id;
35
-
36
- $this->name = 'Manage Multiple Blogs';
37
- $this->slug = 'manage-multiple-blogs';
38
- $this->settings = get_option($this->slug);
39
- if (!$this->settings) {
40
- $this->settings = array(
41
- 'blogs' => array(),
42
- 'current_blog' => array(
43
- 'type' => null
44
- )
45
- );
46
- $this->save_options();
47
- }
48
-
49
-
50
-
51
- if (function_exists('is_multisite')){
52
- if (is_multisite()) {
53
- $this->mmb_multisite = $blog_id;
54
- }
55
- } else if (!empty($wpmu_version)) {
56
- $this->mmb_multisite = $blog_id;
57
- }
58
-
59
- add_action('rightnow_end', array(
60
- $this,
61
- 'add_right_now_info'
62
- ));
63
- add_action('wp_footer', array(
64
- 'MMB_Stats',
65
- 'set_hit_count'
66
- ));
67
- register_activation_hook($mmb_plugin_dir . '/init.php', array(
68
- $this,
69
- 'install'
70
- ));
71
- add_action('init', array(
72
- $this,
73
- 'automatic_login'
74
- ));
75
-
76
- if (!get_option('_worker_public_key'))
77
- add_action('admin_notices', array(
78
- $this,
79
- 'admin_notice'
80
- ));
81
-
82
-
83
- }
84
-
85
- /**
86
- * Add notice to admin dashboard for security reasons
87
- *
88
- */
89
- function admin_notice()
90
- {
91
- echo '<div class="error" style="text-align: center;"><p style="color: red; font-size: 14px; font-weight: bold;">Attention !</p><p>
92
- Please add this site to your <a target="_blank" href="http://managewp.com/user-guide#security">ManageWP.com</a> account now to remove this notice or deactivate the Worker plugin to avoid <a target="_blank" href="http://managewp.com/user-guide#security">security issues</a>.
93
- </p></div>';
94
- }
95
-
96
- /**
97
- * Add an item into the Right Now Dashboard widget
98
- * to inform that the blog can be managed remotely
99
- *
100
- */
101
- function add_right_now_info()
102
- {
103
- echo '<div class="mmb-slave-info">
104
- <p>This site can be managed remotely.</p>
105
- </div>';
106
- }
107
-
108
- /**
109
- * Gets an instance of the Comment class
110
- *
111
- */
112
- function get_comment_instance()
113
- {
114
- if (!isset($this->comment_instance)) {
115
- $this->comment_instance = new MMB_Comment();
116
- }
117
-
118
- return $this->comment_instance;
119
- }
120
-
121
- /**
122
- * Gets an instance of the Plugin class
123
- *
124
- */
125
- function get_plugin_instance()
126
- {
127
- if (!isset($this->plugin_instance)) {
128
- $this->plugin_instance = new MMB_Plugin();
129
- }
130
-
131
- return $this->plugin_instance;
132
- }
133
-
134
- /**
135
- * Gets an instance of the Theme class
136
- *
137
- */
138
- function get_theme_instance()
139
- {
140
- if (!isset($this->theme_instance)) {
141
- $this->theme_instance = new MMB_Theme();
142
- }
143
-
144
- return $this->theme_instance;
145
- }
146
-
147
-
148
- /**
149
- * Gets an instance of MMB_Post class
150
- *
151
- */
152
- function get_post_instance()
153
- {
154
- if (!isset($this->post_instance)) {
155
- $this->post_instance = new MMB_Post();
156
- }
157
-
158
- return $this->post_instance;
159
- }
160
-
161
- /**
162
- * Gets an instance of Blogroll class
163
- *
164
- */
165
- function get_blogroll_instance()
166
- {
167
- if (!isset($this->blogroll_instance)) {
168
- $this->blogroll_instance = new MMB_Blogroll();
169
- }
170
-
171
- return $this->blogroll_instance;
172
- }
173
-
174
-
175
-
176
- /**
177
- * Gets an instance of the WP class
178
- *
179
- */
180
- function get_wp_instance()
181
- {
182
- if (!isset($this->wp_instance)) {
183
- $this->wp_instance = new MMB_WP();
184
- }
185
-
186
- return $this->wp_instance;
187
- }
188
-
189
- /**
190
- * Gets an instance of User
191
- *
192
- */
193
- function get_user_instance()
194
- {
195
- if (!isset($this->user_instance)) {
196
- $this->user_instance = new MMB_User();
197
- }
198
-
199
- return $this->user_instance;
200
- }
201
-
202
- /**
203
- * Gets an instance of stats class
204
- *
205
- */
206
- function get_stats_instance()
207
- {
208
- if (!isset($this->stats_instance)) {
209
- $this->stats_instance = new MMB_Stats();
210
- }
211
- return $this->stats_instance;
212
- }
213
- /**
214
- * Gets an instance of search class
215
- *
216
- */
217
- function get_search_instance()
218
- {
219
- if (!isset($this->search_instance)) {
220
- $this->search_instance = new MMB_Search();
221
- }
222
- //return $this->search_instance;
223
- return $this->search_instance;
224
- }
225
- /**
226
- * Gets an instance of stats class
227
- *
228
- */
229
- function get_backup_instance()
230
- {
231
- if (!isset($this->backup_instance)) {
232
- $this->backup_instance = new MMB_Backup();
233
- }
234
-
235
- return $this->backup_instance;
236
- }
237
-
238
- /**
239
- * Gets an instance of links class
240
- *
241
- */
242
- function get_link_instance()
243
- {
244
- if (!isset($this->link_instance)) {
245
- $this->link_instance = new MMB_Link();
246
- }
247
-
248
- return $this->link_instance;
249
- }
250
-
251
- function get_installer_instance()
252
- {
253
- if (!isset($this->installer_instance)) {
254
- $this->installer_instance = new MMB_Installer();
255
- }
256
- return $this->installer_instance;
257
- }
258
-
259
- /**
260
- * Plugin install callback function
261
- * Check PHP version
262
- */
263
- function install()
264
- {
265
- global $wp_object_cache, $wpdb;
266
- if(!empty($wp_object_cache))
267
- @$wp_object_cache->flush();
268
-
269
- // delete plugin options, just in case
270
- if($this->mmb_multisite != false){
271
- $blog_ids = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM `wp_blogs`'));
272
- if(!empty($blog_ids)){
273
- foreach($blog_ids as $blog_id){
274
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_nossl_key";'));
275
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_public_key";'));
276
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_action_message_id";'));
277
- }
278
- }
279
- } else {
280
- delete_option('_worker_nossl_key');
281
- delete_option('_worker_public_key');
282
- delete_option('_action_message_id');
283
- }
284
-
285
- //Reset backup tasks
286
- delete_option('mwp_backup_tasks');
287
- }
288
-
289
- /**
290
- * Saves the (modified) options into the database
291
- *
292
- */
293
- function save_options()
294
- {
295
- if (get_option($this->slug)) {
296
- update_option($this->slug, $this->settings);
297
- } else {
298
- add_option($this->slug, $this->settings);
299
- }
300
- }
301
-
302
- /**
303
- * Deletes options for communication with master
304
- *
305
- */
306
- function uninstall()
307
- {
308
- global $wp_object_cache, $wpdb;
309
- if(!empty($wp_object_cache))
310
- @$wp_object_cache->flush();
311
-
312
- if($this->mmb_multisite != false){
313
- $blog_ids = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM `wp_blogs`'));
314
- if(!empty($blog_ids)){
315
- foreach($blog_ids as $blog){
316
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_nossl_key";'));
317
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_public_key";'));
318
- $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_action_message_id";'));
319
- }
320
- }
321
- } else {
322
- delete_option('_worker_nossl_key');
323
- delete_option('_worker_public_key');
324
- delete_option('_action_message_id');
325
- }
326
-
327
- //Delete backup tasks
328
- delete_option('mwp_backup_tasks');
329
- wp_clear_scheduled_hook('mwp_backup_tasks');
330
- }
331
-
332
-
333
- /**
334
- * Constructs a url (for ajax purpose)
335
- *
336
- * @param mixed $base_page
337
- */
338
- function construct_url($params = array(), $base_page = 'index.php')
339
- {
340
- $url = "$base_page?_wpnonce=" . wp_create_nonce($this->slug);
341
- foreach ($params as $key => $value) {
342
- $url .= "&$key=$value";
343
- }
344
-
345
- return $url;
346
- }
347
-
348
- /**
349
- * Worker update
350
- *
351
- */
352
- function update_worker_plugin($params)
353
- {
354
- extract($params);
355
- if ($download_url) {
356
- include_once ABSPATH . 'wp-admin/includes/file.php';
357
- include_once ABSPATH . 'wp-admin/includes/misc.php';
358
- include_once ABSPATH . 'wp-admin/includes/template.php';
359
- include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
360
-
361
- if (!$this->is_server_writable()) {
362
- return array(
363
- 'error' => 'Failed, please <a target="_blank" href="http://managewp.com/user-guide#ftp">add FTP details for automatic upgrades.</a></a>'
364
- );
365
- }
366
-
367
- ob_start();
368
- @unlink(dirname(__FILE__));
369
- $upgrader = new Plugin_Upgrader();
370
- $result = $upgrader->run(array(
371
- 'package' => $download_url,
372
- 'destination' => WP_PLUGIN_DIR,
373
- 'clear_destination' => true,
374
- 'clear_working' => true,
375
- 'hook_extra' => array(
376
- 'plugin' => 'worker/init.php'
377
- )
378
- ));
379
- ob_end_clean();
380
- if (is_wp_error($result) || !$result) {
381
- return array(
382
- 'error' => 'ManageWP Worker could not been upgraded.'
383
- );
384
- } else {
385
- return array(
386
- 'success' => 'ManageWP Worker plugin successfully upgraded.'
387
- );
388
- }
389
- }
390
- return array(
391
- 'error' => 'Bad download path for worker installation file.'
392
- );
393
- }
394
-
395
- /**
396
- * Automatically logs in when called from Master
397
- *
398
- */
399
- function automatic_login()
400
- {
401
- global $current_user;
402
-
403
- $where = isset($_GET['mwp_goto']) ? $_GET['mwp_goto'] : '';
404
- $username = isset($_GET['username']) ? $_GET['username'] : '';
405
- $auto_login = isset($_GET['auto_login']) ? $_GET['auto_login'] : 0;
406
-
407
- if ((!is_user_logged_in() || ($this->mmb_multisite && $username != $current_user->user_login)) && $auto_login) {
408
-
409
- $signature = base64_decode($_GET['signature']);
410
- $message_id = trim($_GET['message_id']);
411
-
412
- $auth = $this->authenticate_message($where . $message_id, $signature, $message_id);
413
- if ($auth === true) {
414
- if(isset($current_user->user_login))
415
- do_action('wp_logout');
416
- $user = get_user_by('login', $username);
417
- $user_id = $user->ID;
418
- wp_set_current_user($user_id, $username);
419
- wp_set_auth_cookie($user_id);
420
- do_action('wp_login', $username);
421
- } else {
422
- unset($_SESSION['mwp_frame_options_header']);
423
- wp_die($auth['error']);
424
- }
425
- }
426
-
427
- if ($_GET['auto_login']) {
428
- update_option('mwp_iframe_options_header', microtime(true));
429
- if(!headers_sent())
430
- header('P3P: CP="CAO PSA OUR"'); // IE redirect iframe header
431
- wp_redirect(get_option('siteurl') . "/wp-admin/" . $where);
432
- exit();
433
- }
434
- }
435
-
436
-
437
- }
438
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * core.class.php
5
+ *
6
+ * Upgrade Plugins
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+ class MMB_Core extends MMB_Helper
13
+ {
14
+ var $name;
15
+ var $slug;
16
+ var $settings;
17
+ var $remote_client;
18
+ var $comment_instance;
19
+ var $plugin_instance;
20
+ var $theme_instance;
21
+ var $wp_instance;
22
+ var $post_instance;
23
+ var $stats_instance;
24
+ var $search_instance;
25
+ var $links_instance;
26
+ var $user_instance;
27
+ var $backup_instance;
28
+ var $installer_instance;
29
+ var $mmb_multisite = false;
30
+
31
+
32
+ function __construct()
33
+ {
34
+ global $mmb_plugin_dir, $wpmu_version, $blog_id;
35
+
36
+ $this->name = 'Manage Multiple Blogs';
37
+ $this->slug = 'manage-multiple-blogs';
38
+ $this->settings = get_option($this->slug);
39
+ if (!$this->settings) {
40
+ $this->settings = array(
41
+ 'blogs' => array(),
42
+ 'current_blog' => array(
43
+ 'type' => null
44
+ )
45
+ );
46
+ $this->save_options();
47
+ }
48
+
49
+
50
+
51
+ if (function_exists('is_multisite')){
52
+ if (is_multisite()) {
53
+ $this->mmb_multisite = $blog_id;
54
+ }
55
+ } else if (!empty($wpmu_version)) {
56
+ $this->mmb_multisite = $blog_id;
57
+ }
58
+
59
+ add_action('rightnow_end', array(
60
+ $this,
61
+ 'add_right_now_info'
62
+ ));
63
+ add_action('wp_footer', array(
64
+ 'MMB_Stats',
65
+ 'set_hit_count'
66
+ ));
67
+ register_activation_hook($mmb_plugin_dir . '/init.php', array(
68
+ $this,
69
+ 'install'
70
+ ));
71
+ add_action('init', array(
72
+ $this,
73
+ 'automatic_login'
74
+ ));
75
+
76
+ if (!get_option('_worker_public_key'))
77
+ add_action('admin_notices', array(
78
+ $this,
79
+ 'admin_notice'
80
+ ));
81
+
82
+
83
+ }
84
+
85
+ /**
86
+ * Add notice to admin dashboard for security reasons
87
+ *
88
+ */
89
+ function admin_notice()
90
+ {
91
+ echo '<div class="error" style="text-align: center;"><p style="color: red; font-size: 14px; font-weight: bold;">Attention !</p><p>
92
+ Please add this site to your <a target="_blank" href="http://managewp.com/user-guide#security">ManageWP.com</a> account now to remove this notice or deactivate the Worker plugin to avoid <a target="_blank" href="http://managewp.com/user-guide#security">security issues</a>.
93
+ </p></div>';
94
+ }
95
+
96
+ /**
97
+ * Add an item into the Right Now Dashboard widget
98
+ * to inform that the blog can be managed remotely
99
+ *
100
+ */
101
+ function add_right_now_info()
102
+ {
103
+ echo '<div class="mmb-slave-info">
104
+ <p>This site can be managed remotely.</p>
105
+ </div>';
106
+ }
107
+
108
+ /**
109
+ * Gets an instance of the Comment class
110
+ *
111
+ */
112
+ function get_comment_instance()
113
+ {
114
+ if (!isset($this->comment_instance)) {
115
+ $this->comment_instance = new MMB_Comment();
116
+ }
117
+
118
+ return $this->comment_instance;
119
+ }
120
+
121
+ /**
122
+ * Gets an instance of the Plugin class
123
+ *
124
+ */
125
+ function get_plugin_instance()
126
+ {
127
+ if (!isset($this->plugin_instance)) {
128
+ $this->plugin_instance = new MMB_Plugin();
129
+ }
130
+
131
+ return $this->plugin_instance;
132
+ }
133
+
134
+ /**
135
+ * Gets an instance of the Theme class
136
+ *
137
+ */
138
+ function get_theme_instance()
139
+ {
140
+ if (!isset($this->theme_instance)) {
141
+ $this->theme_instance = new MMB_Theme();
142
+ }
143
+
144
+ return $this->theme_instance;
145
+ }
146
+
147
+
148
+ /**
149
+ * Gets an instance of MMB_Post class
150
+ *
151
+ */
152
+ function get_post_instance()
153
+ {
154
+ if (!isset($this->post_instance)) {
155
+ $this->post_instance = new MMB_Post();
156
+ }
157
+
158
+ return $this->post_instance;
159
+ }
160
+
161
+ /**
162
+ * Gets an instance of Blogroll class
163
+ *
164
+ */
165
+ function get_blogroll_instance()
166
+ {
167
+ if (!isset($this->blogroll_instance)) {
168
+ $this->blogroll_instance = new MMB_Blogroll();
169
+ }
170
+
171
+ return $this->blogroll_instance;
172
+ }
173
+
174
+
175
+
176
+ /**
177
+ * Gets an instance of the WP class
178
+ *
179
+ */
180
+ function get_wp_instance()
181
+ {
182
+ if (!isset($this->wp_instance)) {
183
+ $this->wp_instance = new MMB_WP();
184
+ }
185
+
186
+ return $this->wp_instance;
187
+ }
188
+
189
+ /**
190
+ * Gets an instance of User
191
+ *
192
+ */
193
+ function get_user_instance()
194
+ {
195
+ if (!isset($this->user_instance)) {
196
+ $this->user_instance = new MMB_User();
197
+ }
198
+
199
+ return $this->user_instance;
200
+ }
201
+
202
+ /**
203
+ * Gets an instance of stats class
204
+ *
205
+ */
206
+ function get_stats_instance()
207
+ {
208
+ if (!isset($this->stats_instance)) {
209
+ $this->stats_instance = new MMB_Stats();
210
+ }
211
+ return $this->stats_instance;
212
+ }
213
+ /**
214
+ * Gets an instance of search class
215
+ *
216
+ */
217
+ function get_search_instance()
218
+ {
219
+ if (!isset($this->search_instance)) {
220
+ $this->search_instance = new MMB_Search();
221
+ }
222
+ //return $this->search_instance;
223
+ return $this->search_instance;
224
+ }
225
+ /**
226
+ * Gets an instance of stats class
227
+ *
228
+ */
229
+ function get_backup_instance()
230
+ {
231
+ if (!isset($this->backup_instance)) {
232
+ $this->backup_instance = new MMB_Backup();
233
+ }
234
+
235
+ return $this->backup_instance;
236
+ }
237
+
238
+ /**
239
+ * Gets an instance of links class
240
+ *
241
+ */
242
+ function get_link_instance()
243
+ {
244
+ if (!isset($this->link_instance)) {
245
+ $this->link_instance = new MMB_Link();
246
+ }
247
+
248
+ return $this->link_instance;
249
+ }
250
+
251
+ function get_installer_instance()
252
+ {
253
+ if (!isset($this->installer_instance)) {
254
+ $this->installer_instance = new MMB_Installer();
255
+ }
256
+ return $this->installer_instance;
257
+ }
258
+
259
+ /**
260
+ * Plugin install callback function
261
+ * Check PHP version
262
+ */
263
+ function install()
264
+ {
265
+ global $wp_object_cache, $wpdb;
266
+ if(!empty($wp_object_cache))
267
+ @$wp_object_cache->flush();
268
+
269
+ // delete plugin options, just in case
270
+ if($this->mmb_multisite != false){
271
+ $blog_ids = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM `wp_blogs`'));
272
+ if(!empty($blog_ids)){
273
+ foreach($blog_ids as $blog_id){
274
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_nossl_key";'));
275
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_public_key";'));
276
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_action_message_id";'));
277
+ }
278
+ }
279
+ } else {
280
+ delete_option('_worker_nossl_key');
281
+ delete_option('_worker_public_key');
282
+ delete_option('_action_message_id');
283
+ }
284
+
285
+ //Reset backup tasks
286
+ delete_option('mwp_backup_tasks');
287
+ }
288
+
289
+ /**
290
+ * Saves the (modified) options into the database
291
+ *
292
+ */
293
+ function save_options()
294
+ {
295
+ if (get_option($this->slug)) {
296
+ update_option($this->slug, $this->settings);
297
+ } else {
298
+ add_option($this->slug, $this->settings);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Deletes options for communication with master
304
+ *
305
+ */
306
+ function uninstall()
307
+ {
308
+ global $wp_object_cache, $wpdb;
309
+ if(!empty($wp_object_cache))
310
+ @$wp_object_cache->flush();
311
+
312
+ if($this->mmb_multisite != false){
313
+ $blog_ids = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM `wp_blogs`'));
314
+ if(!empty($blog_ids)){
315
+ foreach($blog_ids as $blog){
316
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_nossl_key";'));
317
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_worker_public_key";'));
318
+ $wpdb->query($wpdb->prepare('DELETE FROM '.$wpdb->prefix.$blog->blog_id.'_options WHERE `option_name` = "_action_message_id";'));
319
+ }
320
+ }
321
+ } else {
322
+ delete_option('_worker_nossl_key');
323
+ delete_option('_worker_public_key');
324
+ delete_option('_action_message_id');
325
+ }
326
+
327
+ //Delete backup tasks
328
+ delete_option('mwp_backup_tasks');
329
+ wp_clear_scheduled_hook('mwp_backup_tasks');
330
+ }
331
+
332
+
333
+ /**
334
+ * Constructs a url (for ajax purpose)
335
+ *
336
+ * @param mixed $base_page
337
+ */
338
+ function construct_url($params = array(), $base_page = 'index.php')
339
+ {
340
+ $url = "$base_page?_wpnonce=" . wp_create_nonce($this->slug);
341
+ foreach ($params as $key => $value) {
342
+ $url .= "&$key=$value";
343
+ }
344
+
345
+ return $url;
346
+ }
347
+
348
+ /**
349
+ * Worker update
350
+ *
351
+ */
352
+ function update_worker_plugin($params)
353
+ {
354
+ extract($params);
355
+ if ($download_url) {
356
+ include_once ABSPATH . 'wp-admin/includes/file.php';
357
+ include_once ABSPATH . 'wp-admin/includes/misc.php';
358
+ include_once ABSPATH . 'wp-admin/includes/template.php';
359
+ include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
360
+
361
+ if (!$this->is_server_writable()) {
362
+ return array(
363
+ 'error' => 'Failed, please <a target="_blank" href="http://managewp.com/user-guide#ftp">add FTP details for automatic upgrades.</a></a>'
364
+ );
365
+ }
366
+
367
+ ob_start();
368
+ @unlink(dirname(__FILE__));
369
+ $upgrader = new Plugin_Upgrader();
370
+ $result = $upgrader->run(array(
371
+ 'package' => $download_url,
372
+ 'destination' => WP_PLUGIN_DIR,
373
+ 'clear_destination' => true,
374
+ 'clear_working' => true,
375
+ 'hook_extra' => array(
376
+ 'plugin' => 'worker/init.php'
377
+ )
378
+ ));
379
+ ob_end_clean();
380
+ if (is_wp_error($result) || !$result) {
381
+ return array(
382
+ 'error' => 'ManageWP Worker plugin could not be upgraded.'
383
+ );
384
+ } else {
385
+ return array(
386
+ 'success' => 'ManageWP Worker plugin successfully upgraded.'
387
+ );
388
+ }
389
+ }
390
+ return array(
391
+ 'error' => 'Bad download path for worker installation file.'
392
+ );
393
+ }
394
+
395
+ /**
396
+ * Automatically logs in when called from Master
397
+ *
398
+ */
399
+ function automatic_login()
400
+ {
401
+ global $current_user;
402
+
403
+ $where = isset($_GET['mwp_goto']) ? $_GET['mwp_goto'] : '';
404
+ $username = isset($_GET['username']) ? $_GET['username'] : '';
405
+ $auto_login = isset($_GET['auto_login']) ? $_GET['auto_login'] : 0;
406
+
407
+ if ((!is_user_logged_in() || ($this->mmb_multisite && $username != $current_user->user_login)) && $auto_login) {
408
+
409
+ $signature = base64_decode($_GET['signature']);
410
+ $message_id = trim($_GET['message_id']);
411
+
412
+ $auth = $this->authenticate_message($where . $message_id, $signature, $message_id);
413
+ if ($auth === true) {
414
+ if(isset($current_user->user_login))
415
+ do_action('wp_logout');
416
+ $user = get_user_by('login', $username);
417
+ $user_id = $user->ID;
418
+ wp_set_current_user($user_id, $username);
419
+ wp_set_auth_cookie($user_id);
420
+ do_action('wp_login', $username);
421
+ } else {
422
+ unset($_SESSION['mwp_frame_options_header']);
423
+ wp_die($auth['error']);
424
+ }
425
+ }
426
+
427
+ if ($_GET['auto_login']) {
428
+ update_option('mwp_iframe_options_header', microtime(true));
429
+ if(!headers_sent())
430
+ header('P3P: CP="CAO PSA OUR"'); // IE redirect iframe header
431
+ wp_redirect(get_option('siteurl') . "/wp-admin/" . $where);
432
+ exit();
433
+ }
434
+ }
435
+
436
+
437
+ }
438
  ?>
helper.class.php CHANGED
@@ -1,404 +1,428 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * helper.class.php
5
- *
6
- * Utility functions
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Helper
14
- {
15
- /**
16
- * A helper function to log data
17
- *
18
- * @param mixed $mixed
19
- */
20
- function _log($mixed)
21
- {
22
- if (is_array($mixed)) {
23
- $mixed = print_r($mixed, 1);
24
- } else if (is_object($mixed)) {
25
- ob_start();
26
- var_dump($mixed);
27
- $mixed = ob_get_clean();
28
- }
29
-
30
- $handle = fopen(dirname(__FILE__) . '/log', 'a');
31
- fwrite($handle, $mixed . PHP_EOL);
32
- fclose($handle);
33
- }
34
-
35
- function _escape(&$array)
36
- {
37
- global $wpdb;
38
-
39
- if (!is_array($array)) {
40
- return ($wpdb->escape($array));
41
- } else {
42
- foreach ((array) $array as $k => $v) {
43
- if (is_array($v)) {
44
- $this->_escape($array[$k]);
45
- } else if (is_object($v)) {
46
- //skip
47
- } else {
48
- $array[$k] = $wpdb->escape($v);
49
- }
50
- }
51
- }
52
- }
53
-
54
- /**
55
- * Initializes the file system
56
- *
57
- */
58
- function init_filesystem()
59
- {
60
- global $wp_filesystem;
61
-
62
- if (!$wp_filesystem || !is_object($wp_filesystem)) {
63
- WP_Filesystem();
64
- }
65
-
66
- if (!is_object($wp_filesystem))
67
- return FALSE;
68
-
69
- return TRUE;
70
- }
71
-
72
- /**
73
- * Gets transient based on WP version
74
- *
75
- * @global string $wp_version
76
- * @param string $option_name
77
- * @return mixed
78
- */
79
-
80
- function mmb_set_transient($option_name = false, $data = false){
81
-
82
- if (!$option_name || !$data) {
83
- return false;
84
- }
85
- if($this->mmb_multisite)
86
- return $this->mmb_set_sitemeta_transient($option_name, $data);
87
-
88
- global $wp_version;
89
-
90
- if (version_compare($wp_version, '2.7.9', '<=')) {
91
- update_option($option_name, $data);
92
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
93
- update_option('_transient_' . $option_name, $data);
94
- } else {
95
- update_option('_site_transient_' . $option_name, $data);
96
- }
97
-
98
- }
99
- function mmb_get_transient($option_name)
100
- {
101
- if (trim($option_name) == '') {
102
- return FALSE;
103
- }
104
- if($this->mmb_multisite)
105
- return $this->mmb_get_sitemeta_transient($option_name);
106
-
107
- global $wp_version;
108
-
109
-
110
- if (version_compare($wp_version, '2.7.9', '<=')) {
111
- return get_option($option_name);
112
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
113
- return get_option('_transient_' . $option_name);
114
- } else {
115
- return get_option('_site_transient_' . $option_name);
116
- }
117
- }
118
-
119
- function mmb_delete_transient($option_name)
120
- {
121
- if (trim($option_name) == '') {
122
- return FALSE;
123
- }
124
-
125
- global $wp_version;
126
-
127
- if (version_compare($wp_version, '2.7.9', '<=')) {
128
- delete_option($option_name);
129
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
130
- delete_option('_transient_' . $option_name);
131
- } else {
132
- delete_option('_site_transient_' . $option_name);
133
- }
134
- }
135
-
136
- function mmb_get_sitemeta_transient($option_name){
137
- global $wpdb;
138
- $option_name = '_site_transient_'. $option_name;
139
-
140
- $result = $wpdb->get_var( $wpdb->prepare("SELECT `meta_value` FROM `{$wpdb->sitemeta}` WHERE meta_key = '{$option_name}' AND `site_id` = '{$this->mmb_multisite}' "));
141
- $result = maybe_unserialize($result);
142
- return $result;
143
- }
144
-
145
- function mmb_set_sitemeta_transient($option_name, $option_value){
146
- global $wpdb;
147
- $option_name = '_site_transient_'. $option_name;
148
-
149
- if($this->mmb_get_sitemeta_transient($option_name)){
150
- $result = $wpdb->update( $wpdb->sitemeta,
151
- array(
152
- 'meta_value' => maybe_serialize($option_value)
153
- ),
154
- array(
155
- 'meta_key' => $option_name,
156
- 'site_id' => $this->mmb_multisite
157
- )
158
- );
159
- }else {
160
- $result = $wpdb->insert( $wpdb->sitemeta,
161
- array(
162
- 'meta_key' => $option_name,
163
- 'meta_value' => maybe_serialize($option_value),
164
- 'site_id' => $this->mmb_multisite
165
- )
166
- );
167
- }
168
- return $result;
169
- }
170
-
171
- function delete_temp_dir($directory)
172
- {
173
- if (substr($directory, -1) == "/") {
174
- $directory = substr($directory, 0, -1);
175
- }
176
- if (!file_exists($directory) || !is_dir($directory)) {
177
- return false;
178
- } elseif (!is_readable($directory)) {
179
- return false;
180
- } else {
181
- $directoryHandle = opendir($directory);
182
-
183
- while ($contents = readdir($directoryHandle)) {
184
- if ($contents != '.' && $contents != '..') {
185
- $path = $directory . "/" . $contents;
186
-
187
- if (is_dir($path)) {
188
- $this->delete_temp_dir($path);
189
- } else {
190
- unlink($path);
191
- }
192
- }
193
- }
194
- closedir($directoryHandle);
195
- rmdir($directory);
196
- return true;
197
- }
198
- }
199
-
200
- function set_worker_message_id($message_id = false)
201
- {
202
- if ($message_id) {
203
- add_option('_action_message_id', $message_id) or update_option('_action_message_id', $message_id);
204
- return $message_id;
205
- }
206
- return false;
207
- }
208
-
209
- function get_worker_message_id()
210
- {
211
- return (int) get_option('_action_message_id');
212
- }
213
-
214
- function set_master_public_key($public_key = false)
215
- {
216
- if ($public_key && !get_option('_worker_public_key')) {
217
- add_option('_worker_public_key', base64_encode($public_key));
218
- return true;
219
- }
220
- return false;
221
- }
222
-
223
- function get_master_public_key()
224
- {
225
- if (!get_option('_worker_public_key'))
226
- return false;
227
- return base64_decode(get_option('_worker_public_key'));
228
- }
229
-
230
-
231
- function get_random_signature()
232
- {
233
- if (!get_option('_worker_nossl_key'))
234
- return false;
235
- return base64_decode(get_option('_worker_nossl_key'));
236
- }
237
-
238
- function set_random_signature($random_key = false)
239
- {
240
- if ($random_key && !get_option('_worker_nossl_key')) {
241
- add_option('_worker_nossl_key', base64_encode($random_key));
242
- return true;
243
- }
244
- return false;
245
- }
246
-
247
-
248
- function authenticate_message($data = false, $signature = false, $message_id = false)
249
- {
250
- if (!$data && !$signature) {
251
- return array(
252
- 'error' => 'Authentication failed.'
253
- );
254
- }
255
-
256
- $current_message = $this->get_worker_message_id();
257
-
258
- if ((int) $current_message > (int) $message_id)
259
- return array(
260
- 'error' => 'Invalid message recieved. You can try to reinstall worker plugin and re-add the site to your account.'
261
- );
262
-
263
- $pl_key = $this->get_master_public_key();
264
- if (!$pl_key) {
265
- return array(
266
- 'error' => 'Authentication failed (public key). You can try to reinstall worker plugin and re-add the site to your account.'
267
- );
268
- }
269
-
270
- if (function_exists('openssl_verify') && !$this->get_random_signature()) {
271
- $verify = openssl_verify($data, $signature, $pl_key);
272
- if ($verify == 1) {
273
- $message_id = $this->set_worker_message_id($message_id);
274
- return true;
275
- } else if ($verify == 0) {
276
- return array(
277
- 'error' => 'Invalid message signature. You can try to reinstall worker plugin and re-add the site to your account.'
278
- );
279
- } else {
280
- return array(
281
- 'error' => 'Command not successful! Please try again.'
282
- );
283
- }
284
- } else if ($this->get_random_signature()) {
285
- if (md5($data . $this->get_random_signature()) == $signature) {
286
- $message_id = $this->set_worker_message_id($message_id);
287
- return true;
288
- }
289
- return array(
290
- 'error' => 'Invalid message signature. You can try to reinstall the worker plugin and then re-add the site to your dashboard.'
291
- );
292
- }
293
- // no rand key - deleted in get_stat maybe
294
- else
295
- return array(
296
- 'error' => 'Invalid message signature, try reinstalling worker plugin and re-adding the site to your dashboard.'
297
- );
298
- }
299
-
300
- function _secure_data($data = false){
301
- if($data == false)
302
- return false;
303
-
304
- $pl_key = $this->get_master_public_key();
305
- if (!$pl_key)
306
- return false;
307
-
308
- $secure = '';
309
- if( function_exists('openssl_public_decrypt') && !$this->get_random_signature()){
310
- if(is_array($data) && !empty($data)){
311
- foreach($data as $input){
312
- openssl_public_decrypt($input, &$decrypted, $pl_key);
313
- $secure .= $decrypted;
314
- }
315
- } else {
316
- openssl_public_decrypt($input, &$decrypted, $pl_key);
317
- $secure = $decrypted;
318
- }
319
- return $secure;
320
- }
321
- return false;
322
-
323
- }
324
-
325
- function check_if_user_exists($username = false)
326
- {
327
- global $wpdb;
328
- if ($username) {
329
- require_once(ABSPATH . WPINC . '/registration.php');
330
- include_once(ABSPATH . 'wp-includes/pluggable.php');
331
-
332
- if (username_exists($username) == null) {
333
- return false;
334
- }
335
- $user = (array) get_userdatabylogin($username);
336
-
337
- if ($user[$wpdb->prefix . 'user_level'] == 10 || isset($user[$wpdb->prefix . 'capabilities']['administrator']) ||
338
- (isset($user['caps']['administrator']) && $user['caps']['administrator'] == 1)){
339
- define('MMB_USER_CAPABILITIES', $user->wp_user_level);
340
- return true;
341
- }
342
- return false;
343
- }
344
- return false;
345
- }
346
-
347
- function refresh_updates()
348
- {
349
- if (rand(1, 3) == '2') {
350
- require_once(ABSPATH . WPINC . '/update.php');
351
- wp_update_plugins();
352
- wp_update_themes();
353
- wp_version_check();
354
- }
355
- }
356
-
357
- function remove_http($url = '')
358
- {
359
- if ($url == 'http://' OR $url == 'https://') {
360
- return $url;
361
- }
362
- return preg_replace('/^(http|https)\:\/\/(www.)?/i', '', $url);
363
-
364
- }
365
-
366
- function mmb_get_error($error_object)
367
- {
368
- if (!is_wp_error($error_object)) {
369
- return $error_object != '' ? $error_object : '';
370
- } else {
371
- $errors = array();
372
- foreach ($error_object->error_data as $error_key => $error_string) {
373
- $errors[] = str_replace('_', ' ', ucfirst($error_key)) . ': ' . $error_string;
374
- }
375
- return implode('<br />', $errors);
376
- }
377
- }
378
-
379
- function is_server_writable(){
380
- if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), false) != 'direct'))
381
- return false;
382
- else
383
- return true;
384
- }
385
-
386
- function mmb_download_url($url, $file_name)
387
- {
388
- if (function_exists('fopen') && function_exists('ini_get') && ini_get('allow_url_fopen') == true && ($destination = @fopen($file_name, 'wb')) && ($source = @fopen($url, "r")) ) {
389
-
390
-
391
- while ($a = @fread($source, 1024* 1024)) {
392
- @fwrite($destination, $a);
393
- }
394
-
395
- fclose($source);
396
- fclose($destination);
397
- } else
398
- if (!fsockopen_download($url, $file_name))
399
- die('Error downloading file ' . $url);
400
- return $file_name;
401
- }
402
-
403
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * helper.class.php
5
+ *
6
+ * Utility functions
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Helper
14
+ {
15
+ /**
16
+ * A helper function to log data
17
+ *
18
+ * @param mixed $mixed
19
+ */
20
+ function _log($mixed)
21
+ {
22
+ if (is_array($mixed)) {
23
+ $mixed = print_r($mixed, 1);
24
+ } else if (is_object($mixed)) {
25
+ ob_start();
26
+ var_dump($mixed);
27
+ $mixed = ob_get_clean();
28
+ }
29
+
30
+ $handle = fopen(dirname(__FILE__) . '/log', 'a');
31
+ fwrite($handle, $mixed . PHP_EOL);
32
+ fclose($handle);
33
+ }
34
+
35
+ function _escape(&$array)
36
+ {
37
+ global $wpdb;
38
+
39
+ if (!is_array($array)) {
40
+ return ($wpdb->escape($array));
41
+ } else {
42
+ foreach ((array) $array as $k => $v) {
43
+ if (is_array($v)) {
44
+ $this->_escape($array[$k]);
45
+ } else if (is_object($v)) {
46
+ //skip
47
+ } else {
48
+ $array[$k] = $wpdb->escape($v);
49
+ }
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Initializes the file system
56
+ *
57
+ */
58
+ function init_filesystem()
59
+ {
60
+ global $wp_filesystem;
61
+
62
+ if (!$wp_filesystem || !is_object($wp_filesystem)) {
63
+ WP_Filesystem();
64
+ }
65
+
66
+ if (!is_object($wp_filesystem))
67
+ return FALSE;
68
+
69
+ return TRUE;
70
+ }
71
+
72
+ /**
73
+ *
74
+ * Check if function exists or not on `suhosin` black list
75
+ *
76
+ */
77
+
78
+ function mmb_function_exists($function_callback){
79
+
80
+ if(!function_exists($function_callback))
81
+ return false;
82
+
83
+ if (extension_loaded('suhosin')) {
84
+ $suhosin = @ini_get("suhosin.executor.func.blacklist");
85
+ if (empty($suhosin) == false) {
86
+ $suhosin = explode(',', $suhosin);
87
+ $blacklist = array_map('trim', $suhosin);
88
+ $blacklist = array_map('strtolower', $blacklist);
89
+ if(in_array($function_callback, $blacklist))
90
+ return false;
91
+ }
92
+ }
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * Gets transient based on WP version
98
+ *
99
+ * @global string $wp_version
100
+ * @param string $option_name
101
+ * @return mixed
102
+ */
103
+
104
+ function mmb_set_transient($option_name = false, $data = false){
105
+
106
+ if (!$option_name || !$data) {
107
+ return false;
108
+ }
109
+ if($this->mmb_multisite)
110
+ return $this->mmb_set_sitemeta_transient($option_name, $data);
111
+
112
+ global $wp_version;
113
+
114
+ if (version_compare($wp_version, '2.7.9', '<=')) {
115
+ update_option($option_name, $data);
116
+ } else if (version_compare($wp_version, '2.9.9', '<=')) {
117
+ update_option('_transient_' . $option_name, $data);
118
+ } else {
119
+ update_option('_site_transient_' . $option_name, $data);
120
+ }
121
+
122
+ }
123
+ function mmb_get_transient($option_name)
124
+ {
125
+ if (trim($option_name) == '') {
126
+ return FALSE;
127
+ }
128
+ if($this->mmb_multisite)
129
+ return $this->mmb_get_sitemeta_transient($option_name);
130
+
131
+ global $wp_version;
132
+
133
+
134
+ if (version_compare($wp_version, '2.7.9', '<=')) {
135
+ return get_option($option_name);
136
+ } else if (version_compare($wp_version, '2.9.9', '<=')) {
137
+ return get_option('_transient_' . $option_name);
138
+ } else {
139
+ return get_option('_site_transient_' . $option_name);
140
+ }
141
+ }
142
+
143
+ function mmb_delete_transient($option_name)
144
+ {
145
+ if (trim($option_name) == '') {
146
+ return FALSE;
147
+ }
148
+
149
+ global $wp_version;
150
+
151
+ if (version_compare($wp_version, '2.7.9', '<=')) {
152
+ delete_option($option_name);
153
+ } else if (version_compare($wp_version, '2.9.9', '<=')) {
154
+ delete_option('_transient_' . $option_name);
155
+ } else {
156
+ delete_option('_site_transient_' . $option_name);
157
+ }
158
+ }
159
+
160
+ function mmb_get_sitemeta_transient($option_name){
161
+ global $wpdb;
162
+ $option_name = '_site_transient_'. $option_name;
163
+
164
+ $result = $wpdb->get_var( $wpdb->prepare("SELECT `meta_value` FROM `{$wpdb->sitemeta}` WHERE meta_key = '{$option_name}' AND `site_id` = '{$this->mmb_multisite}' "));
165
+ $result = maybe_unserialize($result);
166
+ return $result;
167
+ }
168
+
169
+ function mmb_set_sitemeta_transient($option_name, $option_value){
170
+ global $wpdb;
171
+ $option_name = '_site_transient_'. $option_name;
172
+
173
+ if($this->mmb_get_sitemeta_transient($option_name)){
174
+ $result = $wpdb->update( $wpdb->sitemeta,
175
+ array(
176
+ 'meta_value' => maybe_serialize($option_value)
177
+ ),
178
+ array(
179
+ 'meta_key' => $option_name,
180
+ 'site_id' => $this->mmb_multisite
181
+ )
182
+ );
183
+ }else {
184
+ $result = $wpdb->insert( $wpdb->sitemeta,
185
+ array(
186
+ 'meta_key' => $option_name,
187
+ 'meta_value' => maybe_serialize($option_value),
188
+ 'site_id' => $this->mmb_multisite
189
+ )
190
+ );
191
+ }
192
+ return $result;
193
+ }
194
+
195
+ function delete_temp_dir($directory)
196
+ {
197
+ if (substr($directory, -1) == "/") {
198
+ $directory = substr($directory, 0, -1);
199
+ }
200
+ if (!file_exists($directory) || !is_dir($directory)) {
201
+ return false;
202
+ } elseif (!is_readable($directory)) {
203
+ return false;
204
+ } else {
205
+ $directoryHandle = opendir($directory);
206
+
207
+ while ($contents = readdir($directoryHandle)) {
208
+ if ($contents != '.' && $contents != '..') {
209
+ $path = $directory . "/" . $contents;
210
+
211
+ if (is_dir($path)) {
212
+ $this->delete_temp_dir($path);
213
+ } else {
214
+ unlink($path);
215
+ }
216
+ }
217
+ }
218
+ closedir($directoryHandle);
219
+ rmdir($directory);
220
+ return true;
221
+ }
222
+ }
223
+
224
+ function set_worker_message_id($message_id = false)
225
+ {
226
+ if ($message_id) {
227
+ add_option('_action_message_id', $message_id) or update_option('_action_message_id', $message_id);
228
+ return $message_id;
229
+ }
230
+ return false;
231
+ }
232
+
233
+ function get_worker_message_id()
234
+ {
235
+ return (int) get_option('_action_message_id');
236
+ }
237
+
238
+ function set_master_public_key($public_key = false)
239
+ {
240
+ if ($public_key && !get_option('_worker_public_key')) {
241
+ add_option('_worker_public_key', base64_encode($public_key));
242
+ return true;
243
+ }
244
+ return false;
245
+ }
246
+
247
+ function get_master_public_key()
248
+ {
249
+ if (!get_option('_worker_public_key'))
250
+ return false;
251
+ return base64_decode(get_option('_worker_public_key'));
252
+ }
253
+
254
+
255
+ function get_random_signature()
256
+ {
257
+ if (!get_option('_worker_nossl_key'))
258
+ return false;
259
+ return base64_decode(get_option('_worker_nossl_key'));
260
+ }
261
+
262
+ function set_random_signature($random_key = false)
263
+ {
264
+ if ($random_key && !get_option('_worker_nossl_key')) {
265
+ add_option('_worker_nossl_key', base64_encode($random_key));
266
+ return true;
267
+ }
268
+ return false;
269
+ }
270
+
271
+
272
+ function authenticate_message($data = false, $signature = false, $message_id = false)
273
+ {
274
+ if (!$data && !$signature) {
275
+ return array(
276
+ 'error' => 'Authentication failed.'
277
+ );
278
+ }
279
+
280
+ $current_message = $this->get_worker_message_id();
281
+
282
+ if ((int) $current_message > (int) $message_id)
283
+ return array(
284
+ 'error' => 'Invalid message recieved. You can try to reinstall worker plugin and re-add the site to your account.'
285
+ );
286
+
287
+ $pl_key = $this->get_master_public_key();
288
+ if (!$pl_key) {
289
+ return array(
290
+ 'error' => 'Authentication failed (public key). You can try to reinstall worker plugin and re-add the site to your account.'
291
+ );
292
+ }
293
+
294
+ if (function_exists('openssl_verify') && !$this->get_random_signature()) {
295
+ $verify = openssl_verify($data, $signature, $pl_key);
296
+ if ($verify == 1) {
297
+ $message_id = $this->set_worker_message_id($message_id);
298
+ return true;
299
+ } else if ($verify == 0) {
300
+ return array(
301
+ 'error' => 'Invalid message signature. You can try to reinstall worker plugin and re-add the site to your account.'
302
+ );
303
+ } else {
304
+ return array(
305
+ 'error' => 'Command not successful! Please try again.'
306
+ );
307
+ }
308
+ } else if ($this->get_random_signature()) {
309
+ if (md5($data . $this->get_random_signature()) == $signature) {
310
+ $message_id = $this->set_worker_message_id($message_id);
311
+ return true;
312
+ }
313
+ return array(
314
+ 'error' => 'Invalid message signature. You can try to reinstall the worker plugin and then re-add the site to your dashboard.'
315
+ );
316
+ }
317
+ // no rand key - deleted in get_stat maybe
318
+ else
319
+ return array(
320
+ 'error' => 'Invalid message signature, try reinstalling worker plugin and re-adding the site to your dashboard.'
321
+ );
322
+ }
323
+
324
+ function _secure_data($data = false){
325
+ if($data == false)
326
+ return false;
327
+
328
+ $pl_key = $this->get_master_public_key();
329
+ if (!$pl_key)
330
+ return false;
331
+
332
+ $secure = '';
333
+ if( function_exists('openssl_public_decrypt') && !$this->get_random_signature()){
334
+ if(is_array($data) && !empty($data)){
335
+ foreach($data as $input){
336
+ openssl_public_decrypt($input, &$decrypted, $pl_key);
337
+ $secure .= $decrypted;
338
+ }
339
+ } else {
340
+ openssl_public_decrypt($input, &$decrypted, $pl_key);
341
+ $secure = $decrypted;
342
+ }
343
+ return $secure;
344
+ }
345
+ return false;
346
+
347
+ }
348
+
349
+ function check_if_user_exists($username = false)
350
+ {
351
+ global $wpdb;
352
+ if ($username) {
353
+ require_once(ABSPATH . WPINC . '/registration.php');
354
+ include_once(ABSPATH . 'wp-includes/pluggable.php');
355
+
356
+ if (username_exists($username) == null) {
357
+ return false;
358
+ }
359
+ $user = (array) get_userdatabylogin($username);
360
+
361
+ if ($user[$wpdb->prefix . 'user_level'] == 10 || isset($user[$wpdb->prefix . 'capabilities']['administrator']) ||
362
+ (isset($user['caps']['administrator']) && $user['caps']['administrator'] == 1)){
363
+ define('MMB_USER_CAPABILITIES', $user->wp_user_level);
364
+ return true;
365
+ }
366
+ return false;
367
+ }
368
+ return false;
369
+ }
370
+
371
+ function refresh_updates()
372
+ {
373
+ if (rand(1, 3) == '2') {
374
+ require_once(ABSPATH . WPINC . '/update.php');
375
+ wp_update_plugins();
376
+ wp_update_themes();
377
+ wp_version_check();
378
+ }
379
+ }
380
+
381
+ function remove_http($url = '')
382
+ {
383
+ if ($url == 'http://' OR $url == 'https://') {
384
+ return $url;
385
+ }
386
+ return preg_replace('/^(http|https)\:\/\/(www.)?/i', '', $url);
387
+
388
+ }
389
+
390
+ function mmb_get_error($error_object)
391
+ {
392
+ if (!is_wp_error($error_object)) {
393
+ return $error_object != '' ? $error_object : '';
394
+ } else {
395
+ $errors = array();
396
+ foreach ($error_object->error_data as $error_key => $error_string) {
397
+ $errors[] = str_replace('_', ' ', ucfirst($error_key)) . ': ' . $error_string;
398
+ }
399
+ return implode('<br />', $errors);
400
+ }
401
+ }
402
+
403
+ function is_server_writable(){
404
+ if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), false) != 'direct'))
405
+ return false;
406
+ else
407
+ return true;
408
+ }
409
+
410
+ function mmb_download_url($url, $file_name)
411
+ {
412
+ if (function_exists('fopen') && function_exists('ini_get') && ini_get('allow_url_fopen') == true && ($destination = @fopen($file_name, 'wb')) && ($source = @fopen($url, "r")) ) {
413
+
414
+
415
+ while ($a = @fread($source, 1024* 1024)) {
416
+ @fwrite($destination, $a);
417
+ }
418
+
419
+ fclose($source);
420
+ fclose($destination);
421
+ } else
422
+ if (!fsockopen_download($url, $file_name))
423
+ die('Error downloading file ' . $url);
424
+ return $file_name;
425
+ }
426
+
427
+ }
428
  ?>
init.php CHANGED
@@ -1,599 +1,630 @@
1
- <?php
2
- /*
3
- Plugin Name: ManageWP - Worker
4
- Plugin URI: http://managewp.com/
5
- Description: Manage all your blogs from one dashboard. Visit <a href="http://managewp.com">ManageWP.com</a> to sign up.
6
- Author: Prelovac Media
7
- Version: 3.9.5
8
- Author URI: http://www.prelovac.com
9
- */
10
-
11
- /*************************************************************
12
- *
13
- * init.php
14
- *
15
- * Initialize the communication with master
16
- *
17
- *
18
- * Copyright (c) 2011 Prelovac Media
19
- * www.prelovac.com
20
- **************************************************************/
21
-
22
-
23
- define('MMB_WORKER_VERSION', '3.9.5');
24
-
25
- global $wpdb, $mmb_plugin_dir, $mmb_plugin_url;
26
-
27
- if (version_compare(PHP_VERSION, '5.0.0', '<')) // min version 5 supported
28
- exit("<p>ManageWP Worker plugin requires PHP 5 or higher.</p>");
29
-
30
-
31
-
32
- global $wp_version;
33
-
34
- $mmb_wp_version = $wp_version;
35
- $mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
36
- $mmb_plugin_url = WP_PLUGIN_URL . '/' . basename(dirname(__FILE__));
37
-
38
- $mmb_actions = array(
39
- 'remove_site' => 'mmb_remove_site',
40
- 'get_stats' => 'mmb_stats_get',
41
- 'get_stats_notification' => 'mmb_get_stats_notification',
42
- 'backup_clone' => 'mmb_backup_now',
43
- 'restore' => 'mmb_restore_now',
44
- 'optimize_tables' => 'mmb_optimize_tables',
45
- 'check_wp_version' => 'mmb_wp_checkversion',
46
- 'create_post' => 'mmb_post_create',
47
- 'update_worker' => 'mmb_update_worker_plugin',
48
- 'change_comment_status' => 'mmb_change_comment_status',
49
- 'change_post_status' => 'mmb_change_post_status',
50
- 'get_comment_stats' => 'mmb_comment_stats_get',
51
- 'install_addon' => 'mmb_install_addon',
52
- 'do_upgrade' => 'mmb_do_upgrade',
53
- 'add_link' => 'mmb_add_link',
54
- 'add_user' => 'mmb_add_user',
55
- 'email_backup' => 'mmb_email_backup',
56
- 'check_backup_compat' => 'mmb_check_backup_compat',
57
- 'scheduled_backup' => 'mmb_scheduled_backup',
58
- 'execute_php_code' => 'mmb_execute_php_code',
59
- 'delete_backup' => 'mmm_delete_backup'
60
- );
61
-
62
- require_once("$mmb_plugin_dir/helper.class.php");
63
- require_once("$mmb_plugin_dir/core.class.php");
64
- require_once("$mmb_plugin_dir/post.class.php");
65
- require_once("$mmb_plugin_dir/comment.class.php");
66
- require_once("$mmb_plugin_dir/stats.class.php");
67
- require_once("$mmb_plugin_dir/backup.class.php");
68
- require_once("$mmb_plugin_dir/installer.class.php");
69
- require_once("$mmb_plugin_dir/link.class.php");
70
- require_once("$mmb_plugin_dir/user.class.php");
71
- require_once("$mmb_plugin_dir/api.php");
72
-
73
- require_once("$mmb_plugin_dir/plugins/search/search.php");
74
- require_once("$mmb_plugin_dir/plugins/cleanup/cleanup.php");
75
-
76
- //this is an exmaple plugin for extra_html element
77
- //require_once("$mmb_plugin_dir/plugins/extra_html_example/extra_html_example.php");
78
-
79
- $mmb_core = new MMB_Core();
80
- if( microtime(true) - (double)get_option('mwp_iframe_options_header') < 3600 ){
81
- remove_action( 'admin_init', 'send_frame_options_header');
82
- remove_action( 'login_init', 'send_frame_options_header');
83
- }
84
-
85
- add_action('init', 'mmb_parse_request');
86
-
87
-
88
- if (function_exists('register_activation_hook'))
89
- register_activation_hook(__FILE__, array(
90
- $mmb_core,
91
- 'install'
92
- ));
93
-
94
- if (function_exists('register_deactivation_hook'))
95
- register_deactivation_hook(__FILE__, array(
96
- $mmb_core,
97
- 'uninstall'
98
- ));
99
- do_action('after_db_upgrade');
100
- if( !function_exists ( 'mmb_parse_request' )) {
101
-
102
- function mmb_parse_request()
103
- {
104
-
105
- if (!isset($HTTP_RAW_POST_DATA)) {
106
- $HTTP_RAW_POST_DATA = file_get_contents('php://input');
107
- }
108
- ob_start();
109
-
110
- global $mmb_core, $mmb_actions, $new_actions, $wp_db_version, $wpmu_version, $_wp_using_ext_object_cache;
111
-
112
- $data = base64_decode($HTTP_RAW_POST_DATA);
113
- if ($data)
114
- $num = @extract(unserialize($data));
115
-
116
- if ($action) {
117
- $_wp_using_ext_object_cache = false;
118
- @set_time_limit(600);
119
-
120
- update_option('mwp_iframe_options_header', microtime(true));
121
- // mmb_response($mmb_actions, false);
122
- if (!$mmb_core->check_if_user_exists($params['username']))
123
- mmb_response('Username <b>' . $params['username'] . '</b> does not have administrator capabilities. Enter the correct username in the site options.', false);
124
-
125
- /* in case database upgrade required, do database backup and perform upgrade ( wordpress wp_upgrade() function ) */
126
- if( strlen(trim($wp_db_version)) ){
127
- if ( get_option('db_version') != $wp_db_version ) {
128
- /* in multisite network, please update database manualy */
129
- if (empty($wpmu_version) || (function_exists('is_multisite') && !is_multisite())){
130
- if( ! function_exists('wp_upgrade'))
131
- include_once(ABSPATH.'wp-admin/includes/upgrade.php');
132
-
133
- ob_clean();
134
- @wp_upgrade();
135
- @do_action('after_db_upgrade');
136
- ob_end_clean();
137
- }
138
- }
139
- }
140
-
141
- if ($action == 'add_site') {
142
- mmb_add_site($params);
143
- mmb_response('You should never see this.', false);
144
- }
145
- $auth = $mmb_core->authenticate_message($action . $id, $signature, $id);
146
- if ($auth === true) {
147
- if(isset($params['secure'])){
148
- if($decrypted = $mmb_core->_secure_data($params['secure'])){
149
- $decrypted = maybe_unserialize($decrypted);
150
- if(is_array($decrypted)){
151
- foreach($decrypted as $key => $val){
152
- if(!is_numeric($key))
153
- $params[$key] = $val;
154
- }
155
- unset($params['secure']);
156
- } else $params['secure'] = $decrypted;
157
- }
158
- }
159
-
160
- if (array_key_exists($action, $mmb_actions) && function_exists($mmb_actions[$action]))
161
- call_user_func($mmb_actions[$action], $params);
162
- else
163
- mmb_response('Action "' . $action . '" does not exist. Please update your Worker plugin.', false);
164
- } else {
165
- mmb_response($auth['error'], false);
166
- }
167
- }
168
-
169
-
170
- ob_end_clean();
171
- }
172
- }
173
- /* Main response function */
174
- if( !function_exists ( 'mmb_response' )) {
175
-
176
- function mmb_response($response = false, $success = true)
177
- {
178
- $return = array();
179
-
180
- if (empty($response) && strlen($response) == 0)
181
- $return['error'] = 'Empty response.';
182
- else if ($success)
183
- $return['success'] = $response;
184
- else
185
- $return['error'] = $response;
186
-
187
- if( !headers_sent() ){
188
- header('HTTP/1.0 200 OK');
189
- header('Content-Type: text/plain');
190
- }
191
- exit("<MWPHEADER>" . base64_encode(serialize($return))."<ENDMWPHEADER>");
192
- }
193
- }
194
-
195
- if( !function_exists ( 'mmb_add_site' )) {
196
- function mmb_add_site($params)
197
- {
198
- global $mmb_core;
199
-
200
- $num = extract($params);
201
-
202
- if ($num) {
203
- if (!get_option('_action_message_id') && !get_option('_worker_public_key')) {
204
- $public_key = base64_decode($public_key);
205
-
206
- if (function_exists('openssl_verify')) {
207
- $verify = openssl_verify($action . $id, base64_decode($signature), $public_key);
208
- if ($verify == 1) {
209
- $mmb_core->set_master_public_key($public_key);
210
- $mmb_core->set_worker_message_id($id);
211
- $mmb_core->get_stats_instance();
212
- mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
213
- } else if ($verify == 0) {
214
- mmb_response('Invalid message signature. Please contact us if you see this message often.', false);
215
- } else {
216
- mmb_response('Command not successful. Please try again.', false);
217
- }
218
- } else {
219
- if (!get_option('_worker_nossl_key')) {
220
- srand();
221
-
222
- $random_key = md5(base64_encode($public_key) . rand(0, getrandmax()));
223
-
224
- $mmb_core->set_random_signature($random_key);
225
- $mmb_core->set_worker_message_id($id);
226
- $mmb_core->set_master_public_key($public_key);
227
- $mmb_core->get_stats_instance();
228
- mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
229
- } else
230
- mmb_response('Please deactivate & activate ManageWP Worker plugin on your site, then re-add the site to your dashboard.', false);
231
- }
232
- } else {
233
- mmb_response('Please deactivate & activate ManageWP Worker plugin on your site and re-add the site to your dashboard.', false);
234
- }
235
- } else {
236
- mmb_response('Invalid parameters received. Please try again.', false);
237
- }
238
- }
239
- }
240
-
241
- if( !function_exists ( 'mmb_remove_site' )) {
242
- function mmb_remove_site($params)
243
- {
244
- extract($params);
245
- global $mmb_core;
246
- $mmb_core->uninstall();
247
-
248
- include_once(ABSPATH . 'wp-admin/includes/plugin.php');
249
- $plugin_slug = basename(dirname(__FILE__)) . '/' . basename(__FILE__);
250
-
251
- if ($deactivate) {
252
- deactivate_plugins($plugin_slug, true);
253
- }
254
-
255
- if (!is_plugin_active($plugin_slug))
256
- mmb_response(array(
257
- 'deactivated' => 'Site removed successfully. <br /><br />ManageWP Worker plugin successfully deactivated.'
258
- ), true);
259
- else
260
- mmb_response(array(
261
- 'removed_data' => 'Site removed successfully. <br /><br /><b>ManageWP Worker plugin was not deactivated.</b>'
262
- ), true);
263
-
264
- }
265
- }
266
- if( !function_exists ( 'mmb_stats_get' )) {
267
- function mmb_stats_get($params)
268
- {
269
- global $mmb_core;
270
- $mmb_core->get_stats_instance();
271
- mmb_response($mmb_core->stats_instance->get($params), true);
272
- }
273
- }
274
- if( !function_exists ( 'mmb_get_stats_notification' )) {
275
- function mmb_get_stats_notification($params)
276
- {
277
- global $mmb_core;
278
- $mmb_core->get_stats_instance();
279
- $stat = $mmb_core->stats_instance->get_stats_notification($params);
280
- mmb_response($stat, true);
281
- }
282
- }
283
- //post
284
- if( !function_exists ( 'mmb_post_create' )) {
285
- function mmb_post_create($params)
286
- {
287
- global $mmb_core;
288
- $mmb_core->get_post_instance();
289
- $return = $mmb_core->post_instance->create($params);
290
- if (is_int($return))
291
- mmb_response($return, true);
292
- else
293
- mmb_response($return, false);
294
- }
295
- }
296
-
297
- if( !function_exists ( 'mmb_change_post_status' )) {
298
- function mmb_change_post_status($params)
299
- {
300
- global $mmb_core;
301
- $mmb_core->get_post_instance();
302
- $return = $mmb_core->post_instance->change_status($params);
303
- //mmb_response($return, true);
304
-
305
- }
306
- }
307
-
308
- //comments
309
- if( !function_exists ( 'mmb_change_comment_status' )) {
310
- function mmb_change_comment_status($params)
311
- {
312
- global $mmb_core;
313
- $mmb_core->get_comment_instance();
314
- $return = $mmb_core->comment_instance->change_status($params);
315
- //mmb_response($return, true);
316
- if ($return){
317
- $mmb_core->get_stats_instance();
318
- mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
319
- }else
320
- mmb_response('Comment not updated', false);
321
- }
322
-
323
- }
324
- if( !function_exists ( 'mmb_comment_stats_get' )) {
325
- function mmb_comment_stats_get($params)
326
- {
327
- global $mmb_core;
328
- $mmb_core->get_stats_instance();
329
- mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
330
- }
331
- }
332
-
333
- if( !function_exists ( 'mmb_backup_now' )) {
334
- //backup
335
- function mmb_backup_now($params)
336
- {
337
- global $mmb_core;
338
-
339
- $mmb_core->get_backup_instance();
340
- $return = $mmb_core->backup_instance->backup($params);
341
-
342
- if (is_array($return) && array_key_exists('error', $return))
343
- mmb_response($return['error'], false);
344
- else {
345
- mmb_response($return, true);
346
- }
347
- }
348
- }
349
-
350
- if( !function_exists ( 'mmb_email_backup' )) {
351
- function mmb_email_backup($params)
352
- {
353
- global $mmb_core;
354
- $mmb_core->get_backup_instance();
355
- $return = $mmb_core->backup_instance->email_backup($params);
356
-
357
- if (is_array($return) && array_key_exists('error', $return))
358
- mmb_response($return['error'], false);
359
- else {
360
- mmb_response($return, true);
361
- }
362
- }
363
- }
364
- if( !function_exists ( 'mmb_check_backup_compat' )) {
365
- function mmb_check_backup_compat($params)
366
- {
367
- global $mmb_core;
368
- $mmb_core->get_backup_instance();
369
- $return = $mmb_core->backup_instance->check_backup_compat($params);
370
-
371
- if (is_array($return) && array_key_exists('error', $return))
372
- mmb_response($return['error'], false);
373
- else {
374
- mmb_response($return, true);
375
- }
376
- }
377
- }
378
-
379
- if( !function_exists ( 'mmb_scheduled_backup' )) {
380
- function mmb_scheduled_backup($params)
381
- {
382
-
383
- global $mmb_core;
384
- $mmb_core->get_backup_instance();
385
- $return = $mmb_core->backup_instance->set_backup_task($params);
386
- mmb_response($return, $return);
387
- }
388
- }
389
-
390
- if( !function_exists ( 'mmm_delete_backup' )) {
391
- function mmm_delete_backup($params)
392
- {
393
- global $mmb_core;
394
- $mmb_core->get_backup_instance();
395
- $return = $mmb_core->backup_instance->delete_backup($params);
396
- mmb_response($return, $return);
397
- }
398
- }
399
-
400
- if( !function_exists ( 'mmb_optimize_tables' )) {
401
- function mmb_optimize_tables($params)
402
- {
403
- global $mmb_core;
404
- $mmb_core->get_backup_instance();
405
- $return = $mmb_core->backup_instance->optimize_tables();
406
- if ($return)
407
- mmb_response($return, true);
408
- else
409
- mmb_response(false, false);
410
- }
411
- }
412
- if( !function_exists ( 'mmb_restore_now' )) {
413
- function mmb_restore_now($params)
414
- {
415
- global $mmb_core;
416
- $mmb_core->get_backup_instance();
417
- $return = $mmb_core->backup_instance->restore($params);
418
- if (is_array($return) && array_key_exists('error', $return))
419
- mmb_response($return['error'], false);
420
- else
421
- mmb_response($return, true);
422
-
423
- }
424
- }
425
- if( !function_exists ( 'mmb_update_worker_plugin' )) {
426
- function mmb_update_worker_plugin($params)
427
- {
428
- global $mmb_core;
429
- mmb_response($mmb_core->update_worker_plugin($params), true);
430
- }
431
- }
432
-
433
- if( !function_exists ( 'mmb_wp_checkversion' )) {
434
- function mmb_wp_checkversion($params)
435
- {
436
- include_once(ABSPATH . 'wp-includes/version.php');
437
- global $mmb_wp_version, $mmb_core;
438
- mmb_response($mmb_wp_version, true);
439
- }
440
- }
441
- if( !function_exists ( 'mmb_search_posts_by_term' )) {
442
- function mmb_search_posts_by_term($params)
443
- {
444
- global $mmb_core;
445
- $mmb_core->get_search_instance();
446
-
447
- $search_type = trim($params['search_type']);
448
- $search_term = strtolower(trim($params['search_term']));
449
-
450
- switch ($search_type){
451
- case 'page_post':
452
- $return = $mmb_core->search_instance->search_posts_by_term($params);
453
- if($return){
454
- $return = serialize($return);
455
- mmb_response($return, true);
456
- }else{
457
- mmb_response('No posts found', false);
458
- }
459
- break;
460
-
461
- case 'plugin':
462
- $plugins = get_option('active_plugins');
463
-
464
- $have_plugin = false;
465
- foreach ($plugins as $plugin) {
466
- if(strpos($plugin, $search_term)>-1){
467
- $have_plugin = true;
468
- }
469
- }
470
- if($have_plugin){
471
- mmb_response(serialize($plugin), true);
472
- }else{
473
- mmb_response(false, false);
474
- }
475
- break;
476
- case 'theme':
477
- $theme = strtolower(get_option('template'));
478
- if(strpos($theme, $search_term)>-1){
479
- mmb_response($theme, true);
480
- }else{
481
- mmb_response(false, false);
482
- }
483
- break;
484
- default: mmb_response(false, false);
485
- }
486
- $return = $mmb_core->search_instance->search_posts_by_term($params);
487
-
488
-
489
-
490
- if ($return_if_true) {
491
- mmb_response($return_value, true);
492
- } else {
493
- mmb_response($return_if_false, false);
494
- }
495
- }
496
- }
497
-
498
- if( !function_exists ( 'mmb_install_addon' )) {
499
- function mmb_install_addon($params)
500
- {
501
- global $mmb_core;
502
- $mmb_core->get_installer_instance();
503
- $return = $mmb_core->installer_instance->install_remote_file($params);
504
- mmb_response($return, true);
505
-
506
- }
507
- }
508
-
509
- if( !function_exists ( 'mmb_do_upgrade' )) {
510
- function mmb_do_upgrade($params)
511
- {
512
- global $mmb_core, $mmb_upgrading;
513
- $mmb_core->get_installer_instance();
514
- $return = $mmb_core->installer_instance->do_upgrade($params);
515
- mmb_response($return, true);
516
-
517
- }
518
- }
519
- if( !function_exists ( 'mmb_add_link' )) {
520
- function mmb_add_link($params)
521
- {
522
- global $mmb_core;
523
- $mmb_core->get_link_instance();
524
- $return = $mmb_core->link_instance->add_link($params);
525
- if (is_array($return) && array_key_exists('error', $return))
526
-
527
- mmb_response($return['error'], false);
528
- else {
529
- mmb_response($return, true);
530
- }
531
-
532
- }
533
- }
534
-
535
-
536
- if( !function_exists ( 'mmb_add_user' )) {
537
- function mmb_add_user($params)
538
- {
539
- global $mmb_core;
540
- $mmb_core->get_user_instance();
541
- $return = $mmb_core->user_instance->add_user($params);
542
- if (is_array($return) && array_key_exists('error', $return))
543
-
544
- mmb_response($return['error'], false);
545
- else {
546
- mmb_response($return, true);
547
- }
548
-
549
- }
550
- }
551
- add_filter('install_plugin_complete_actions','mmb_iframe_plugins_fix');
552
- if( !function_exists ( 'mmb_iframe_plugins_fix' )) {
553
- function mmb_iframe_plugins_fix($update_actions)
554
- {
555
- foreach($update_actions as $key => $action)
556
- {
557
- $update_actions[$key] = str_replace('target="_parent"','',$action);
558
- }
559
-
560
- return $update_actions;
561
-
562
- }
563
- }
564
- if( !function_exists ( 'mmb_execute_php_code' )) {
565
- function mmb_execute_php_code($params)
566
- {
567
- ob_start();
568
- eval($params['code']);
569
- $return = ob_get_flush();
570
- mmb_response(print_r($return, true), true);
571
- }
572
- }
573
-
574
- if(!function_exists('mmb_more_reccurences')){
575
- //Backup Tasks
576
- add_filter('cron_schedules', 'mmb_more_reccurences');
577
- function mmb_more_reccurences() {
578
- return array(
579
- 'minutely' => array('interval' => 60, 'display' => 'Once in a minute'),
580
- 'fiveminutes' => array('interval' => 300, 'display' => 'Once in a five minutes')
581
- );
582
- }
583
- }
584
-
585
- if (!wp_next_scheduled('mwp_backup_tasks')) {
586
- wp_schedule_event( time(), 'fiveminutes', 'mwp_backup_tasks' );
587
- }
588
- add_action('mwp_backup_tasks', 'mwp_check_backup_tasks');
589
-
590
-
591
-
592
- function mwp_check_backup_tasks() {
593
- global $mmb_core;
594
- $mmb_core->get_backup_instance()->check_backup_tasks();
595
- }
596
-
597
-
598
-
599
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*
3
+ Plugin Name: ManageWP - Worker
4
+ Plugin URI: http://managewp.com/
5
+ Description: Manage all your blogs from one dashboard. Visit <a href="http://managewp.com">ManageWP.com</a> to sign up.
6
+ Author: Prelovac Media
7
+ Version: 3.9.6
8
+ Author URI: http://www.prelovac.com
9
+ */
10
+
11
+ /*************************************************************
12
+ *
13
+ * init.php
14
+ *
15
+ * Initialize the communication with master
16
+ *
17
+ *
18
+ * Copyright (c) 2011 Prelovac Media
19
+ * www.prelovac.com
20
+ **************************************************************/
21
+
22
+
23
+ define('MMB_WORKER_VERSION', '3.9.6');
24
+
25
+ global $wpdb, $mmb_plugin_dir, $mmb_plugin_url;
26
+
27
+ if (version_compare(PHP_VERSION, '5.0.0', '<')) // min version 5 supported
28
+ exit("<p>ManageWP Worker plugin requires PHP 5 or higher.</p>");
29
+
30
+
31
+
32
+ global $wp_version;
33
+
34
+ $mmb_wp_version = $wp_version;
35
+ $mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
36
+ $mmb_plugin_url = WP_PLUGIN_URL . '/' . basename(dirname(__FILE__));
37
+
38
+ $mmb_actions = array(
39
+ 'remove_site' => 'mmb_remove_site',
40
+ 'get_stats' => 'mmb_stats_get',
41
+ 'get_stats_notification' => 'mmb_get_stats_notification',
42
+ 'backup_clone' => 'mmb_backup_now',
43
+ 'restore' => 'mmb_restore_now',
44
+ 'optimize_tables' => 'mmb_optimize_tables',
45
+ 'check_wp_version' => 'mmb_wp_checkversion',
46
+ 'create_post' => 'mmb_post_create',
47
+ 'update_worker' => 'mmb_update_worker_plugin',
48
+ 'change_comment_status' => 'mmb_change_comment_status',
49
+ 'change_post_status' => 'mmb_change_post_status',
50
+ 'get_comment_stats' => 'mmb_comment_stats_get',
51
+ 'install_addon' => 'mmb_install_addon',
52
+ 'do_upgrade' => 'mmb_do_upgrade',
53
+ 'add_link' => 'mmb_add_link',
54
+ 'add_user' => 'mmb_add_user',
55
+ 'email_backup' => 'mmb_email_backup',
56
+ 'check_backup_compat' => 'mmb_check_backup_compat',
57
+ 'scheduled_backup' => 'mmb_scheduled_backup',
58
+ 'execute_php_code' => 'mmb_execute_php_code',
59
+ 'delete_backup' => 'mmm_delete_backup',
60
+ 'remote_backup_now' => 'mmb_remote_backup_now',
61
+ 'clean_orphan_backups' => 'mmb_clean_orphan_backups'
62
+ );
63
+
64
+ require_once("$mmb_plugin_dir/helper.class.php");
65
+ require_once("$mmb_plugin_dir/core.class.php");
66
+ require_once("$mmb_plugin_dir/post.class.php");
67
+ require_once("$mmb_plugin_dir/comment.class.php");
68
+ require_once("$mmb_plugin_dir/stats.class.php");
69
+ require_once("$mmb_plugin_dir/backup.class.php");
70
+ require_once("$mmb_plugin_dir/installer.class.php");
71
+ require_once("$mmb_plugin_dir/link.class.php");
72
+ require_once("$mmb_plugin_dir/user.class.php");
73
+ require_once("$mmb_plugin_dir/api.php");
74
+
75
+ require_once("$mmb_plugin_dir/plugins/search/search.php");
76
+ require_once("$mmb_plugin_dir/plugins/cleanup/cleanup.php");
77
+
78
+ //this is an exmaple plugin for extra_html element
79
+ //require_once("$mmb_plugin_dir/plugins/extra_html_example/extra_html_example.php");
80
+
81
+ $mmb_core = new MMB_Core();
82
+ if( microtime(true) - (double)get_option('mwp_iframe_options_header') < 3600 ){
83
+ remove_action( 'admin_init', 'send_frame_options_header');
84
+ remove_action( 'login_init', 'send_frame_options_header');
85
+ }
86
+
87
+ add_action('init', 'mmb_parse_request');
88
+
89
+
90
+ if (function_exists('register_activation_hook'))
91
+ register_activation_hook(__FILE__, array(
92
+ $mmb_core,
93
+ 'install'
94
+ ));
95
+
96
+ if (function_exists('register_deactivation_hook'))
97
+ register_deactivation_hook(__FILE__, array(
98
+ $mmb_core,
99
+ 'uninstall'
100
+ ));
101
+ do_action('after_db_upgrade');
102
+ if( !function_exists ( 'mmb_parse_request' )) {
103
+
104
+ function mmb_parse_request()
105
+ {
106
+
107
+ if (!isset($HTTP_RAW_POST_DATA)) {
108
+ $HTTP_RAW_POST_DATA = file_get_contents('php://input');
109
+ }
110
+ ob_start();
111
+
112
+ global $mmb_core, $mmb_actions, $new_actions, $wp_db_version, $wpmu_version, $_wp_using_ext_object_cache;
113
+
114
+ $data = base64_decode($HTTP_RAW_POST_DATA);
115
+ if ($data)
116
+ $num = @extract(unserialize($data));
117
+
118
+ if ($action) {
119
+ $_wp_using_ext_object_cache = false;
120
+ @set_time_limit(600);
121
+
122
+ update_option('mwp_iframe_options_header', microtime(true));
123
+ // mmb_response($mmb_actions, false);
124
+ if (!$mmb_core->check_if_user_exists($params['username']))
125
+ mmb_response('Username <b>' . $params['username'] . '</b> does not have administrator capabilities. Enter the correct username in the site options.', false);
126
+
127
+ /* in case database upgrade required, do database backup and perform upgrade ( wordpress wp_upgrade() function ) */
128
+ if( strlen(trim($wp_db_version)) ){
129
+ if ( get_option('db_version') != $wp_db_version ) {
130
+ /* in multisite network, please update database manualy */
131
+ if (empty($wpmu_version) || (function_exists('is_multisite') && !is_multisite())){
132
+ if( ! function_exists('wp_upgrade'))
133
+ include_once(ABSPATH.'wp-admin/includes/upgrade.php');
134
+
135
+ ob_clean();
136
+ @wp_upgrade();
137
+ @do_action('after_db_upgrade');
138
+ ob_end_clean();
139
+ }
140
+ }
141
+ }
142
+
143
+ if ($action == 'add_site') {
144
+ mmb_add_site($params);
145
+ mmb_response('You should never see this.', false);
146
+ }
147
+ $auth = $mmb_core->authenticate_message($action . $id, $signature, $id);
148
+ if ($auth === true) {
149
+ if(isset($params['secure'])){
150
+ if($decrypted = $mmb_core->_secure_data($params['secure'])){
151
+ $decrypted = maybe_unserialize($decrypted);
152
+ if(is_array($decrypted)){
153
+ foreach($decrypted as $key => $val){
154
+ if(!is_numeric($key))
155
+ $params[$key] = $val;
156
+ }
157
+ unset($params['secure']);
158
+ } else $params['secure'] = $decrypted;
159
+ }
160
+ }
161
+
162
+ if (array_key_exists($action, $mmb_actions) && function_exists($mmb_actions[$action]))
163
+ call_user_func($mmb_actions[$action], $params);
164
+ else
165
+ mmb_response('Action "' . $action . '" does not exist. Please update your Worker plugin.', false);
166
+ } else {
167
+ mmb_response($auth['error'], false);
168
+ }
169
+ }
170
+
171
+
172
+ ob_end_clean();
173
+ }
174
+ }
175
+ /* Main response function */
176
+ if( !function_exists ( 'mmb_response' )) {
177
+
178
+ function mmb_response($response = false, $success = true)
179
+ {
180
+ $return = array();
181
+
182
+ if (empty($response) && strlen($response) == 0)
183
+ $return['error'] = 'Empty response.';
184
+ else if ($success)
185
+ $return['success'] = $response;
186
+ else
187
+ $return['error'] = $response;
188
+
189
+ if( !headers_sent() ){
190
+ header('HTTP/1.0 200 OK');
191
+ header('Content-Type: text/plain');
192
+ }
193
+ exit("<MWPHEADER>" . base64_encode(serialize($return))."<ENDMWPHEADER>");
194
+ }
195
+ }
196
+
197
+
198
+
199
+ if( !function_exists ( 'mmb_add_site' )) {
200
+ function mmb_add_site($params)
201
+ {
202
+ global $mmb_core;
203
+
204
+ $num = extract($params);
205
+
206
+ if ($num) {
207
+ if (!get_option('_action_message_id') && !get_option('_worker_public_key')) {
208
+ $public_key = base64_decode($public_key);
209
+
210
+ if (function_exists('openssl_verify')) {
211
+ $verify = openssl_verify($action . $id, base64_decode($signature), $public_key);
212
+ if ($verify == 1) {
213
+ $mmb_core->set_master_public_key($public_key);
214
+ $mmb_core->set_worker_message_id($id);
215
+ $mmb_core->get_stats_instance();
216
+ mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
217
+ } else if ($verify == 0) {
218
+ mmb_response('Invalid message signature. Please contact us if you see this message often.', false);
219
+ } else {
220
+ mmb_response('Command not successful. Please try again.', false);
221
+ }
222
+ } else {
223
+ if (!get_option('_worker_nossl_key')) {
224
+ srand();
225
+
226
+ $random_key = md5(base64_encode($public_key) . rand(0, getrandmax()));
227
+
228
+ $mmb_core->set_random_signature($random_key);
229
+ $mmb_core->set_worker_message_id($id);
230
+ $mmb_core->set_master_public_key($public_key);
231
+ $mmb_core->get_stats_instance();
232
+ mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
233
+ } else
234
+ mmb_response('Please deactivate & activate ManageWP Worker plugin on your site, then re-add the site to your dashboard.', false);
235
+ }
236
+ } else {
237
+ mmb_response('Please deactivate & activate ManageWP Worker plugin on your site and re-add the site to your dashboard.', false);
238
+ }
239
+ } else {
240
+ mmb_response('Invalid parameters received. Please try again.', false);
241
+ }
242
+ }
243
+ }
244
+
245
+ if( !function_exists ( 'mmb_remove_site' )) {
246
+ function mmb_remove_site($params)
247
+ {
248
+ extract($params);
249
+ global $mmb_core;
250
+ $mmb_core->uninstall();
251
+
252
+ include_once(ABSPATH . 'wp-admin/includes/plugin.php');
253
+ $plugin_slug = basename(dirname(__FILE__)) . '/' . basename(__FILE__);
254
+
255
+ if ($deactivate) {
256
+ deactivate_plugins($plugin_slug, true);
257
+ }
258
+
259
+ if (!is_plugin_active($plugin_slug))
260
+ mmb_response(array(
261
+ 'deactivated' => 'Site removed successfully. <br /><br />ManageWP Worker plugin successfully deactivated.'
262
+ ), true);
263
+ else
264
+ mmb_response(array(
265
+ 'removed_data' => 'Site removed successfully. <br /><br /><b>ManageWP Worker plugin was not deactivated.</b>'
266
+ ), true);
267
+
268
+ }
269
+ }
270
+ if( !function_exists ( 'mmb_stats_get' )) {
271
+ function mmb_stats_get($params)
272
+ {
273
+ global $mmb_core;
274
+ $mmb_core->get_stats_instance();
275
+ mmb_response($mmb_core->stats_instance->get($params), true);
276
+ }
277
+ }
278
+ if( !function_exists ( 'mmb_get_stats_notification' )) {
279
+ function mmb_get_stats_notification($params)
280
+ {
281
+ global $mmb_core;
282
+ $mmb_core->get_stats_instance();
283
+ $stat = $mmb_core->stats_instance->get_stats_notification($params);
284
+ mmb_response($stat, true);
285
+ }
286
+ }
287
+ //post
288
+ if( !function_exists ( 'mmb_post_create' )) {
289
+ function mmb_post_create($params)
290
+ {
291
+ global $mmb_core;
292
+ $mmb_core->get_post_instance();
293
+ $return = $mmb_core->post_instance->create($params);
294
+ if (is_int($return))
295
+ mmb_response($return, true);
296
+ else
297
+ mmb_response($return, false);
298
+ }
299
+ }
300
+
301
+ if( !function_exists ( 'mmb_change_post_status' )) {
302
+ function mmb_change_post_status($params)
303
+ {
304
+ global $mmb_core;
305
+ $mmb_core->get_post_instance();
306
+ $return = $mmb_core->post_instance->change_status($params);
307
+ //mmb_response($return, true);
308
+
309
+ }
310
+ }
311
+
312
+ //comments
313
+ if( !function_exists ( 'mmb_change_comment_status' )) {
314
+ function mmb_change_comment_status($params)
315
+ {
316
+ global $mmb_core;
317
+ $mmb_core->get_comment_instance();
318
+ $return = $mmb_core->comment_instance->change_status($params);
319
+ //mmb_response($return, true);
320
+ if ($return){
321
+ $mmb_core->get_stats_instance();
322
+ mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
323
+ }else
324
+ mmb_response('Comment not updated', false);
325
+ }
326
+
327
+ }
328
+ if( !function_exists ( 'mmb_comment_stats_get' )) {
329
+ function mmb_comment_stats_get($params)
330
+ {
331
+ global $mmb_core;
332
+ $mmb_core->get_stats_instance();
333
+ mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
334
+ }
335
+ }
336
+
337
+ if( !function_exists ( 'mmb_backup_now' )) {
338
+ //backup
339
+ function mmb_backup_now($params)
340
+ {
341
+ global $mmb_core;
342
+
343
+ $mmb_core->get_backup_instance();
344
+ $return = $mmb_core->backup_instance->backup($params);
345
+
346
+ if (is_array($return) && array_key_exists('error', $return))
347
+ mmb_response($return['error'], false);
348
+ else {
349
+ mmb_response($return, true);
350
+ }
351
+ }
352
+ }
353
+
354
+ if( !function_exists ( 'mmb_email_backup' )) {
355
+ function mmb_email_backup($params)
356
+ {
357
+ global $mmb_core;
358
+ $mmb_core->get_backup_instance();
359
+ $return = $mmb_core->backup_instance->email_backup($params);
360
+
361
+ if (is_array($return) && array_key_exists('error', $return))
362
+ mmb_response($return['error'], false);
363
+ else {
364
+ mmb_response($return, true);
365
+ }
366
+ }
367
+ }
368
+ if( !function_exists ( 'mmb_check_backup_compat' )) {
369
+ function mmb_check_backup_compat($params)
370
+ {
371
+ global $mmb_core;
372
+ $mmb_core->get_backup_instance();
373
+ $return = $mmb_core->backup_instance->check_backup_compat($params);
374
+
375
+ if (is_array($return) && array_key_exists('error', $return))
376
+ mmb_response($return['error'], false);
377
+ else {
378
+ mmb_response($return, true);
379
+ }
380
+ }
381
+ }
382
+
383
+ if( !function_exists ( 'mmb_scheduled_backup' )) {
384
+ function mmb_scheduled_backup($params)
385
+ {
386
+
387
+ global $mmb_core;
388
+ $mmb_core->get_backup_instance();
389
+ $return = $mmb_core->backup_instance->set_backup_task($params);
390
+ mmb_response($return, $return);
391
+ }
392
+ }
393
+
394
+ if( !function_exists ( 'mmm_delete_backup' )) {
395
+ function mmm_delete_backup($params)
396
+ {
397
+ global $mmb_core;
398
+ $mmb_core->get_backup_instance();
399
+ $return = $mmb_core->backup_instance->delete_backup($params);
400
+ mmb_response($return, $return);
401
+ }
402
+ }
403
+
404
+ if( !function_exists ( 'mmb_optimize_tables' )) {
405
+ function mmb_optimize_tables($params)
406
+ {
407
+ global $mmb_core;
408
+ $mmb_core->get_backup_instance();
409
+ $return = $mmb_core->backup_instance->optimize_tables();
410
+ if ($return)
411
+ mmb_response($return, true);
412
+ else
413
+ mmb_response(false, false);
414
+ }
415
+ }
416
+ if( !function_exists ( 'mmb_restore_now' )) {
417
+ function mmb_restore_now($params)
418
+ {
419
+ global $mmb_core;
420
+ $mmb_core->get_backup_instance();
421
+ $return = $mmb_core->backup_instance->restore($params);
422
+ if (is_array($return) && array_key_exists('error', $return))
423
+ mmb_response($return['error'], false);
424
+ else
425
+ mmb_response($return, true);
426
+
427
+ }
428
+ }
429
+
430
+ if( !function_exists ( 'mmb_remote_backup_now' )) {
431
+ function mmb_remote_backup_now($params)
432
+ {
433
+ global $mmb_core;
434
+ $backup_instance = $mmb_core->get_backup_instance();
435
+ $return = $mmb_core->backup_instance->remote_backup_now($params);
436
+ if (is_array($return) && array_key_exists('error', $return))
437
+ mmb_response($return['error'], false);
438
+ else
439
+ mmb_response($return, true);
440
+ }
441
+ }
442
+
443
+
444
+ if( !function_exists ( 'mmb_clean_orphan_backups' )) {
445
+ function mmb_clean_orphan_backups()
446
+ {
447
+ global $mmb_core;
448
+ $backup_instance = $mmb_core->get_backup_instance();
449
+ $return = $mmb_core->backup_instance->cleanup();
450
+ if(is_array($return))
451
+ mmb_response($return, true);
452
+ else
453
+ mmb_response($return, false);
454
+ }
455
+ }
456
+
457
+ if( !function_exists ( 'mmb_update_worker_plugin' )) {
458
+ function mmb_update_worker_plugin($params)
459
+ {
460
+ global $mmb_core;
461
+ mmb_response($mmb_core->update_worker_plugin($params), true);
462
+ }
463
+ }
464
+
465
+ if( !function_exists ( 'mmb_wp_checkversion' )) {
466
+ function mmb_wp_checkversion($params)
467
+ {
468
+ include_once(ABSPATH . 'wp-includes/version.php');
469
+ global $mmb_wp_version, $mmb_core;
470
+ mmb_response($mmb_wp_version, true);
471
+ }
472
+ }
473
+ if( !function_exists ( 'mmb_search_posts_by_term' )) {
474
+ function mmb_search_posts_by_term($params)
475
+ {
476
+ global $mmb_core;
477
+ $mmb_core->get_search_instance();
478
+
479
+ $search_type = trim($params['search_type']);
480
+ $search_term = strtolower(trim($params['search_term']));
481
+
482
+ switch ($search_type){
483
+ case 'page_post':
484
+ $return = $mmb_core->search_instance->search_posts_by_term($params);
485
+ if($return){
486
+ $return = serialize($return);
487
+ mmb_response($return, true);
488
+ }else{
489
+ mmb_response('No posts found', false);
490
+ }
491
+ break;
492
+
493
+ case 'plugin':
494
+ $plugins = get_option('active_plugins');
495
+
496
+ $have_plugin = false;
497
+ foreach ($plugins as $plugin) {
498
+ if(strpos($plugin, $search_term)>-1){
499
+ $have_plugin = true;
500
+ }
501
+ }
502
+ if($have_plugin){
503
+ mmb_response(serialize($plugin), true);
504
+ }else{
505
+ mmb_response(false, false);
506
+ }
507
+ break;
508
+ case 'theme':
509
+ $theme = strtolower(get_option('template'));
510
+ if(strpos($theme, $search_term)>-1){
511
+ mmb_response($theme, true);
512
+ }else{
513
+ mmb_response(false, false);
514
+ }
515
+ break;
516
+ default: mmb_response(false, false);
517
+ }
518
+ $return = $mmb_core->search_instance->search_posts_by_term($params);
519
+
520
+
521
+
522
+ if ($return_if_true) {
523
+ mmb_response($return_value, true);
524
+ } else {
525
+ mmb_response($return_if_false, false);
526
+ }
527
+ }
528
+ }
529
+
530
+ if( !function_exists ( 'mmb_install_addon' )) {
531
+ function mmb_install_addon($params)
532
+ {
533
+ global $mmb_core;
534
+ $mmb_core->get_installer_instance();
535
+ $return = $mmb_core->installer_instance->install_remote_file($params);
536
+ mmb_response($return, true);
537
+
538
+ }
539
+ }
540
+
541
+ if( !function_exists ( 'mmb_do_upgrade' )) {
542
+ function mmb_do_upgrade($params)
543
+ {
544
+ global $mmb_core, $mmb_upgrading;
545
+ $mmb_core->get_installer_instance();
546
+ $return = $mmb_core->installer_instance->do_upgrade($params);
547
+ mmb_response($return, true);
548
+
549
+ }
550
+ }
551
+ if( !function_exists ( 'mmb_add_link' )) {
552
+ function mmb_add_link($params)
553
+ {
554
+ global $mmb_core;
555
+ $mmb_core->get_link_instance();
556
+ $return = $mmb_core->link_instance->add_link($params);
557
+ if (is_array($return) && array_key_exists('error', $return))
558
+
559
+ mmb_response($return['error'], false);
560
+ else {
561
+ mmb_response($return, true);
562
+ }
563
+
564
+ }
565
+ }
566
+
567
+
568
+ if( !function_exists ( 'mmb_add_user' )) {
569
+ function mmb_add_user($params)
570
+ {
571
+ global $mmb_core;
572
+ $mmb_core->get_user_instance();
573
+ $return = $mmb_core->user_instance->add_user($params);
574
+ if (is_array($return) && array_key_exists('error', $return))
575
+
576
+ mmb_response($return['error'], false);
577
+ else {
578
+ mmb_response($return, true);
579
+ }
580
+
581
+ }
582
+ }
583
+ add_filter('install_plugin_complete_actions','mmb_iframe_plugins_fix');
584
+ if( !function_exists ( 'mmb_iframe_plugins_fix' )) {
585
+ function mmb_iframe_plugins_fix($update_actions)
586
+ {
587
+ foreach($update_actions as $key => $action)
588
+ {
589
+ $update_actions[$key] = str_replace('target="_parent"','',$action);
590
+ }
591
+
592
+ return $update_actions;
593
+
594
+ }
595
+ }
596
+ if( !function_exists ( 'mmb_execute_php_code' )) {
597
+ function mmb_execute_php_code($params)
598
+ {
599
+ ob_start();
600
+ eval($params['code']);
601
+ $return = ob_get_flush();
602
+ mmb_response(print_r($return, true), true);
603
+ }
604
+ }
605
+
606
+ if(!function_exists('mmb_more_reccurences')){
607
+ //Backup Tasks
608
+ add_filter('cron_schedules', 'mmb_more_reccurences');
609
+ function mmb_more_reccurences() {
610
+ return array(
611
+ 'minutely' => array('interval' => 60, 'display' => 'Once in a minute'),
612
+ 'fiveminutes' => array('interval' => 300, 'display' => 'Once in a five minutes')
613
+ );
614
+ }
615
+ }
616
+
617
+ if (!wp_next_scheduled('mwp_backup_tasks')) {
618
+ wp_schedule_event( time(), 'fiveminutes', 'mwp_backup_tasks' );
619
+ }
620
+ add_action('mwp_backup_tasks', 'mwp_check_backup_tasks');
621
+
622
+
623
+ if( !function_exists('mwp_check_backup_tasks') ){
624
+ function mwp_check_backup_tasks() {
625
+ global $mmb_core;
626
+ $mmb_core->get_backup_instance();
627
+ $mmb_core->backup_instance->check_backup_tasks();
628
+ }
629
+ }
630
+ ?>
installer.class.php CHANGED
@@ -1,451 +1,452 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * installer.class.php
5
- *
6
- * Upgrade WordPress
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Installer extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- @set_time_limit(300);
18
- parent::__construct();
19
- include_once(ABSPATH . 'wp-admin/includes/file.php');
20
- include_once(ABSPATH . 'wp-admin/includes/plugin.php');
21
- include_once(ABSPATH . 'wp-admin/includes/theme.php');
22
- include_once(ABSPATH . 'wp-admin/includes/misc.php');
23
- include_once(ABSPATH . 'wp-admin/includes/template.php');
24
- @include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
25
-
26
- global $wp_filesystem;
27
- if (!$wp_filesystem)
28
- WP_Filesystem();
29
-
30
- }
31
-
32
- function mmb_maintenance_mode($enable = false, $maintenance_message = '')
33
- {
34
- global $wp_filesystem;
35
-
36
- $maintenance_message .= '<?php $upgrading = ' . time() . '; ?>';
37
-
38
- $file = $wp_filesystem->abspath() . '.maintenance';
39
- if ($enable) {
40
- $wp_filesystem->delete($file);
41
- $wp_filesystem->put_contents($file, $maintenance_message, FS_CHMOD_FILE);
42
- } else {
43
- $wp_filesystem->delete($file);
44
- }
45
- }
46
-
47
- function install_remote_file($params)
48
- {
49
- global $wp_filesystem;
50
- extract($params);
51
-
52
- if (!isset($package) || empty($package))
53
- return array(
54
- 'error' => '<p>No files received. Internal error.</p>'
55
- );
56
-
57
- if (defined('WP_INSTALLING') && file_exists(ABSPATH . '.maintenance'))
58
- return array(
59
- 'error' => '<p>Site under maintanace.</p>'
60
- );
61
- ;
62
-
63
- $upgrader = new WP_Upgrader();
64
- $destination = $type == 'themes' ? WP_CONTENT_DIR . '/themes' : WP_PLUGIN_DIR;
65
-
66
-
67
- foreach ($package as $package_url) {
68
- $key = basename($package_url);
69
- $install_info[$key] = @$upgrader->run(array(
70
- 'package' => $package_url,
71
- 'destination' => $destination,
72
- 'clear_destination' => false, //Do not overwrite files.
73
- 'clear_working' => true,
74
- 'hook_extra' => array()
75
- ));
76
- }
77
-
78
- if ($activate) {
79
- if($type == 'plugins'){
80
- include_once(ABSPATH.'wp-admin/includes/plugin.php');
81
- $all_plugins = get_plugins();
82
- foreach ($all_plugins as $plugin_slug => $plugin) {
83
- $plugin_dir = preg_split('/\//', $plugin_slug);
84
- foreach ($install_info as $key => $install) {
85
- if (!$install || is_wp_error($install))
86
- continue;
87
-
88
- if ($install['destination_name'] == $plugin_dir[0]) {
89
- $install_info[$key]['activated'] = activate_plugin($plugin_slug, '', false);
90
- }
91
- }
92
- }
93
- }else if(count($install_info) == 1){
94
- include_once(ABSPATH.'wp-includes/theme.php');
95
- $all_themes = get_themes();
96
- foreach ($all_themes as $theme_name => $theme_data) {
97
-
98
- foreach ($install_info as $key => $install) {
99
- if (!$install || is_wp_error($install))
100
- continue;
101
-
102
- if ($theme_data['Template'] == $install['destination_name']) {
103
- $install_info[$key]['activated'] = switch_theme($theme_data['Template'], $theme_data['Stylesheet']);
104
- }
105
- }
106
- }
107
- }
108
- }
109
- ob_clean();
110
- $this->mmb_maintenance_mode(false);
111
- return $install_info;
112
- }
113
-
114
- function do_upgrade($params = null){
115
-
116
- if($params == null || empty($params))
117
- return array('failed' => 'No upgrades passed.');
118
-
119
- if (!$this->is_server_writable()) {
120
- return array(
121
- 'error' => 'Failed, please <a target="_blank" href="http://managewp.com/user-guide#ftp">add FTP details</a></a>'
122
- );
123
- }
124
- $params = isset($params['upgrades_all']) ? $params['upgrades_all'] : $params;
125
-
126
- $core_upgrade = isset($params['wp_upgrade']) ? $params['wp_upgrade'] : array();
127
- $upgrade_plugins = isset($params['upgrade_plugins']) ? $params['upgrade_plugins'] : array();
128
- $upgrade_themes = isset($params['upgrade_themes']) ? $params['upgrade_themes'] : array();
129
-
130
-
131
- $upgrades = array();
132
- if(!empty($core_upgrade)){
133
- $upgrades['core'] = $this->upgrade_core($core_upgrade);
134
- }
135
-
136
- if(!empty($upgrade_plugins)){
137
- $plugin_files = array();
138
- foreach($upgrade_plugins as $plugin){
139
- $plugin_files[$plugin->file] = $plugin->old_version;
140
- }
141
-
142
- $upgrades['plugins'] = $this->upgrade_plugins($plugin_files);
143
-
144
- }
145
-
146
- if(!empty($upgrade_themes)){
147
- $theme_temps = array();
148
- foreach($upgrade_themes as $theme){
149
- $theme_temps[] = $theme['theme_tmp'];
150
- }
151
-
152
- $upgrades['themes'] = $this->upgrade_themes($theme_temps);
153
- $this->mmb_maintenance_mode(false);
154
- }
155
- ob_clean();
156
- $this->mmb_maintenance_mode(false);
157
- return $upgrades;
158
- }
159
-
160
- /**
161
- * Upgrades WordPress locally
162
- *
163
- */
164
- function upgrade_core($current)
165
- {
166
- ob_start();
167
- if(!function_exists('wp_version_check'))
168
- include_once(ABSPATH.'/wp-admin/includes/update.php');
169
-
170
- @wp_version_check();
171
-
172
- if(!function_exists('get_core_updates'))
173
- include_once(ABSPATH.'/wp-admin/includes/update.php');
174
-
175
- $updates = get_core_updates();
176
-
177
- $current_update = false;
178
- ob_end_flush();
179
- ob_end_clean();
180
-
181
- if(!empty($updates)){
182
- $updated = $updates[0];
183
- if ( !isset( $updated->response ) || $updated->response == 'latest' )
184
- return array('upgraded' => ' Upgraded successfully.');
185
-
186
- if ($updated->response == "development" && $current->response == "upgrade") {
187
- return array('upgraded' => '<font color="#900">Transient mismatch. Please upgrade manualy</font>');
188
- }
189
- else if ($updated->response == $current->response || ($updated->response == "upgrade" && $current->response == "development")){
190
- if($updated->locale != $current->locale){
191
- foreach($updates as $update){
192
- if($update->locale == $current->locale){
193
- $current_update = $update;
194
- break;
195
- }
196
- }
197
- if($current_update == false)
198
- return array('error' => ' Localization mismatch. Try again.');
199
- } else {
200
- $current_update = $updated;
201
- }
202
- }
203
- else
204
- return array('error' => ' Transient mismatch. Try again.');
205
- } else
206
- return array('error' => ' Refresh transient failed. Try again.');
207
- if($current_update != false){
208
- global $mmb_wp_version, $wp_filesystem, $wp_version;
209
-
210
- if (version_compare($wp_version, '3.1.9', '>')) {
211
- if(!class_exists('Core_Upgrader'))
212
- include_once(ABSPATH.'wp-admin/includes/class-wp-upgrader.php');
213
-
214
- $core = new Core_Upgrader();
215
- $result = $core->upgrade($current_update);
216
- if(is_wp_error($result)){
217
- return array(
218
- 'error' => $this->mmb_get_error($result)
219
- );
220
- }
221
- else
222
- return array(
223
- 'upgraded' => ' Upgraded successfully.'
224
- );
225
-
226
- } else {
227
- if(!class_exists('WP_Upgrader')){
228
- include_once(ABSPATH.'wp-admin/includes/update.php');
229
- if(function_exists('wp_update_core')){
230
- $result = wp_update_core($current_update);
231
- if(is_wp_error($result)){
232
- return array(
233
- 'error' => $this->mmb_get_error($result)
234
- );
235
- }
236
- else
237
- return array(
238
- 'upgraded' => ' Upgraded successfully.'
239
- );
240
- }
241
- }
242
-
243
- if(class_exists('WP_Upgrader')){
244
- $upgrader = new WP_Upgrader();
245
-
246
- // Is an update available?
247
- if (!isset($current_update->response) || $current_update->response == 'latest')
248
- return array(
249
- 'upgraded' => ' Upgraded successfully.'
250
- );
251
-
252
- $res = $upgrader->fs_connect(array(
253
- ABSPATH,
254
- WP_CONTENT_DIR
255
- ));
256
- if (is_wp_error($res))
257
- return array(
258
- 'error' => $this->mmb_get_error($res)
259
- );
260
-
261
- $wp_dir = trailingslashit($wp_filesystem->abspath());
262
-
263
- $download = $upgrader->download_package($current_update->package);
264
- if (is_wp_error($download))
265
- return array(
266
- 'error' => $this->mmb_get_error($download)
267
- );
268
-
269
- $working_dir = $upgrader->unpack_package($download);
270
- if (is_wp_error($working_dir))
271
- return array(
272
- 'error' => $this->mmb_get_error($working_dir)
273
- );
274
-
275
- if (!$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true)) {
276
- $wp_filesystem->delete($working_dir, true);
277
- return array(
278
- 'error' => 'Unable to move update files.'
279
- );
280
- }
281
-
282
- $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE);
283
-
284
- require(ABSPATH . 'wp-admin/includes/update-core.php');
285
-
286
-
287
- $update_core = update_core($working_dir, $wp_dir);
288
- ob_end_clean();
289
-
290
- if (is_wp_error($update_core))
291
- return array(
292
- 'error' => $this->mmb_get_error($update_core)
293
- );
294
- ob_end_flush();
295
- return array(
296
- 'upgraded' => 'Upgraded successfully.'
297
- );
298
- } else {
299
- return array(
300
- 'error' => 'Upgrade failed.'
301
- );
302
- }
303
- }
304
- } else {
305
- return array(
306
- 'error' => 'Upgrade failed.'
307
- );
308
- }
309
- }
310
-
311
- function upgrade_plugins($plugins = false){
312
- if(!$plugins || empty($plugins))
313
- return array(
314
- 'error' => 'No plugin files for upgrade.'
315
- );
316
- $return = array();
317
- if (class_exists('Plugin_Upgrader') && class_exists('Bulk_Plugin_Upgrader_Skin')) {
318
-
319
- $upgrader = new Plugin_Upgrader(new Bulk_Plugin_Upgrader_Skin(compact('nonce', 'url')));
320
- $result = $upgrader->bulk_upgrade(array_keys($plugins));
321
-
322
- if( !function_exists('wp_update_plugins') )
323
- include_once(ABSPATH . 'wp-includes/update.php');
324
-
325
- @wp_update_plugins();
326
- $current_plugins = $this->mmb_get_transient('update_plugins');
327
-
328
- if (!empty($result)) {
329
- foreach ($result as $plugin_slug => $plugin_info) {
330
- if (!$plugin_info || is_wp_error($plugin_info)) {
331
- $return[$plugin_slug] = $this->mmb_get_error($plugin_info);
332
- } else {
333
- if(isset($current_plugins->response[$plugin_slug]) && !empty($current_plugins->response[$plugin_slug])){
334
- $return[$plugin_slug] = false;
335
- } else {
336
- $return[$plugin_slug] = 1;
337
- }
338
- }
339
- }
340
- ob_end_clean();
341
- return array(
342
- 'upgraded' => $return
343
- );
344
- }
345
- else
346
- return array(
347
- 'error' => 'Upgrade failed.'
348
- );
349
- } else {
350
- ob_end_clean();
351
- return array(
352
- 'error' => 'WordPress update required first.'
353
- );
354
- }
355
- }
356
-
357
- function upgrade_themes($themes = false){
358
- if(!$themes || empty($themes))
359
- return array(
360
- 'error' => 'No theme files for upgrade.'
361
- );
362
- if (class_exists('Theme_Upgrader') && class_exists('Bulk_Theme_Upgrader_Skin')) {
363
-
364
-
365
- $upgrader = new Theme_Upgrader(new Bulk_Theme_Upgrader_Skin(compact('title', 'nonce', 'url', 'theme')));
366
- $result = $upgrader->bulk_upgrade($themes);
367
-
368
- if( !function_exists('wp_update_themes') )
369
- include_once(ABSPATH . 'wp-includes/update.php');
370
-
371
- @wp_update_themes();
372
- $current_themes = $this->mmb_get_transient('update_themes');
373
-
374
- $return = array();
375
- if (!empty($result)) {
376
- foreach ($result as $theme_tmp => $theme_info) {
377
- if (is_wp_error($theme_info) || !$theme_info) {
378
- $return[$theme_tmp] = $this->mmb_get_error($theme_info);
379
- } else {
380
- if(isset($current_themes->response[$theme_tmp]) && !empty($current_themes->response[$theme_tmp])){
381
- $return[$theme_tmp] = false;
382
- } else {
383
- $return[$theme_tmp] = 1;
384
- }
385
- }
386
- }
387
-
388
- return array(
389
- 'upgraded' => $return
390
- );
391
- } else
392
- return array(
393
- 'error' => 'Upgrade failed.'
394
- );
395
- } else {
396
- ob_end_clean();
397
- return array(
398
- 'error' => 'WordPress update required first'
399
- );
400
- }
401
- }
402
-
403
- function get_upgradable_plugins()
404
- {
405
- $current = $this->mmb_get_transient('update_plugins');
406
- $upgradable_plugins = array();
407
- if (!empty($current->response)) {
408
- foreach ($current->response as $plugin_path => $plugin_data) {
409
- if($plugin_path == 'worker/init.php')
410
- continue;
411
-
412
- if (!function_exists('get_plugin_data'))
413
- include_once ABSPATH . 'wp-admin/includes/plugin.php';
414
-
415
- $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_path);
416
-
417
- $current->response[$plugin_path]->name = $data['Name'];
418
- $current->response[$plugin_path]->old_version = $data['Version'];
419
- $current->response[$plugin_path]->file = $plugin_path;
420
- $upgradable_plugins[] = $current->response[$plugin_path];
421
- }
422
- return $upgradable_plugins;
423
- } else
424
- return array();
425
-
426
- }
427
-
428
- function get_upgradable_themes()
429
- {
430
- $all_themes = get_themes();
431
- $upgrade_themes = array();
432
-
433
- $current = $this->mmb_get_transient('update_themes');
434
- foreach ((array) $all_themes as $theme_template => $theme_data) {
435
- if (!empty($current->response)) {
436
- foreach ($current->response as $current_themes => $theme) {
437
- if ($theme_data['Template'] == $current_themes) {
438
- $current->response[$current_themes]['name'] = $theme_data['Name'];
439
- $current->response[$current_themes]['old_version'] = $theme_data['Version'];
440
- $current->response[$current_themes]['theme_tmp'] = $theme_data['Template'];
441
- $upgrade_themes[] = $current->response[$current_themes];
442
- continue;
443
- }
444
- }
445
- }
446
- }
447
-
448
- return $upgrade_themes;
449
- }
450
- }
 
451
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * installer.class.php
5
+ *
6
+ * Upgrade WordPress
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Installer extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ @set_time_limit(300);
18
+ parent::__construct();
19
+ include_once(ABSPATH . 'wp-admin/includes/file.php');
20
+ include_once(ABSPATH . 'wp-admin/includes/plugin.php');
21
+ include_once(ABSPATH . 'wp-admin/includes/theme.php');
22
+ include_once(ABSPATH . 'wp-admin/includes/misc.php');
23
+ include_once(ABSPATH . 'wp-admin/includes/template.php');
24
+ @include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
25
+
26
+ global $wp_filesystem;
27
+ if (!$wp_filesystem)
28
+ WP_Filesystem();
29
+
30
+ }
31
+
32
+ function mmb_maintenance_mode($enable = false, $maintenance_message = '')
33
+ {
34
+ global $wp_filesystem;
35
+
36
+ $maintenance_message .= '<?php $upgrading = ' . time() . '; ?>';
37
+
38
+ $file = $wp_filesystem->abspath() . '.maintenance';
39
+ if ($enable) {
40
+ $wp_filesystem->delete($file);
41
+ $wp_filesystem->put_contents($file, $maintenance_message, FS_CHMOD_FILE);
42
+ } else {
43
+ $wp_filesystem->delete($file);
44
+ }
45
+ }
46
+
47
+ function install_remote_file($params)
48
+ {
49
+ global $wp_filesystem;
50
+ extract($params);
51
+
52
+ if (!isset($package) || empty($package))
53
+ return array(
54
+ 'error' => '<p>No files received. Internal error.</p>'
55
+ );
56
+
57
+ if (defined('WP_INSTALLING') && file_exists(ABSPATH . '.maintenance'))
58
+ return array(
59
+ 'error' => '<p>Site under maintanace.</p>'
60
+ );
61
+ ;
62
+
63
+ $upgrader = new WP_Upgrader();
64
+ $destination = $type == 'themes' ? WP_CONTENT_DIR . '/themes' : WP_PLUGIN_DIR;
65
+
66
+
67
+ foreach ($package as $package_url) {
68
+ $key = basename($package_url);
69
+ $install_info[$key] = @$upgrader->run(array(
70
+ 'package' => $package_url,
71
+ 'destination' => $destination,
72
+ 'clear_destination' => false, //Do not overwrite files.
73
+ 'clear_working' => true,
74
+ 'hook_extra' => array()
75
+ ));
76
+ }
77
+
78
+ if ($activate) {
79
+ if($type == 'plugins'){
80
+ include_once(ABSPATH.'wp-admin/includes/plugin.php');
81
+ $all_plugins = get_plugins();
82
+ foreach ($all_plugins as $plugin_slug => $plugin) {
83
+ $plugin_dir = preg_split('/\//', $plugin_slug);
84
+ foreach ($install_info as $key => $install) {
85
+ if (!$install || is_wp_error($install))
86
+ continue;
87
+
88
+ if ($install['destination_name'] == $plugin_dir[0]) {
89
+ $install_info[$key]['activated'] = activate_plugin($plugin_slug, '', false);
90
+ }
91
+ }
92
+ }
93
+ }else if(count($install_info) == 1){
94
+ include_once(ABSPATH.'wp-includes/theme.php');
95
+ $all_themes = get_themes();
96
+ foreach ($all_themes as $theme_name => $theme_data) {
97
+
98
+ foreach ($install_info as $key => $install) {
99
+ if (!$install || is_wp_error($install))
100
+ continue;
101
+
102
+ if ($theme_data['Template'] == $install['destination_name']) {
103
+ $install_info[$key]['activated'] = switch_theme($theme_data['Template'], $theme_data['Stylesheet']);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ }
109
+ ob_clean();
110
+ $this->mmb_maintenance_mode(false);
111
+ return $install_info;
112
+ }
113
+
114
+ function do_upgrade($params = null){
115
+
116
+ if($params == null || empty($params))
117
+ return array('failed' => 'No upgrades passed.');
118
+
119
+ if (!$this->is_server_writable()) {
120
+ return array(
121
+ 'error' => 'Failed, please <a target="_blank" href="http://managewp.com/user-guide#ftp">add FTP details</a></a>'
122
+ );
123
+ }
124
+ $params = isset($params['upgrades_all']) ? $params['upgrades_all'] : $params;
125
+
126
+ $core_upgrade = isset($params['wp_upgrade']) ? $params['wp_upgrade'] : array();
127
+ $upgrade_plugins = isset($params['upgrade_plugins']) ? $params['upgrade_plugins'] : array();
128
+ $upgrade_themes = isset($params['upgrade_themes']) ? $params['upgrade_themes'] : array();
129
+
130
+
131
+ $upgrades = array();
132
+ if(!empty($core_upgrade)){
133
+ $upgrades['core'] = $this->upgrade_core($core_upgrade);
134
+ }
135
+
136
+ if(!empty($upgrade_plugins)){
137
+ $plugin_files = array();
138
+ foreach($upgrade_plugins as $plugin){
139
+ $plugin_files[$plugin->file] = $plugin->old_version;
140
+ }
141
+
142
+ $upgrades['plugins'] = $this->upgrade_plugins($plugin_files);
143
+
144
+ }
145
+
146
+ if(!empty($upgrade_themes)){
147
+ $theme_temps = array();
148
+ foreach($upgrade_themes as $theme){
149
+ $theme_temps[] = $theme['theme_tmp'];
150
+ }
151
+
152
+ $upgrades['themes'] = $this->upgrade_themes($theme_temps);
153
+ $this->mmb_maintenance_mode(false);
154
+ }
155
+ ob_clean();
156
+ $this->mmb_maintenance_mode(false);
157
+ return $upgrades;
158
+ }
159
+
160
+ /**
161
+ * Upgrades WordPress locally
162
+ *
163
+ */
164
+ function upgrade_core($current)
165
+ {
166
+ ob_start();
167
+ if(!function_exists('wp_version_check'))
168
+ include_once(ABSPATH.'/wp-admin/includes/update.php');
169
+
170
+ @wp_version_check();
171
+
172
+ if(!function_exists('get_core_updates'))
173
+ include_once(ABSPATH.'/wp-admin/includes/update.php');
174
+
175
+ $updates = get_core_updates();
176
+
177
+ $current_update = false;
178
+ ob_end_flush();
179
+ ob_end_clean();
180
+
181
+ if(!empty($updates)){
182
+ $updated = $updates[0];
183
+ if ( !isset( $updated->response ) || $updated->response == 'latest' )
184
+ return array('upgraded' => ' Upgraded successfully.');
185
+
186
+ if ($updated->response == "development" && $current->response == "upgrade") {
187
+ return array('upgraded' => '<font color="#900">Transient mismatch. Please upgrade manualy</font>');
188
+ }
189
+ else if ($updated->response == $current->response || ($updated->response == "upgrade" && $current->response == "development")){
190
+ if($updated->locale != $current->locale){
191
+ foreach($updates as $update){
192
+ if($update->locale == $current->locale){
193
+ $current_update = $update;
194
+ break;
195
+ }
196
+ }
197
+ if($current_update == false)
198
+ return array('error' => ' Localization mismatch. Try again.');
199
+ } else {
200
+ $current_update = $updated;
201
+ }
202
+ }
203
+ else
204
+ return array('error' => ' Transient mismatch. Try again.');
205
+ } else
206
+ return array('error' => ' Refresh transient failed. Try again.');
207
+ if($current_update != false){
208
+ global $mmb_wp_version, $wp_filesystem, $wp_version;
209
+
210
+ if (version_compare($wp_version, '3.1.9', '>')) {
211
+ if(!class_exists('Core_Upgrader'))
212
+ include_once(ABSPATH.'wp-admin/includes/class-wp-upgrader.php');
213
+
214
+ $core = new Core_Upgrader();
215
+ $result = $core->upgrade($current_update);
216
+ if(is_wp_error($result)){
217
+ return array(
218
+ 'error' => $this->mmb_get_error($result)
219
+ );
220
+ }
221
+ else
222
+ return array(
223
+ 'upgraded' => ' Upgraded successfully.'
224
+ );
225
+
226
+ } else {
227
+ if(!class_exists('WP_Upgrader')){
228
+ include_once(ABSPATH.'wp-admin/includes/update.php');
229
+ if(function_exists('wp_update_core')){
230
+ $result = wp_update_core($current_update);
231
+ if(is_wp_error($result)){
232
+ return array(
233
+ 'error' => $this->mmb_get_error($result)
234
+ );
235
+ }
236
+ else
237
+ return array(
238
+ 'upgraded' => ' Upgraded successfully.'
239
+ );
240
+ }
241
+ }
242
+
243
+ if(class_exists('WP_Upgrader')){
244
+ $upgrader = new WP_Upgrader();
245
+
246
+ // Is an update available?
247
+ if (!isset($current_update->response) || $current_update->response == 'latest')
248
+ return array(
249
+ 'upgraded' => ' Upgraded successfully.'
250
+ );
251
+
252
+ $res = $upgrader->fs_connect(array(
253
+ ABSPATH,
254
+ WP_CONTENT_DIR
255
+ ));
256
+ if (is_wp_error($res))
257
+ return array(
258
+ 'error' => $this->mmb_get_error($res)
259
+ );
260
+
261
+ $wp_dir = trailingslashit($wp_filesystem->abspath());
262
+
263
+ $download = $upgrader->download_package($current_update->package);
264
+ if (is_wp_error($download))
265
+ return array(
266
+ 'error' => $this->mmb_get_error($download)
267
+ );
268
+
269
+ $working_dir = $upgrader->unpack_package($download);
270
+ if (is_wp_error($working_dir))
271
+ return array(
272
+ 'error' => $this->mmb_get_error($working_dir)
273
+ );
274
+
275
+ if (!$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true)) {
276
+ $wp_filesystem->delete($working_dir, true);
277
+ return array(
278
+ 'error' => 'Unable to move update files.'
279
+ );
280
+ }
281
+
282
+ $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE);
283
+
284
+ require(ABSPATH . 'wp-admin/includes/update-core.php');
285
+
286
+
287
+ $update_core = update_core($working_dir, $wp_dir);
288
+ ob_end_clean();
289
+
290
+ if (is_wp_error($update_core))
291
+ return array(
292
+ 'error' => $this->mmb_get_error($update_core)
293
+ );
294
+ ob_end_flush();
295
+ return array(
296
+ 'upgraded' => 'Upgraded successfully.'
297
+ );
298
+ } else {
299
+ return array(
300
+ 'error' => 'Upgrade failed.'
301
+ );
302
+ }
303
+ }
304
+ } else {
305
+ return array(
306
+ 'error' => 'Upgrade failed.'
307
+ );
308
+ }
309
+ }
310
+
311
+ function upgrade_plugins($plugins = false){
312
+ if(!$plugins || empty($plugins))
313
+ return array(
314
+ 'error' => 'No plugin files for upgrade.'
315
+ );
316
+ $return = array();
317
+ if (class_exists('Plugin_Upgrader') && class_exists('Bulk_Plugin_Upgrader_Skin')) {
318
+
319
+ $upgrader = new Plugin_Upgrader(new Bulk_Plugin_Upgrader_Skin(compact('nonce', 'url')));
320
+ $result = $upgrader->bulk_upgrade(array_keys($plugins));
321
+
322
+ if( !function_exists('wp_update_plugins') )
323
+ include_once(ABSPATH . 'wp-includes/update.php');
324
+
325
+ @wp_update_plugins();
326
+ $current_plugins = $this->mmb_get_transient('update_plugins');
327
+
328
+ if (!empty($result)) {
329
+ foreach ($result as $plugin_slug => $plugin_info) {
330
+ if (!$plugin_info || is_wp_error($plugin_info)) {
331
+ $return[$plugin_slug] = $this->mmb_get_error($plugin_info);
332
+ } else {
333
+ if(isset($current_plugins->response[$plugin_slug]) && !empty($current_plugins->response[$plugin_slug])){
334
+ $return[$plugin_slug] = false;
335
+ } else {
336
+ $return[$plugin_slug] = 1;
337
+ }
338
+ }
339
+ }
340
+ ob_end_clean();
341
+ return array(
342
+ 'upgraded' => $return
343
+ );
344
+ }
345
+ else
346
+ return array(
347
+ 'error' => 'Upgrade failed.'
348
+ );
349
+ } else {
350
+ ob_end_clean();
351
+ return array(
352
+ 'error' => 'WordPress update required first.'
353
+ );
354
+ }
355
+ }
356
+
357
+ function upgrade_themes($themes = false){
358
+ if(!$themes || empty($themes))
359
+ return array(
360
+ 'error' => 'No theme files for upgrade.'
361
+ );
362
+ if (class_exists('Theme_Upgrader') && class_exists('Bulk_Theme_Upgrader_Skin')) {
363
+
364
+
365
+ $upgrader = new Theme_Upgrader(new Bulk_Theme_Upgrader_Skin(compact('title', 'nonce', 'url', 'theme')));
366
+ $result = $upgrader->bulk_upgrade($themes);
367
+
368
+ if( !function_exists('wp_update_themes') )
369
+ include_once(ABSPATH . 'wp-includes/update.php');
370
+
371
+ @wp_update_themes();
372
+ $current_themes = $this->mmb_get_transient('update_themes');
373
+
374
+ $return = array();
375
+ if (!empty($result)) {
376
+ foreach ($result as $theme_tmp => $theme_info) {
377
+ if (is_wp_error($theme_info) || !$theme_info) {
378
+ $return[$theme_tmp] = $this->mmb_get_error($theme_info);
379
+ } else {
380
+ if(isset($current_themes->response[$theme_tmp]) && !empty($current_themes->response[$theme_tmp])){
381
+ $return[$theme_tmp] = false;
382
+ } else {
383
+ $return[$theme_tmp] = 1;
384
+ }
385
+ }
386
+ }
387
+
388
+ return array(
389
+ 'upgraded' => $return
390
+ );
391
+ } else
392
+ return array(
393
+ 'error' => 'Upgrade failed.'
394
+ );
395
+ } else {
396
+ ob_end_clean();
397
+ return array(
398
+ 'error' => 'WordPress update required first'
399
+ );
400
+ }
401
+ }
402
+
403
+ function get_upgradable_plugins()
404
+ {
405
+ $current = $this->mmb_get_transient('update_plugins');
406
+ $upgradable_plugins = array();
407
+ if (!empty($current->response)) {
408
+ if (!function_exists('get_plugin_data'))
409
+ include_once ABSPATH . 'wp-admin/includes/plugin.php';
410
+ foreach ($current->response as $plugin_path => $plugin_data) {
411
+ if($plugin_path == 'worker/init.php')
412
+ continue;
413
+
414
+ $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_path);
415
+ if(strlen($data['Name']) > 0 && strlen($data['Version']) > 0) {
416
+ $current->response[$plugin_path]->name = $data['Name'];
417
+ $current->response[$plugin_path]->old_version = $data['Version'];
418
+ $current->response[$plugin_path]->file = $plugin_path;
419
+ $upgradable_plugins[] = $current->response[$plugin_path];
420
+ }
421
+ }
422
+ return $upgradable_plugins;
423
+ } else
424
+ return array();
425
+
426
+ }
427
+
428
+ function get_upgradable_themes()
429
+ {
430
+ $all_themes = get_themes();
431
+ $upgrade_themes = array();
432
+
433
+ $current = $this->mmb_get_transient('update_themes');
434
+ foreach ((array) $all_themes as $theme_template => $theme_data) {
435
+ if (!empty($current->response)) {
436
+ foreach ($current->response as $current_themes => $theme) {
437
+ if ($theme_data['Template'] == $current_themes) {
438
+ if(strlen($theme_data['Name']) > 0 && strlen($theme_data['Version']) > 0) {
439
+ $current->response[$current_themes]['name'] = $theme_data['Name'];
440
+ $current->response[$current_themes]['old_version'] = $theme_data['Version'];
441
+ $current->response[$current_themes]['theme_tmp'] = $theme_data['Template'];
442
+ $upgrade_themes[] = $current->response[$current_themes];
443
+ }
444
+ }
445
+ }
446
+ }
447
+ }
448
+
449
+ return $upgrade_themes;
450
+ }
451
+ }
452
  ?>
lib/dropbox.php CHANGED
@@ -1,144 +1,144 @@
1
- <?php
2
- /**
3
- * Dropbox Uploader
4
- *
5
- * Copyright (c) 2009 Jaka Jancar
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in
15
- * all copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- * THE SOFTWARE.
24
- *
25
- * @author Jaka Jancar [jaka@kubje.org] [http://jaka.kubje.org/]
26
- * @version 1.1.5
27
- */
28
- class DropboxUploader {
29
- protected $email;
30
- protected $password;
31
- protected $caCertSourceType = self::CACERT_SOURCE_SYSTEM;
32
- const CACERT_SOURCE_SYSTEM = 0;
33
- const CACERT_SOURCE_FILE = 1;
34
- const CACERT_SOURCE_DIR = 2;
35
- protected $caCertSource;
36
- protected $loggedIn = false;
37
- protected $cookies = array();
38
-
39
- /**
40
- * Constructor
41
- *
42
- * @param string $email
43
- * @param string|null $password
44
- */
45
- public function __construct($email, $password) {
46
- // Check requirements
47
- if (!extension_loaded('curl'))
48
- throw new Exception('DropboxUploader requires the cURL extension.');
49
-
50
- $this->email = $email;
51
- $this->password = $password;
52
- }
53
-
54
- public function setCaCertificateFile($file)
55
- {
56
- $this->caCertSourceType = self::CACERT_SOURCE_FILE;
57
- $this->caCertSource = $file;
58
- }
59
-
60
- public function setCaCertificateDir($dir)
61
- {
62
- $this->caCertSourceType = self::CACERT_SOURCE_DIR;
63
- $this->caCertSource = $dir;
64
- }
65
-
66
- public function upload($filename, $remoteDir='/') {
67
- if (!file_exists($filename) or !is_file($filename) or !is_readable($filename))
68
- throw new Exception("File '$filename' does not exist or is not readable.");
69
-
70
- if (!is_string($remoteDir))
71
- throw new Exception("Remote directory must be a string, is ".gettype($remoteDir)." instead.");
72
-
73
- if (!$this->loggedIn)
74
- $this->login();
75
-
76
- $data = $this->request('https://www.dropbox.com/home');
77
- $token = $this->extractToken($data, 'https://dl-web.dropbox.com/upload');
78
-
79
- $data = $this->request('https://dl-web.dropbox.com/upload', true, array('plain'=>'yes', 'file'=>'@'.$filename, 'dest'=>$remoteDir, 't'=>$token));
80
- if (strpos($data, 'HTTP/1.1 302 FOUND') === false)
81
- throw new Exception('Upload failed!');
82
- }
83
-
84
- protected function login() {
85
- $data = $this->request('https://www.dropbox.com/login');
86
- $token = $this->extractToken($data, '/login');
87
-
88
- $data = $this->request('https://www.dropbox.com/login', true, array('login_email'=>$this->email, 'login_password'=>$this->password, 't'=>$token));
89
-
90
- if (stripos($data, 'location: /home') === false)
91
- throw new Exception('Login unsuccessful.');
92
-
93
- $this->loggedIn = true;
94
- }
95
-
96
- protected function request($url, $post=false, $postData=array()) {
97
- $ch = curl_init();
98
- curl_setopt($ch, CURLOPT_URL, $url);
99
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
100
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
101
- switch ($this->caCertSourceType) {
102
- case self::CACERT_SOURCE_FILE:
103
- curl_setopt($ch, CURLOPT_CAINFO, $this->caCertSource);
104
- break;
105
- case self::CACERT_SOURCE_DIR:
106
- curl_setopt($ch, CURLOPT_CAPATH, $this->caCertSource);
107
- break;
108
- }
109
- curl_setopt($ch, CURLOPT_HEADER, 1);
110
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
111
- if ($post) {
112
- curl_setopt($ch, CURLOPT_POST, $post);
113
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
114
- }
115
-
116
- // Send cookies
117
- $rawCookies = array();
118
- foreach ($this->cookies as $k=>$v)
119
- $rawCookies[] = "$k=$v";
120
- $rawCookies = implode(';', $rawCookies);
121
- curl_setopt($ch, CURLOPT_COOKIE, $rawCookies);
122
-
123
- $data = curl_exec($ch);
124
-
125
- if ($data === false)
126
- throw new Exception('Cannot execute request: '.curl_error($ch));
127
-
128
- // Store received cookies
129
- preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches, PREG_SET_ORDER);
130
- foreach ($matches as $match)
131
- $this->cookies[$match[1]] = $match[2];
132
-
133
- curl_close($ch);
134
-
135
- return $data;
136
- }
137
-
138
- protected function extractToken($html, $formAction) {
139
- if (!preg_match('/<form [^>]*'.preg_quote($formAction, '/').'[^>]*>.*?(<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is', $html, $matches) || !isset($matches[2]))
140
- throw new Exception("Cannot extract token! (form action=$formAction)");
141
- return $matches[2];
142
- }
143
-
144
- }
1
+ <?php
2
+ /**
3
+ * Dropbox Uploader
4
+ *
5
+ * Copyright (c) 2009 Jaka Jancar
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ * THE SOFTWARE.
24
+ *
25
+ * @author Jaka Jancar [jaka@kubje.org] [http://jaka.kubje.org/]
26
+ * @version 1.1.5
27
+ */
28
+ class DropboxUploader {
29
+ protected $email;
30
+ protected $password;
31
+ protected $caCertSourceType = self::CACERT_SOURCE_SYSTEM;
32
+ const CACERT_SOURCE_SYSTEM = 0;
33
+ const CACERT_SOURCE_FILE = 1;
34
+ const CACERT_SOURCE_DIR = 2;
35
+ protected $caCertSource;
36
+ protected $loggedIn = false;
37
+ protected $cookies = array();
38
+
39
+ /**
40
+ * Constructor
41
+ *
42
+ * @param string $email
43
+ * @param string|null $password
44
+ */
45
+ public function __construct($email, $password) {
46
+ // Check requirements
47
+ if (!extension_loaded('curl'))
48
+ throw new Exception('DropboxUploader requires the cURL extension.');
49
+
50
+ $this->email = $email;
51
+ $this->password = $password;
52
+ }
53
+
54
+ public function setCaCertificateFile($file)
55
+ {
56
+ $this->caCertSourceType = self::CACERT_SOURCE_FILE;
57
+ $this->caCertSource = $file;
58
+ }
59
+
60
+ public function setCaCertificateDir($dir)
61
+ {
62
+ $this->caCertSourceType = self::CACERT_SOURCE_DIR;
63
+ $this->caCertSource = $dir;
64
+ }
65
+
66
+ public function upload($filename, $remoteDir='/') {
67
+ if (!file_exists($filename) or !is_file($filename) or !is_readable($filename))
68
+ throw new Exception("File '$filename' does not exist or is not readable.");
69
+
70
+ if (!is_string($remoteDir))
71
+ throw new Exception("Remote directory must be a string, is ".gettype($remoteDir)." instead.");
72
+
73
+ if (!$this->loggedIn)
74
+ $this->login();
75
+
76
+ $data = $this->request('https://www.dropbox.com/home');
77
+ $token = $this->extractToken($data, 'https://dl-web.dropbox.com/upload');
78
+
79
+ $data = $this->request('https://dl-web.dropbox.com/upload', true, array('plain'=>'yes', 'file'=>'@'.$filename, 'dest'=>$remoteDir, 't'=>$token));
80
+ if (strpos($data, 'HTTP/1.1 302 FOUND') === false)
81
+ throw new Exception('Upload failed!');
82
+ }
83
+
84
+ protected function login() {
85
+ $data = $this->request('https://www.dropbox.com/login');
86
+ $token = $this->extractToken($data, '/login');
87
+
88
+ $data = $this->request('https://www.dropbox.com/login', true, array('login_email'=>$this->email, 'login_password'=>$this->password, 't'=>$token));
89
+
90
+ if (stripos($data, 'location: /home') === false)
91
+ throw new Exception('Login unsuccessful.');
92
+
93
+ $this->loggedIn = true;
94
+ }
95
+
96
+ protected function request($url, $post=false, $postData=array()) {
97
+ $ch = curl_init();
98
+ curl_setopt($ch, CURLOPT_URL, $url);
99
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
100
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
101
+ switch ($this->caCertSourceType) {
102
+ case self::CACERT_SOURCE_FILE:
103
+ curl_setopt($ch, CURLOPT_CAINFO, $this->caCertSource);
104
+ break;
105
+ case self::CACERT_SOURCE_DIR:
106
+ curl_setopt($ch, CURLOPT_CAPATH, $this->caCertSource);
107
+ break;
108
+ }
109
+ curl_setopt($ch, CURLOPT_HEADER, 1);
110
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
111
+ if ($post) {
112
+ curl_setopt($ch, CURLOPT_POST, $post);
113
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
114
+ }
115
+
116
+ // Send cookies
117
+ $rawCookies = array();
118
+ foreach ($this->cookies as $k=>$v)
119
+ $rawCookies[] = "$k=$v";
120
+ $rawCookies = implode(';', $rawCookies);
121
+ curl_setopt($ch, CURLOPT_COOKIE, $rawCookies);
122
+
123
+ $data = curl_exec($ch);
124
+
125
+ if ($data === false)
126
+ throw new Exception('Cannot execute request: '.curl_error($ch));
127
+
128
+ // Store received cookies
129
+ preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches, PREG_SET_ORDER);
130
+ foreach ($matches as $match)
131
+ $this->cookies[$match[1]] = $match[2];
132
+
133
+ curl_close($ch);
134
+
135
+ return $data;
136
+ }
137
+
138
+ protected function extractToken($html, $formAction) {
139
+ if (!preg_match('/<form [^>]*'.preg_quote($formAction, '/').'[^>]*>.*?(<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is', $html, $matches) || !isset($matches[2]))
140
+ throw new Exception("Cannot extract token! (form action=$formAction)");
141
+ return $matches[2];
142
+ }
143
+
144
+ }
lib/s3.php CHANGED
@@ -1,910 +1,910 @@
1
- <?php
2
- /**
3
- * $Id$
4
- *
5
- * Copyright (c) 2007, Donovan Schonknecht. All rights reserved.
6
- *
7
- * Redistribution and use in source and binary forms, with or without
8
- * modification, are permitted provided that the following conditions are met:
9
- *
10
- * - Redistributions of source code must retain the above copyright notice,
11
- * this list of conditions and the following disclaimer.
12
- * - Redistributions in binary form must reproduce the above copyright
13
- * notice, this list of conditions and the following disclaimer in the
14
- * documentation and/or other materials provided with the distribution.
15
- *
16
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
- * POSSIBILITY OF SUCH DAMAGE.
27
- */
28
-
29
- /**
30
- * Amazon S3 PHP class
31
- *
32
- * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
33
- * @version 0.2.3
34
- */
35
- class S3 {
36
- // ACL flags
37
- const ACL_PRIVATE = 'private';
38
- const ACL_PUBLIC_READ = 'public-read';
39
- const ACL_PUBLIC_READ_WRITE = 'public-read-write';
40
-
41
- private static $__accessKey; // AWS Access key
42
- private static $__secretKey; // AWS Secret key
43
-
44
-
45
- /**
46
- * Constructor, used if you're not calling the class statically
47
- *
48
- * @param string $accessKey Access key
49
- * @param string $secretKey Secret key
50
- * @return void
51
- */
52
- public function __construct($accessKey = null, $secretKey = null) {
53
- if ($accessKey !== null && $secretKey !== null)
54
- self::setAuth($accessKey, $secretKey);
55
- }
56
-
57
-
58
- /**
59
- * Set access information
60
- *
61
- * @param string $accessKey Access key
62
- * @param string $secretKey Secret key
63
- * @return void
64
- */
65
- public static function setAuth($accessKey, $secretKey) {
66
- self::$__accessKey = $accessKey;
67
- self::$__secretKey = $secretKey;
68
- }
69
-
70
-
71
- /**
72
- * Get a list of buckets
73
- *
74
- * @param boolean $detailed Returns detailed bucket list when true
75
- * @return array | false
76
- */
77
- public static function listBuckets($detailed = false) {
78
- $rest = new S3Request('GET', '', '');
79
- $rest = $rest->getResponse();
80
- if ($rest->error === false && $rest->code !== 200)
81
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
82
- if ($rest->error !== false) {
83
- trigger_error(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
84
- return false;
85
- }
86
- $results = array(); //var_dump($rest->body);
87
- if (!isset($rest->body->Buckets)) return $results;
88
-
89
- if ($detailed) {
90
- if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
91
- $results['owner'] = array(
92
- 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
93
- );
94
- $results['buckets'] = array();
95
- foreach ($rest->body->Buckets->Bucket as $b)
96
- $results['buckets'][] = array(
97
- 'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
98
- );
99
- } else
100
- foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
101
-
102
- return $results;
103
- }
104
-
105
-
106
- /*
107
- * Get contents for a bucket
108
- *
109
- * If maxKeys is null this method will loop through truncated result sets
110
- *
111
- * @param string $bucket Bucket name
112
- * @param string $prefix Prefix
113
- * @param string $marker Marker (last file listed)
114
- * @param string $maxKeys Max keys (maximum number of keys to return)
115
- * @return array | false
116
- */
117
- public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null) {
118
- $rest = new S3Request('GET', $bucket, '');
119
- if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
120
- if ($marker !== null && $prefix !== '') $rest->setParameter('marker', $marker);
121
- if ($maxKeys !== null && $prefix !== '') $rest->setParameter('max-keys', $maxKeys);
122
- $response = $rest->getResponse();
123
- if ($response->error === false && $response->code !== 200)
124
- $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
125
- if ($response->error !== false) {
126
- trigger_error(sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
127
- return false;
128
- }
129
-
130
- $results = array();
131
-
132
- $lastMarker = null;
133
- if (isset($response->body, $response->body->Contents))
134
- foreach ($response->body->Contents as $c) {
135
- $results[(string)$c->Key] = array(
136
- 'name' => (string)$c->Key,
137
- 'time' => strToTime((string)$c->LastModified),
138
- 'size' => (int)$c->Size,
139
- 'hash' => substr((string)$c->ETag, 1, -1)
140
- );
141
- $lastMarker = (string)$c->Key;
142
- //$response->body->IsTruncated = 'true'; break;
143
- }
144
-
145
-
146
- if (isset($response->body->IsTruncated) &&
147
- (string)$response->body->IsTruncated == 'false') return $results;
148
-
149
- // Loop through truncated results if maxKeys isn't specified
150
- if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true')
151
- do {
152
- $rest = new S3Request('GET', $bucket, '');
153
- if ($prefix !== null) $rest->setParameter('prefix', $prefix);
154
- $rest->setParameter('marker', $lastMarker);
155
-
156
- if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break;
157
- if (isset($response->body, $response->body->Contents))
158
- foreach ($response->body->Contents as $c) {
159
- $results[(string)$c->Key] = array(
160
- 'name' => (string)$c->Key,
161
- 'time' => strToTime((string)$c->LastModified),
162
- 'size' => (int)$c->Size,
163
- 'hash' => substr((string)$c->ETag, 1, -1)
164
- );
165
- $lastMarker = (string)$c->Key;
166
- }
167
- } while ($response !== false && (string)$response->body->IsTruncated == 'true');
168
-
169
- return $results;
170
- }
171
-
172
-
173
- /**
174
- * Put a bucket
175
- *
176
- * @param string $bucket Bucket name
177
- * @param constant $acl ACL flag
178
- * @return boolean
179
- */
180
- public function putBucket($bucket, $acl = self::ACL_PRIVATE) {
181
- $rest = new S3Request('PUT', $bucket, '');
182
- $rest->setAmzHeader('x-amz-acl', $acl);
183
- $rest = $rest->getResponse();
184
- if ($rest->error === false && $rest->code !== 200)
185
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
186
- if ($rest->error !== false) {
187
- trigger_error(sprintf("S3::putBucket({$bucket}): [%s] %s",
188
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
189
- return false;
190
- }
191
- return true;
192
- }
193
-
194
-
195
- /**
196
- * Delete an empty bucket
197
- *
198
- * @param string $bucket Bucket name
199
- * @return boolean
200
- */
201
- public function deleteBucket($bucket = '') {
202
- $rest = new S3Request('DELETE', $bucket);
203
- $rest = $rest->getResponse();
204
- if ($rest->error === false && $rest->code !== 204)
205
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
206
- if ($rest->error !== false) {
207
- trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
208
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
209
- return false;
210
- }
211
- return true;
212
- }
213
-
214
-
215
- /**
216
- * Create input info array for putObject()
217
- *
218
- * @param string $file Input file
219
- * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
220
- * @return array | false
221
- */
222
- public static function inputFile($file, $md5sum = true) {
223
- if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
224
- trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
225
- return false;
226
- }
227
- return array('file' => $file, 'size' => filesize($file),
228
- 'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
229
- base64_encode(md5_file($file, true))) : '');
230
- }
231
-
232
-
233
- /**
234
- * Use a resource for input
235
- *
236
- * @param string $file Input file
237
- * @param integer $bufferSize Input byte size
238
- * @param string $md5sum MD5 hash to send (optional)
239
- * @return array | false
240
- */
241
- public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
242
- if (!is_resource($resource) || $bufferSize <= 0) {
243
- trigger_error('S3::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
244
- return false;
245
- }
246
- $input = array('size' => $bufferSize, 'md5sum' => $md5sum);
247
- $input['fp'] =& $resource;
248
- return $input;
249
- }
250
-
251
-
252
- /**
253
- * Put an object
254
- *
255
- * @param mixed $input Input data
256
- * @param string $bucket Bucket name
257
- * @param string $uri Object URI
258
- * @param constant $acl ACL constant
259
- * @param array $metaHeaders Array of x-amz-meta-* headers
260
- * @param string $contentType Content type
261
- * @return boolean
262
- */
263
- public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
264
- if ($input == false) return false;
265
- $rest = new S3Request('PUT', $bucket, $uri);
266
-
267
- if (is_string($input)) $input = array(
268
- 'data' => $input, 'size' => strlen($input),
269
- 'md5sum' => base64_encode(md5($input, true))
270
- );
271
-
272
- // Data
273
- if (isset($input['fp']))
274
- $rest->fp =& $input['fp'];
275
- elseif (isset($input['file']))
276
- $rest->fp = @fopen($input['file'], 'rb');
277
- elseif (isset($input['data']))
278
- $rest->data = $input['data'];
279
-
280
- // Content-Length (required)
281
- if (isset($input['size']) && $input['size'] > 0)
282
- $rest->size = $input['size'];
283
- else {
284
- if (isset($input['file']))
285
- $rest->size = filesize($input['file']);
286
- elseif (isset($input['data']))
287
- $rest->size = strlen($input['data']);
288
- }
289
-
290
- // Content-Type
291
- if ($contentType !== null)
292
- $input['type'] = $contentType;
293
- elseif (!isset($input['type']) && isset($input['file']))
294
- $input['type'] = self::__getMimeType($input['file']);
295
- else
296
- $input['type'] = 'application/octet-stream';
297
-
298
- // We need to post with the content-length and content-type, MD5 is optional
299
- if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
300
- $rest->setHeader('Content-Type', $input['type']);
301
- if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
302
-
303
- $rest->setAmzHeader('x-amz-acl', $acl);
304
- foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
305
- $rest->getResponse();
306
- } else
307
- $rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
308
-
309
- if ($rest->response->error === false && $rest->response->code !== 200)
310
- $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
311
- if ($rest->response->error !== false) {
312
- trigger_error(sprintf("S3::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
313
- return false;
314
- }
315
- return true;
316
- }
317
-
318
-
319
- /**
320
- * Puts an object from a file (legacy function)
321
- *
322
- * @param string $file Input file path
323
- * @param string $bucket Bucket name
324
- * @param string $uri Object URI
325
- * @param constant $acl ACL constant
326
- * @param array $metaHeaders Array of x-amz-meta-* headers
327
- * @param string $contentType Content type
328
- * @return boolean
329
- */
330
- public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
331
- return self::putObject(S3::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
332
- }
333
-
334
-
335
- /**
336
- * Put an object from a string (legacy function)
337
- *
338
- * @param string $string Input data
339
- * @param string $bucket Bucket name
340
- * @param string $uri Object URI
341
- * @param constant $acl ACL constant
342
- * @param array $metaHeaders Array of x-amz-meta-* headers
343
- * @param string $contentType Content type
344
- * @return boolean
345
- */
346
- public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
347
- return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
348
- }
349
-
350
-
351
- /**
352
- * Get an object
353
- *
354
- * @param string $bucket Bucket name
355
- * @param string $uri Object URI
356
- * @param mixed &$saveTo Filename or resource to write to
357
- * @return mixed
358
- */
359
- public static function getObject($bucket = '', $uri = '', $saveTo = false) {
360
- $rest = new S3Request('GET', $bucket, $uri);
361
- if ($saveTo !== false) {
362
- if (is_resource($saveTo))
363
- $rest->fp =& $saveTo;
364
- else
365
- if (($rest->fp = @fopen($saveTo, 'wb')) == false)
366
- $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
367
- }
368
- if ($rest->response->error === false) $rest->getResponse();
369
-
370
- if ($rest->response->error === false && $rest->response->code !== 200)
371
- $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
372
- if ($rest->response->error !== false) {
373
- trigger_error(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
374
- $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
375
- return false;
376
- }
377
- $rest->file = realpath($saveTo);
378
- return $rest->response;
379
- }
380
-
381
-
382
- /**
383
- * Get object information
384
- *
385
- * @param string $bucket Bucket name
386
- * @param string $uri Object URI
387
- * @param boolean $returnInfo Return response information
388
- * @return mixed | false
389
- */
390
- public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
391
- $rest = new S3Request('HEAD', $bucket, $uri);
392
- $rest = $rest->getResponse();
393
- if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
394
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
395
- if ($rest->error !== false) {
396
- trigger_error(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
397
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
398
- return false;
399
- }
400
- return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
401
- }
402
-
403
-
404
- /**
405
- * Set logging for a bucket
406
- *
407
- * @param string $bucket Bucket name
408
- * @param string $targetBucket Target bucket (where logs are stored)
409
- * @param string $targetPrefix Log prefix (e,g; domain.com-)
410
- * @return boolean
411
- */
412
- public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
413
- $dom = new DOMDocument;
414
- $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
415
- $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
416
-
417
- $loggingEnabled = $dom->createElement('LoggingEnabled');
418
-
419
- $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
420
- $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
421
-
422
- // TODO: Add TargetGrants
423
-
424
- $bucketLoggingStatus->appendChild($loggingEnabled);
425
- $dom->appendChild($bucketLoggingStatus);
426
-
427
- $rest = new S3Request('PUT', $bucket, '');
428
- $rest->setParameter('logging', null);
429
- $rest->data = $dom->saveXML();
430
- $rest->size = strlen($rest->data);
431
- $rest->setHeader('Content-Type', 'application/xml');
432
- $rest = $rest->getResponse();
433
- if ($rest->error === false && $rest->code !== 200)
434
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
435
- if ($rest->error !== false) {
436
- trigger_error(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s",
437
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
438
- return false;
439
- }
440
- return true;
441
- }
442
-
443
-
444
- /**
445
- * Get logging status for a bucket
446
- *
447
- * This will return false if logging is not enabled.
448
- * Note: To enable logging, you also need to grant write access to the log group
449
- *
450
- * @param string $bucket Bucket name
451
- * @return array | false
452
- */
453
- public static function getBucketLogging($bucket = '') {
454
- $rest = new S3Request('GET', $bucket, '');
455
- $rest->setParameter('logging', null);
456
- $rest = $rest->getResponse();
457
- if ($rest->error === false && $rest->code !== 200)
458
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
459
- if ($rest->error !== false) {
460
- trigger_error(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
461
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
462
- return false;
463
- }
464
- if (!isset($rest->body->LoggingEnabled)) return false; // No logging
465
- return array(
466
- 'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
467
- 'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
468
- );
469
- }
470
-
471
-
472
- /**
473
- * Set object or bucket Access Control Policy
474
- *
475
- * @param string $bucket Bucket name
476
- * @param string $uri Object URI
477
- * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
478
- * @return boolean
479
- */
480
- public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
481
- $dom = new DOMDocument;
482
- $dom->formatOutput = true;
483
- $accessControlPolicy = $dom->createElement('AccessControlPolicy');
484
- $accessControlList = $dom->createElement('AccessControlList');
485
-
486
- // It seems the owner has to be passed along too
487
- $owner = $dom->createElement('Owner');
488
- $owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
489
- $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
490
- $accessControlPolicy->appendChild($owner);
491
-
492
- foreach ($acp['acl'] as $g) {
493
- $grant = $dom->createElement('Grant');
494
- $grantee = $dom->createElement('Grantee');
495
- $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
496
- if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
497
- $grantee->setAttribute('xsi:type', 'CanonicalUser');
498
- $grantee->appendChild($dom->createElement('ID', $g['id']));
499
- } elseif (isset($g['email'])) { // AmazonCustomerByEmail
500
- $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
501
- $grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
502
- } elseif ($g['type'] == 'Group') { // Group
503
- $grantee->setAttribute('xsi:type', 'Group');
504
- $grantee->appendChild($dom->createElement('URI', $g['uri']));
505
- }
506
- $grant->appendChild($grantee);
507
- $grant->appendChild($dom->createElement('Permission', $g['permission']));
508
- $accessControlList->appendChild($grant);
509
- }
510
-
511
- $accessControlPolicy->appendChild($accessControlList);
512
- $dom->appendChild($accessControlPolicy);
513
-
514
- $rest = new S3Request('PUT', $bucket, '');
515
- $rest->setParameter('acl', null);
516
- $rest->data = $dom->saveXML();
517
- $rest->size = strlen($rest->data);
518
- $rest->setHeader('Content-Type', 'application/xml');
519
- $rest = $rest->getResponse();
520
- if ($rest->error === false && $rest->code !== 200)
521
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
522
- if ($rest->error !== false) {
523
- trigger_error(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
524
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
525
- return false;
526
- }
527
- return true;
528
- }
529
-
530
-
531
- /**
532
- * Get object or bucket Access Control Policy
533
- *
534
- * Currently this will trigger an error if there is no ACL on an object (will fix soon)
535
- *
536
- * @param string $bucket Bucket name
537
- * @param string $uri Object URI
538
- * @return mixed | false
539
- */
540
- public static function getAccessControlPolicy($bucket, $uri = '') {
541
- $rest = new S3Request('GET', $bucket, $uri);
542
- $rest->setParameter('acl', null);
543
- $rest = $rest->getResponse();
544
- if ($rest->error === false && $rest->code !== 200)
545
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
546
- if ($rest->error !== false) {
547
- trigger_error(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
548
- $rest->error['code'], $rest->error['message']), E_USER_WARNING);
549
- return false;
550
- }
551
-
552
- $acp = array();
553
- if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) {
554
- $acp['owner'] = array(
555
- 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
556
- );
557
- }
558
- if (isset($rest->body->AccessControlList)) {
559
- $acp['acl'] = array();
560
- foreach ($rest->body->AccessControlList->Grant as $grant) {
561
- foreach ($grant->Grantee as $grantee) {
562
- if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
563
- $acp['acl'][] = array(
564
- 'type' => 'CanonicalUser',
565
- 'id' => (string)$grantee->ID,
566
- 'name' => (string)$grantee->DisplayName,
567
- 'permission' => (string)$grant->Permission
568
- );
569
- elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
570
- $acp['acl'][] = array(
571
- 'type' => 'AmazonCustomerByEmail',
572
- 'email' => (string)$grantee->EmailAddress,
573
- 'permission' => (string)$grant->Permission
574
- );
575
- elseif (isset($grantee->URI)) // Group
576
- $acp['acl'][] = array(
577
- 'type' => 'Group',
578
- 'uri' => (string)$grantee->URI,
579
- 'permission' => (string)$grant->Permission
580
- );
581
- else continue;
582
- }
583
- }
584
- }
585
- return $acp;
586
- }
587
-
588
-
589
- /**
590
- * Delete an object
591
- *
592
- * @param string $bucket Bucket name
593
- * @param string $uri Object URI
594
- * @return mixed
595
- */
596
- public static function deleteObject($bucket = '', $uri = '') {
597
- $rest = new S3Request('DELETE', $bucket, $uri);
598
- $rest = $rest->getResponse();
599
- if ($rest->error === false && $rest->code !== 204)
600
- $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
601
- if ($rest->error !== false) {
602
- trigger_error(sprintf("S3::deleteObject(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
603
- return false;
604
- }
605
- return true;
606
- }
607
-
608
-
609
- /**
610
- * Get MIME type for file
611
- *
612
- * @internal Used to get mime types
613
- * @param string &$file File path
614
- * @return string
615
- */
616
- public static function __getMimeType(&$file) {
617
- $type = false;
618
- // Fileinfo documentation says fileinfo_open() will use the
619
- // MAGIC env var for the magic file
620
- if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
621
- ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
622
- if (($type = finfo_file($finfo, $file)) !== false) {
623
- // Remove the charset and grab the last content-type
624
- $type = explode(' ', str_replace('; charset=', ';charset=', $type));
625
- $type = array_pop($type);
626
- $type = explode(';', $type);
627
- $type = array_shift($type);
628
- }
629
- finfo_close($finfo);
630
-
631
- // If anyone is still using mime_content_type()
632
- } elseif (function_exists('mime_content_type'))
633
- $type = mime_content_type($file);
634
-
635
- if ($type !== false && strlen($type) > 0) return $type;
636
-
637
- // Otherwise do it the old fashioned way
638
- static $exts = array(
639
- 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
640
- 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
641
- 'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
642
- 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
643
- 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
644
- 'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
645
- 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
646
- 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
647
- 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
648
- 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
649
- 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
650
- );
651
- $ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
652
- return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
653
- }
654
-
655
-
656
- /**
657
- * Generate the auth string: "AWS AccessKey:Signature"
658
- *
659
- * This uses the hash extension if loaded
660
- *
661
- * @internal Signs the request
662
- * @param string $string String to sign
663
- * @return string
664
- */
665
- public static function __getSignature($string) {
666
- return 'AWS '.self::$__accessKey.':'.base64_encode(extension_loaded('hash') ?
667
- hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
668
- (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
669
- pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
670
- (str_repeat(chr(0x36), 64))) . $string)))));
671
- }
672
-
673
-
674
- }
675
-
676
- final class S3Request {
677
- private $verb, $bucket, $uri, $resource = '', $parameters = array(),
678
- $amzHeaders = array(), $headers = array(
679
- 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
680
- );
681
- public $fp = false, $size = 0, $data = false, $response;
682
-
683
-
684
- /**
685
- * Constructor
686
- *
687
- * @param string $verb Verb
688
- * @param string $bucket Bucket name
689
- * @param string $uri Object URI
690
- * @return mixed
691
- */
692
- function __construct($verb, $bucket = '', $uri = '') {
693
- $this->verb = $verb;
694
- $this->bucket = strtolower($bucket);
695
- $this->uri = $uri !== '' ? '/'.$uri : '/';
696
-
697
- if ($this->bucket !== '') {
698
- $this->bucket = explode('/', $this->bucket);
699
- $this->resource = '/'.$this->bucket[0].$this->uri;
700
- $this->headers['Host'] = $this->bucket[0].'.s3.amazonaws.com';
701
- $this->bucket = implode('/', $this->bucket);
702
- } else {
703
- $this->headers['Host'] = 's3.amazonaws.com';
704
- if (strlen($this->uri) > 1)
705
- $this->resource = '/'.$this->bucket.$this->uri;
706
- else $this->resource = $this->uri;
707
- }
708
- $this->headers['Date'] = gmdate('D, d M Y H:i:s T');
709
-
710
- $this->response = new STDClass;
711
- $this->response->error = false;
712
- }
713
-
714
-
715
- /**
716
- * Set request parameter
717
- *
718
- * @param string $key Key
719
- * @param string $value Value
720
- * @return void
721
- */
722
- public function setParameter($key, $value) {
723
- $this->parameters[$key] = $value;
724
- }
725
-
726
-
727
- /**
728
- * Set request header
729
- *
730
- * @param string $key Key
731
- * @param string $value Value
732
- * @return void
733
- */
734
- public function setHeader($key, $value) {
735
- $this->headers[$key] = $value;
736
- }
737
-
738
-
739
- /**
740
- * Set x-amz-meta-* header
741
- *
742
- * @param string $key Key
743
- * @param string $value Value
744
- * @return void
745
- */
746
- public function setAmzHeader($key, $value) {
747
- $this->amzHeaders[$key] = $value;
748
- }
749
-
750
-
751
- /**
752
- * Get the S3 response
753
- *
754
- * @return object | false
755
- */
756
- public function getResponse() {
757
- $query = '';
758
- if (sizeof($this->parameters) > 0) {
759
- $query = substr($this->uri, -1) !== '?' ? '?' : '&';
760
- foreach ($this->parameters as $var => $value)
761
- if ($value == null || $value == '') $query .= $var.'&';
762
- else $query .= $var.'='.$value.'&';
763
- $query = substr($query, 0, -1);
764
- $this->uri .= $query;
765
- if (isset($this->parameters['acl']) || !isset($this->parameters['logging']))
766
- $this->resource .= $query;
767
- }
768
- $url = (extension_loaded('openssl')?'https://':'http://').$this->headers['Host'].$this->uri;
769
- //var_dump($this->bucket, $this->uri, $this->resource, $url);
770
-
771
- // Basic setup
772
- $curl = curl_init();
773
- curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
774
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
775
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
776
- curl_setopt($curl, CURLOPT_URL, $url);
777
-
778
- // Headers
779
- $headers = array(); $amz = array();
780
- foreach ($this->amzHeaders as $header => $value)
781
- if (strlen($value) > 0) $headers[] = $header.': '.$value;
782
- foreach ($this->headers as $header => $value)
783
- if (strlen($value) > 0) $headers[] = $header.': '.$value;
784
- foreach ($this->amzHeaders as $header => $value)
785
- if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
786
- $amz = (sizeof($amz) > 0) ? "\n".implode("\n", $amz) : '';
787
-
788
- // Authorization string
789
- $headers[] = 'Authorization: ' . S3::__getSignature(
790
- $this->verb."\n".
791
- $this->headers['Content-MD5']."\n".
792
- $this->headers['Content-Type']."\n".
793
- $this->headers['Date'].$amz."\n".$this->resource
794
- );
795
-
796
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
797
- curl_setopt($curl, CURLOPT_HEADER, false);
798
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
799
- curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
800
- curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
801
-
802
- // Request types
803
- switch ($this->verb) {
804
- case 'GET': break;
805
- case 'PUT':
806
- if ($this->fp !== false) {
807
- curl_setopt($curl, CURLOPT_PUT, true);
808
- curl_setopt($curl, CURLOPT_INFILE, $this->fp);
809
- if ($this->size > 0)
810
- curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
811
- } elseif ($this->data !== false) {
812
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
813
- curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
814
- if ($this->size > 0)
815
- curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
816
- } else
817
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
818
- break;
819
- case 'HEAD':
820
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
821
- curl_setopt($curl, CURLOPT_NOBODY, true);
822
- break;
823
- case 'DELETE':
824
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
825
- break;
826
- default: break;
827
- }
828
-
829
- // Execute, grab errors
830
- if (curl_exec($curl))
831
- $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
832
- else
833
- $this->response->error = array(
834
- 'code' => curl_errno($curl),
835
- 'message' => curl_error($curl),
836
- 'resource' => $this->resource
837
- );
838
-
839
- @curl_close($curl);
840
-
841
- // Parse body into XML
842
- if ($this->response->error === false && isset($this->response->headers['type']) &&
843
- $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
844
- $this->response->body = simplexml_load_string($this->response->body);
845
-
846
- // Grab S3 errors
847
- if (!in_array($this->response->code, array(200, 204)) &&
848
- isset($this->response->body->Code, $this->response->body->Message)) {
849
- $this->response->error = array(
850
- 'code' => (string)$this->response->body->Code,
851
- 'message' => (string)$this->response->body->Message
852
- );
853
- if (isset($this->response->body->Resource))
854
- $this->response->error['resource'] = (string)$this->response->body->Resource;
855
- unset($this->response->body);
856
- }
857
- }
858
-
859
- // Clean up file resources
860
- if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
861
-
862
- return $this->response;
863
- }
864
-
865
-
866
- /**
867
- * CURL write callback
868
- *
869
- * @param resource &$curl CURL resource
870
- * @param string &$data Data
871
- * @return integer
872
- */
873
- private function __responseWriteCallback(&$curl, &$data) {
874
- if ($this->response->code == 200 && $this->fp !== false)
875
- return fwrite($this->fp, $data);
876
- else
877
- $this->response->body .= $data;
878
- return strlen($data);
879
- }
880
-
881
-
882
- /**
883
- * CURL header callback
884
- *
885
- * @param resource &$curl CURL resource
886
- * @param string &$data Data
887
- * @return integer
888
- */
889
- private function __responseHeaderCallback(&$curl, &$data) {
890
- if (($strlen = strlen($data)) <= 2) return $strlen;
891
- if (substr($data, 0, 4) == 'HTTP')
892
- $this->response->code = (int)substr($data, 9, 3);
893
- else {
894
- list($header, $value) = explode(': ', trim($data));
895
- if ($header == 'Last-Modified')
896
- $this->response->headers['time'] = strtotime($value);
897
- elseif ($header == 'Content-Length')
898
- $this->response->headers['size'] = (int)$value;
899
- elseif ($header == 'Content-Type')
900
- $this->response->headers['type'] = $value;
901
- elseif ($header == 'ETag')
902
- $this->response->headers['hash'] = substr($value, 1, -1);
903
- elseif (preg_match('/^x-amz-meta-.*$/', $header))
904
- $this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
905
- }
906
- return $strlen;
907
- }
908
-
909
- }
910
  ?>
1
+ <?php
2
+ /**
3
+ * $Id$
4
+ *
5
+ * Copyright (c) 2007, Donovan Schonknecht. All rights reserved.
6
+ *
7
+ * Redistribution and use in source and binary forms, with or without
8
+ * modification, are permitted provided that the following conditions are met:
9
+ *
10
+ * - Redistributions of source code must retain the above copyright notice,
11
+ * this list of conditions and the following disclaimer.
12
+ * - Redistributions in binary form must reproduce the above copyright
13
+ * notice, this list of conditions and the following disclaimer in the
14
+ * documentation and/or other materials provided with the distribution.
15
+ *
16
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ * POSSIBILITY OF SUCH DAMAGE.
27
+ */
28
+
29
+ /**
30
+ * Amazon S3 PHP class
31
+ *
32
+ * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
33
+ * @version 0.2.3
34
+ */
35
+ class S3 {
36
+ // ACL flags
37
+ const ACL_PRIVATE = 'private';
38
+ const ACL_PUBLIC_READ = 'public-read';
39
+ const ACL_PUBLIC_READ_WRITE = 'public-read-write';
40
+
41
+ private static $__accessKey; // AWS Access key
42
+ private static $__secretKey; // AWS Secret key
43
+
44
+
45
+ /**
46
+ * Constructor, used if you're not calling the class statically
47
+ *
48
+ * @param string $accessKey Access key
49
+ * @param string $secretKey Secret key
50
+ * @return void
51
+ */
52
+ public function __construct($accessKey = null, $secretKey = null) {
53
+ if ($accessKey !== null && $secretKey !== null)
54
+ self::setAuth($accessKey, $secretKey);
55
+ }
56
+
57
+
58
+ /**
59
+ * Set access information
60
+ *
61
+ * @param string $accessKey Access key
62
+ * @param string $secretKey Secret key
63
+ * @return void
64
+ */
65
+ public static function setAuth($accessKey, $secretKey) {
66
+ self::$__accessKey = $accessKey;
67
+ self::$__secretKey = $secretKey;
68
+ }
69
+
70
+
71
+ /**
72
+ * Get a list of buckets
73
+ *
74
+ * @param boolean $detailed Returns detailed bucket list when true
75
+ * @return array | false
76
+ */
77
+ public static function listBuckets($detailed = false) {
78
+ $rest = new S3Request('GET', '', '');
79
+ $rest = $rest->getResponse();
80
+ if ($rest->error === false && $rest->code !== 200)
81
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
82
+ if ($rest->error !== false) {
83
+ trigger_error(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
84
+ return false;
85
+ }
86
+ $results = array(); //var_dump($rest->body);
87
+ if (!isset($rest->body->Buckets)) return $results;
88
+
89
+ if ($detailed) {
90
+ if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
91
+ $results['owner'] = array(
92
+ 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
93
+ );
94
+ $results['buckets'] = array();
95
+ foreach ($rest->body->Buckets->Bucket as $b)
96
+ $results['buckets'][] = array(
97
+ 'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
98
+ );
99
+ } else
100
+ foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
101
+
102
+ return $results;
103
+ }
104
+
105
+
106
+ /*
107
+ * Get contents for a bucket
108
+ *
109
+ * If maxKeys is null this method will loop through truncated result sets
110
+ *
111
+ * @param string $bucket Bucket name
112
+ * @param string $prefix Prefix
113
+ * @param string $marker Marker (last file listed)
114
+ * @param string $maxKeys Max keys (maximum number of keys to return)
115
+ * @return array | false
116
+ */
117
+ public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null) {
118
+ $rest = new S3Request('GET', $bucket, '');
119
+ if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
120
+ if ($marker !== null && $prefix !== '') $rest->setParameter('marker', $marker);
121
+ if ($maxKeys !== null && $prefix !== '') $rest->setParameter('max-keys', $maxKeys);
122
+ $response = $rest->getResponse();
123
+ if ($response->error === false && $response->code !== 200)
124
+ $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
125
+ if ($response->error !== false) {
126
+ trigger_error(sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
127
+ return false;
128
+ }
129
+
130
+ $results = array();
131
+
132
+ $lastMarker = null;
133
+ if (isset($response->body, $response->body->Contents))
134
+ foreach ($response->body->Contents as $c) {
135
+ $results[(string)$c->Key] = array(
136
+ 'name' => (string)$c->Key,
137
+ 'time' => strToTime((string)$c->LastModified),
138
+ 'size' => (int)$c->Size,
139
+ 'hash' => substr((string)$c->ETag, 1, -1)
140
+ );
141
+ $lastMarker = (string)$c->Key;
142
+ //$response->body->IsTruncated = 'true'; break;
143
+ }
144
+
145
+
146
+ if (isset($response->body->IsTruncated) &&
147
+ (string)$response->body->IsTruncated == 'false') return $results;
148
+
149
+ // Loop through truncated results if maxKeys isn't specified
150
+ if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true')
151
+ do {
152
+ $rest = new S3Request('GET', $bucket, '');
153
+ if ($prefix !== null) $rest->setParameter('prefix', $prefix);
154
+ $rest->setParameter('marker', $lastMarker);
155
+
156
+ if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break;
157
+ if (isset($response->body, $response->body->Contents))
158
+ foreach ($response->body->Contents as $c) {
159
+ $results[(string)$c->Key] = array(
160
+ 'name' => (string)$c->Key,
161
+ 'time' => strToTime((string)$c->LastModified),
162
+ 'size' => (int)$c->Size,
163
+ 'hash' => substr((string)$c->ETag, 1, -1)
164
+ );
165
+ $lastMarker = (string)$c->Key;
166
+ }
167
+ } while ($response !== false && (string)$response->body->IsTruncated == 'true');
168
+
169
+ return $results;
170
+ }
171
+
172
+
173
+ /**
174
+ * Put a bucket
175
+ *
176
+ * @param string $bucket Bucket name
177
+ * @param constant $acl ACL flag
178
+ * @return boolean
179
+ */
180
+ public function putBucket($bucket, $acl = self::ACL_PRIVATE) {
181
+ $rest = new S3Request('PUT', $bucket, '');
182
+ $rest->setAmzHeader('x-amz-acl', $acl);
183
+ $rest = $rest->getResponse();
184
+ if ($rest->error === false && $rest->code !== 200)
185
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
186
+ if ($rest->error !== false) {
187
+ trigger_error(sprintf("S3::putBucket({$bucket}): [%s] %s",
188
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
189
+ return false;
190
+ }
191
+ return true;
192
+ }
193
+
194
+
195
+ /**
196
+ * Delete an empty bucket
197
+ *
198
+ * @param string $bucket Bucket name
199
+ * @return boolean
200
+ */
201
+ public function deleteBucket($bucket = '') {
202
+ $rest = new S3Request('DELETE', $bucket);
203
+ $rest = $rest->getResponse();
204
+ if ($rest->error === false && $rest->code !== 204)
205
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
206
+ if ($rest->error !== false) {
207
+ trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
208
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
209
+ return false;
210
+ }
211
+ return true;
212
+ }
213
+
214
+
215
+ /**
216
+ * Create input info array for putObject()
217
+ *
218
+ * @param string $file Input file
219
+ * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
220
+ * @return array | false
221
+ */
222
+ public static function inputFile($file, $md5sum = true) {
223
+ if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
224
+ trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
225
+ return false;
226
+ }
227
+ return array('file' => $file, 'size' => filesize($file),
228
+ 'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
229
+ base64_encode(md5_file($file, true))) : '');
230
+ }
231
+
232
+
233
+ /**
234
+ * Use a resource for input
235
+ *
236
+ * @param string $file Input file
237
+ * @param integer $bufferSize Input byte size
238
+ * @param string $md5sum MD5 hash to send (optional)
239
+ * @return array | false
240
+ */
241
+ public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
242
+ if (!is_resource($resource) || $bufferSize <= 0) {
243
+ trigger_error('S3::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
244
+ return false;
245
+ }
246
+ $input = array('size' => $bufferSize, 'md5sum' => $md5sum);
247
+ $input['fp'] =& $resource;
248
+ return $input;
249
+ }
250
+
251
+
252
+ /**
253
+ * Put an object
254
+ *
255
+ * @param mixed $input Input data
256
+ * @param string $bucket Bucket name
257
+ * @param string $uri Object URI
258
+ * @param constant $acl ACL constant
259
+ * @param array $metaHeaders Array of x-amz-meta-* headers
260
+ * @param string $contentType Content type
261
+ * @return boolean
262
+ */
263
+ public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
264
+ if ($input == false) return false;
265
+ $rest = new S3Request('PUT', $bucket, $uri);
266
+
267
+ if (is_string($input)) $input = array(
268
+ 'data' => $input, 'size' => strlen($input),
269
+ 'md5sum' => base64_encode(md5($input, true))
270
+ );
271
+
272
+ // Data
273
+ if (isset($input['fp']))
274
+ $rest->fp =& $input['fp'];
275
+ elseif (isset($input['file']))
276
+ $rest->fp = @fopen($input['file'], 'rb');
277
+ elseif (isset($input['data']))
278
+ $rest->data = $input['data'];
279
+
280
+ // Content-Length (required)
281
+ if (isset($input['size']) && $input['size'] > 0)
282
+ $rest->size = $input['size'];
283
+ else {
284
+ if (isset($input['file']))
285
+ $rest->size = filesize($input['file']);
286
+ elseif (isset($input['data']))
287
+ $rest->size = strlen($input['data']);
288
+ }
289
+
290
+ // Content-Type
291
+ if ($contentType !== null)
292
+ $input['type'] = $contentType;
293
+ elseif (!isset($input['type']) && isset($input['file']))
294
+ $input['type'] = self::__getMimeType($input['file']);
295
+ else
296
+ $input['type'] = 'application/octet-stream';
297
+
298
+ // We need to post with the content-length and content-type, MD5 is optional
299
+ if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
300
+ $rest->setHeader('Content-Type', $input['type']);
301
+ if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
302
+
303
+ $rest->setAmzHeader('x-amz-acl', $acl);
304
+ foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
305
+ $rest->getResponse();
306
+ } else
307
+ $rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
308
+
309
+ if ($rest->response->error === false && $rest->response->code !== 200)
310
+ $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
311
+ if ($rest->response->error !== false) {
312
+ trigger_error(sprintf("S3::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
313
+ return false;
314
+ }
315
+ return true;
316
+ }
317
+
318
+
319
+ /**
320
+ * Puts an object from a file (legacy function)
321
+ *
322
+ * @param string $file Input file path
323
+ * @param string $bucket Bucket name
324
+ * @param string $uri Object URI
325
+ * @param constant $acl ACL constant
326
+ * @param array $metaHeaders Array of x-amz-meta-* headers
327
+ * @param string $contentType Content type
328
+ * @return boolean
329
+ */
330
+ public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
331
+ return self::putObject(S3::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
332
+ }
333
+
334
+
335
+ /**
336
+ * Put an object from a string (legacy function)
337
+ *
338
+ * @param string $string Input data
339
+ * @param string $bucket Bucket name
340
+ * @param string $uri Object URI
341
+ * @param constant $acl ACL constant
342
+ * @param array $metaHeaders Array of x-amz-meta-* headers
343
+ * @param string $contentType Content type
344
+ * @return boolean
345
+ */
346
+ public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
347
+ return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
348
+ }
349
+
350
+
351
+ /**
352
+ * Get an object
353
+ *
354
+ * @param string $bucket Bucket name
355
+ * @param string $uri Object URI
356
+ * @param mixed &$saveTo Filename or resource to write to
357
+ * @return mixed
358
+ */
359
+ public static function getObject($bucket = '', $uri = '', $saveTo = false) {
360
+ $rest = new S3Request('GET', $bucket, $uri);
361
+ if ($saveTo !== false) {
362
+ if (is_resource($saveTo))
363
+ $rest->fp =& $saveTo;
364
+ else
365
+ if (($rest->fp = @fopen($saveTo, 'wb')) == false)
366
+ $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
367
+ }
368
+ if ($rest->response->error === false) $rest->getResponse();
369
+
370
+ if ($rest->response->error === false && $rest->response->code !== 200)
371
+ $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
372
+ if ($rest->response->error !== false) {
373
+ trigger_error(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
374
+ $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
375
+ return false;
376
+ }
377
+ $rest->file = realpath($saveTo);
378
+ return $rest->response;
379
+ }
380
+
381
+
382
+ /**
383
+ * Get object information
384
+ *
385
+ * @param string $bucket Bucket name
386
+ * @param string $uri Object URI
387
+ * @param boolean $returnInfo Return response information
388
+ * @return mixed | false
389
+ */
390
+ public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
391
+ $rest = new S3Request('HEAD', $bucket, $uri);
392
+ $rest = $rest->getResponse();
393
+ if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
394
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
395
+ if ($rest->error !== false) {
396
+ trigger_error(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
397
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
398
+ return false;
399
+ }
400
+ return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
401
+ }
402
+
403
+
404
+ /**
405
+ * Set logging for a bucket
406
+ *
407
+ * @param string $bucket Bucket name
408
+ * @param string $targetBucket Target bucket (where logs are stored)
409
+ * @param string $targetPrefix Log prefix (e,g; domain.com-)
410
+ * @return boolean
411
+ */
412
+ public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
413
+ $dom = new DOMDocument;
414
+ $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
415
+ $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
416
+
417
+ $loggingEnabled = $dom->createElement('LoggingEnabled');
418
+
419
+ $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
420
+ $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
421
+
422
+ // TODO: Add TargetGrants
423
+
424
+ $bucketLoggingStatus->appendChild($loggingEnabled);
425
+ $dom->appendChild($bucketLoggingStatus);
426
+
427
+ $rest = new S3Request('PUT', $bucket, '');
428
+ $rest->setParameter('logging', null);
429
+ $rest->data = $dom->saveXML();
430
+ $rest->size = strlen($rest->data);
431
+ $rest->setHeader('Content-Type', 'application/xml');
432
+ $rest = $rest->getResponse();
433
+ if ($rest->error === false && $rest->code !== 200)
434
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
435
+ if ($rest->error !== false) {
436
+ trigger_error(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s",
437
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
438
+ return false;
439
+ }
440
+ return true;
441
+ }
442
+
443
+
444
+ /**
445
+ * Get logging status for a bucket
446
+ *
447
+ * This will return false if logging is not enabled.
448
+ * Note: To enable logging, you also need to grant write access to the log group
449
+ *
450
+ * @param string $bucket Bucket name
451
+ * @return array | false
452
+ */
453
+ public static function getBucketLogging($bucket = '') {
454
+ $rest = new S3Request('GET', $bucket, '');
455
+ $rest->setParameter('logging', null);
456
+ $rest = $rest->getResponse();
457
+ if ($rest->error === false && $rest->code !== 200)
458
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
459
+ if ($rest->error !== false) {
460
+ trigger_error(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
461
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
462
+ return false;
463
+ }
464
+ if (!isset($rest->body->LoggingEnabled)) return false; // No logging
465
+ return array(
466
+ 'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
467
+ 'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
468
+ );
469
+ }
470
+
471
+
472
+ /**
473
+ * Set object or bucket Access Control Policy
474
+ *
475
+ * @param string $bucket Bucket name
476
+ * @param string $uri Object URI
477
+ * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
478
+ * @return boolean
479
+ */
480
+ public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
481
+ $dom = new DOMDocument;
482
+ $dom->formatOutput = true;
483
+ $accessControlPolicy = $dom->createElement('AccessControlPolicy');
484
+ $accessControlList = $dom->createElement('AccessControlList');
485
+
486
+ // It seems the owner has to be passed along too
487
+ $owner = $dom->createElement('Owner');
488
+ $owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
489
+ $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
490
+ $accessControlPolicy->appendChild($owner);
491
+
492
+ foreach ($acp['acl'] as $g) {
493
+ $grant = $dom->createElement('Grant');
494
+ $grantee = $dom->createElement('Grantee');
495
+ $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
496
+ if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
497
+ $grantee->setAttribute('xsi:type', 'CanonicalUser');
498
+ $grantee->appendChild($dom->createElement('ID', $g['id']));
499
+ } elseif (isset($g['email'])) { // AmazonCustomerByEmail
500
+ $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
501
+ $grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
502
+ } elseif ($g['type'] == 'Group') { // Group
503
+ $grantee->setAttribute('xsi:type', 'Group');
504
+ $grantee->appendChild($dom->createElement('URI', $g['uri']));
505
+ }
506
+ $grant->appendChild($grantee);
507
+ $grant->appendChild($dom->createElement('Permission', $g['permission']));
508
+ $accessControlList->appendChild($grant);
509
+ }
510
+
511
+ $accessControlPolicy->appendChild($accessControlList);
512
+ $dom->appendChild($accessControlPolicy);
513
+
514
+ $rest = new S3Request('PUT', $bucket, '');
515
+ $rest->setParameter('acl', null);
516
+ $rest->data = $dom->saveXML();
517
+ $rest->size = strlen($rest->data);
518
+ $rest->setHeader('Content-Type', 'application/xml');
519
+ $rest = $rest->getResponse();
520
+ if ($rest->error === false && $rest->code !== 200)
521
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
522
+ if ($rest->error !== false) {
523
+ trigger_error(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
524
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
525
+ return false;
526
+ }
527
+ return true;
528
+ }
529
+
530
+
531
+ /**
532
+ * Get object or bucket Access Control Policy
533
+ *
534
+ * Currently this will trigger an error if there is no ACL on an object (will fix soon)
535
+ *
536
+ * @param string $bucket Bucket name
537
+ * @param string $uri Object URI
538
+ * @return mixed | false
539
+ */
540
+ public static function getAccessControlPolicy($bucket, $uri = '') {
541
+ $rest = new S3Request('GET', $bucket, $uri);
542
+ $rest->setParameter('acl', null);
543
+ $rest = $rest->getResponse();
544
+ if ($rest->error === false && $rest->code !== 200)
545
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
546
+ if ($rest->error !== false) {
547
+ trigger_error(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
548
+ $rest->error['code'], $rest->error['message']), E_USER_WARNING);
549
+ return false;
550
+ }
551
+
552
+ $acp = array();
553
+ if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) {
554
+ $acp['owner'] = array(
555
+ 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
556
+ );
557
+ }
558
+ if (isset($rest->body->AccessControlList)) {
559
+ $acp['acl'] = array();
560
+ foreach ($rest->body->AccessControlList->Grant as $grant) {
561
+ foreach ($grant->Grantee as $grantee) {
562
+ if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
563
+ $acp['acl'][] = array(
564
+ 'type' => 'CanonicalUser',
565
+ 'id' => (string)$grantee->ID,
566
+ 'name' => (string)$grantee->DisplayName,
567
+ 'permission' => (string)$grant->Permission
568
+ );
569
+ elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
570
+ $acp['acl'][] = array(
571
+ 'type' => 'AmazonCustomerByEmail',
572
+ 'email' => (string)$grantee->EmailAddress,
573
+ 'permission' => (string)$grant->Permission
574
+ );
575
+ elseif (isset($grantee->URI)) // Group
576
+ $acp['acl'][] = array(
577
+ 'type' => 'Group',
578
+ 'uri' => (string)$grantee->URI,
579
+ 'permission' => (string)$grant->Permission
580
+ );
581
+ else continue;
582
+ }
583
+ }
584
+ }
585
+ return $acp;
586
+ }
587
+
588
+
589
+ /**
590
+ * Delete an object
591
+ *
592
+ * @param string $bucket Bucket name
593
+ * @param string $uri Object URI
594
+ * @return mixed
595
+ */
596
+ public static function deleteObject($bucket = '', $uri = '') {
597
+ $rest = new S3Request('DELETE', $bucket, $uri);
598
+ $rest = $rest->getResponse();
599
+ if ($rest->error === false && $rest->code !== 204)
600
+ $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
601
+ if ($rest->error !== false) {
602
+ trigger_error(sprintf("S3::deleteObject(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
603
+ return false;
604
+ }
605
+ return true;
606
+ }
607
+
608
+
609
+ /**
610
+ * Get MIME type for file
611
+ *
612
+ * @internal Used to get mime types
613
+ * @param string &$file File path
614
+ * @return string
615
+ */
616
+ public static function __getMimeType(&$file) {
617
+ $type = false;
618
+ // Fileinfo documentation says fileinfo_open() will use the
619
+ // MAGIC env var for the magic file
620
+ if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
621
+ ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
622
+ if (($type = finfo_file($finfo, $file)) !== false) {
623
+ // Remove the charset and grab the last content-type
624
+ $type = explode(' ', str_replace('; charset=', ';charset=', $type));
625
+ $type = array_pop($type);
626
+ $type = explode(';', $type);
627
+ $type = array_shift($type);
628
+ }
629
+ finfo_close($finfo);
630
+
631
+ // If anyone is still using mime_content_type()
632
+ } elseif (function_exists('mime_content_type'))
633
+ $type = mime_content_type($file);
634
+
635
+ if ($type !== false && strlen($type) > 0) return $type;
636
+
637
+ // Otherwise do it the old fashioned way
638
+ static $exts = array(
639
+ 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
640
+ 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
641
+ 'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
642
+ 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
643
+ 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
644
+ 'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
645
+ 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
646
+ 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
647
+ 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
648
+ 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
649
+ 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
650
+ );
651
+ $ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
652
+ return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
653
+ }
654
+
655
+
656
+ /**
657
+ * Generate the auth string: "AWS AccessKey:Signature"
658
+ *
659
+ * This uses the hash extension if loaded
660
+ *
661
+ * @internal Signs the request
662
+ * @param string $string String to sign
663
+ * @return string
664
+ */
665
+ public static function __getSignature($string) {
666
+ return 'AWS '.self::$__accessKey.':'.base64_encode(extension_loaded('hash') ?
667
+ hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
668
+ (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
669
+ pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
670
+ (str_repeat(chr(0x36), 64))) . $string)))));
671
+ }
672
+
673
+
674
+ }
675
+
676
+ final class S3Request {
677
+ private $verb, $bucket, $uri, $resource = '', $parameters = array(),
678
+ $amzHeaders = array(), $headers = array(
679
+ 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
680
+ );
681
+ public $fp = false, $size = 0, $data = false, $response;
682
+
683
+
684
+ /**
685
+ * Constructor
686
+ *
687
+ * @param string $verb Verb
688
+ * @param string $bucket Bucket name
689
+ * @param string $uri Object URI
690
+ * @return mixed
691
+ */
692
+ function __construct($verb, $bucket = '', $uri = '') {
693
+ $this->verb = $verb;
694
+ $this->bucket = strtolower($bucket);
695
+ $this->uri = $uri !== '' ? '/'.$uri : '/';
696
+
697
+ if ($this->bucket !== '') {
698
+ $this->bucket = explode('/', $this->bucket);
699
+ $this->resource = '/'.$this->bucket[0].$this->uri;
700
+ $this->headers['Host'] = $this->bucket[0].'.s3.amazonaws.com';
701
+ $this->bucket = implode('/', $this->bucket);
702
+ } else {
703
+ $this->headers['Host'] = 's3.amazonaws.com';
704
+ if (strlen($this->uri) > 1)
705
+ $this->resource = '/'.$this->bucket.$this->uri;
706
+ else $this->resource = $this->uri;
707
+ }
708
+ $this->headers['Date'] = gmdate('D, d M Y H:i:s T');
709
+
710
+ $this->response = new STDClass;
711
+ $this->response->error = false;
712
+ }
713
+
714
+
715
+ /**
716
+ * Set request parameter
717
+ *
718
+ * @param string $key Key
719
+ * @param string $value Value
720
+ * @return void
721
+ */
722
+ public function setParameter($key, $value) {
723
+ $this->parameters[$key] = $value;
724
+ }
725
+
726
+
727
+ /**
728
+ * Set request header
729
+ *
730
+ * @param string $key Key
731
+ * @param string $value Value
732
+ * @return void
733
+ */
734
+ public function setHeader($key, $value) {
735
+ $this->headers[$key] = $value;
736
+ }
737
+
738
+
739
+ /**
740
+ * Set x-amz-meta-* header
741
+ *
742
+ * @param string $key Key
743
+ * @param string $value Value
744
+ * @return void
745
+ */
746
+ public function setAmzHeader($key, $value) {
747
+ $this->amzHeaders[$key] = $value;
748
+ }
749
+
750
+
751
+ /**
752
+ * Get the S3 response
753
+ *
754
+ * @return object | false
755
+ */
756
+ public function getResponse() {
757
+ $query = '';
758
+ if (sizeof($this->parameters) > 0) {
759
+ $query = substr($this->uri, -1) !== '?' ? '?' : '&';
760
+ foreach ($this->parameters as $var => $value)
761
+ if ($value == null || $value == '') $query .= $var.'&';
762
+ else $query .= $var.'='.$value.'&';
763
+ $query = substr($query, 0, -1);
764
+ $this->uri .= $query;
765
+ if (isset($this->parameters['acl']) || !isset($this->parameters['logging']))
766
+ $this->resource .= $query;
767
+ }
768
+ $url = (extension_loaded('openssl')?'https://':'http://').$this->headers['Host'].$this->uri;
769
+ //var_dump($this->bucket, $this->uri, $this->resource, $url);
770
+
771
+ // Basic setup
772
+ $curl = curl_init();
773
+ curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
774
+ curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
775
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
776
+ curl_setopt($curl, CURLOPT_URL, $url);
777
+
778
+ // Headers
779
+ $headers = array(); $amz = array();
780
+ foreach ($this->amzHeaders as $header => $value)
781
+ if (strlen($value) > 0) $headers[] = $header.': '.$value;
782
+ foreach ($this->headers as $header => $value)
783
+ if (strlen($value) > 0) $headers[] = $header.': '.$value;
784
+ foreach ($this->amzHeaders as $header => $value)
785
+ if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
786
+ $amz = (sizeof($amz) > 0) ? "\n".implode("\n", $amz) : '';
787
+
788
+ // Authorization string
789
+ $headers[] = 'Authorization: ' . S3::__getSignature(
790
+ $this->verb."\n".
791
+ $this->headers['Content-MD5']."\n".
792
+ $this->headers['Content-Type']."\n".
793
+ $this->headers['Date'].$amz."\n".$this->resource
794
+ );
795
+
796
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
797
+ curl_setopt($curl, CURLOPT_HEADER, false);
798
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
799
+ curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
800
+ curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
801
+
802
+ // Request types
803
+ switch ($this->verb) {
804
+ case 'GET': break;
805
+ case 'PUT':
806
+ if ($this->fp !== false) {
807
+ curl_setopt($curl, CURLOPT_PUT, true);
808
+ curl_setopt($curl, CURLOPT_INFILE, $this->fp);
809
+ if ($this->size > 0)
810
+ curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
811
+ } elseif ($this->data !== false) {
812
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
813
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
814
+ if ($this->size > 0)
815
+ curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
816
+ } else
817
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
818
+ break;
819
+ case 'HEAD':
820
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
821
+ curl_setopt($curl, CURLOPT_NOBODY, true);
822
+ break;
823
+ case 'DELETE':
824
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
825
+ break;
826
+ default: break;
827
+ }
828
+
829
+ // Execute, grab errors
830
+ if (curl_exec($curl))
831
+ $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
832
+ else
833
+ $this->response->error = array(
834
+ 'code' => curl_errno($curl),
835
+ 'message' => curl_error($curl),
836
+ 'resource' => $this->resource
837
+ );
838
+
839
+ @curl_close($curl);
840
+
841
+ // Parse body into XML
842
+ if ($this->response->error === false && isset($this->response->headers['type']) &&
843
+ $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
844
+ $this->response->body = simplexml_load_string($this->response->body);
845
+
846
+ // Grab S3 errors
847
+ if (!in_array($this->response->code, array(200, 204)) &&
848
+ isset($this->response->body->Code, $this->response->body->Message)) {
849
+ $this->response->error = array(
850
+ 'code' => (string)$this->response->body->Code,
851
+ 'message' => (string)$this->response->body->Message
852
+ );
853
+ if (isset($this->response->body->Resource))
854
+ $this->response->error['resource'] = (string)$this->response->body->Resource;
855
+ unset($this->response->body);
856
+ }
857
+ }
858
+
859
+ // Clean up file resources
860
+ if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
861
+
862
+ return $this->response;
863
+ }
864
+
865
+
866
+ /**
867
+ * CURL write callback
868
+ *
869
+ * @param resource &$curl CURL resource
870
+ * @param string &$data Data
871
+ * @return integer
872
+ */
873
+ private function __responseWriteCallback(&$curl, &$data) {
874
+ if ($this->response->code == 200 && $this->fp !== false)
875
+ return fwrite($this->fp, $data);
876
+ else
877
+ $this->response->body .= $data;
878
+ return strlen($data);
879
+ }
880
+
881
+
882
+ /**
883
+ * CURL header callback
884
+ *
885
+ * @param resource &$curl CURL resource
886
+ * @param string &$data Data
887
+ * @return integer
888
+ */
889
+ private function __responseHeaderCallback(&$curl, &$data) {
890
+ if (($strlen = strlen($data)) <= 2) return $strlen;
891
+ if (substr($data, 0, 4) == 'HTTP')
892
+ $this->response->code = (int)substr($data, 9, 3);
893
+ else {
894
+ list($header, $value) = explode(': ', trim($data));
895
+ if ($header == 'Last-Modified')
896
+ $this->response->headers['time'] = strtotime($value);
897
+ elseif ($header == 'Content-Length')
898
+ $this->response->headers['size'] = (int)$value;
899
+ elseif ($header == 'Content-Type')
900
+ $this->response->headers['type'] = $value;
901
+ elseif ($header == 'ETag')
902
+ $this->response->headers['hash'] = substr($value, 1, -1);
903
+ elseif (preg_match('/^x-amz-meta-.*$/', $header))
904
+ $this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
905
+ }
906
+ return $strlen;
907
+ }
908
+
909
+ }
910
  ?>
link.class.php CHANGED
@@ -1,39 +1,39 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * user.class.php
5
- *
6
- * Add Users
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Link extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- parent::__construct();
18
- }
19
-
20
- function add_link($args)
21
- {
22
- extract($args);
23
-
24
- $params['link_url'] = esc_html($url);
25
- $params['link_url'] = esc_url($params['link_url']);
26
- $params['link_name'] = esc_html($name);
27
- $params['link_id'] = '';
28
- $params['link_description'] = $description;
29
-
30
- if(!function_exists(wp_insert_link))
31
- include_once (ABSPATH . 'wp-admin/includes/bookmark.php');
32
-
33
- $is_success = wp_insert_link($params);
34
-
35
- return $is_success ? true : array('error' => 'Failed to add link');
36
- }
37
-
38
- }
39
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * user.class.php
5
+ *
6
+ * Add Users
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Link extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ parent::__construct();
18
+ }
19
+
20
+ function add_link($args)
21
+ {
22
+ extract($args);
23
+
24
+ $params['link_url'] = esc_html($url);
25
+ $params['link_url'] = esc_url($params['link_url']);
26
+ $params['link_name'] = esc_html($name);
27
+ $params['link_id'] = '';
28
+ $params['link_description'] = $description;
29
+
30
+ if(!function_exists(wp_insert_link))
31
+ include_once (ABSPATH . 'wp-admin/includes/bookmark.php');
32
+
33
+ $is_success = wp_insert_link($params);
34
+
35
+ return $is_success ? true : array('error' => 'Failed to add link');
36
+ }
37
+
38
+ }
39
  ?>
plugins/cleanup/cleanup.php CHANGED
@@ -1,176 +1,176 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- *
5
- *
6
- * ManageWP Worker Plugin
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- add_filter('mmb_stats_filter', 'mmb_get_extended_info');
14
-
15
-
16
- function mmb_get_extended_info($stats)
17
- {
18
- $stats['num_revisions'] = mmb_num_revisions();
19
- //$stats['num_revisions'] = 5;
20
- $stats['overhead'] = mmb_get_overhead();
21
- $stats['num_spam_comments'] = mmb_num_spam_comments();
22
- return $stats;
23
- }
24
-
25
- /* Revisions */
26
-
27
- mmb_add_action('cleanup_delete', 'cleanup_delete_worker');
28
-
29
- function cleanup_delete_worker($params = array()){
30
- global $mmb_core;
31
-
32
- $params_array = explode('_', $params['actions']);
33
- $return_array = array();
34
- foreach ($params_array as $param){
35
- switch ($param){
36
- case 'revision' :
37
- if(mmb_delete_all_revisions()){
38
- $return_array['revision'] = 'Revisions deleted.';
39
- }else{
40
- $return_array['revision'] = 'Revisions not deleted.';
41
- }
42
- break;
43
- case 'overhead' :
44
- if(mmb_clear_overhead()){
45
- $return_array['overhead'] = 'Overhead cleared.';
46
- }else{
47
- $return_array['overhead'] = 'Overhead not cleared.';
48
- }
49
- break;
50
- case 'comment' :
51
- if(mmb_delete_spam_comments()){
52
- $return_array['comment'] = 'Comments deleted';
53
- }else{
54
- $return_array['comment'] = 'Comments not deleted';
55
- }
56
- break;
57
- default:
58
- break;
59
- }
60
-
61
- }
62
-
63
- unset($params);
64
-
65
- mmb_response($return_array, true);
66
- }
67
-
68
- function mmb_num_revisions() {
69
- global $wpdb;
70
- $sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'";
71
- $num_revisions = $wpdb->get_var($wpdb->prepare($sql));
72
- return $num_revisions;
73
- }
74
-
75
- function mmb_select_all_revisions() {
76
- global $wpdb;
77
- $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'revision'";
78
- $revisions = $wpdb->get_results($wpdb->prepare($sql));
79
- return $revisions;
80
- }
81
-
82
- function mmb_delete_all_revisions() {
83
- global $wpdb;
84
- $sql = "DELETE a,b,c FROM $wpdb->posts a LEFT JOIN $wpdb->term_relationships b ON (a.ID = b.object_id) LEFT JOIN $wpdb->postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision'";
85
- $revisions = $wpdb->query($wpdb->prepare($sql));
86
- return $revisions;
87
- }
88
-
89
-
90
-
91
- /* Optimize */
92
-
93
- function mmb_get_overhead()
94
- {
95
- global $wpdb, $mmb_core;
96
- $tot_data = 0;
97
- $tot_idx = 0;
98
- $tot_all = 0;
99
- $query = 'SHOW TABLE STATUS FROM '. DB_NAME;
100
- $tables = $wpdb->get_results($wpdb->prepare($query),ARRAY_A);
101
- foreach($tables as $table)
102
- {
103
- if(in_array($table['Engine'], array('MyISAM', 'ISAM', 'HEAP', 'MEMORY', 'ARCHIVE'))){
104
-
105
- if($wpdb->base_prefix != $wpdb->prefix){
106
- if(preg_match('/^'.$wpdb->prefix.'*/Ui', $table['Name'])){
107
- $total_gain += $table['Data_free'] / 1024;
108
- }
109
- } else if(preg_match('/^'.$wpdb->prefix.'[0-9]{1,20}_*/Ui', $table['Name'])){
110
- continue;
111
- }
112
- else {
113
- $total_gain += $table['Data_free'] / 1024;
114
- }
115
- } elseif ($table['Engine'] == 'InnoDB'){
116
- $total_gain += $table['Data_free'] > 100*1024*1024 ? $table['Data_free'] / 1024 : 0;
117
- }
118
- }
119
- return round($total_gain,3);
120
- }
121
-
122
-
123
- function mmb_clear_overhead()
124
- {
125
- global $wpdb;
126
- $tables = $wpdb->get_col("SHOW TABLES");
127
- foreach ($tables as $table_name) {
128
- if($wpdb->base_prefix != $wpdb->prefix){
129
- if(preg_match('/^'.$wpdb->prefix.'*/Ui', $table_name)){
130
- $table_string .= $table_name . ",";
131
- }
132
- } else if(preg_match('/^'.$wpdb->prefix.'[0-9]{1,20}_*/Ui', $table_name)){
133
- continue;
134
- }
135
- else
136
- $table_string .= $table_name . ",";
137
- }
138
- $table_string = substr($table_string,0,strlen($table_string)-1); //remove last ,
139
-
140
- $table_string = rtrim($table_string);
141
-
142
- $query = "OPTIMIZE TABLE $table_string";
143
-
144
- $optimize = $wpdb->query($query);
145
- return $optimize ? true : false;
146
- }
147
-
148
-
149
-
150
-
151
- /* Spam Comments */
152
-
153
- function mmb_num_spam_comments()
154
- {
155
- global $wpdb;
156
- $sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = 'spam'";
157
- $num_spams = $wpdb->get_var($wpdb->prepare($sql));
158
- return $num_spams;
159
- }
160
-
161
- function mmb_delete_spam_comments()
162
- {
163
- global $wpdb;
164
- $sql = "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam'";
165
- $spams = $wpdb->query($wpdb->prepare($sql));
166
- return $sql;
167
- }
168
-
169
-
170
- function mmb_get_spam_comments() {
171
- global $wpdb;
172
- $sql = "SELECT * FROM $wpdb->comments as a LEFT JOIN $wpdb->commentmeta as b WHERE a.comment_ID = b.comment_id AND a.comment_approved = 'spam'";
173
- $spams = $wpdb->get_results($wpdb->prepare($sql));
174
- return $spams;
175
- }
176
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ *
5
+ *
6
+ * ManageWP Worker Plugin
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ add_filter('mmb_stats_filter', 'mmb_get_extended_info');
14
+
15
+
16
+ function mmb_get_extended_info($stats)
17
+ {
18
+ $stats['num_revisions'] = mmb_num_revisions();
19
+ //$stats['num_revisions'] = 5;
20
+ $stats['overhead'] = mmb_get_overhead();
21
+ $stats['num_spam_comments'] = mmb_num_spam_comments();
22
+ return $stats;
23
+ }
24
+
25
+ /* Revisions */
26
+
27
+ mmb_add_action('cleanup_delete', 'cleanup_delete_worker');
28
+
29
+ function cleanup_delete_worker($params = array()){
30
+ global $mmb_core;
31
+
32
+ $params_array = explode('_', $params['actions']);
33
+ $return_array = array();
34
+ foreach ($params_array as $param){
35
+ switch ($param){
36
+ case 'revision' :
37
+ if(mmb_delete_all_revisions()){
38
+ $return_array['revision'] = 'Revisions deleted.';
39
+ }else{
40
+ $return_array['revision_error'] = 'Revisions not deleted.';
41
+ }
42
+ break;
43
+ case 'overhead' :
44
+ if(mmb_clear_overhead()){
45
+ $return_array['overhead'] = 'Overhead cleared.';
46
+ }else{
47
+ $return_array['overhead_error'] = 'Overhead not cleared.';
48
+ }
49
+ break;
50
+ case 'comment' :
51
+ if(mmb_delete_spam_comments()){
52
+ $return_array['comment'] = 'Comments deleted';
53
+ }else{
54
+ $return_array['comment_error'] = 'Comments not deleted';
55
+ }
56
+ break;
57
+ default:
58
+ break;
59
+ }
60
+
61
+ }
62
+
63
+ unset($params);
64
+
65
+ mmb_response($return_array, true);
66
+ }
67
+
68
+ function mmb_num_revisions() {
69
+ global $wpdb;
70
+ $sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'";
71
+ $num_revisions = $wpdb->get_var($wpdb->prepare($sql));
72
+ return $num_revisions;
73
+ }
74
+
75
+ function mmb_select_all_revisions() {
76
+ global $wpdb;
77
+ $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'revision'";
78
+ $revisions = $wpdb->get_results($wpdb->prepare($sql));
79
+ return $revisions;
80
+ }
81
+
82
+ function mmb_delete_all_revisions() {
83
+ global $wpdb;
84
+ $sql = "DELETE a,b,c FROM $wpdb->posts a LEFT JOIN $wpdb->term_relationships b ON (a.ID = b.object_id) LEFT JOIN $wpdb->postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision'";
85
+ $revisions = $wpdb->query($wpdb->prepare($sql));
86
+ return $revisions;
87
+ }
88
+
89
+
90
+
91
+ /* Optimize */
92
+
93
+ function mmb_get_overhead()
94
+ {
95
+ global $wpdb, $mmb_core;
96
+ $tot_data = 0;
97
+ $tot_idx = 0;
98
+ $tot_all = 0;
99
+ $query = 'SHOW TABLE STATUS FROM '. DB_NAME;
100
+ $tables = $wpdb->get_results($wpdb->prepare($query),ARRAY_A);
101
+ foreach($tables as $table)
102
+ {
103
+ if(in_array($table['Engine'], array('MyISAM', 'ISAM', 'HEAP', 'MEMORY', 'ARCHIVE'))){
104
+
105
+ if($wpdb->base_prefix != $wpdb->prefix){
106
+ if(preg_match('/^'.$wpdb->prefix.'*/Ui', $table['Name'])){
107
+ $total_gain += $table['Data_free'] / 1024;
108
+ }
109
+ } else if(preg_match('/^'.$wpdb->prefix.'[0-9]{1,20}_*/Ui', $table['Name'])){
110
+ continue;
111
+ }
112
+ else {
113
+ $total_gain += $table['Data_free'] / 1024;
114
+ }
115
+ } elseif ($table['Engine'] == 'InnoDB'){
116
+ //$total_gain += $table['Data_free'] > 100*1024*1024 ? $table['Data_free'] / 1024 : 0;
117
+ }
118
+ }
119
+ return round($total_gain,3);
120
+ }
121
+
122
+
123
+ function mmb_clear_overhead()
124
+ {
125
+ global $wpdb;
126
+ $tables = $wpdb->get_col("SHOW TABLES");
127
+ foreach ($tables as $table_name) {
128
+ if($wpdb->base_prefix != $wpdb->prefix){
129
+ if(preg_match('/^'.$wpdb->prefix.'*/Ui', $table_name)){
130
+ $table_string .= $table_name . ",";
131
+ }
132
+ } else if(preg_match('/^'.$wpdb->prefix.'[0-9]{1,20}_*/Ui', $table_name)){
133
+ continue;
134
+ }
135
+ else
136
+ $table_string .= $table_name . ",";
137
+ }
138
+ $table_string = substr($table_string,0,strlen($table_string)-1); //remove last ,
139
+
140
+ $table_string = rtrim($table_string);
141
+
142
+ $query = "OPTIMIZE TABLE $table_string";
143
+
144
+ $optimize = $wpdb->query($query);
145
+ return $optimize ? true : false;
146
+ }
147
+
148
+
149
+
150
+
151
+ /* Spam Comments */
152
+
153
+ function mmb_num_spam_comments()
154
+ {
155
+ global $wpdb;
156
+ $sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = 'spam'";
157
+ $num_spams = $wpdb->get_var($wpdb->prepare($sql));
158
+ return $num_spams;
159
+ }
160
+
161
+ function mmb_delete_spam_comments()
162
+ {
163
+ global $wpdb;
164
+ $sql = "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam'";
165
+ $spams = $wpdb->query($wpdb->prepare($sql));
166
+ return $sql;
167
+ }
168
+
169
+
170
+ function mmb_get_spam_comments() {
171
+ global $wpdb;
172
+ $sql = "SELECT * FROM $wpdb->comments as a LEFT JOIN $wpdb->commentmeta as b WHERE a.comment_ID = b.comment_id AND a.comment_approved = 'spam'";
173
+ $spams = $wpdb->get_results($wpdb->prepare($sql));
174
+ return $spams;
175
+ }
176
  ?>
plugins/extra_html_example/extra_html_example.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- // add filter for the stats structure
4
- add_filter('mmb_stats_filter', mmb_extra_html_example);
5
-
6
- function mmb_extra_html_example($stats)
7
- {
8
- $count_posts = wp_count_posts();
9
-
10
- $published_posts = $count_posts->publish;
11
-
12
- // add 'extra_html' element. This is what gets displayed in the dashboard
13
- $stats['extra_html'] = '<p>Hello from '.get_bloginfo('name').' with '.$published_posts.' published posts.</p>';
14
-
15
- // return the whole array back
16
- return $stats;
17
- }
18
  ?>
1
+ <?php
2
+
3
+ // add filter for the stats structure
4
+ add_filter('mmb_stats_filter', mmb_extra_html_example);
5
+
6
+ function mmb_extra_html_example($stats)
7
+ {
8
+ $count_posts = wp_count_posts();
9
+
10
+ $published_posts = $count_posts->publish;
11
+
12
+ // add 'extra_html' element. This is what gets displayed in the dashboard
13
+ $stats['extra_html'] = '<p>Hello from '.get_bloginfo('name').' with '.$published_posts.' published posts.</p>';
14
+
15
+ // return the whole array back
16
+ return $stats;
17
+ }
18
  ?>
plugins/search/search.php CHANGED
@@ -1,130 +1,130 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * stats.class.php
5
- *
6
- * Various searches on worker
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- mmb_add_action('search_posts_by_term', 'search_posts_by_term');
14
-
15
- function search_posts_by_term($params = false){
16
-
17
- global $wpdb, $current_user;
18
-
19
- $search_type = trim($params['search_type']);
20
- $search_term = strtolower(trim($params['search_term']));
21
- switch ($search_type){
22
- case 'page_post':
23
- $num_posts = 10;
24
- $num_content_char = 30;
25
-
26
- $term_orig = trim($params['search_term']);
27
-
28
- $term_base= addslashes(trim($params['search_term']));
29
-
30
- $query = "SELECT *
31
- FROM $wpdb->posts
32
- WHERE $wpdb->posts.post_status = 'publish'
33
- AND ($wpdb->posts.post_title LIKE '%$term_base%'
34
- OR $wpdb->posts.post_content LIKE '%$term_base%')
35
- ORDER BY $wpdb->posts.post_modified DESC
36
- LIMIT 0, $num_posts
37
- ";
38
-
39
- $posts_array = $wpdb->get_results($query);
40
-
41
- $ret_posts = array();
42
-
43
- foreach($posts_array as $post){
44
- //highlight searched term
45
-
46
- if (substr_count(strtolower($post->post_title), strtolower($term_orig))){
47
- $str_position_start = strpos(strtolower($post->post_title), strtolower($term_orig));
48
-
49
- $post->post_title = substr($post->post_title, 0, $str_position_start).'<b>'.
50
- substr($post->post_title, $str_position_start, strlen($term_orig)).'</b>'.
51
- substr($post->post_title, $str_position_start + strlen($term_orig));
52
-
53
- }
54
- $post->post_content = html_entity_decode($post->post_content);
55
-
56
- $post->post_content = strip_tags($post->post_content);
57
-
58
-
59
-
60
- if (substr_count(strtolower($post->post_content), strtolower($term_orig))){
61
- $str_position_start = strpos(strtolower($post->post_content), strtolower($term_orig));
62
-
63
- $start = $str_position_start > $num_content_char ? $str_position_start - $num_content_char: 0;
64
- $first_len = $str_position_start > $num_content_char? $num_content_char : $str_position_start;
65
-
66
- $start_substring = $start>0 ? '...' : '';
67
- $post->post_content = $start_substring . substr($post->post_content, $start, $first_len).'<b>'.
68
- substr($post->post_content, $str_position_start, strlen($term_orig)).'</b>'.
69
- substr($post->post_content, $str_position_start + strlen($term_orig), $num_content_char) . '...';
70
-
71
-
72
- }else{
73
- $post->post_content = substr($post->post_content,0, 50). '...';
74
- }
75
-
76
- $ret_posts[] = array(
77
- 'ID' => $post->ID
78
- ,'post_permalink' => get_permalink($post->ID)
79
- ,'post_date' => $post->post_date
80
- ,'post_title' => $post->post_title
81
- ,'post_content' => $post->post_content
82
- ,'post_modified' => $post->post_modified
83
- ,'comment_count' => $post->comment_count
84
-
85
-
86
- );
87
- }
88
- mmb_response($ret_posts, true);
89
- break;
90
-
91
- case 'plugin':
92
- $plugins = get_option('active_plugins');
93
-
94
- if(!function_exists('get_plugin_data'))
95
- include_once( ABSPATH.'/wp-admin/includes/plugin.php');
96
-
97
- $have_plugin = array();
98
- foreach ($plugins as $plugin) {
99
- $pl = WP_PLUGIN_DIR . '/' . $plugin ;
100
- $pl_extended = get_plugin_data($pl);
101
- $pl_name = $pl_extended['Name'];
102
- if(strpos(strtolower($pl_name), $search_term)>-1){
103
-
104
- $have_plugin[] = $pl_name;
105
- }
106
- }
107
- if($have_plugin){
108
- mmb_response($have_plugin, true);
109
- }else{
110
- mmb_response('Not found', false);
111
- }
112
- break;
113
- case 'theme':
114
- $theme = strtolower(get_option('stylesheet'));
115
- $tm = ABSPATH . 'wp-content/themes/'. $theme . '/style.css' ;
116
- $tm_extended = get_theme_data($tm);
117
- $tm_name = $tm_extended['Name'];
118
- $have_theme = array();
119
- if(strpos(strtolower($tm_name), $search_term)>-1){
120
- $have_theme[] = $tm_name;
121
- mmb_response($have_theme, true);
122
- }else{
123
- mmb_response('Not found', false);
124
- }
125
- break;
126
- default: mmb_response('Not found', false);
127
- }
128
- }
129
-
130
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * stats.class.php
5
+ *
6
+ * Various searches on worker
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ mmb_add_action('search_posts_by_term', 'search_posts_by_term');
14
+
15
+ function search_posts_by_term($params = false){
16
+
17
+ global $wpdb, $current_user;
18
+
19
+ $search_type = trim($params['search_type']);
20
+ $search_term = strtolower(trim($params['search_term']));
21
+ switch ($search_type){
22
+ case 'page_post':
23
+ $num_posts = 10;
24
+ $num_content_char = 30;
25
+
26
+ $term_orig = trim($params['search_term']);
27
+
28
+ $term_base= addslashes(trim($params['search_term']));
29
+
30
+ $query = "SELECT *
31
+ FROM $wpdb->posts
32
+ WHERE $wpdb->posts.post_status = 'publish'
33
+ AND ($wpdb->posts.post_title LIKE '%$term_base%'
34
+ OR $wpdb->posts.post_content LIKE '%$term_base%')
35
+ ORDER BY $wpdb->posts.post_modified DESC
36
+ LIMIT 0, $num_posts
37
+ ";
38
+
39
+ $posts_array = $wpdb->get_results($query);
40
+
41
+ $ret_posts = array();
42
+
43
+ foreach($posts_array as $post){
44
+ //highlight searched term
45
+
46
+ if (substr_count(strtolower($post->post_title), strtolower($term_orig))){
47
+ $str_position_start = strpos(strtolower($post->post_title), strtolower($term_orig));
48
+
49
+ $post->post_title = substr($post->post_title, 0, $str_position_start).'<b>'.
50
+ substr($post->post_title, $str_position_start, strlen($term_orig)).'</b>'.
51
+ substr($post->post_title, $str_position_start + strlen($term_orig));
52
+
53
+ }
54
+ $post->post_content = html_entity_decode($post->post_content);
55
+
56
+ $post->post_content = strip_tags($post->post_content);
57
+
58
+
59
+
60
+ if (substr_count(strtolower($post->post_content), strtolower($term_orig))){
61
+ $str_position_start = strpos(strtolower($post->post_content), strtolower($term_orig));
62
+
63
+ $start = $str_position_start > $num_content_char ? $str_position_start - $num_content_char: 0;
64
+ $first_len = $str_position_start > $num_content_char? $num_content_char : $str_position_start;
65
+
66
+ $start_substring = $start>0 ? '...' : '';
67
+ $post->post_content = $start_substring . substr($post->post_content, $start, $first_len).'<b>'.
68
+ substr($post->post_content, $str_position_start, strlen($term_orig)).'</b>'.
69
+ substr($post->post_content, $str_position_start + strlen($term_orig), $num_content_char) . '...';
70
+
71
+
72
+ }else{
73
+ $post->post_content = substr($post->post_content,0, 50). '...';
74
+ }
75
+
76
+ $ret_posts[] = array(
77
+ 'ID' => $post->ID
78
+ ,'post_permalink' => get_permalink($post->ID)
79
+ ,'post_date' => $post->post_date
80
+ ,'post_title' => $post->post_title
81
+ ,'post_content' => $post->post_content
82
+ ,'post_modified' => $post->post_modified
83
+ ,'comment_count' => $post->comment_count
84
+
85
+
86
+ );
87
+ }
88
+ mmb_response($ret_posts, true);
89
+ break;
90
+
91
+ case 'plugin':
92
+ $plugins = get_option('active_plugins');
93
+
94
+ if(!function_exists('get_plugin_data'))
95
+ include_once( ABSPATH.'/wp-admin/includes/plugin.php');
96
+
97
+ $have_plugin = array();
98
+ foreach ($plugins as $plugin) {
99
+ $pl = WP_PLUGIN_DIR . '/' . $plugin ;
100
+ $pl_extended = get_plugin_data($pl);
101
+ $pl_name = $pl_extended['Name'];
102
+ if(strpos(strtolower($pl_name), $search_term)>-1){
103
+
104
+ $have_plugin[] = $pl_name;
105
+ }
106
+ }
107
+ if($have_plugin){
108
+ mmb_response($have_plugin, true);
109
+ }else{
110
+ mmb_response('Not found', false);
111
+ }
112
+ break;
113
+ case 'theme':
114
+ $theme = strtolower(get_option('stylesheet'));
115
+ $tm = ABSPATH . 'wp-content/themes/'. $theme . '/style.css' ;
116
+ $tm_extended = get_theme_data($tm);
117
+ $tm_name = $tm_extended['Name'];
118
+ $have_theme = array();
119
+ if(strpos(strtolower($tm_name), $search_term)>-1){
120
+ $have_theme[] = $tm_name;
121
+ mmb_response($have_theme, true);
122
+ }else{
123
+ mmb_response('Not found', false);
124
+ }
125
+ break;
126
+ default: mmb_response('Not found', false);
127
+ }
128
+ }
129
+
130
  ?>
post.class.php CHANGED
@@ -1,340 +1,340 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * post.class.php
5
- *
6
- * Create remote post
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_Post extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- parent::__construct();
18
- }
19
-
20
- function create($args)
21
- {
22
- /**
23
- * algorithm
24
- * 1. create post using wp_insert_post (insert tags also here itself)
25
- * 2. use wp_create_categories() to create(not exists) and insert in the post
26
- * 3. insert meta values
27
- */
28
-
29
- include_once ABSPATH . 'wp-admin/includes/taxonomy.php';
30
- include_once ABSPATH . 'wp-admin/includes/image.php';
31
- include_once ABSPATH . 'wp-admin/includes/file.php';
32
-
33
- $post_struct = $args['post_data'];
34
-
35
- $post_data = $post_struct['post_data'];
36
- $new_custom = $post_struct['post_extras']['post_meta'];
37
- $post_categories = explode(',', $post_struct['post_extras']['post_categories']);
38
- $post_atta_img = $post_struct['post_extras']['post_atta_images'];
39
- $post_upload_dir = $post_struct['post_extras']['post_upload_dir'];
40
- $post_checksum = $post_struct['post_extras']['post_checksum'];
41
- $post_featured_img = $post_struct['post_extras']['featured_img'];
42
-
43
- $upload = wp_upload_dir();
44
-
45
- // create dynamic url RegExp
46
- $mwp_base_url = parse_url($post_upload_dir['url']);
47
- $mwp_regexp_url = $mwp_base_url['host'] . $mwp_base_url['path'];
48
- $rep = array(
49
- '/',
50
- '+',
51
- '.',
52
- ':',
53
- '?'
54
- );
55
- $with = array(
56
- '\/',
57
- '\+',
58
- '\.',
59
- '\:',
60
- '\?'
61
- );
62
- $mwp_regexp_url = str_replace($rep, $with, $mwp_regexp_url);
63
-
64
- // rename all src ../wp-content/ with hostname/wp-content/
65
- $mmb_dot_url = '..' . $mmb_base_url['path'];
66
- $mmb_dot_url = str_replace($rep, $with, $mmb_dot_url);
67
- $dot_match_count = preg_match_all('/(<a[^>]+href=\"([^"]+)\"[^>]*>)?(<\s*img.[^\/>]*src="([^"]*' . $mmb_dot_url . '[^\s]+\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $dot_get_urls, PREG_SET_ORDER);
68
- if ($dot_match_count > 0) {
69
- foreach ($dot_get_urls as $dot_url) {
70
- $match_dot = '/' . str_replace($rep, $with, $dot_url[4]) . '/';
71
- $replace_dot = 'http://' . $mmb_base_url['host'] . substr($dot_url[4], 2, strlen($dot_url[4]));
72
- $post_data['post_content'] = preg_replace($match_dot, $replace_dot, $post_data['post_content']);
73
-
74
- if ($dot_url[1] != '') {
75
- $match_dot_a = '/' . str_replace($rep, $with, $dot_url[2]) . '/';
76
- $replace_dot_a = 'http://' . $mmb_base_url['host'] . substr($dot_url[2], 2, strlen($dot_url[2]));
77
- $post_data['post_content'] = preg_replace($match_dot_a, $replace_dot_a, $post_data['post_content']);
78
- }
79
- }
80
- }
81
-
82
-
83
-
84
- //to find all the images
85
- $match_count = preg_match_all('/(<a[^>]+href=\"([^"]+)\"[^>]*>)?(<\s*img.[^\/>]*src="([^"]+' . $mmb_regexp_url . '[^\s]+\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $get_urls, PREG_SET_ORDER);
86
- if ($match_count > 0) {
87
- $attachments = array();
88
- $post_content = $post_data['post_content'];
89
-
90
- foreach ($get_urls as $get_url_k => $get_url) {
91
- // unset url in attachment array
92
- foreach ($post_atta_img as $atta_url_k => $atta_url_v) {
93
- $match_patt_url = '/' . str_replace($rep, $with, substr($atta_url_v['src'], 0, strrpos($atta_url_v['src'], '.'))) . '/';
94
- if (preg_match($match_patt_url, $get_url[4])) {
95
- unset($post_atta_img[$atta_url_k]);
96
- }
97
- }
98
-
99
- if (isset($get_urls[$get_url_k][6])) { // url have parent, don't download this url
100
- if ($get_url[1] != '') {
101
- // change src url
102
- $s_mmb_mp = '/' . str_replace($rep, $with, $get_url[4]) . '/';
103
-
104
- $s_img_atta = wp_get_attachment_image_src($get_urls[$get_url_k][6]);
105
- $s_mmb_rp = $s_img_atta[0];
106
- $post_content = preg_replace($s_mmb_mp, $s_mmb_rp, $post_content);
107
- // change attachment url
108
- if (preg_match('/attachment_id/i', $get_url[2])) {
109
- $mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/';
110
- $mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $get_urls[$get_url_k][6];
111
- $post_content = preg_replace($mmb_mp, $mmb_rp, $post_content);
112
- }
113
- }
114
- continue;
115
- }
116
-
117
- $no_thumb = '';
118
- if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) {
119
- $no_thumb = preg_replace('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4]);
120
- } else {
121
- $no_thumb = $get_url[4];
122
- }
123
- $file_name = basename($no_thumb);
124
- $tmp_file = download_url($no_thumb);
125
-
126
- $attach_upload['url'] = $upload['url'] . '/' . $file_name;
127
- $attach_upload['path'] = $upload['path'] . '/' . $file_name;
128
- $renamed = @rename($tmp_file, $attach_upload['path']);
129
- if ($renamed === true) {
130
- $match_pattern = '/' . str_replace($rep, $with, $get_url[4]) . '/';
131
- $replace_pattern = $attach_upload['url'];
132
- $post_content = preg_replace($match_pattern, $replace_pattern, $post_content);
133
- if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) {
134
- $match_pattern = '/' . str_replace($rep, $with, preg_replace('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4])) . '/';
135
- $post_content = preg_replace($match_pattern, $replace_pattern, $post_content);
136
- }
137
-
138
- $attachment = array(
139
- 'post_title' => $file_name,
140
- 'post_content' => '',
141
- 'post_type' => 'attachment',
142
- //'post_parent' => $post_id,
143
- 'post_mime_type' => 'image/' . $get_url[5],
144
- 'guid' => $attach_upload['url']
145
- );
146
-
147
- // Save the data
148
-
149
- $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
150
-
151
- $attachments[$attach_id] = 0;
152
-
153
- // featured image
154
- if ($post_featured_img != '') {
155
- $feat_img_url = '';
156
- if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) {
157
- $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8);
158
- } else {
159
- $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.'));
160
- }
161
- $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/';
162
- if (preg_match($m_feat_url, $get_url[4])) {
163
- $post_featured_img = '';
164
- $attachments[$attach_id] = $attach_id;
165
- }
166
- }
167
-
168
- // set $get_urls value[6] - parent atta_id
169
- foreach ($get_urls as $url_k => $url_v) {
170
- if ($get_url_k != $url_k) {
171
- $s_get_url = '';
172
- if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $url_v[4])) {
173
- $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.') - 8);
174
- } else {
175
- $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.'));
176
- }
177
- $m_patt_url = '/' . str_replace($rep, $with, $s_get_url) . '/';
178
- if (preg_match($m_patt_url, $get_url[4])) {
179
- array_push($get_urls[$url_k], $attach_id);
180
- }
181
- }
182
- }
183
-
184
-
185
- $some_data = wp_generate_attachment_metadata($attach_id, $attach_upload['path']);
186
- wp_update_attachment_metadata($attach_id, $some_data);
187
-
188
-
189
- // changing href of a tag
190
- if ($get_url[1] != '') {
191
- $mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/';
192
- if (preg_match('/attachment_id/i', $get_url[2])) {
193
- $mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $attach_id;
194
- $post_content = preg_replace($mmb_mp, $mmb_rp, $post_content);
195
- }
196
- }
197
- }
198
- @unlink($tmp_file);
199
- }
200
-
201
-
202
- $post_data['post_content'] = $post_content;
203
-
204
- }
205
- if (count($post_atta_img)) {
206
- foreach ($post_atta_img as $img) {
207
- $file_name = basename($img['src']);
208
- $tmp_file = download_url($img['src']);
209
- $attach_upload['url'] = $upload['url'] . '/' . $file_name;
210
- $attach_upload['path'] = $upload['path'] . '/' . $file_name;
211
- $renamed = @rename($tmp_file, $attach_upload['path']);
212
- if ($renamed === true) {
213
- $atta_ext = end(explode('.', $file_name));
214
-
215
- $attachment = array(
216
- 'post_title' => $file_name,
217
- 'post_content' => '',
218
- 'post_type' => 'attachment',
219
- //'post_parent' => $post_id,
220
- 'post_mime_type' => 'image/' . $atta_ext,
221
- 'guid' => $attach_upload['url']
222
- );
223
-
224
- // Save the data
225
- $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
226
- wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path']));
227
- $attachments[$attach_id] = 0;
228
-
229
- // featured image
230
- if ($post_featured_img != '') {
231
- $feat_img_url = '';
232
- if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) {
233
- $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8);
234
- } else {
235
- $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.'));
236
- }
237
- $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/';
238
- if (preg_match($m_feat_url, $img['src'])) {
239
- $post_featured_img = '';
240
- $attachments[$attach_id] = $attach_id;
241
- }
242
- }
243
-
244
- }
245
- @unlink($tmp_file);
246
- }
247
- }
248
-
249
-
250
- // create post
251
- $post_id = wp_insert_post($post_data);
252
-
253
- if (count($attachments)) {
254
- foreach ($attachments as $atta_id => $featured_id) {
255
- $result = wp_update_post(array(
256
- 'ID' => $atta_id,
257
- 'post_parent' => $post_id
258
- ));
259
- if ($featured_id > 0) {
260
- $new_custom['_thumbnail_id'] = array(
261
- $featured_id
262
- );
263
- }
264
- }
265
- }
266
-
267
- // featured image
268
- if ($post_featured_img != '') {
269
- $file_name = basename($post_featured_img);
270
- $tmp_file = download_url($post_featured_img);
271
- $attach_upload['url'] = $upload['url'] . '/' . $file_name;
272
- $attach_upload['path'] = $upload['path'] . '/' . $file_name;
273
- $renamed = @rename($tmp_file, $attach_upload['path']);
274
- if ($renamed === true) {
275
- $atta_ext = end(explode('.', $file_name));
276
-
277
- $attachment = array(
278
- 'post_title' => $file_name,
279
- 'post_content' => '',
280
- 'post_type' => 'attachment',
281
- 'post_parent' => $post_id,
282
- 'post_mime_type' => 'image/' . $atta_ext,
283
- 'guid' => $attach_upload['url']
284
- );
285
-
286
- // Save the data
287
- $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
288
- wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path']));
289
- $new_custom['_thumbnail_id'] = array(
290
- $attach_id
291
- );
292
- }
293
- @unlink($tmp_file);
294
- }
295
-
296
- if ($post_id && is_array($post_categories)) {
297
- //insert categories
298
-
299
- $cat_ids = wp_create_categories($post_categories, $post_id);
300
- }
301
-
302
-
303
- //get current custom fields
304
- $cur_custom = get_post_custom($post_id);
305
- //check which values doesnot exists in new custom fields
306
- $diff_values = array_diff_key($cur_custom, $new_custom);
307
-
308
- if (is_array($diff_values))
309
- foreach ($diff_values as $meta_key => $value) {
310
- delete_post_meta($post_id, $meta_key);
311
- }
312
- //insert new post meta
313
- foreach ($new_custom as $meta_key => $value) {
314
- if (strpos($meta_key, '_mmb') === 0 || strpos($meta_key, '_edit') === 0) {
315
- continue;
316
- } else {
317
- update_post_meta($post_id, $meta_key, $value[0]);
318
- }
319
- }
320
- return $post_id;
321
- }
322
-
323
-
324
- function change_status($args)
325
- {
326
-
327
- global $wpdb;
328
- $post_id = $args['post_id'];
329
- $status = $args['status'];
330
- $success = false;
331
-
332
- if(in_array($status, array('draft', 'publish', 'trash'))){
333
- $sql = "update ".$wpdb->prefix."posts set post_status = '$status' where ID = '$post_id'";
334
- $success = $wpdb->query($sql);
335
- }
336
-
337
- return $success;
338
- }
339
- }
340
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * post.class.php
5
+ *
6
+ * Create remote post
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_Post extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ parent::__construct();
18
+ }
19
+
20
+ function create($args)
21
+ {
22
+ /**
23
+ * algorithm
24
+ * 1. create post using wp_insert_post (insert tags also here itself)
25
+ * 2. use wp_create_categories() to create(not exists) and insert in the post
26
+ * 3. insert meta values
27
+ */
28
+
29
+ include_once ABSPATH . 'wp-admin/includes/taxonomy.php';
30
+ include_once ABSPATH . 'wp-admin/includes/image.php';
31
+ include_once ABSPATH . 'wp-admin/includes/file.php';
32
+
33
+ $post_struct = $args['post_data'];
34
+
35
+ $post_data = $post_struct['post_data'];
36
+ $new_custom = $post_struct['post_extras']['post_meta'];
37
+ $post_categories = explode(',', $post_struct['post_extras']['post_categories']);
38
+ $post_atta_img = $post_struct['post_extras']['post_atta_images'];
39
+ $post_upload_dir = $post_struct['post_extras']['post_upload_dir'];
40
+ $post_checksum = $post_struct['post_extras']['post_checksum'];
41
+ $post_featured_img = $post_struct['post_extras']['featured_img'];
42
+
43
+ $upload = wp_upload_dir();
44
+
45
+ // create dynamic url RegExp
46
+ $mwp_base_url = parse_url($post_upload_dir['url']);
47
+ $mwp_regexp_url = $mwp_base_url['host'] . $mwp_base_url['path'];
48
+ $rep = array(
49
+ '/',
50
+ '+',
51
+ '.',
52
+ ':',
53
+ '?'
54
+ );
55
+ $with = array(
56
+ '\/',
57
+ '\+',
58
+ '\.',
59
+ '\:',
60
+ '\?'
61
+ );
62
+ $mwp_regexp_url = str_replace($rep, $with, $mwp_regexp_url);
63
+
64
+ // rename all src ../wp-content/ with hostname/wp-content/
65
+ $mmb_dot_url = '..' . $mmb_base_url['path'];
66
+ $mmb_dot_url = str_replace($rep, $with, $mmb_dot_url);
67
+ $dot_match_count = preg_match_all('/(<a[^>]+href=\"([^"]+)\"[^>]*>)?(<\s*img.[^\/>]*src="([^"]*' . $mmb_dot_url . '[^\s]+\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $dot_get_urls, PREG_SET_ORDER);
68
+ if ($dot_match_count > 0) {
69
+ foreach ($dot_get_urls as $dot_url) {
70
+ $match_dot = '/' . str_replace($rep, $with, $dot_url[4]) . '/';
71
+ $replace_dot = 'http://' . $mmb_base_url['host'] . substr($dot_url[4], 2, strlen($dot_url[4]));
72
+ $post_data['post_content'] = preg_replace($match_dot, $replace_dot, $post_data['post_content']);
73
+
74
+ if ($dot_url[1] != '') {
75
+ $match_dot_a = '/' . str_replace($rep, $with, $dot_url[2]) . '/';
76
+ $replace_dot_a = 'http://' . $mmb_base_url['host'] . substr($dot_url[2], 2, strlen($dot_url[2]));
77
+ $post_data['post_content'] = preg_replace($match_dot_a, $replace_dot_a, $post_data['post_content']);
78
+ }
79
+ }
80
+ }
81
+
82
+
83
+
84
+ //to find all the images
85
+ $match_count = preg_match_all('/(<a[^>]+href=\"([^"]+)\"[^>]*>)?(<\s*img.[^\/>]*src="([^"]+' . $mmb_regexp_url . '[^\s]+\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $get_urls, PREG_SET_ORDER);
86
+ if ($match_count > 0) {
87
+ $attachments = array();
88
+ $post_content = $post_data['post_content'];
89
+
90
+ foreach ($get_urls as $get_url_k => $get_url) {
91
+ // unset url in attachment array
92
+ foreach ($post_atta_img as $atta_url_k => $atta_url_v) {
93
+ $match_patt_url = '/' . str_replace($rep, $with, substr($atta_url_v['src'], 0, strrpos($atta_url_v['src'], '.'))) . '/';
94
+ if (preg_match($match_patt_url, $get_url[4])) {
95
+ unset($post_atta_img[$atta_url_k]);
96
+ }
97
+ }
98
+
99
+ if (isset($get_urls[$get_url_k][6])) { // url have parent, don't download this url
100
+ if ($get_url[1] != '') {
101
+ // change src url
102
+ $s_mmb_mp = '/' . str_replace($rep, $with, $get_url[4]) . '/';
103
+
104
+ $s_img_atta = wp_get_attachment_image_src($get_urls[$get_url_k][6]);
105
+ $s_mmb_rp = $s_img_atta[0];
106
+ $post_content = preg_replace($s_mmb_mp, $s_mmb_rp, $post_content);
107
+ // change attachment url
108
+ if (preg_match('/attachment_id/i', $get_url[2])) {
109
+ $mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/';
110
+ $mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $get_urls[$get_url_k][6];
111
+ $post_content = preg_replace($mmb_mp, $mmb_rp, $post_content);
112
+ }
113
+ }
114
+ continue;
115
+ }
116
+
117
+ $no_thumb = '';
118
+ if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) {
119
+ $no_thumb = preg_replace('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4]);
120
+ } else {
121
+ $no_thumb = $get_url[4];
122
+ }
123
+ $file_name = basename($no_thumb);
124
+ $tmp_file = download_url($no_thumb);
125
+
126
+ $attach_upload['url'] = $upload['url'] . '/' . $file_name;
127
+ $attach_upload['path'] = $upload['path'] . '/' . $file_name;
128
+ $renamed = @rename($tmp_file, $attach_upload['path']);
129
+ if ($renamed === true) {
130
+ $match_pattern = '/' . str_replace($rep, $with, $get_url[4]) . '/';
131
+ $replace_pattern = $attach_upload['url'];
132
+ $post_content = preg_replace($match_pattern, $replace_pattern, $post_content);
133
+ if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) {
134
+ $match_pattern = '/' . str_replace($rep, $with, preg_replace('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4])) . '/';
135
+ $post_content = preg_replace($match_pattern, $replace_pattern, $post_content);
136
+ }
137
+
138
+ $attachment = array(
139
+ 'post_title' => $file_name,
140
+ 'post_content' => '',
141
+ 'post_type' => 'attachment',
142
+ //'post_parent' => $post_id,
143
+ 'post_mime_type' => 'image/' . $get_url[5],
144
+ 'guid' => $attach_upload['url']
145
+ );
146
+
147
+ // Save the data
148
+
149
+ $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
150
+
151
+ $attachments[$attach_id] = 0;
152
+
153
+ // featured image
154
+ if ($post_featured_img != '') {
155
+ $feat_img_url = '';
156
+ if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) {
157
+ $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8);
158
+ } else {
159
+ $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.'));
160
+ }
161
+ $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/';
162
+ if (preg_match($m_feat_url, $get_url[4])) {
163
+ $post_featured_img = '';
164
+ $attachments[$attach_id] = $attach_id;
165
+ }
166
+ }
167
+
168
+ // set $get_urls value[6] - parent atta_id
169
+ foreach ($get_urls as $url_k => $url_v) {
170
+ if ($get_url_k != $url_k) {
171
+ $s_get_url = '';
172
+ if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $url_v[4])) {
173
+ $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.') - 8);
174
+ } else {
175
+ $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.'));
176
+ }
177
+ $m_patt_url = '/' . str_replace($rep, $with, $s_get_url) . '/';
178
+ if (preg_match($m_patt_url, $get_url[4])) {
179
+ array_push($get_urls[$url_k], $attach_id);
180
+ }
181
+ }
182
+ }
183
+
184
+
185
+ $some_data = wp_generate_attachment_metadata($attach_id, $attach_upload['path']);
186
+ wp_update_attachment_metadata($attach_id, $some_data);
187
+
188
+
189
+ // changing href of a tag
190
+ if ($get_url[1] != '') {
191
+ $mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/';
192
+ if (preg_match('/attachment_id/i', $get_url[2])) {
193
+ $mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $attach_id;
194
+ $post_content = preg_replace($mmb_mp, $mmb_rp, $post_content);
195
+ }
196
+ }
197
+ }
198
+ @unlink($tmp_file);
199
+ }
200
+
201
+
202
+ $post_data['post_content'] = $post_content;
203
+
204
+ }
205
+ if (count($post_atta_img)) {
206
+ foreach ($post_atta_img as $img) {
207
+ $file_name = basename($img['src']);
208
+ $tmp_file = download_url($img['src']);
209
+ $attach_upload['url'] = $upload['url'] . '/' . $file_name;
210
+ $attach_upload['path'] = $upload['path'] . '/' . $file_name;
211
+ $renamed = @rename($tmp_file, $attach_upload['path']);
212
+ if ($renamed === true) {
213
+ $atta_ext = end(explode('.', $file_name));
214
+
215
+ $attachment = array(
216
+ 'post_title' => $file_name,
217
+ 'post_content' => '',
218
+ 'post_type' => 'attachment',
219
+ //'post_parent' => $post_id,
220
+ 'post_mime_type' => 'image/' . $atta_ext,
221
+ 'guid' => $attach_upload['url']
222
+ );
223
+
224
+ // Save the data
225
+ $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
226
+ wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path']));
227
+ $attachments[$attach_id] = 0;
228
+
229
+ // featured image
230
+ if ($post_featured_img != '') {
231
+ $feat_img_url = '';
232
+ if (preg_match('/-\d{3}x\d{3}\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) {
233
+ $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8);
234
+ } else {
235
+ $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.'));
236
+ }
237
+ $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/';
238
+ if (preg_match($m_feat_url, $img['src'])) {
239
+ $post_featured_img = '';
240
+ $attachments[$attach_id] = $attach_id;
241
+ }
242
+ }
243
+
244
+ }
245
+ @unlink($tmp_file);
246
+ }
247
+ }
248
+
249
+
250
+ // create post
251
+ $post_id = wp_insert_post($post_data);
252
+
253
+ if (count($attachments)) {
254
+ foreach ($attachments as $atta_id => $featured_id) {
255
+ $result = wp_update_post(array(
256
+ 'ID' => $atta_id,
257
+ 'post_parent' => $post_id
258
+ ));
259
+ if ($featured_id > 0) {
260
+ $new_custom['_thumbnail_id'] = array(
261
+ $featured_id
262
+ );
263
+ }
264
+ }
265
+ }
266
+
267
+ // featured image
268
+ if ($post_featured_img != '') {
269
+ $file_name = basename($post_featured_img);
270
+ $tmp_file = download_url($post_featured_img);
271
+ $attach_upload['url'] = $upload['url'] . '/' . $file_name;
272
+ $attach_upload['path'] = $upload['path'] . '/' . $file_name;
273
+ $renamed = @rename($tmp_file, $attach_upload['path']);
274
+ if ($renamed === true) {
275
+ $atta_ext = end(explode('.', $file_name));
276
+
277
+ $attachment = array(
278
+ 'post_title' => $file_name,
279
+ 'post_content' => '',
280
+ 'post_type' => 'attachment',
281
+ 'post_parent' => $post_id,
282
+ 'post_mime_type' => 'image/' . $atta_ext,
283
+ 'guid' => $attach_upload['url']
284
+ );
285
+
286
+ // Save the data
287
+ $attach_id = wp_insert_attachment($attachment, $attach_upload['path']);
288
+ wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path']));
289
+ $new_custom['_thumbnail_id'] = array(
290
+ $attach_id
291
+ );
292
+ }
293
+ @unlink($tmp_file);
294
+ }
295
+
296
+ if ($post_id && is_array($post_categories)) {
297
+ //insert categories
298
+
299
+ $cat_ids = wp_create_categories($post_categories, $post_id);
300
+ }
301
+
302
+
303
+ //get current custom fields
304
+ $cur_custom = get_post_custom($post_id);
305
+ //check which values doesnot exists in new custom fields
306
+ $diff_values = array_diff_key($cur_custom, $new_custom);
307
+
308
+ if (is_array($diff_values))
309
+ foreach ($diff_values as $meta_key => $value) {
310
+ delete_post_meta($post_id, $meta_key);
311
+ }
312
+ //insert new post meta
313
+ foreach ($new_custom as $meta_key => $value) {
314
+ if (strpos($meta_key, '_mmb') === 0 || strpos($meta_key, '_edit') === 0) {
315
+ continue;
316
+ } else {
317
+ update_post_meta($post_id, $meta_key, $value[0]);
318
+ }
319
+ }
320
+ return $post_id;
321
+ }
322
+
323
+
324
+ function change_status($args)
325
+ {
326
+
327
+ global $wpdb;
328
+ $post_id = $args['post_id'];
329
+ $status = $args['status'];
330
+ $success = false;
331
+
332
+ if(in_array($status, array('draft', 'publish', 'trash'))){
333
+ $sql = "update ".$wpdb->prefix."posts set post_status = '$status' where ID = '$post_id'";
334
+ $success = $wpdb->query($sql);
335
+ }
336
+
337
+ return $success;
338
+ }
339
+ }
340
  ?>
readme.txt CHANGED
@@ -1,144 +1,150 @@
1
- === ManageWP Worker ===
2
- Contributors: freediver
3
- Donate link: https://www.networkforgood.org/donation/MakeDonation.aspx?ORGID2=520781390
4
- Tags: managewp, managewp worker, admin, manage blogs, multi blog manager, manage multiple blogs, remote blog management
5
- Requires at least: 3.0
6
- Tested up to: 3.2
7
- Stable tag: trunk
8
-
9
- ManageWP Worker plugin allows you to remotely manage your blogs from one dashboard.
10
-
11
- == Description ==
12
-
13
- ManageWP is a revolutionary plugin that allows you to manage multiple WordPress blogs from one dashboard.
14
-
15
- Main features:
16
-
17
- * Secure! No passwords for sites required, uses OpenSSL encrypted protocol
18
- * One click upgrades of WordPress, plugin and themes across all your sites
19
- * One click to access administration dashboard for any site
20
- * Add sub-users (writes, staff..) to your account
21
- * Bulk publish posts to multiple sites at once
22
- * Bulk upload themes and plugins to multiple sites at once
23
- * Automatic backups of your sites
24
- * Clone or migrate site to another domain
25
- * Much, much more...
26
-
27
- Check out [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs")
28
-
29
- API for developers available at [ManageWP.com/API](http://managewp.com/api "ManageWP API")
30
-
31
- == Changelog ==
32
-
33
- = 3.9.5 =
34
- * Now supporting scheduled backups to Amazon S3 and Dropbox
35
- * Revamped cloning procedure
36
- * You can now have sites in different colors
37
- * W3 Total Cache comptability improved
38
-
39
- = 3.9.3 =
40
- * Included support for WordPress 3.2 partial updates
41
-
42
- = 3.9.2 =
43
- * Fixed problem with full backups
44
- * Fixed problem with wordpress dev version upgrades
45
-
46
- = 3.9.1 =
47
- * Support for sub-users (limited access users)
48
- * Bulk add user
49
- * 'Select all' feature for bulk posting
50
- * Featured image support for bulk posting
51
- * Reload button on the dashboard (on the top of the Right now widget) will now refresh information about available updates
52
- * Fixed a problem with the import tool
53
- * Fixed a problem when remote dashboard would not work for some servers
54
-
55
- = 3.9.0 =
56
- * New feature: Up to 50% faster dashboard loading
57
- * New feature: You can now ignore WordPress/plugin/theme updates
58
- * New feature: Setting 'Show favicon' for websites in the dashboad
59
- * New feature: Full backups now include WordPress and other folders in the root of the site
60
- * Fixed: Bug with W3 TotalCache object cache causing weird behaviour in the dashboard
61
- * Fixed: All groups now show when adding a site
62
-
63
- = 3.8.8 =
64
- * New feature: Bulk add links to blogroll
65
- * New feature: Manual backups to email address
66
- * New feature: Backup requirements check (under �Manage Backups�)
67
- * New feature: Popup menu for groups allowing to show dashboard for that group only
68
- * New feature: Favorite list for plugins and themes for later quick installation to multiple blogs
69
- * New feature: Invite friends
70
- * Fixed: problem with backups and write permissions when upload dir was wrongly set
71
- * Fixed: problem adding sites where WordPress is installed in a folder
72
- * Fixed: 408 error message problem when adding site
73
- * Fixed: site time out problems when adding site
74
- * Fixed: problems with some WP plugins (WP Sentinel)
75
- * Fixed: problems with upgrade notifications
76
-
77
- = 3.8.7 =
78
- * Fixed 408 error when adding sites
79
- * Added support for IDN domains
80
- * Fixed bug with WordPress updates
81
- * Added comment moderation to the dashboard
82
- * Added quick links for sites (menu appears on hover)
83
-
84
-
85
- = 3.8.6 =
86
- * Added seach websites feature
87
- * Enhanced dashboard actions (spam comments, post revisions, table overhead)
88
- * Added developer [API] (http://managewp.com/api "ManageWP API")
89
- * Improved Migrate/Clone site feature
90
-
91
- = 3.8.4 =
92
- * Fixed remote dashboard problems for sites with redirects
93
- * Fixed IE7 issues in the dashboard
94
-
95
- = 3.8.3 =
96
- * Fixed problem with capabilities
97
-
98
- = 3.8.2 =
99
- * New interface
100
- * SSL security protocol
101
- * No passwords required
102
- * Improved clone/backup
103
-
104
-
105
- = 3.6.3 =
106
- * Initial public release
107
-
108
- == Installation ==
109
-
110
- 1. Upload the plugin folder to your /wp-content/plugins/ folder
111
- 2. Go to the Plugins page and activate ManageWP Worker
112
- 3. Visit [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs"), sign up and add your site
113
-
114
- Alternately
115
-
116
- 1. Visit [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs"), sign up and add your site
117
- 2. ManageWP will warn you the worker plugin is not installed and offer a link for quick installation
118
-
119
- == Screenshots ==
120
-
121
- 1. ManageWP dashboard with available upgrades, site statistics and management functions
122
-
123
-
124
-
125
- == License ==
126
-
127
- This file is part of ManageWP Worker.
128
-
129
- ManageWP Worker is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
130
-
131
- ManageWP Worker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
132
-
133
- You should have received a copy of the GNU General Public License along with ManageWP Worker. If not, see <http://www.gnu.org/licenses/>.
134
-
135
-
136
- == Frequently Asked Questions ==
137
-
138
- = I have problems adding my site =
139
-
140
- Make sure you use the latest version of the worker plugin on the site you are trying to add. If you do, sometimes deactivating and activating it again will help. If you still have problems, [contact us](http://managewp.com/contact "ManageWP Contact").
141
-
142
- = I have problems installing new plugins or upgrading WordPress through ManageWP =
143
-
 
 
 
 
 
 
144
  ManageWP Worker relies on properly set file permissions on your server. See the [user guide](http://managewp.com/user-guide#ftp "ManageWP user guide") for more tips.
1
+ === ManageWP Worker ===
2
+ Contributors: freediver
3
+ Donate link: https://www.networkforgood.org/donation/MakeDonation.aspx?ORGID2=520781390
4
+ Tags: managewp, managewp worker, admin, manage blogs, multi blog manager, manage multiple blogs, remote blog management
5
+ Requires at least: 3.0
6
+ Tested up to: 3.2
7
+ Stable tag: trunk
8
+
9
+ ManageWP Worker plugin allows you to remotely manage your blogs from one dashboard.
10
+
11
+ == Description ==
12
+
13
+ ManageWP is a revolutionary plugin that allows you to manage multiple WordPress blogs from one dashboard.
14
+
15
+ Main features:
16
+
17
+ * Secure! No passwords for sites required, uses OpenSSL encrypted protocol
18
+ * One click upgrades of WordPress, plugin and themes across all your sites
19
+ * One click to access administration dashboard for any site
20
+ * Add sub-users (writes, staff..) to your account
21
+ * Bulk publish posts to multiple sites at once
22
+ * Bulk upload themes and plugins to multiple sites at once
23
+ * Automatic backups of your sites
24
+ * Clone or migrate site to another domain
25
+ * Much, much more...
26
+
27
+ Check out [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs")
28
+
29
+ API for developers available at [ManageWP.com/API](http://managewp.com/api "ManageWP API")
30
+
31
+ == Changelog ==
32
+
33
+ == 3.9.6 ==
34
+ * Improved dashboard performance
35
+ * Fixed bug with W3TC, we hope it is fully comptabile now
36
+ * Improved backup feature
37
+ * Various other fixes and improvements
38
+
39
+ = 3.9.5 =
40
+ * Now supporting scheduled backups to Amazon S3 and Dropbox
41
+ * Revamped cloning procedure
42
+ * You can now have sites in different colors
43
+ * W3 Total Cache comptability improved
44
+
45
+ = 3.9.3 =
46
+ * Included support for WordPress 3.2 partial updates
47
+
48
+ = 3.9.2 =
49
+ * Fixed problem with full backups
50
+ * Fixed problem with wordpress dev version upgrades
51
+
52
+ = 3.9.1 =
53
+ * Support for sub-users (limited access users)
54
+ * Bulk add user
55
+ * 'Select all' feature for bulk posting
56
+ * Featured image support for bulk posting
57
+ * Reload button on the dashboard (on the top of the Right now widget) will now refresh information about available updates
58
+ * Fixed a problem with the import tool
59
+ * Fixed a problem when remote dashboard would not work for some servers
60
+
61
+ = 3.9.0 =
62
+ * New feature: Up to 50% faster dashboard loading
63
+ * New feature: You can now ignore WordPress/plugin/theme updates
64
+ * New feature: Setting 'Show favicon' for websites in the dashboad
65
+ * New feature: Full backups now include WordPress and other folders in the root of the site
66
+ * Fixed: Bug with W3 TotalCache object cache causing weird behaviour in the dashboard
67
+ * Fixed: All groups now show when adding a site
68
+
69
+ = 3.8.8 =
70
+ * New feature: Bulk add links to blogroll
71
+ * New feature: Manual backups to email address
72
+ * New feature: Backup requirements check (under �Manage Backups�)
73
+ * New feature: Popup menu for groups allowing to show dashboard for that group only
74
+ * New feature: Favorite list for plugins and themes for later quick installation to multiple blogs
75
+ * New feature: Invite friends
76
+ * Fixed: problem with backups and write permissions when upload dir was wrongly set
77
+ * Fixed: problem adding sites where WordPress is installed in a folder
78
+ * Fixed: 408 error message problem when adding site
79
+ * Fixed: site time out problems when adding site
80
+ * Fixed: problems with some WP plugins (WP Sentinel)
81
+ * Fixed: problems with upgrade notifications
82
+
83
+ = 3.8.7 =
84
+ * Fixed 408 error when adding sites
85
+ * Added support for IDN domains
86
+ * Fixed bug with WordPress updates
87
+ * Added comment moderation to the dashboard
88
+ * Added quick links for sites (menu appears on hover)
89
+
90
+
91
+ = 3.8.6 =
92
+ * Added seach websites feature
93
+ * Enhanced dashboard actions (spam comments, post revisions, table overhead)
94
+ * Added developer [API] (http://managewp.com/api "ManageWP API")
95
+ * Improved Migrate/Clone site feature
96
+
97
+ = 3.8.4 =
98
+ * Fixed remote dashboard problems for sites with redirects
99
+ * Fixed IE7 issues in the dashboard
100
+
101
+ = 3.8.3 =
102
+ * Fixed problem with capabilities
103
+
104
+ = 3.8.2 =
105
+ * New interface
106
+ * SSL security protocol
107
+ * No passwords required
108
+ * Improved clone/backup
109
+
110
+
111
+ = 3.6.3 =
112
+ * Initial public release
113
+
114
+ == Installation ==
115
+
116
+ 1. Upload the plugin folder to your /wp-content/plugins/ folder
117
+ 2. Go to the Plugins page and activate ManageWP Worker
118
+ 3. Visit [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs"), sign up and add your site
119
+
120
+ Alternately
121
+
122
+ 1. Visit [ManageWP.com](http://managewp.com/ "Manage Multiple Blogs"), sign up and add your site
123
+ 2. ManageWP will warn you the worker plugin is not installed and offer a link for quick installation
124
+
125
+ == Screenshots ==
126
+
127
+ 1. ManageWP dashboard with available upgrades, site statistics and management functions
128
+
129
+
130
+
131
+ == License ==
132
+
133
+ This file is part of ManageWP Worker.
134
+
135
+ ManageWP Worker is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
136
+
137
+ ManageWP Worker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
138
+
139
+ You should have received a copy of the GNU General Public License along with ManageWP Worker. If not, see <http://www.gnu.org/licenses/>.
140
+
141
+
142
+ == Frequently Asked Questions ==
143
+
144
+ = I have problems adding my site =
145
+
146
+ Make sure you use the latest version of the worker plugin on the site you are trying to add. If you do, sometimes deactivating and activating it again will help. If you still have problems, [contact us](http://managewp.com/contact "ManageWP Contact").
147
+
148
+ = I have problems installing new plugins or upgrading WordPress through ManageWP =
149
+
150
  ManageWP Worker relies on properly set file permissions on your server. See the [user guide](http://managewp.com/user-guide#ftp "ManageWP user guide") for more tips.
stats.class.php CHANGED
@@ -1,431 +1,431 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * stats.class.php
5
- *
6
- * Get Site Stats
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
-
14
- class MMB_Stats extends MMB_Core
15
- {
16
- function __construct()
17
- {
18
- parent::__construct();
19
- }
20
-
21
- /*************************************************************
22
- * FACADE functions
23
- * (functions to be called after a remote call from Master)
24
- **************************************************************/
25
-
26
- function get($params)
27
- {
28
- $num = extract($params);
29
-
30
- if ($refresh == 'transient') {
31
- include_once(ABSPATH . 'wp-includes/update.php');
32
- @wp_update_plugins();
33
- @wp_update_themes();
34
- @wp_version_check();
35
- }
36
-
37
- global $wpdb, $mmb_wp_version, $mmb_plugin_dir, $wp_version, $wp_local_package;
38
- $stats = array();
39
-
40
- //define constants
41
- $num_pending_comments = 10;
42
- $num_approved_comments = 3;
43
- $num_spam_comments = 0;
44
- $num_draft_comments = 0;
45
- $num_trash_comments = 0;
46
-
47
- include_once(ABSPATH . '/wp-admin/includes/update.php');
48
-
49
- $stats['worker_version'] = MMB_WORKER_VERSION;
50
- $stats['wordpress_version'] = $wp_version;
51
- $stats['wordpress_locale_pckg'] = $wp_local_package;
52
- $stats['wp_multisite'] = $this->mmb_multisite;
53
- $stats['php_version'] = phpversion();
54
- $stats['mysql_version'] = $wpdb->db_version();
55
-
56
- if (function_exists('get_core_updates')) {
57
- $updates = get_core_updates();
58
- if (!empty($updates)) {
59
- $current_transient = $updates[0];
60
- if ($current_transient->response == "development" || version_compare($wp_version, $current_transient->current, '<')) {
61
- $current_transient->current_version = $wp_version;
62
- $stats['core_updates'] = $current_transient;
63
- } else
64
- $stats['core_updates'] = false;
65
- } else
66
- $stats['core_updates'] = false;
67
- }
68
-
69
- $mmb_user_hits = get_option('user_hit_count');
70
- if (is_array($mmb_user_hits)) {
71
- end($mmb_user_hits);
72
- $last_key_date = key($mmb_user_hits);
73
- $current_date = date('Y-m-d');
74
- if ($last_key_date != $curent_date)
75
- $this->set_hit_count(true);
76
- }
77
- $stats['hit_counter'] = get_option('user_hit_count');
78
-
79
- $this->get_installer_instance();
80
- $stats['upgradable_themes'] = $this->installer_instance->get_upgradable_themes();
81
- $stats['upgradable_plugins'] = $this->installer_instance->get_upgradable_plugins();
82
-
83
- $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
84
- foreach ($pending_comments as &$comment) {
85
- $commented_post = get_post($comment->comment_post_ID);
86
- $comment->post_title = $commented_post->post_title;
87
- }
88
- $stats['comments']['pending'] = $pending_comments;
89
-
90
-
91
- $approved_comments = get_comments('status=approve&number=' . $num_approved_comments);
92
- foreach ($approved_comments as &$comment) {
93
- $commented_post = get_post($comment->comment_post_ID);
94
- $comment->post_title = $commented_post->post_title;
95
- }
96
- $stats['comments']['approved'] = $approved_comments;
97
-
98
-
99
- $all_posts = get_posts('post_status=publish&numberposts=3&orderby=modified&order=desc');
100
- $recent_posts = array();
101
-
102
- foreach ($all_posts as $id => $recent_post) {
103
- $recent = new stdClass();
104
- $recent->post_permalink = get_permalink($recent_post->ID);
105
- $recent->ID = $recent_post->ID;
106
- $recent->post_date = $recent_post->post_date;
107
- $recent->post_title = $recent_post->post_title;
108
- $recent->post_modified = $recent_post->post_modified;
109
- $recent->comment_count = $recent_post->comment_count;
110
- $recent_posts[] = $recent;
111
- }
112
-
113
-
114
- $all_drafts = get_posts('post_status=draft&numberposts=20&orderby=modified&order=desc');
115
- $recent_drafts = array();
116
- foreach ($all_drafts as $id => $recent_draft) {
117
- $recent = new stdClass();
118
- $recent->post_permalink = get_permalink($recent_draft->ID);
119
- $recent->ID = $recent_draft->ID;
120
- $recent->post_date = $recent_draft->post_date;
121
- $recent->post_title = $recent_draft->post_title;
122
- $recent->post_modified = $recent_draft->post_modified;
123
-
124
- $recent_drafts[] = $recent;
125
- }
126
-
127
- $all_scheduled = get_posts('post_status=future&numberposts=20&orderby=post_date&order=desc');
128
- $scheduled_posts = array();
129
- foreach ($all_scheduled as $id => $scheduled) {
130
- $recent = new stdClass();
131
- $recent->post_permalink = get_permalink($scheduled->ID);
132
- $recent->ID = $scheduled->ID;
133
- $recent->post_date = $scheduled->post_date;
134
- $recent->post_title = $scheduled->post_title;
135
- $recent->post_modified = $scheduled->post_modified;
136
-
137
- $scheduled_posts[] = $recent;
138
- }
139
-
140
-
141
- $all_pages_published = get_pages('post_status=publish&numberposts=3&orderby=modified&order=desc');
142
- $recent_pages_published = array();
143
- foreach ((array)$all_pages_published as $id => $recent_page_published) {
144
- $recent = new stdClass();
145
- $recent->post_permalink = get_permalink($recent_page_published->ID);
146
-
147
- $recent->ID = $recent_page_published->ID;
148
- $recent->post_date = $recent_page_published->post_date;
149
- $recent->post_title = $recent_page_published->post_title;
150
- $recent->post_modified = $recent_page_published->post_modified;
151
-
152
- $recent_posts[] = $recent;
153
- }
154
- usort($recent_posts, 'cmp_posts_worker');
155
- $stats['posts'] = array_slice($recent_posts, 0, 20);
156
-
157
- $all_pages_drafts = get_pages('post_status=draft&numberposts=20&orderby=modified&order=desc');
158
- $recent_pages_drafts = array();
159
- foreach ((array)$all_pages_drafts as $id => $recent_pages_draft) {
160
- $recent = new stdClass();
161
- $recent->post_permalink = get_permalink($recent_pages_draft->ID);
162
- $recent->ID = $recent_pages_draft->ID;
163
- $recent->post_date = $recent_pages_draft->post_date;
164
- $recent->post_title = $recent_pages_draft->post_title;
165
- $recent->post_modified = $recent_pages_draft->post_modified;
166
-
167
- $recent_drafts[] = $recent;
168
- }
169
- usort($recent_drafts, 'cmp_posts_worker');
170
- $stats['drafts'] = array_slice($recent_drafts, 0, 20);
171
-
172
-
173
- $pages_scheduled = get_pages('post_status=future&numberposts=20&orderby=modified&order=desc');
174
- $recent_pages_drafts = array();
175
- foreach ((array)$pages_scheduled as $id => $scheduled) {
176
- $recent = new stdClass();
177
- $recent->post_permalink = get_permalink($scheduled->ID);
178
- $recent->ID = $scheduled->ID;
179
- $recent->post_date = $scheduled->post_date;
180
- $recent->post_title = $scheduled->post_title;
181
- $recent->post_modified = $scheduled->post_modified;
182
-
183
- $scheduled_posts[] = $recent;
184
- }
185
- usort($scheduled_posts, 'cmp_posts_worker');
186
- $stats['scheduled'] = array_slice($scheduled_posts, 0, 20);
187
-
188
-
189
-
190
- if (!function_exists('get_filesystem_method'))
191
- include_once(ABSPATH . 'wp-admin/includes/file.php');
192
-
193
- $stats['writable'] = $this->is_server_writable();
194
-
195
- //Backup Results
196
- $stats['mwp_backups'] = $this->get_backup_instance()->get_backup_stats();
197
-
198
- //Backup requirements
199
- $stats['mwp_backup_req'] = $this->get_backup_instance()->check_backup_compat();
200
-
201
- $stats['sheduled_backup'] = '12.07.2011 13:00';
202
- $stats['sheduled_next'] = '12.08.2011 13:00';
203
-
204
- $stats = apply_filters('mmb_stats_filter', $stats);
205
-
206
- return $stats;
207
- }
208
-
209
- function get_stats_notification($params)
210
- {
211
-
212
- global $mmb_wp_version, $mmb_plugin_dir;
213
- $stats = array();
214
-
215
- //define constants
216
- $num_pending_comments = 1000;
217
-
218
-
219
- require_once(ABSPATH . '/wp-admin/includes/update.php');
220
-
221
- $stats['worker_version'] = MMB_WORKER_VERSION;
222
- $stats['wordpress_version'] = $mmb_wp_version;
223
-
224
- $updates = $this->mmb_get_transient('update_core');
225
-
226
- if ($updates->updates[0]->response == 'development' || version_compare($mmb_wp_version, $updates->updates[0]->current, '<')) {
227
- $updates->updates[0]->current_version = $mmb_wp_version;
228
- $stats['core_updates'] = $updates->updates[0];
229
- } else
230
- $stats['core_updates'] = false;
231
-
232
- $mmb_user_hits = get_option('user_hit_count');
233
- if (is_array($mmb_user_hits)) {
234
- end($mmb_user_hits);
235
- $last_key_date = key($mmb_user_hits);
236
- $current_date = date('Y-m-d');
237
- if ($last_key_date != $curent_date)
238
- $this->set_hit_count(true);
239
- }
240
-
241
-
242
- $this->get_theme_instance();
243
- $this->get_plugin_instance();
244
- $stats['upgradable_themes'] = $this->theme_instance->get_upgradable_themes();
245
- $stats['upgradable_plugins'] = $this->plugin_instance->get_upgradable_plugins();
246
-
247
- $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
248
-
249
- $stats['comments_pending'] = count($pending_comments);
250
-
251
- return $stats;
252
- }
253
-
254
-
255
- function get_comments_stats(){
256
- $num_pending_comments = 3;
257
- $num_approved_comments = 3;
258
- $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
259
- foreach ($pending_comments as &$comment) {
260
- $commented_post = get_post($comment->comment_post_ID);
261
- $comment->post_title = $commented_post->post_title;
262
- }
263
- $stats['comments']['pending'] = $pending_comments;
264
-
265
-
266
- $approved_comments = get_comments('status=approve&number=' . $num_approved_comments);
267
- foreach ($approved_comments as &$comment) {
268
- $commented_post = get_post($comment->comment_post_ID);
269
- $comment->post_title = $commented_post->post_title;
270
- }
271
- $stats['comments']['approved'] = $approved_comments;
272
-
273
- return $stats;
274
- }
275
- function get_initial_stats()
276
- {
277
- global $mmb_plugin_dir;
278
-
279
- $stats = array();
280
-
281
- $stats['email'] = get_option('admin_email');
282
- $stats['no_openssl'] = $this->get_random_signature();
283
- $stats['content_path'] = WP_CONTENT_DIR;
284
- $stats['worker_path'] = $mmb_plugin_dir;
285
- $stats['worker_version'] = MMB_WORKER_VERSION;
286
- $stats['site_title'] = get_bloginfo('name');
287
- $stats['site_tagline'] = get_bloginfo('description');
288
- $stats['site_home'] = get_option('home');
289
-
290
-
291
- if (!function_exists('get_filesystem_method'))
292
- include_once(ABSPATH . 'wp-admin/includes/file.php');
293
-
294
- $stats['writable'] = $this->is_server_writable();
295
-
296
- return $stats;
297
- }
298
-
299
-
300
-
301
- function set_hit_count($fix_count = false)
302
- {
303
- if ($fix_count || (!is_admin() && !MMB_Stats::detect_bots())) {
304
- $date = date('Y-m-d');
305
- $user_hit_count = (array) get_option('user_hit_count');
306
- if (!$user_hit_count) {
307
- $user_hit_count[$date] = 1;
308
- update_option('user_hit_count', $user_hit_count);
309
- } else {
310
- $dated_keys = array_keys($user_hit_count);
311
- $last_visit_date = $dated_keys[count($dated_keys) - 1];
312
-
313
- $days = intval((strtotime($date) - strtotime($last_visit_date)) / 60 / 60 / 24);
314
-
315
- if ($days > 1) {
316
- $date_to_add = date('Y-m-d', strtotime($last_visit_date));
317
-
318
- for ($i = 1; $i < $days; $i++) {
319
- if (count($user_hit_count) > 14) {
320
- $shifted = @array_shift($user_hit_count);
321
- }
322
-
323
- $next_key = strtotime('+1 day', strtotime($date_to_add));
324
- if ($next_key == $date) {
325
- break;
326
- } else {
327
- $user_hit_count[$next_key] = 0;
328
- }
329
- }
330
-
331
- }
332
-
333
- if (!isset($user_hit_count[$date])) {
334
- $user_hit_count[$date] = 0;
335
- }
336
- if (!$fix_count)
337
- $user_hit_count[$date] = ((int)$user_hit_count[$date] ) + 1;
338
-
339
- if (count($user_hit_count) > 14) {
340
- $shifted = @array_shift($user_hit_count);
341
- }
342
-
343
- update_option('user_hit_count', $user_hit_count);
344
-
345
- }
346
- }
347
- }
348
-
349
- function get_hit_count()
350
- {
351
- // Check if there are no hits on last key date
352
- $mmb_user_hits = get_option('user_hit_count');
353
- if (is_array($mmb_user_hits)) {
354
- end($mmb_user_hits);
355
- $last_key_date = key($mmb_user_hits);
356
- $current_date = date('Y-m-d');
357
- if ($last_key_date != $curent_date)
358
- $this->set_hit_count(true);
359
- }
360
-
361
- return get_option('user_hit_count');
362
- }
363
-
364
- function detect_bots()
365
- {
366
- $agent = $_SERVER['HTTP_USER_AGENT'];
367
-
368
- if ($agent == '')
369
- return false;
370
-
371
- $bot_list = array(
372
- "Teoma",
373
- "alexa",
374
- "froogle",
375
- "Gigabot",
376
- "inktomi",
377
- "looksmart",
378
- "URL_Spider_SQL",
379
- "Firefly",
380
- "NationalDirectory",
381
- "Ask Jeeves",
382
- "TECNOSEEK",
383
- "InfoSeek",
384
- "WebFindBot",
385
- "girafabot",
386
- "crawler",
387
- "www.galaxy.com",
388
- "Googlebot",
389
- "Scooter",
390
- "Slurp",
391
- "msnbot",
392
- "appie",
393
- "FAST",
394
- "WebBug",
395
- "Spade",
396
- "ZyBorg",
397
- "rabaz",
398
- "Baiduspider",
399
- "Feedfetcher-Google",
400
- "TechnoratiSnoop",
401
- "Rankivabot",
402
- "Mediapartners-Google",
403
- "Sogou web spider",
404
- "WebAlta Crawler",
405
- "aolserver"
406
- );
407
-
408
- $thebot = '';
409
- foreach ($bot_list as $bot) {
410
- if ((boolean)strpos($bot, $agent)) {
411
- $thebot = $bot;
412
- break;
413
- }
414
- }
415
-
416
- if ($thebot != '') {
417
- return $thebot;
418
- } else
419
- return false;
420
- }
421
-
422
-
423
- }
424
-
425
- function cmp_posts_worker($a, $b)
426
- {
427
- return ($a->post_modified < $b->post_modified);
428
- }
429
-
430
-
431
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * stats.class.php
5
+ *
6
+ * Get Site Stats
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+
14
+ class MMB_Stats extends MMB_Core
15
+ {
16
+ function __construct()
17
+ {
18
+ parent::__construct();
19
+ }
20
+
21
+ /*************************************************************
22
+ * FACADE functions
23
+ * (functions to be called after a remote call from Master)
24
+ **************************************************************/
25
+
26
+ function get($params)
27
+ {
28
+ $num = extract($params);
29
+
30
+ if ($refresh == 'transient') {
31
+ include_once(ABSPATH . 'wp-includes/update.php');
32
+ @wp_update_plugins();
33
+ @wp_update_themes();
34
+ @wp_version_check();
35
+ }
36
+
37
+ global $wpdb, $mmb_wp_version, $mmb_plugin_dir, $wp_version, $wp_local_package;
38
+ $stats = array();
39
+
40
+ //define constants
41
+ $num_pending_comments = 10;
42
+ $num_approved_comments = 3;
43
+ $num_spam_comments = 0;
44
+ $num_draft_comments = 0;
45
+ $num_trash_comments = 0;
46
+
47
+ include_once(ABSPATH . '/wp-admin/includes/update.php');
48
+
49
+ $stats['worker_version'] = MMB_WORKER_VERSION;
50
+ $stats['wordpress_version'] = $wp_version;
51
+ $stats['wordpress_locale_pckg'] = $wp_local_package;
52
+ $stats['wp_multisite'] = $this->mmb_multisite;
53
+ $stats['php_version'] = phpversion();
54
+ $stats['mysql_version'] = $wpdb->db_version();
55
+
56
+ if (function_exists('get_core_updates')) {
57
+ $updates = get_core_updates();
58
+ if (!empty($updates)) {
59
+ $current_transient = $updates[0];
60
+ if ($current_transient->response == "development" || version_compare($wp_version, $current_transient->current, '<')) {
61
+ $current_transient->current_version = $wp_version;
62
+ $stats['core_updates'] = $current_transient;
63
+ } else
64
+ $stats['core_updates'] = false;
65
+ } else
66
+ $stats['core_updates'] = false;
67
+ }
68
+
69
+ $mmb_user_hits = get_option('user_hit_count');
70
+ if (is_array($mmb_user_hits)) {
71
+ end($mmb_user_hits);
72
+ $last_key_date = key($mmb_user_hits);
73
+ $current_date = date('Y-m-d');
74
+ if ($last_key_date != $curent_date)
75
+ $this->set_hit_count(true);
76
+ }
77
+ $stats['hit_counter'] = get_option('user_hit_count');
78
+
79
+ $this->get_installer_instance();
80
+ $stats['upgradable_themes'] = $this->installer_instance->get_upgradable_themes();
81
+ $stats['upgradable_plugins'] = $this->installer_instance->get_upgradable_plugins();
82
+
83
+ $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
84
+ foreach ($pending_comments as &$comment) {
85
+ $commented_post = get_post($comment->comment_post_ID);
86
+ $comment->post_title = $commented_post->post_title;
87
+ }
88
+ $stats['comments']['pending'] = $pending_comments;
89
+
90
+
91
+ $approved_comments = get_comments('status=approve&number=' . $num_approved_comments);
92
+ foreach ($approved_comments as &$comment) {
93
+ $commented_post = get_post($comment->comment_post_ID);
94
+ $comment->post_title = $commented_post->post_title;
95
+ }
96
+ $stats['comments']['approved'] = $approved_comments;
97
+
98
+
99
+ $all_posts = get_posts('post_status=publish&numberposts=3&orderby=modified&order=desc');
100
+ $recent_posts = array();
101
+
102
+ foreach ($all_posts as $id => $recent_post) {
103
+ $recent = new stdClass();
104
+ $recent->post_permalink = get_permalink($recent_post->ID);
105
+ $recent->ID = $recent_post->ID;
106
+ $recent->post_date = $recent_post->post_date;
107
+ $recent->post_title = $recent_post->post_title;
108
+ $recent->post_modified = $recent_post->post_modified;
109
+ $recent->comment_count = $recent_post->comment_count;
110
+ $recent_posts[] = $recent;
111
+ }
112
+
113
+
114
+ $all_drafts = get_posts('post_status=draft&numberposts=20&orderby=modified&order=desc');
115
+ $recent_drafts = array();
116
+ foreach ($all_drafts as $id => $recent_draft) {
117
+ $recent = new stdClass();
118
+ $recent->post_permalink = get_permalink($recent_draft->ID);
119
+ $recent->ID = $recent_draft->ID;
120
+ $recent->post_date = $recent_draft->post_date;
121
+ $recent->post_title = $recent_draft->post_title;
122
+ $recent->post_modified = $recent_draft->post_modified;
123
+
124
+ $recent_drafts[] = $recent;
125
+ }
126
+
127
+ $all_scheduled = get_posts('post_status=future&numberposts=20&orderby=post_date&order=desc');
128
+ $scheduled_posts = array();
129
+ foreach ($all_scheduled as $id => $scheduled) {
130
+ $recent = new stdClass();
131
+ $recent->post_permalink = get_permalink($scheduled->ID);
132
+ $recent->ID = $scheduled->ID;
133
+ $recent->post_date = $scheduled->post_date;
134
+ $recent->post_title = $scheduled->post_title;
135
+ $recent->post_modified = $scheduled->post_modified;
136
+
137
+ $scheduled_posts[] = $recent;
138
+ }
139
+
140
+
141
+ $all_pages_published = get_pages('post_status=publish&numberposts=3&orderby=modified&order=desc');
142
+ $recent_pages_published = array();
143
+ foreach ((array)$all_pages_published as $id => $recent_page_published) {
144
+ $recent = new stdClass();
145
+ $recent->post_permalink = get_permalink($recent_page_published->ID);
146
+
147
+ $recent->ID = $recent_page_published->ID;
148
+ $recent->post_date = $recent_page_published->post_date;
149
+ $recent->post_title = $recent_page_published->post_title;
150
+ $recent->post_modified = $recent_page_published->post_modified;
151
+
152
+ $recent_posts[] = $recent;
153
+ }
154
+ usort($recent_posts, 'cmp_posts_worker');
155
+ $stats['posts'] = array_slice($recent_posts, 0, 20);
156
+
157
+ $all_pages_drafts = get_pages('post_status=draft&numberposts=20&orderby=modified&order=desc');
158
+ $recent_pages_drafts = array();
159
+ foreach ((array)$all_pages_drafts as $id => $recent_pages_draft) {
160
+ $recent = new stdClass();
161
+ $recent->post_permalink = get_permalink($recent_pages_draft->ID);
162
+ $recent->ID = $recent_pages_draft->ID;
163
+ $recent->post_date = $recent_pages_draft->post_date;
164
+ $recent->post_title = $recent_pages_draft->post_title;
165
+ $recent->post_modified = $recent_pages_draft->post_modified;
166
+
167
+ $recent_drafts[] = $recent;
168
+ }
169
+ usort($recent_drafts, 'cmp_posts_worker');
170
+ $stats['drafts'] = array_slice($recent_drafts, 0, 20);
171
+
172
+
173
+ $pages_scheduled = get_pages('post_status=future&numberposts=20&orderby=modified&order=desc');
174
+ $recent_pages_drafts = array();
175
+ foreach ((array)$pages_scheduled as $id => $scheduled) {
176
+ $recent = new stdClass();
177
+ $recent->post_permalink = get_permalink($scheduled->ID);
178
+ $recent->ID = $scheduled->ID;
179
+ $recent->post_date = $scheduled->post_date;
180
+ $recent->post_title = $scheduled->post_title;
181
+ $recent->post_modified = $scheduled->post_modified;
182
+
183
+ $scheduled_posts[] = $recent;
184
+ }
185
+ usort($scheduled_posts, 'cmp_posts_worker');
186
+ $stats['scheduled'] = array_slice($scheduled_posts, 0, 20);
187
+
188
+
189
+
190
+ if (!function_exists('get_filesystem_method'))
191
+ include_once(ABSPATH . 'wp-admin/includes/file.php');
192
+
193
+ $stats['writable'] = $this->is_server_writable();
194
+
195
+ //Backup Results
196
+ $stats['mwp_backups'] = $this->get_backup_instance()->get_backup_stats();
197
+
198
+ //Backup requirements
199
+ $stats['mwp_backup_req'] = $this->get_backup_instance()->check_backup_compat();
200
+
201
+ $stats['sheduled_backup'] = '12.07.2011 13:00';
202
+ $stats['sheduled_next'] = '12.08.2011 13:00';
203
+
204
+ $stats = apply_filters('mmb_stats_filter', $stats);
205
+
206
+ return $stats;
207
+ }
208
+
209
+ function get_stats_notification($params)
210
+ {
211
+
212
+ global $mmb_wp_version, $mmb_plugin_dir;
213
+ $stats = array();
214
+
215
+ //define constants
216
+ $num_pending_comments = 1000;
217
+
218
+
219
+ require_once(ABSPATH . '/wp-admin/includes/update.php');
220
+
221
+ $stats['worker_version'] = MMB_WORKER_VERSION;
222
+ $stats['wordpress_version'] = $mmb_wp_version;
223
+
224
+ $updates = $this->mmb_get_transient('update_core');
225
+
226
+ if ($updates->updates[0]->response == 'development' || version_compare($mmb_wp_version, $updates->updates[0]->current, '<')) {
227
+ $updates->updates[0]->current_version = $mmb_wp_version;
228
+ $stats['core_updates'] = $updates->updates[0];
229
+ } else
230
+ $stats['core_updates'] = false;
231
+
232
+ $mmb_user_hits = get_option('user_hit_count');
233
+ if (is_array($mmb_user_hits)) {
234
+ end($mmb_user_hits);
235
+ $last_key_date = key($mmb_user_hits);
236
+ $current_date = date('Y-m-d');
237
+ if ($last_key_date != $curent_date)
238
+ $this->set_hit_count(true);
239
+ }
240
+
241
+
242
+ $this->get_theme_instance();
243
+ $this->get_plugin_instance();
244
+ $stats['upgradable_themes'] = $this->theme_instance->get_upgradable_themes();
245
+ $stats['upgradable_plugins'] = $this->plugin_instance->get_upgradable_plugins();
246
+
247
+ $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
248
+
249
+ $stats['comments_pending'] = count($pending_comments);
250
+
251
+ return $stats;
252
+ }
253
+
254
+
255
+ function get_comments_stats(){
256
+ $num_pending_comments = 3;
257
+ $num_approved_comments = 3;
258
+ $pending_comments = get_comments('status=hold&number=' . $num_pending_comments);
259
+ foreach ($pending_comments as &$comment) {
260
+ $commented_post = get_post($comment->comment_post_ID);
261
+ $comment->post_title = $commented_post->post_title;
262
+ }
263
+ $stats['comments']['pending'] = $pending_comments;
264
+
265
+
266
+ $approved_comments = get_comments('status=approve&number=' . $num_approved_comments);
267
+ foreach ($approved_comments as &$comment) {
268
+ $commented_post = get_post($comment->comment_post_ID);
269
+ $comment->post_title = $commented_post->post_title;
270
+ }
271
+ $stats['comments']['approved'] = $approved_comments;
272
+
273
+ return $stats;
274
+ }
275
+ function get_initial_stats()
276
+ {
277
+ global $mmb_plugin_dir;
278
+
279
+ $stats = array();
280
+
281
+ $stats['email'] = get_option('admin_email');
282
+ $stats['no_openssl'] = $this->get_random_signature();
283
+ $stats['content_path'] = WP_CONTENT_DIR;
284
+ $stats['worker_path'] = $mmb_plugin_dir;
285
+ $stats['worker_version'] = MMB_WORKER_VERSION;
286
+ $stats['site_title'] = get_bloginfo('name');
287
+ $stats['site_tagline'] = get_bloginfo('description');
288
+ $stats['site_home'] = get_option('home');
289
+
290
+
291
+ if (!function_exists('get_filesystem_method'))
292
+ include_once(ABSPATH . 'wp-admin/includes/file.php');
293
+
294
+ $stats['writable'] = $this->is_server_writable();
295
+
296
+ return $stats;
297
+ }
298
+
299
+
300
+
301
+ function set_hit_count($fix_count = false)
302
+ {
303
+ if ($fix_count || (!is_admin() && !MMB_Stats::detect_bots())) {
304
+ $date = date('Y-m-d');
305
+ $user_hit_count = (array) get_option('user_hit_count');
306
+ if (!$user_hit_count) {
307
+ $user_hit_count[$date] = 1;
308
+ update_option('user_hit_count', $user_hit_count);
309
+ } else {
310
+ $dated_keys = array_keys($user_hit_count);
311
+ $last_visit_date = $dated_keys[count($dated_keys) - 1];
312
+
313
+ $days = intval((strtotime($date) - strtotime($last_visit_date)) / 60 / 60 / 24);
314
+
315
+ if ($days > 1) {
316
+ $date_to_add = date('Y-m-d', strtotime($last_visit_date));
317
+
318
+ for ($i = 1; $i < $days; $i++) {
319
+ if (count($user_hit_count) > 14) {
320
+ $shifted = @array_shift($user_hit_count);
321
+ }
322
+
323
+ $next_key = strtotime('+1 day', strtotime($date_to_add));
324
+ if ($next_key == $date) {
325
+ break;
326
+ } else {
327
+ $user_hit_count[$next_key] = 0;
328
+ }
329
+ }
330
+
331
+ }
332
+
333
+ if (!isset($user_hit_count[$date])) {
334
+ $user_hit_count[$date] = 0;
335
+ }
336
+ if (!$fix_count)
337
+ $user_hit_count[$date] = ((int)$user_hit_count[$date] ) + 1;
338
+
339
+ if (count($user_hit_count) > 14) {
340
+ $shifted = @array_shift($user_hit_count);
341
+ }
342
+
343
+ update_option('user_hit_count', $user_hit_count);
344
+
345
+ }
346
+ }
347
+ }
348
+
349
+ function get_hit_count()
350
+ {
351
+ // Check if there are no hits on last key date
352
+ $mmb_user_hits = get_option('user_hit_count');
353
+ if (is_array($mmb_user_hits)) {
354
+ end($mmb_user_hits);
355
+ $last_key_date = key($mmb_user_hits);
356
+ $current_date = date('Y-m-d');
357
+ if ($last_key_date != $curent_date)
358
+ $this->set_hit_count(true);
359
+ }
360
+
361
+ return get_option('user_hit_count');
362
+ }
363
+
364
+ function detect_bots()
365
+ {
366
+ $agent = $_SERVER['HTTP_USER_AGENT'];
367
+
368
+ if ($agent == '')
369
+ return false;
370
+
371
+ $bot_list = array(
372
+ "Teoma",
373
+ "alexa",
374
+ "froogle",
375
+ "Gigabot",
376
+ "inktomi",
377
+ "looksmart",
378
+ "URL_Spider_SQL",
379
+ "Firefly",
380
+ "NationalDirectory",
381
+ "Ask Jeeves",
382
+ "TECNOSEEK",
383
+ "InfoSeek",
384
+ "WebFindBot",
385
+ "girafabot",
386
+ "crawler",
387
+ "www.galaxy.com",
388
+ "Googlebot",
389
+ "Scooter",
390
+ "Slurp",
391
+ "msnbot",
392
+ "appie",
393
+ "FAST",
394
+ "WebBug",
395
+ "Spade",
396
+ "ZyBorg",
397
+ "rabaz",
398
+ "Baiduspider",
399
+ "Feedfetcher-Google",
400
+ "TechnoratiSnoop",
401
+ "Rankivabot",
402
+ "Mediapartners-Google",
403
+ "Sogou web spider",
404
+ "WebAlta Crawler",
405
+ "aolserver"
406
+ );
407
+
408
+ $thebot = '';
409
+ foreach ($bot_list as $bot) {
410
+ if ((boolean)strpos($bot, $agent)) {
411
+ $thebot = $bot;
412
+ break;
413
+ }
414
+ }
415
+
416
+ if ($thebot != '') {
417
+ return $thebot;
418
+ } else
419
+ return false;
420
+ }
421
+
422
+
423
+ }
424
+
425
+ function cmp_posts_worker($a, $b)
426
+ {
427
+ return ($a->post_modified < $b->post_modified);
428
+ }
429
+
430
+
431
  ?>
user.class.php CHANGED
@@ -1,53 +1,53 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * user.class.php
5
- *
6
- * Add Users
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
-
13
- class MMB_User extends MMB_Core
14
- {
15
- function __construct()
16
- {
17
- parent::__construct();
18
- }
19
-
20
- function add_user($args)
21
- {
22
-
23
- if(!function_exists('username_exists') || !function_exists('email_exists'))
24
- include_once(ABSPATH . WPINC . '/registration.php');
25
-
26
- if(username_exists($args['user_login']))
27
- return array('error' => 'Username already exists');
28
-
29
- if (email_exists($args['user_email']))
30
- return array('error' => 'Email already exists');
31
-
32
- if(!function_exists('wp_insert_user'))
33
- include_once (ABSPATH . 'wp-admin/includes/user.php');
34
-
35
- $user_id = wp_insert_user($args);
36
-
37
- if($user_id){
38
-
39
- if($args['email_notify']){
40
- //require_once ABSPATH . WPINC . '/pluggable.php';
41
- wp_new_user_notification($user_id, $args['user_pass']);
42
-
43
- }
44
-
45
- return $user_id;
46
- }else{
47
- return array('error' => 'User not added. Please try again.');
48
- }
49
-
50
- }
51
-
52
- }
53
  ?>
1
+ <?php
2
+ /*************************************************************
3
+ *
4
+ * user.class.php
5
+ *
6
+ * Add Users
7
+ *
8
+ *
9
+ * Copyright (c) 2011 Prelovac Media
10
+ * www.prelovac.com
11
+ **************************************************************/
12
+
13
+ class MMB_User extends MMB_Core
14
+ {
15
+ function __construct()
16
+ {
17
+ parent::__construct();
18
+ }
19
+
20
+ function add_user($args)
21
+ {
22
+
23
+ if(!function_exists('username_exists') || !function_exists('email_exists'))
24
+ include_once(ABSPATH . WPINC . '/registration.php');
25
+
26
+ if(username_exists($args['user_login']))
27
+ return array('error' => 'Username already exists');
28
+
29
+ if (email_exists($args['user_email']))
30
+ return array('error' => 'Email already exists');
31
+
32
+ if(!function_exists('wp_insert_user'))
33
+ include_once (ABSPATH . 'wp-admin/includes/user.php');
34
+
35
+ $user_id = wp_insert_user($args);
36
+
37
+ if($user_id){
38
+
39
+ if($args['email_notify']){
40
+ //require_once ABSPATH . WPINC . '/pluggable.php';
41
+ wp_new_user_notification($user_id, $args['user_pass']);
42
+
43
+ }
44
+
45
+ return $user_id;
46
+ }else{
47
+ return array('error' => 'User not added. Please try again.');
48
+ }
49
+
50
+ }
51
+
52
+ }
53
  ?>
version CHANGED
@@ -1 +1 @@
1
- 3.9.5
1
+ 3.9.6