ManageWP Worker - Version 3.9.29

Version Description

  • New: Worker plugin is now 36% faster and uses 83% less memory
  • New: Backup no longer relies on WordPress cron
  • New: New Server-Client communication fixing some of the previous issues
  • New: Notes and Recent backups widgets
  • New: Refreshed app interface :)
Download this release

Release Info

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

Code changes from version 3.9.28 to 3.9.29

api.php DELETED
@@ -1,41 +0,0 @@
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
- if( !function_exists('mmb_add_action')) :
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
- endif;
26
-
27
- if( !function_exists('mmb_function_exists') ) :
28
- function mmb_function_exists($callback)
29
- {
30
- global $mwp_core;
31
- if (count($callback) === 2) {
32
- if (!method_exists($callback[0], $callback[1]))
33
- wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Class ' . get_class($callback[0]) . ' does not contain <b>"' . $callback[1] . '"</b> function</p>', '', '50%'));
34
- } else {
35
- if (!function_exists($callback))
36
- wp_die($mwp_core->mwp_dashboard_widget('Information', '', '<p>Function <b>"' . $callback . '"</b> does not exists.</p>', '', '50%'));
37
- }
38
- }
39
- endif;
40
-
41
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backup.class.php DELETED
@@ -1,3527 +0,0 @@
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
- if(basename($_SERVER['SCRIPT_FILENAME']) == "backup.class.php"):
13
- echo "Sorry but you cannot browse this file directly!";
14
- exit;
15
- endif;
16
- define('MWP_BACKUP_DIR', WP_CONTENT_DIR . '/managewp/backups');
17
- define('MWP_DB_DIR', MWP_BACKUP_DIR . '/mwp_db');
18
-
19
- set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__).'/lib/PHPSecLib');
20
- require_once ('Net/SFTP.php');
21
-
22
- $zip_errors = array(
23
- 'No error',
24
- 'No error',
25
- 'Unexpected end of zip file',
26
- 'A generic error in the zipfile format was detected',
27
- 'zip was unable to allocate itself memory',
28
- 'A severe error in the zipfile format was detected',
29
- 'Entry too large to be split with zipsplit',
30
- 'Invalid comment format',
31
- 'zip -T failed or out of memory',
32
- 'The user aborted zip prematurely',
33
- 'zip encountered an error while using a temp file. Please check if there is enough disk space',
34
- 'Read or seek error',
35
- 'zip has nothing to do',
36
- 'Missing or empty zip file',
37
- 'Error writing to a file. Please check if there is enough disk space',
38
- 'zip was unable to create a file to write to',
39
- 'bad command line parameters',
40
- 'no error',
41
- 'zip could not open a specified file to read'
42
- );
43
- $unzip_errors = array(
44
- 'No error',
45
- 'One or more warning errors were encountered, but processing completed successfully anyway',
46
- 'A generic error in the zipfile format was detected',
47
- 'A severe error in the zipfile format was detected.',
48
- 'unzip was unable to allocate itself memory.',
49
- 'unzip was unable to allocate memory, or encountered an encryption error',
50
- 'unzip was unable to allocate memory during decompression to disk',
51
- 'unzip was unable allocate memory during in-memory decompression',
52
- 'unused',
53
- 'The specified zipfiles were not found',
54
- 'Bad command line parameters',
55
- 'No matching files were found',
56
- 50 => 'The disk is (or was) full during extraction',
57
- 51 => 'The end of the ZIP archive was encountered prematurely.',
58
- 80 => 'The user aborted unzip prematurely.',
59
- 81 => 'Testing or extraction of one or more files failed due to unsupported compression methods or unsupported decryption.',
60
- 82 => 'No files were found due to bad decryption password(s)'
61
- );
62
-
63
- /**
64
- * The main class for processing database and full backups on ManageWP worker.
65
- *
66
- * @copyright 2011-2012 Prelovac Media
67
- * @version 3.9.24
68
- * @package ManageWP
69
- * @subpackage backup
70
- *
71
- */
72
- class MMB_Backup extends MMB_Core {
73
- var $site_name;
74
- var $statuses;
75
- var $tasks;
76
- var $s3;
77
- var $ftp;
78
- var $dropbox;
79
- var $google_drive;
80
-
81
- /**
82
- * Initializes site_name, statuses, and tasks attributes.
83
- *
84
- * @return void
85
- */
86
- function __construct() {
87
- parent::__construct();
88
- $this->site_name = str_replace(array(
89
- "_",
90
- "/",
91
- "~"
92
- ), array(
93
- "",
94
- "-",
95
- "-"
96
- ), rtrim($this->remove_http(get_bloginfo('url')), "/"));
97
- $this->statuses = array(
98
- 'db_dump' => 1,
99
- 'db_zip' => 2,
100
- 'files_zip' => 3,
101
- 's3' => 4,
102
- 'dropbox' => 5,
103
- 'ftp' => 6,
104
- 'email' => 7,
105
- 'google_drive' => 8,
106
- 'finished' => 100
107
- );
108
- $this->tasks = get_option('mwp_backup_tasks');
109
- }
110
-
111
- /**
112
- * Tries to increase memory limit to 384M and execution time to 600s.
113
- *
114
- * @return array an array with two keys for execution time and memory limit (0 - if not changed, 1 - if succesfully)
115
- */
116
- function set_memory() {
117
- $changed = array('execution_time' => 0, 'memory_limit' => 0);
118
- @ignore_user_abort(true);
119
- $memory_limit = trim(ini_get('memory_limit'));
120
- $last = strtolower(substr($memory_limit, -1));
121
-
122
- if($last == 'g')
123
- $memory_limit = ((int) $memory_limit)*1024;
124
- else if($last == 'm')
125
- $memory_limit = (int) $memory_limit;
126
- if($last == 'k')
127
- $memory_limit = ((int) $memory_limit)/1024;
128
-
129
- if ( $memory_limit < 384 ) {
130
- @ini_set('memory_limit', '384M');
131
- $changed['memory_limit'] = 1;
132
- }
133
-
134
- if ( (int) @ini_get('max_execution_time') < 4000 ) {
135
- @ini_set('max_execution_time', 4000);
136
- @set_time_limit(4000);
137
- $changed['execution_time'] = 1;
138
- }
139
-
140
- return $changed;
141
- }
142
-
143
- /**
144
- * Returns backup settings from local database for all tasks
145
- *
146
- * @return mixed|boolean
147
- */
148
- function get_backup_settings() {
149
- $backup_settings = get_option('mwp_backup_tasks');
150
-
151
- if (!empty($backup_settings))
152
- return $backup_settings;
153
- else
154
- return false;
155
- }
156
-
157
- /**
158
- * Sets backup task defined from master, if task name is "Backup Now" this function fires processing backup.
159
- *
160
- * @param mixed $params parameters sent from master
161
- * @return mixed|boolean $this->tasks variable if success, array with error message if error has ocurred, false if $params are empty
162
- */
163
- function set_backup_task($params) {
164
- //$params => [$task_name, $args, $error]
165
- if (!empty($params)) {
166
-
167
- //Make sure backup cron job is set
168
- if (!wp_next_scheduled('mwp_backup_tasks')) {
169
- wp_schedule_event( time(), 'tenminutes', 'mwp_backup_tasks' );
170
- }
171
-
172
- extract($params);
173
-
174
- //$before = $this->get_backup_settings();
175
- $before = $this->tasks;
176
- if (!$before || empty($before))
177
- $before = array();
178
-
179
- if (isset($args['remove'])) {
180
- unset($before[$task_name]);
181
- $return = array(
182
- 'removed' => true
183
- );
184
- } else {
185
- if (isset($params['account_info']) && is_array($params['account_info'])) { //only if sends from master first time(secure data)
186
- $args['account_info'] = $account_info;
187
- }
188
-
189
- $before[$task_name]['task_args'] = $args;
190
- if (strlen($args['schedule']))
191
- $before[$task_name]['task_args']['next'] = $this->schedule_next($args['type'], $args['schedule']);
192
-
193
- $return = $before[$task_name];
194
- }
195
-
196
- //Update with error
197
- if (isset($error)) {
198
- if (is_array($error)) {
199
- $before[$task_name]['task_results'][count($before[$task_name]['task_results']) - 1]['error'] = $error['error'];
200
- } else {
201
- $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['error'] = $error;
202
- }
203
- }
204
-
205
- if (isset($time) && $time) { //set next result time before backup
206
- if (is_array($before[$task_name]['task_results'])) {
207
- $before[$task_name]['task_results'] = array_values($before[$task_name]['task_results']);
208
- }
209
- $before[$task_name]['task_results'][count($before[$task_name]['task_results'])]['time'] = $time;
210
- }
211
-
212
- $this->update_tasks($before);
213
- //update_option('mwp_backup_tasks', $before);
214
-
215
- if ($task_name == 'Backup Now') {
216
- $result = $this->backup($args, $task_name);
217
- $backup_settings = $this->tasks;
218
-
219
- if (is_array($result) && array_key_exists('error', $result)) {
220
- $return = $result;
221
- } else {
222
- $return = $backup_settings[$task_name];
223
- }
224
- }
225
- return $return;
226
- }
227
-
228
- return false;
229
- }
230
-
231
- /**
232
- * Checks if scheduled task is ready for execution,
233
- * if it is ready master sends google_drive_token, failed_emails, success_emails if are needed.
234
- *
235
- * @return void
236
- */
237
- function check_backup_tasks() {
238
- $this->check_cron_remove();
239
-
240
- $failed_emails = array();
241
- $settings = $this->tasks;
242
- if (is_array($settings) && !empty($settings)) {
243
- foreach ($settings as $task_name => $setting) {
244
- if (isset($setting['task_args']['next']) && $setting['task_args']['next'] < time()) {
245
- //if ($setting['task_args']['next'] && $_GET['force_backup']) {
246
- if ($setting['task_args']['url'] && $setting['task_args']['task_id'] && $setting['task_args']['site_key']) {
247
- //Check orphan task
248
- $check_data = array(
249
- 'task_name' => $task_name,
250
- 'task_id' => $setting['task_args']['task_id'],
251
- 'site_key' => $setting['task_args']['site_key'],
252
- 'worker_version' => MMB_WORKER_VERSION
253
- );
254
-
255
- if (isset($setting['task_args']['account_info']['mwp_google_drive']['google_drive_token'])) {
256
- $check_data['mwp_google_drive_refresh_token'] = true;
257
- }
258
-
259
- $check = $this->validate_task($check_data, $setting['task_args']['url']);
260
- if($check == 'paused' || $check == 'deleted'){
261
- continue;
262
- }
263
- $worker_upto_3_9_22 = (MMB_WORKER_VERSION <= '3.9.22'); // worker version is less or equals to 3.9.22
264
-
265
- // This is the patch done in worker 3.9.22 because old worked provided message in the following format:
266
- // token - not found or token - {...json...}
267
- // The new message is a serialized string with google_drive_token or message.
268
- if ($worker_upto_3_9_22) {
269
- $potential_token = substr($check, 8);
270
- if (substr($check, 0, 8) == 'token - ' && $potential_token != 'not found') {
271
- $this->tasks[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
272
- $settings[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
273
- $setting['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
274
- }
275
- } else {
276
- $potential_token = isset($check['google_drive_token']) ? $check['google_drive_token'] : false;
277
- if ($potential_token) {
278
- $this->tasks[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
279
- $settings[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
280
- $setting['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $potential_token;
281
- }
282
- }
283
-
284
- }
285
-
286
- $update = array(
287
- 'task_name' => $task_name,
288
- 'args' => $settings[$task_name]['task_args']
289
- );
290
-
291
- if ($check != 'paused') {
292
- $update['time'] = time();
293
- }
294
-
295
- //Update task with next schedule
296
- $this->set_backup_task($update);
297
-
298
- if($check == 'paused'){
299
- continue;
300
- }
301
-
302
-
303
- $result = $this->backup($setting['task_args'], $task_name);
304
- $error = '';
305
-
306
- if (is_array($result) && array_key_exists('error', $result)) {
307
- $error = $result;
308
- $this->set_backup_task(array(
309
- 'task_name' => $task_name,
310
- 'args' => $settings[$task_name]['task_args'],
311
- 'error' => $error
312
- ));
313
- } else {
314
- if (@count($setting['task_args']['account_info'])) {
315
- // Old way through sheduling.
316
- // wp_schedule_single_event(time(), 'mmb_scheduled_remote_upload', array('args' => array('task_name' => $task_name)));
317
- $nonce = substr(wp_hash(wp_nonce_tick() . 'mmb-backup-nonce' . 0, 'nonce'), -12, 10);
318
- $cron_url = site_url('index.php');
319
- $backup_file = $this->tasks[$task_name]['task_results'][count($this->tasks[$task_name]['task_results']) - 1]['server']['file_url'];
320
- $del_host_file = $this->tasks[$task_name]['task_args']['del_host_file'];
321
- $public_key = get_option('_worker_public_key');
322
- $args = array(
323
- 'body' => array(
324
- 'backup_cron_action' => 'mmb_remote_upload',
325
- 'args' => json_encode(array('task_name' => $task_name, 'backup_file' => $backup_file, 'del_host_file' => $del_host_file)),
326
- 'mmb_backup_nonce' => $nonce,
327
- 'public_key' => $public_key,
328
- ),
329
- 'timeout' => 0.01,
330
- 'blocking' => false,
331
- 'sslverify' => apply_filters('https_local_ssl_verify', true)
332
- );
333
- wp_remote_post($cron_url, $args);
334
- }
335
- }
336
-
337
- break; //Only one backup per cron
338
- }
339
- }
340
- }
341
-
342
- }
343
-
344
- /**
345
- * Runs backup task invoked from ManageWP master.
346
- *
347
- * @param string $task_name name of backup task
348
- * @param string|bool[optional] $google_drive_token false if backup destination is not Google Drive, json of Google Drive token if it is remote destination (default: false)
349
- * @return mixed array with backup statistics if successful, array with error message if not
350
- */
351
- function task_now($task_name, $google_drive_token = false) {
352
- if ($google_drive_token) {
353
- $this->tasks[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $google_drive_token;
354
- }
355
-
356
- $settings = $this->tasks;
357
- if(!array_key_exists($task_name,$settings)){
358
- return array('error' => $task_name." does not exist.");
359
- } else {
360
- $setting = $settings[$task_name];
361
- }
362
-
363
- $this->set_backup_task(array(
364
- 'task_name' => $task_name,
365
- 'args' => $settings[$task_name]['task_args'],
366
- 'time' => time()
367
- ));
368
-
369
- //Run backup
370
- $result = $this->backup($setting['task_args'], $task_name);
371
-
372
- //Check for error
373
- if (is_array($result) && array_key_exists('error', $result)) {
374
- $this->set_backup_task(array(
375
- 'task_name' => $task_name,
376
- 'args' => $settings[$task_name]['task_args'],
377
- 'error' => $result['error']
378
- ));
379
- return $result;
380
- } else {
381
- return $this->get_backup_stats();
382
- }
383
- }
384
-
385
- /**
386
- * Backup a full wordpress instance, including a database dump, which is placed in mwp_db dir in root folder.
387
- * All backups are compressed by zip and placed in wp-content/managewp/backups folder.
388
- *
389
- * @param string $args arguments passed from master
390
- * [type] -> db, full
391
- * [what] -> daily, weekly, monthly
392
- * [account_info] -> remote destinations ftp, amazons3, dropbox, google_drive, email with their parameters
393
- * [include] -> array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
394
- * [exclude] -> array of files of folders to exclude, relative to site's root
395
- * @param bool|string[optional] $task_name the name of backup task, which backup is done (default: false)
396
- * @return bool|array false if $args are missing, array with error if error has occured, ture if is successful
397
- */
398
- function backup($args, $task_name = false) {
399
- if (!$args || empty($args))
400
- return false;
401
-
402
- extract($args); //extract settings
403
-
404
- if (!empty($account_info)) {
405
- $found = false;
406
- $destinations = array('mwp_ftp','mwp_sftp', 'mwp_amazon_s3', 'mwp_dropbox', 'mwp_google_drive', 'mwp_email');
407
- foreach($destinations as $dest) {
408
- $found = $found || (isset($account_info[$dest]));
409
- }
410
- if (!$found) {
411
- $error_message = 'Remote destination is not supported, please update your client plugin.';
412
- return array(
413
- 'error' => $error_message
414
- );
415
- }
416
- }
417
-
418
- //Try increase memory limit and execution time
419
- $this->set_memory();
420
-
421
- //Remove old backup(s)
422
- $removed = $this->remove_old_backups($task_name);
423
- if (is_array($removed) && isset($removed['error'])) {
424
- $error_message = $removed['error'];
425
- return $removed;
426
- }
427
-
428
- $new_file_path = MWP_BACKUP_DIR;
429
-
430
- if (!file_exists($new_file_path)) {
431
- if (!mkdir($new_file_path, 0755, true))
432
- return array(
433
- 'error' => 'Permission denied, make sure you have write permissions to the wp-content folder.'
434
- );
435
- }
436
-
437
- @file_put_contents($new_file_path . '/index.php', ''); //safe
438
-
439
- //Prepare .zip file name
440
- $hash = md5(time());
441
- $label = $type ? $type : 'manual';
442
- $backup_file = $new_file_path . '/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
443
- $backup_url = WP_CONTENT_URL . '/managewp/backups/' . $this->site_name . '_' . $label . '_' . $what . '_' . date('Y-m-d') . '_' . $hash . '.zip';
444
-
445
- $begin_compress = microtime(true);
446
-
447
- //Optimize tables?
448
- if (isset($optimize_tables) && !empty($optimize_tables)) {
449
- $this->optimize_tables();
450
- }
451
-
452
- //What to backup - db or full?
453
- if (trim($what) == 'db') {
454
- $db_backup = $this->backup_db_compress($task_name, $backup_file);
455
- if (is_array($db_backup) && array_key_exists('error', $db_backup)) {
456
- $error_message = $db_backup['error'];
457
- return array(
458
- 'error' => $error_message
459
- );
460
- }
461
- } elseif (trim($what) == 'full') {
462
- if (!$exclude) {
463
- $exclude = array();
464
- }
465
- if (!$include) {
466
- $include = array();
467
- }
468
- $content_backup = $this->backup_full($task_name, $backup_file, $exclude, $include);
469
- if (is_array($content_backup) && array_key_exists('error', $content_backup)) {
470
- $error_message = $content_backup['error'];
471
- return array(
472
- 'error' => $error_message
473
- );
474
- }
475
- }
476
-
477
- $end_compress = microtime(true);
478
-
479
- //Update backup info
480
- if ($task_name) {
481
- //backup task (scheduled)
482
- $backup_settings = $this->tasks;
483
- $paths = array();
484
- $size = ceil(filesize($backup_file) / 1024);
485
- $duration = round($end_compress - $begin_compress, 2);
486
-
487
- if ($size > 1000) {
488
- $paths['size'] = ceil($size / 1024) . "MB";
489
- } else {
490
- $paths['size'] = $size . 'KB';
491
- }
492
-
493
- $paths['duration'] = $duration . 's';
494
-
495
- if ($task_name != 'Backup Now') {
496
- $paths['server'] = array(
497
- 'file_path' => $backup_file,
498
- 'file_url' => $backup_url
499
- );
500
- } else {
501
- $paths['server'] = array(
502
- 'file_path' => $backup_file,
503
- 'file_url' => $backup_url
504
- );
505
- }
506
-
507
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_ftp'])) {
508
- $paths['ftp'] = basename($backup_url);
509
- }
510
-
511
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_sftp'])) {
512
- $paths['sftp'] = basename($backup_url);
513
- }
514
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
515
- $paths['amazons3'] = basename($backup_url);
516
- }
517
-
518
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
519
- $paths['dropbox'] = basename($backup_url);
520
- }
521
-
522
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_email'])) {
523
- $paths['email'] = basename($backup_url);
524
- }
525
-
526
- if (isset($backup_settings[$task_name]['task_args']['account_info']['mwp_google_drive'])) {
527
- $paths['google_drive'] = basename($backup_url);
528
- }
529
-
530
- $temp = $backup_settings[$task_name]['task_results'];
531
- $temp = @array_values($temp);
532
- $paths['time'] = time();
533
-
534
- if ($task_name != 'Backup Now') {
535
- $paths['status'] = $temp[count($temp) - 1]['status'];
536
- $temp[count($temp) - 1] = $paths;
537
-
538
- } else {
539
- $temp[count($temp)] = $paths;
540
- }
541
-
542
- $backup_settings[$task_name]['task_results'] = $temp;
543
- $this->update_tasks($backup_settings);
544
- //update_option('mwp_backup_tasks', $backup_settings);
545
- }
546
-
547
- // If there are not remote destination, set up task status to finished
548
- if (@count($backup_settings[$task_name]['task_args']['account_info']) == 0) {
549
- $this->update_status($task_name, $this->statuses['finished'], true);
550
- }
551
-
552
- return true;
553
- }
554
-
555
- /**
556
- * Backup a full wordpress instance, including a database dump, which is placed in mwp_db dir in root folder.
557
- * All backups are compressed by zip and placed in wp-content/managewp/backups folder.
558
- *
559
- * @param string $task_name the name of backup task, which backup is done
560
- * @param string $backup_file relative path to file which backup is stored
561
- * @param array[optional] $exclude the list of files and folders, which are excluded from backup (default: array())
562
- * @param array[optional] $include the list of folders in wordpress root which are included to backup, expect wp-admin, wp-content, wp-includes, which are default (default: array())
563
- * @return bool|array true if backup is successful, or an array with error message if is failed
564
- */
565
- function backup_full($task_name, $backup_file, $exclude = array(), $include = array()) {
566
- $this->update_status($task_name, $this->statuses['db_dump']);
567
- $db_result = $this->backup_db();
568
-
569
- if ($db_result == false) {
570
- return array(
571
- 'error' => 'Failed to backup database.'
572
- );
573
- } else if (is_array($db_result) && isset($db_result['error'])) {
574
- return array(
575
- 'error' => $db_result['error']
576
- );
577
- }
578
-
579
- $this->update_status($task_name, $this->statuses['db_dump'], true);
580
- $this->update_status($task_name, $this->statuses['db_zip']);
581
-
582
- @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
583
- $zip_db_result = $this->zip_backup_db($task_name, $backup_file);
584
-
585
- if (!$zip_db_result) {
586
- $zip_archive_db_result = false;
587
- if (class_exists("ZipArchive")) {
588
- $this->_log("DB zip, fallback to ZipArchive");
589
- $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
590
- }
591
-
592
- if (!$zip_archive_db_result) {
593
- $this->_log("DB zip, fallback to PclZip");
594
- $pclzip_db_result = $this->pclzip_backup_db($task_name, $backup_file);
595
- if (!$pclzip_db_result) {
596
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
597
- @unlink($db_result);
598
- @rmdir(MWP_DB_DIR);
599
-
600
- if($archive->error_code!=''){
601
- $archive->error_code = 'pclZip error ('.$archive->error_code . '): .';
602
- }
603
- return array(
604
- 'error' => 'Failed to zip database. ' . $archive->error_code . $archive->error_string
605
- );
606
- }
607
- }
608
- }
609
-
610
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
611
- @unlink($db_result);
612
- @rmdir(MWP_DB_DIR);
613
-
614
- $remove = array(
615
- trim(basename(WP_CONTENT_DIR)) . "/managewp/backups",
616
- trim(basename(WP_CONTENT_DIR)) . "/" . md5('mmb-worker') . "/mwp_backups",
617
- trim(basename(WP_CONTENT_DIR)) . "/cache",
618
- trim(basename(WP_CONTENT_DIR)) . "/w3tc",
619
- );
620
- $exclude = array_merge($exclude, $remove);
621
-
622
- $this->update_status($task_name, $this->statuses['db_zip'], true);
623
- $this->update_status($task_name, $this->statuses['files_zip']);
624
-
625
- $zip_result = $this->zip_backup($task_name, $backup_file, $exclude, $include);
626
-
627
- if (isset($zip_result['error'])) {
628
- return $zip_result;
629
- }
630
-
631
- if (!$zip_result) {
632
- $zip_archive_result = false;
633
- if (class_exists("ZipArchive")) {
634
- $this->_log("Files zip fallback to ZipArchive");
635
- $zip_archive_result = $this->zip_archive_backup($task_name, $backup_file, $exclude, $include);
636
- }
637
-
638
- if (!$zip_archive_result) {
639
- $this->_log("Files zip fallback to PclZip");
640
- $pclzip_result = $this->pclzip_backup($task_name, $backup_file, $exclude, $include);
641
- if (!$pclzip_result) {
642
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
643
- @unlink($db_result);
644
- @rmdir(MWP_DB_DIR);
645
-
646
- if (!$pclzip_result) {
647
- @unlink($backup_file);
648
- return array(
649
- 'error' => 'Failed to zip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
650
- );
651
- }
652
- }
653
- }
654
- }
655
-
656
- //Reconnect
657
- $this->wpdb_reconnect();
658
-
659
- $this->update_status($task_name, $this->statuses['files_zip'], true);
660
- return true;
661
- }
662
-
663
- /**
664
- * Zipping database dump and index.php in folder mwp_db by system zip command, requires zip installed on OS.
665
- *
666
- * @param string $task_name the name of backup task
667
- * @param string $backup_file absolute path to zip file
668
- * @return bool is compress successful or not
669
- */
670
- function zip_backup_db($task_name, $backup_file) {
671
- $backup_file = escapeshellarg($backup_file);
672
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
673
- $comp_level = $disable_comp ? '-0' : '-1';
674
- $zip = $this->get_zip();
675
- //Add database file
676
- chdir(MWP_BACKUP_DIR);
677
- $command = "$zip -q -r $comp_level $backup_file 'mwp_db'";
678
-
679
- ob_start();
680
- $this->_log("Executing $command");
681
- $result = $this->mmb_exec($command);
682
- ob_get_clean();
683
-
684
- return $result;
685
- }
686
-
687
- /**
688
- * Zipping database dump and index.php in folder mwp_db by ZipArchive class, requires php zip extension.
689
- *
690
- * @param string $task_name the name of backup task
691
- * @param string $db_result relative path to database dump file
692
- * @param string $backup_file absolute path to zip file
693
- * @return bool is compress successful or not
694
- */
695
- function zip_archive_backup_db($task_name, $db_result, $backup_file) {
696
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
697
- if (!$disable_comp) {
698
- $this->_log("Compression is not supported by ZipArchive");
699
- }
700
- $zip = new ZipArchive();
701
- $result = $zip->open($backup_file, ZIPARCHIVE::OVERWRITE); // Tries to open $backup_file for acrhiving
702
- if ($result === true) {
703
- $result = $result && $zip->addFile(MWP_BACKUP_DIR.'/mwp_db/index.php', "mwp_db/index.php"); // Tries to add mwp_db/index.php to $backup_file
704
- $result = $result && $zip->addFile($db_result, "mwp_db/" . basename($db_result)); // Tries to add db dump form mwp_db dir to $backup_file
705
- $result = $result && $zip->close(); // Tries to close $backup_file
706
- } else {
707
- $result = false;
708
- }
709
-
710
- return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
711
- }
712
-
713
- /**
714
- * Zipping database dump and index.php in folder mwp_db by PclZip library.
715
- *
716
- * @param string $task_name the name of backup task
717
- * @param string $backup_file absolute path to zip file
718
- * @return bool is compress successful or not
719
- */
720
- function pclzip_backup_db($task_name, $backup_file) {
721
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
722
- define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
723
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
724
- $zip = new PclZip($backup_file);
725
-
726
- if ($disable_comp) {
727
- $result = $zip->add(MWP_BACKUP_DIR."/mwp_db/", PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR, PCLZIP_OPT_NO_COMPRESSION) !== 0;
728
- } else {
729
- $result = $zip->add(MWP_BACKUP_DIR."/mwp_db/", PCLZIP_OPT_REMOVE_PATH, MWP_BACKUP_DIR) !== 0;
730
- }
731
-
732
- return $result;
733
- }
734
-
735
- /**
736
- * Zipping whole site root folder and append to backup file with database dump
737
- * by system zip command, requires zip installed on OS.
738
- *
739
- * @param string $task_name the name of backup task
740
- * @param string $backup_file absolute path to zip file
741
- * @param array $exclude array of files of folders to exclude, relative to site's root
742
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
743
- * @return array|bool true if successful or an array with error message if not
744
- */
745
- function zip_backup($task_name, $backup_file, $exclude, $include) {
746
- global $zip_errors;
747
- $backup_file = escapeshellarg($backup_file);
748
- $sys = substr(PHP_OS, 0, 3);
749
-
750
- //Exclude paths
751
- $exclude_data = "-x";
752
-
753
- $exclude_file_data = '';
754
-
755
- // TODO: Prevent to $exclude include blank string '', beacuse zip 12 error will be occured.
756
- if (!empty($exclude)) {
757
- foreach ($exclude as $data) {
758
- if (is_dir(ABSPATH . $data)) {
759
- if ($sys == 'WIN')
760
- $exclude_data .= " $data/*.*";
761
- else
762
- $exclude_data .= " '$data/*'";
763
- } else {
764
- if ($sys == 'WIN'){
765
- if(file_exists(ABSPATH . $data)){
766
- $exclude_data .= " $data";
767
- $exclude_file_data .= " $data";
768
- }
769
- } else {
770
- if(file_exists(ABSPATH . $data)){
771
- $exclude_data .= " '$data'";
772
- $exclude_file_data .= " '$data'";
773
- }
774
- }
775
- }
776
- }
777
- }
778
-
779
- if($exclude_file_data){
780
- $exclude_file_data = "-x".$exclude_file_data;
781
- }
782
-
783
- //Include paths by default
784
- $add = array(
785
- trim(WPINC),
786
- trim(basename(WP_CONTENT_DIR)),
787
- "wp-admin"
788
- );
789
-
790
- $include_data = ". -i";
791
- foreach ($add as $data) {
792
- if ($sys == 'WIN')
793
- $include_data .= " $data/*.*";
794
- else
795
- $include_data .= " '$data/*'";
796
- }
797
-
798
- //Additional includes?
799
- if (!empty($include) && is_array($include)) {
800
- foreach ($include as $data) {
801
- if(empty($data))
802
- continue;
803
- if ($data) {
804
- if ($sys == 'WIN')
805
- $include_data .= " $data/*.*";
806
- else
807
- $include_data .= " '$data/*'";
808
- }
809
- }
810
- }
811
-
812
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
813
- $comp_level = $disable_comp ? '-0' : '-1';
814
- $zip = $this->get_zip();
815
- chdir(ABSPATH);
816
- ob_start();
817
- $command = "$zip -q -j $comp_level $backup_file .* * $exclude_file_data";
818
- $this->_log("Executing $command");
819
- if($exclude_data==="-x")
820
- {
821
- $exclude_data="";
822
- }
823
- $result_f = $this->mmb_exec($command, false, true);
824
- if (!$result_f || $result_f == 18) { // disregard permissions error, file can't be accessed
825
- $command = "$zip -q -r $comp_level $backup_file $include_data $exclude_data";
826
- $result_d = $this->mmb_exec($command, false, true);
827
- $this->_log("Executing $command");
828
- if ($result_d && $result_d != 18) {
829
- @unlink($backup_file);
830
- if ($result_d > 0 && $result_d < 18)
831
- return array(
832
- 'error' => 'Failed to archive files (' . $zip_errors[$result_d] . ') .'
833
- );
834
- else {
835
- if ($result_d === -1) return false;
836
- return array(
837
- 'error' => 'Failed to archive files.'
838
- );
839
- }
840
- }
841
- } else {
842
- return false;
843
- }
844
-
845
- ob_get_clean();
846
-
847
- return true;
848
- }
849
-
850
- /**
851
- * Zipping whole site root folder and append to backup file with database dump
852
- * by ZipArchive class, requires php zip extension.
853
- *
854
- * @param string $task_name the name of backup task
855
- * @param string $backup_file absolute path to zip file
856
- * @param array $exclude array of files of folders to exclude, relative to site's root
857
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
858
- * @return array|bool true if successful or an array with error message if not
859
- */
860
- function zip_archive_backup($task_name, $backup_file, $exclude, $include, $overwrite = false) {
861
- $filelist = $this->get_backup_files($exclude, $include);
862
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
863
- if (!$disable_comp) {
864
- $this->_log("Compression is not supported by ZipArchive");
865
- }
866
-
867
- $zip = new ZipArchive();
868
- if ($overwrite) {
869
- $result = $zip->open($backup_file, ZipArchive::OVERWRITE); // Tries to open $backup_file for acrhiving
870
- } else {
871
- $result = $zip->open($backup_file); // Tries to open $backup_file for acrhiving
872
- }
873
- if ($result === true) {
874
- foreach ($filelist as $file) {
875
- $result = $result && $zip->addFile($file, sprintf("%s", str_replace(ABSPATH, '', $file))); // Tries to add a new file to $backup_file
876
- }
877
- $result = $result && $zip->close(); // Tries to close $backup_file
878
- } else {
879
- $result = false;
880
- }
881
-
882
- return $result; // true if $backup_file iz zipped successfully, false if error is occured in zip process
883
- }
884
-
885
- /**
886
- * Zipping whole site root folder and append to backup file with database dump
887
- * by PclZip library.
888
- *
889
- * @param string $task_name the name of backup task
890
- * @param string $backup_file absolute path to zip file
891
- * @param array $exclude array of files of folders to exclude, relative to site's root
892
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
893
- * @return array|bool true if successful or an array with error message if not
894
- */
895
- function pclzip_backup($task_name, $backup_file, $exclude, $include) {
896
- define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
897
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
898
- $zip = new PclZip($backup_file);
899
- $add = array(
900
- trim(WPINC),
901
- trim(basename(WP_CONTENT_DIR)),
902
- "wp-admin"
903
- );
904
-
905
- $include_data = array();
906
- if (!empty($include)) {
907
- foreach ($include as $data) {
908
- if ($data && file_exists(ABSPATH . $data))
909
- $include_data[] = ABSPATH . $data . '/';
910
- }
911
- }
912
- $include_data = array_merge($add, $include_data);
913
-
914
- if ($handle = opendir(ABSPATH)) {
915
- while (false !== ($file = readdir($handle))) {
916
- if ($file != "." && $file != ".." && !is_dir($file) && file_exists(ABSPATH . $file)) {
917
- $include_data[] = ABSPATH . $file;
918
- }
919
- }
920
- closedir($handle);
921
- }
922
-
923
- $disable_comp = $this->tasks[$task_name]['task_args']['disable_comp'];
924
-
925
- if ($disable_comp) {
926
- $result = $zip->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH, PCLZIP_OPT_NO_COMPRESSION) !== 0;
927
- } else {
928
- $result = $zip->add($include_data, PCLZIP_OPT_REMOVE_PATH, ABSPATH) !== 0;
929
- }
930
-
931
- $exclude_data = array();
932
- if (!empty($exclude)) {
933
- foreach ($exclude as $data) {
934
- if (file_exists(ABSPATH . $data)) {
935
- if (is_dir(ABSPATH . $data))
936
- $exclude_data[] = $data . '/';
937
- else
938
- $exclude_data[] = $data;
939
- }
940
- }
941
- }
942
- $result = $result && $zip->delete(PCLZIP_OPT_BY_NAME, $exclude_data);
943
-
944
- return $result;
945
- }
946
-
947
- /**
948
- * Gets an array of relative paths of all files in site root recursively.
949
- * By default, there are all files from root folder, all files from folders wp-admin, wp-content, wp-includes recursively.
950
- * Parameter $include adds other folders from site root, and excludes any file or folder by relative path to site's root.
951
- *
952
- * @param array $exclude array of files of folders to exclude, relative to site's root
953
- * @param array $include array of folders from site root which are included to backup (wp-admin, wp-content, wp-includes are default)
954
- * @return array array with all files in site root dir
955
- */
956
- function get_backup_files($exclude, $include) {
957
- $add = array(
958
- trim(WPINC),
959
- trim(basename(WP_CONTENT_DIR)),
960
- "wp-admin"
961
- );
962
-
963
- $include = array_merge($add, $include);
964
-
965
- $filelist = array();
966
- if ($handle = opendir(ABSPATH)) {
967
- while (false !== ($file = readdir($handle))) {
968
- if (is_dir($file) && file_exists(ABSPATH . $file) && !(in_array($file, $include))) {
969
- $exclude[] = $file;
970
- }
971
- }
972
- closedir($handle);
973
- }
974
-
975
- $filelist = get_all_files_from_dir(ABSPATH, $exclude);
976
-
977
- return $filelist;
978
- }
979
-
980
- /**
981
- * Backup a database dump of WordPress site.
982
- * All backups are compressed by zip and placed in wp-content/managewp/backups folder.
983
- *
984
- * @param string $task_name the name of backup task, which backup is done
985
- * @param string $backup_file relative path to file which backup is stored
986
- * @return bool|array true if backup is successful, or an array with error message if is failed
987
- */
988
- function backup_db_compress($task_name, $backup_file) {
989
- $this->update_status($task_name, $this->statuses['db_dump']);
990
- $db_result = $this->backup_db();
991
-
992
- if ($db_result == false) {
993
- return array(
994
- 'error' => 'Failed to backup database.'
995
- );
996
- } else if (is_array($db_result) && isset($db_result['error'])) {
997
- return array(
998
- 'error' => $db_result['error']
999
- );
1000
- }
1001
-
1002
- $this->update_status($task_name, $this->statuses['db_dump'], true);
1003
- $this->update_status($task_name, $this->statuses['db_zip']);
1004
- @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
1005
- $zip_db_result = $this->zip_backup_db($task_name, $backup_file);
1006
-
1007
- if (!$zip_db_result) {
1008
- $zip_archive_db_result = false;
1009
- if (class_exists("ZipArchive")) {
1010
- $this->_log("DB zip, fallback to ZipArchive");
1011
- $zip_archive_db_result = $this->zip_archive_backup_db($task_name, $db_result, $backup_file);
1012
- }
1013
-
1014
- if (!$zip_archive_db_result) {
1015
- $this->_log("DB zip, fallback to PclZip");
1016
- $pclzip_db_result = $this->pclzip_backup_db($task_name, $backup_file);
1017
- if (!$pclzip_db_result) {
1018
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
1019
- @unlink($db_result);
1020
- @rmdir(MWP_DB_DIR);
1021
-
1022
- return array(
1023
- 'error' => 'Failed to zip database. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
1024
- );
1025
- }
1026
- }
1027
- }
1028
-
1029
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
1030
- @unlink($db_result);
1031
- @rmdir(MWP_DB_DIR);
1032
-
1033
- $this->update_status($task_name, $this->statuses['db_zip'], true);
1034
-
1035
- return true;
1036
- }
1037
-
1038
- /**
1039
- * Creates database dump and places it in mwp_db folder in site's root.
1040
- * This function dispatches if OS mysql command does not work calls a php alternative.
1041
- *
1042
- * @return string|array path to dump file if successful, or an array with error message if is failed
1043
- */
1044
- function backup_db() {
1045
- $db_folder = MWP_DB_DIR . '/';
1046
- if (!file_exists($db_folder)) {
1047
- if (!mkdir($db_folder, 0755, true))
1048
- return array(
1049
- 'error' => 'Error creating database backup folder (' . $db_folder . '). Make sure you have correct write permissions.'
1050
- );
1051
- }
1052
-
1053
- $file = $db_folder . DB_NAME . '.sql';
1054
- $result = $this->backup_db_dump($file); // try mysqldump always then fallback to php dump
1055
- return $result;
1056
- }
1057
-
1058
- /**
1059
- * Creates database dump by system mysql command.
1060
- *
1061
- * @param string $file absolute path to file in which dump should be placed
1062
- * @return string|array path to dump file if successful, or an array with error message if is failed
1063
- */
1064
- function backup_db_dump($file) {
1065
- global $wpdb;
1066
- $paths = $this->check_mysql_paths();
1067
- $brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
1068
- //should use --result-file=file_name instead of >
1069
- $host = '--host="';
1070
- $hostname = '';
1071
- $socketname = '';
1072
- if(strpos(DB_HOST,':')!==false)
1073
- {
1074
- $host_sock = explode(':',DB_HOST);
1075
- $hostname = $host_sock[0];
1076
- $socketname = $host_sock[1];
1077
- $port = intval($host_sock[1]);
1078
- if($port===0){
1079
- $command = "%s --force --host=%s --socket=%s --user=%s --password=%s --add-drop-table --skip-lock-tables %s --result-file=%s";
1080
- $command = sprintf($command, $paths['mysqldump'], escapeshellarg($hostname), escapeshellarg($socketname), escapeshellarg(DB_USER), escapeshellarg(DB_PASSWORD), escapeshellarg(DB_NAME),escapeshellarg($file));
1081
-
1082
- }
1083
- else
1084
- {
1085
- $command = "%s --force --host=%s --port=%s --user=%s --password=%s --add-drop-table --skip-lock-tables %s --result-file=%s";
1086
- $command = sprintf($command, $paths['mysqldump'], escapeshellarg($hostname),escapeshellarg($port), escapeshellarg(DB_USER), escapeshellarg(DB_PASSWORD), escapeshellarg(DB_NAME),escapeshellarg($file));
1087
-
1088
- }
1089
- //$command = sprintf($command, $paths['mysqldump'], escapeshellarg($hostname), escapeshellarg($socketname), escapeshellarg(DB_USER), escapeshellarg(DB_PASSWORD), escapeshellarg(DB_NAME),escapeshellarg($file));
1090
- }
1091
- else
1092
- {
1093
- $hostname = DB_HOST;
1094
- $command = "%s --force --host=%s --user=%s --password=%s --add-drop-table --skip-lock-tables %s --result-file=%s";
1095
- $command = sprintf($command, $paths['mysqldump'], escapeshellarg($hostname), escapeshellarg(DB_USER), escapeshellarg(DB_PASSWORD), escapeshellarg(DB_NAME),escapeshellarg($file));
1096
- }
1097
-
1098
-
1099
- //$command = $brace . $paths['mysqldump'] . $brace . ' --force --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --add-drop-table --skip-lock-tables "' . DB_NAME . '" > ' . $brace . $file . $brace;
1100
- ob_start();
1101
- $result = $this->mmb_exec($command);
1102
- ob_get_clean();
1103
-
1104
- if (!$result) { // Fallback to php
1105
- $this->_log("DB dump fallback to php");
1106
- $result = $this->backup_db_php($file);
1107
- return $result;
1108
- }
1109
-
1110
- if (filesize($file) == 0 || !is_file($file) || !$result) {
1111
- @unlink($file);
1112
- return false;
1113
- } else {
1114
- return $file;
1115
- }
1116
- }
1117
-
1118
- /**
1119
- * Creates database dump by php functions.
1120
- *
1121
- * @param string $file absolute path to file in which dump should be placed
1122
- * @return string|array path to dump file if successful, or an array with error message if is failed
1123
- */
1124
- function backup_db_php($file) {
1125
- global $wpdb;
1126
- $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
1127
- foreach ($tables as $table) {
1128
- //drop existing table
1129
- $dump_data = "DROP TABLE IF EXISTS $table[0];";
1130
- file_put_contents($file, $dump_data, FILE_APPEND);
1131
- //create table
1132
- $create_table = $wpdb->get_row("SHOW CREATE TABLE $table[0]", ARRAY_N);
1133
- $dump_data = "\n\n" . $create_table[1] . ";\n\n";
1134
- file_put_contents($file, $dump_data, FILE_APPEND);
1135
-
1136
- $count = $wpdb->get_var("SELECT count(*) FROM $table[0]");
1137
- if ($count > 100)
1138
- $count = ceil($count / 100);
1139
- else if ($count > 0)
1140
- $count = 1;
1141
-
1142
- for ($i = 0; $i < $count; $i++) {
1143
- $low_limit = $i * 100;
1144
- $qry = "SELECT * FROM $table[0] LIMIT $low_limit, 100";
1145
- $rows = $wpdb->get_results($qry, ARRAY_A);
1146
- if (is_array($rows)) {
1147
- foreach ($rows as $row) {
1148
- //insert single row
1149
- $dump_data = "INSERT INTO $table[0] VALUES(";
1150
- $num_values = count($row);
1151
- $j = 1;
1152
- foreach ($row as $value) {
1153
- $value = addslashes($value);
1154
- $value = preg_replace("/\n/Ui", "\\n", $value);
1155
- $num_values == $j ? $dump_data .= "'" . $value . "'" : $dump_data .= "'" . $value . "', ";
1156
- $j++;
1157
- unset($value);
1158
- }
1159
- $dump_data .= ");\n";
1160
- file_put_contents($file, $dump_data, FILE_APPEND);
1161
- }
1162
- }
1163
- }
1164
- $dump_data = "\n\n\n";
1165
- file_put_contents($file, $dump_data, FILE_APPEND);
1166
-
1167
- unset($rows);
1168
- unset($dump_data);
1169
- }
1170
-
1171
- if (filesize($file) == 0 || !is_file($file)) {
1172
- @unlink($file);
1173
- return array(
1174
- 'error' => 'Database backup failed. Try to enable MySQL dump on your server.'
1175
- );
1176
- }
1177
-
1178
- return $file;
1179
- }
1180
-
1181
- /**
1182
- * Restores full WordPress site or database only form backup zip file.
1183
- *
1184
- * @param array array of arguments passed to backup restore
1185
- * [task_name] -> name of backup task
1186
- * [result_id] -> id of baskup task result, which should be restored
1187
- * [google_drive_token] -> json of Google Drive token, if it is remote destination
1188
- * @return bool|array true if successful, or an array with error message if is failed
1189
- */
1190
- function restore($args) {
1191
- global $wpdb;
1192
- if (empty($args)) {
1193
- return false;
1194
- }
1195
- extract($args);
1196
- if (isset($google_drive_token)) {
1197
- $this->tasks[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $google_drive_token;
1198
- }
1199
- $this->set_memory();
1200
-
1201
- $unlink_file = true; //Delete file after restore
1202
-
1203
- //Detect source
1204
- if ($backup_url) {
1205
- //This is for clone (overwrite)
1206
- include_once ABSPATH . 'wp-admin/includes/file.php';
1207
- $backup_file = download_url($backup_url);
1208
- if (is_wp_error($backup_file)) {
1209
- return array(
1210
- 'error' => 'Unable to download backup file ('.$backup_file->get_error_message().')'
1211
- );
1212
- }
1213
- $what = 'full';
1214
- } else {
1215
- $tasks = $this->tasks;
1216
- $task_name = stripslashes($task_name);
1217
- $task = $tasks[$task_name];
1218
- if (isset($task['task_results'][$result_id]['server'])) {
1219
- $backup_file = $task['task_results'][$result_id]['server']['file_path'];
1220
- $unlink_file = false; //Don't delete file if stored on server
1221
- } elseif (isset($task['task_results'][$result_id]['ftp'])) {
1222
- $ftp_file = $task['task_results'][$result_id]['ftp'];
1223
- $args = $task['task_args']['account_info']['mwp_ftp'];
1224
- $args['backup_file'] = $ftp_file;
1225
- $backup_file = $this->get_ftp_backup($args);
1226
-
1227
- if ($backup_file == false) {
1228
- return array(
1229
- 'error' => 'Failed to download file from FTP.'
1230
- );
1231
- }
1232
- }elseif (isset($task['task_results'][$result_id]['sftp'])) {
1233
- $ftp_file = $task['task_results'][$result_id]['sftp'];
1234
- $args = $task['task_args']['account_info']['mwp_sftp'];
1235
- $args['backup_file'] = $ftp_file;
1236
- $backup_file = $this->get_sftp_backup($args);
1237
-
1238
- if ($backup_file == false) {
1239
- return array(
1240
- 'error' => 'Failed to download file from SFTP.'
1241
- );
1242
- }
1243
- }
1244
-
1245
- elseif (isset($task['task_results'][$result_id]['amazons3'])) {
1246
- $amazons3_file = $task['task_results'][$result_id]['amazons3'];
1247
- $args = $task['task_args']['account_info']['mwp_amazon_s3'];
1248
- $args['backup_file'] = $amazons3_file;
1249
- $backup_file = $this->get_amazons3_backup($args);
1250
-
1251
- if ($backup_file == false) {
1252
- return array(
1253
- 'error' => 'Failed to download file from Amazon S3.'
1254
- );
1255
- }
1256
- } elseif(isset($task['task_results'][$result_id]['dropbox'])){
1257
- $dropbox_file = $task['task_results'][$result_id]['dropbox'];
1258
- $args = $task['task_args']['account_info']['mwp_dropbox'];
1259
- $args['backup_file'] = $dropbox_file;
1260
- $backup_file = $this->get_dropbox_backup($args);
1261
-
1262
- if ($backup_file == false) {
1263
- return array(
1264
- 'error' => 'Failed to download file from Dropbox.'
1265
- );
1266
- }
1267
- } elseif (isset($task['task_results'][$result_id]['google_drive'])) {
1268
- $google_drive_file = $task['task_results'][$result_id]['google_drive'];
1269
- $args = $task['task_args']['account_info']['mwp_google_drive'];
1270
- $args['backup_file'] = $google_drive_file;
1271
- $backup_file = $this->get_google_drive_backup($args);
1272
-
1273
- if (is_array($backup_file) && isset($backup_file['error'])) {
1274
- return array(
1275
- 'error' => 'Failed to download file from Google Drive, reason: ' . $backup_file['error']
1276
- );
1277
- } elseif ($backup_file == false) {
1278
- return array(
1279
- 'error' => 'Failed to download file from Google Drive.'
1280
- );
1281
- }
1282
- }
1283
-
1284
- $what = $tasks[$task_name]['task_args']['what'];
1285
- }
1286
-
1287
- $this->wpdb_reconnect();
1288
-
1289
- if ($backup_file && file_exists($backup_file)) {
1290
- if ($overwrite) {
1291
- //Keep old db credentials before overwrite
1292
- if (!copy(ABSPATH . 'wp-config.php', ABSPATH . 'mwp-temp-wp-config.php')) {
1293
- @unlink($backup_file);
1294
- return array(
1295
- 'error' => 'Error creating wp-config file.
1296
- Please check if your WordPress installation folder has correct permissions to allow writing files.
1297
- In most cases permissions should be 755 but occasionally it\'s required to put 777.
1298
- If you are unsure on how to do this yourself, you can ask your hosting provider for help.'
1299
- );
1300
- }
1301
-
1302
- $db_host = DB_HOST;
1303
- $db_user = DB_USER;
1304
- $db_password = DB_PASSWORD;
1305
- $home = rtrim(get_option('home'), "/");
1306
- $site_url = get_option('site_url');
1307
-
1308
- $clone_options = array();
1309
- if (trim($clone_from_url) || trim($mwp_clone)) {
1310
- $clone_options['_worker_nossl_key'] = get_option('_worker_nossl_key');
1311
- $clone_options['_worker_public_key'] = get_option('_worker_public_key');
1312
- $clone_options['_action_message_id'] = get_option('_action_message_id');
1313
- }
1314
- $clone_options['upload_path'] = get_option('upload_path');
1315
- $clone_options['upload_url_path'] = get_option('upload_url_path');
1316
-
1317
-
1318
- $clone_options['mwp_backup_tasks'] = maybe_serialize(get_option('mwp_backup_tasks'));
1319
- $clone_options['mwp_notifications'] = maybe_serialize(get_option('mwp_notifications'));
1320
- $clone_options['mwp_pageview_alerts'] = maybe_serialize(get_option('mwp_pageview_alerts'));
1321
- } else {
1322
- $restore_options = array();
1323
- $restore_options['mwp_notifications'] = get_option('mwp_notifications');
1324
- $restore_options['mwp_pageview_alerts'] = get_option('mwp_pageview_alerts');
1325
- $restore_options['user_hit_count'] = get_option('user_hit_count');
1326
- $restore_options['mwp_backup_tasks'] = get_option('mwp_backup_tasks');
1327
- }
1328
-
1329
- chdir(ABSPATH);
1330
- $unzip = $this->get_unzip();
1331
- $command = "$unzip -o $backup_file";
1332
- ob_start();
1333
- $result = $this->mmb_exec($command);
1334
- ob_get_clean();
1335
-
1336
- if (!$result) { //fallback to pclzip
1337
- $this->_log("Files uznip fallback to pclZip");
1338
- define('PCLZIP_TEMPORARY_DIR', MWP_BACKUP_DIR . '/');
1339
- require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
1340
- $archive = new PclZip($backup_file);
1341
- $result = $archive->extract(PCLZIP_OPT_PATH, ABSPATH, PCLZIP_OPT_REPLACE_NEWER);
1342
- }
1343
-
1344
- if ($unlink_file) {
1345
- @unlink($backup_file);
1346
- }
1347
-
1348
- if (!$result) {
1349
- return array(
1350
- 'error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string
1351
- );
1352
- }
1353
-
1354
- $db_result = $this->restore_db();
1355
-
1356
- if (!$db_result) {
1357
- return array(
1358
- 'error' => 'Error restoring database.'
1359
- );
1360
- } else if(is_array($db_result) && isset($db_result['error'])){
1361
- return array(
1362
- 'error' => $db_result['error']
1363
- );
1364
- }
1365
-
1366
- } else {
1367
- return array(
1368
- 'error' => 'Error restoring. Cannot find backup file.'
1369
- );
1370
- }
1371
-
1372
- $this->wpdb_reconnect();
1373
-
1374
- //Replace options and content urls
1375
- if ($overwrite) {
1376
- //Get New Table prefix
1377
- $new_table_prefix = trim($this->get_table_prefix());
1378
- //Retrieve old wp_config
1379
- @unlink(ABSPATH . 'wp-config.php');
1380
- //Replace table prefix
1381
- $lines = file(ABSPATH . 'mwp-temp-wp-config.php');
1382
-
1383
- foreach ($lines as $line) {
1384
- if (strstr($line, '$table_prefix')) {
1385
- $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
1386
- }
1387
- file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
1388
- }
1389
-
1390
- @unlink(ABSPATH . 'mwp-temp-wp-config.php');
1391
-
1392
- //Replace options
1393
- $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
1394
- $old = $wpdb->get_var($query);
1395
- $old = rtrim($old, "/");
1396
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
1397
- $wpdb->query($wpdb->prepare($query, $home));
1398
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'siteurl'";
1399
- $wpdb->query($wpdb->prepare($query, $home));
1400
- //Replace content urls
1401
- $regexp1 = 'src="(.*)$old(.*)"';
1402
- $regexp2 = 'href="(.*)$old(.*)"';
1403
- $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
1404
- $wpdb->query($wpdb->prepare($query, array($old, $home, $regexp1, $regexp2)));
1405
-
1406
- if (trim($new_password)) {
1407
- $new_password = wp_hash_password($new_password);
1408
- }
1409
- if (!trim($clone_from_url) && !trim($mwp_clone)) {
1410
- if ($new_user && $new_password) {
1411
- $query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
1412
- $wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
1413
- }
1414
- } else {
1415
- if ($clone_from_url) {
1416
- if ($new_user && $new_password) {
1417
- $query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
1418
- $wpdb->query($wpdb->prepare($query, $new_password, $new_user));
1419
- }
1420
- }
1421
-
1422
- if ($mwp_clone) {
1423
- if ($admin_email) {
1424
- //Clean Install
1425
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
1426
- $wpdb->query($wpdb->prepare($query, $admin_email));
1427
- $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
1428
- $temp_user = $wpdb->get_row($query);
1429
- if (!empty($temp_user)) {
1430
- $query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
1431
- $wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
1432
- }
1433
-
1434
- }
1435
- }
1436
- }
1437
-
1438
- if (is_array($clone_options) && !empty($clone_options)) {
1439
- foreach ($clone_options as $key => $option) {
1440
- if (!empty($key)) {
1441
- $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = %s";
1442
- $res = $wpdb->get_var($wpdb->prepare($query, $key));
1443
- if ($res == false) {
1444
- $query = "INSERT INTO " . $new_table_prefix . "options (option_value,option_name) VALUES(%s,%s)";
1445
- $wpdb->query($wpdb->prepare($query, $option, $key));
1446
- } else {
1447
- $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = %s";
1448
- $wpdb->query($wpdb->prepare($query, $option, $key));
1449
- }
1450
- }
1451
- }
1452
- }
1453
-
1454
- //Remove hit count
1455
- $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'user_hit_count'";
1456
- $wpdb->query($query);
1457
-
1458
- //Restore previous backups
1459
-
1460
- $wpdb->query("UPDATE " . $new_table_prefix . "options SET option_value = ".serialize($current_tasks_tmp)." WHERE option_name = 'mwp_backup_tasks'");
1461
-
1462
- //Check for .htaccess permalinks update
1463
- $this->replace_htaccess($home);
1464
- } else {
1465
- //restore worker options
1466
- if (is_array($restore_options) && !empty($restore_options)) {
1467
- foreach ($restore_options as $key => $option) {
1468
- $result = $wpdb->update( $wpdb->options, array( 'option_value' => maybe_serialize($option) ), array( 'option_name' => $key ) );
1469
- }
1470
- }
1471
- }
1472
-
1473
- return true;
1474
- }
1475
-
1476
- /**
1477
- * This function dispathces database restoring between mysql system command and php functions.
1478
- * If system command fails, it calls the php alternative.
1479
- *
1480
- * @return bool|array true if successful, array with error message if not
1481
- */
1482
- function restore_db() {
1483
- global $wpdb;
1484
- $paths = $this->check_mysql_paths();
1485
- $file_path = ABSPATH . 'mwp_db';
1486
- @chmod($file_path,0755);
1487
- $file_name = glob($file_path . '/*.sql');
1488
- $file_name = $file_name[0];
1489
-
1490
- if(!$file_name){
1491
- return array('error' => 'Cannot access database file.');
1492
- }
1493
-
1494
- $port = 0;
1495
- $host = DB_HOST;
1496
-
1497
- if (strpos($host, ':') !== false){
1498
- list($host, $port) = explode(':', $host);
1499
- }
1500
- $socket = false;
1501
-
1502
- if (strpos($host, '/') !== false || strpos($host, '\\') !== false) {
1503
- $socket = true;
1504
- }
1505
-
1506
- if ($socket) {
1507
- $connection = sprintf('--socket=%s', escapeshellarg($host));
1508
- } else {
1509
- $connection = sprintf('--host=%s --port=%s', escapeshellarg($host), escapeshellarg($port));
1510
- }
1511
-
1512
- $command = "%s %s --user=%s --password=%s --default-character-set=%s %s < %s";
1513
- $command = sprintf($command, escapeshellarg($paths['mysql']), $connection, escapeshellarg(DB_USER), escapeshellarg(DB_PASSWORD), escapeshellarg('utf8'), escapeshellarg(DB_NAME), escapeshellarg($file_name));
1514
-
1515
- ob_start();
1516
- $result = $this->mmb_exec($command);
1517
- ob_get_clean();
1518
- if (!$result) {
1519
- $this->_log('DB restore fallback to PHP');
1520
- //try php
1521
- return $this->restore_db_php($file_name);
1522
- }
1523
- @unlink($file_name);
1524
- return true;
1525
- }
1526
-
1527
- /**
1528
- * Restores database dump by php functions.
1529
- *
1530
- * @param string $file_name relative path to database dump, which should be restored
1531
- * @return bool is successful or not
1532
- */
1533
- function restore_db_php($file_name) {
1534
- global $wpdb;
1535
- $current_query = '';
1536
- // Read in entire file
1537
- $lines = file($file_name);
1538
- // Loop through each line
1539
- foreach ($lines as $line) {
1540
- // Skip it if it's a comment
1541
- if (substr($line, 0, 2) == '--' || $line == '')
1542
- continue;
1543
-
1544
- // Add this line to the current query
1545
- $current_query .= $line;
1546
- // If it has a semicolon at the end, it's the end of the query
1547
- if (substr(trim($line), -1, 1) == ';') {
1548
- // Perform the query
1549
- $result = $wpdb->query($current_query);
1550
- if ($result === false)
1551
- return false;
1552
- // Reset temp variable to empty
1553
- $current_query = '';
1554
- }
1555
- }
1556
-
1557
- @unlink($file_name);
1558
- return true;
1559
- }
1560
-
1561
- /**
1562
- * Retruns table_prefix for this WordPress installation.
1563
- * It is used by restore.
1564
- *
1565
- * @return string table prefix from wp-config.php file, (default: wp_)
1566
- */
1567
- function get_table_prefix() {
1568
- $lines = file(ABSPATH . 'wp-config.php');
1569
- foreach ($lines as $line) {
1570
- if (strstr($line, '$table_prefix')) {
1571
- $pattern = "/(\'|\")[^(\'|\")]*/";
1572
- preg_match($pattern, $line, $matches);
1573
- $prefix = substr($matches[0], 1);
1574
- return $prefix;
1575
- break;
1576
- }
1577
- }
1578
- return 'wp_'; //default
1579
- }
1580
-
1581
- /**
1582
- * Change all tables to InnoDB engine, and executes mysql OPTIMIZE TABLE for each table.
1583
- *
1584
- * @return bool optimized successfully or not
1585
- */
1586
- function optimize_tables()
1587
- {
1588
- global $wpdb;
1589
- $query = 'SHOW TABLE STATUS';
1590
- $tables = $wpdb->get_results($query, ARRAY_A);
1591
- $table_string = '';
1592
- foreach ($tables as $table) {
1593
- $table_string .= $table['Name'] . ",";
1594
- }
1595
- $table_string = rtrim($table_string, ",");
1596
- $optimize = $wpdb->query("OPTIMIZE TABLE $table_string");
1597
-
1598
- return (bool)$optimize;
1599
-
1600
- }
1601
-
1602
- /**
1603
- * Returns mysql and mysql dump command path on OS.
1604
- *
1605
- * @return array array with system mysql and mysqldump command, blank if does not exist
1606
- */
1607
- function check_mysql_paths() {
1608
- global $wpdb;
1609
- $paths = array(
1610
- 'mysql' => '',
1611
- 'mysqldump' => ''
1612
- );
1613
- if (substr(PHP_OS, 0, 3) == 'WIN') {
1614
- $mysql_install = $wpdb->get_row("SHOW VARIABLES LIKE 'basedir'");
1615
- if ($mysql_install) {
1616
- $install_path = str_replace('\\', '/', $mysql_install->Value);
1617
- $paths['mysql'] = $install_path . 'bin/mysql.exe';
1618
- $paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
1619
- } else {
1620
- $paths['mysql'] = 'mysql.exe';
1621
- $paths['mysqldump'] = 'mysqldump.exe';
1622
- }
1623
- } else {
1624
- $paths['mysql'] = $this->mmb_exec('which mysql', true);
1625
- if (empty($paths['mysql']))
1626
- $paths['mysql'] = 'mysql'; // try anyway
1627
-
1628
- $paths['mysqldump'] = $this->mmb_exec('which mysqldump', true);
1629
- if (empty($paths['mysqldump'])){
1630
- $paths['mysqldump'] = 'mysqldump'; // try anyway
1631
- $baseDir = $wpdb->get_var('select @@basedir');
1632
- if ($baseDir) {
1633
- $paths['mysqldump'] = $baseDir.'/bin/mysqldump';
1634
- }
1635
- }
1636
- }
1637
-
1638
- return $paths;
1639
- }
1640
-
1641
- /**
1642
- * Check if exec, system, passthru functions exist
1643
- *
1644
- * @return string|bool exec if exists, then system, then passthru, then false if no one exist
1645
- */
1646
- function check_sys() {
1647
- if ($this->mmb_function_exists('exec'))
1648
- return 'exec';
1649
-
1650
- if ($this->mmb_function_exists('system'))
1651
- return 'system';
1652
-
1653
- if ($this->mmb_function_exists('passhtru'))
1654
- return 'passthru';
1655
-
1656
- return false;
1657
- }
1658
-
1659
- /**
1660
- * Executes an external system command.
1661
- *
1662
- * @param string $command external command to execute
1663
- * @param bool[optional] $string return as a system output string (default: false)
1664
- * @param bool[optional] $rawreturn return as a status of executed command
1665
- * @return bool|int|string output depends on parameters $string and $rawreturn, -1 if no one execute function is enabled
1666
- */
1667
- function mmb_exec($command, $string = false, $rawreturn = false) {
1668
- if ($command == '')
1669
- return false;
1670
-
1671
- if ($this->mmb_function_exists('exec')) {
1672
- $log = @exec($command, $output, $return);
1673
- $this->_log("Type: exec");
1674
- $this->_log("Command: ".$command);
1675
- $this->_log("Return: ".$return);
1676
- if ($string)
1677
- return $log;
1678
- if ($rawreturn)
1679
- return $return;
1680
-
1681
- return $return ? false : true;
1682
- } elseif ($this->mmb_function_exists('system')) {
1683
- $log = @system($command, $return);
1684
- $this->_log("Type: system");
1685
- $this->_log("Command: ".$command);
1686
- $this->_log("Return: ".$return);
1687
- if ($string)
1688
- return $log;
1689
-
1690
- if ($rawreturn)
1691
- return $return;
1692
-
1693
- return $return ? false : true;
1694
- } elseif ($this->mmb_function_exists('passthru') && !$string) {
1695
- $log = passthru($command, $return);
1696
- $this->_log("Type: passthru");
1697
- $this->_log("Command: ".$command);
1698
- $this->_log("Return: ".$return);
1699
- if ($rawreturn)
1700
- return $return;
1701
-
1702
- return $return ? false : true;
1703
- }
1704
-
1705
- if ($rawreturn)
1706
- return -1;
1707
-
1708
- return false;
1709
- }
1710
-
1711
- /**
1712
- * Returns a path to system command for zip execution.
1713
- *
1714
- * @return string command for zip execution
1715
- */
1716
- function get_zip() {
1717
- $zip = $this->mmb_exec('which zip', true);
1718
- if (!$zip)
1719
- $zip = "zip";
1720
- return $zip;
1721
- }
1722
-
1723
- /**
1724
- * Returns a path to system command for unzip execution.
1725
- *
1726
- * @return string command for unzip execution
1727
- */
1728
- function get_unzip() {
1729
- $unzip = $this->mmb_exec('which unzip', true);
1730
- if (!$unzip)
1731
- $unzip = "unzip";
1732
- return $unzip;
1733
- }
1734
-
1735
- /**
1736
- * Returns all important information of worker's system status to master.
1737
- *
1738
- * @return mixed associative array with information of server OS, php version, is backup folder writable, execute function, zip and unzip command, execution time, memory limit and path to error log if exists
1739
- */
1740
- function check_backup_compat() {
1741
- $reqs = array();
1742
- if (strpos($_SERVER['DOCUMENT_ROOT'], '/') === 0) {
1743
- $reqs['Server OS']['status'] = 'Linux (or compatible)';
1744
- $reqs['Server OS']['pass'] = true;
1745
- } else {
1746
- $reqs['Server OS']['status'] = 'Windows';
1747
- $reqs['Server OS']['pass'] = true;
1748
- $pass = false;
1749
- }
1750
- $reqs['PHP Version']['status'] = phpversion();
1751
- if ((float) phpversion() >= 5.1) {
1752
- $reqs['PHP Version']['pass'] = true;
1753
- } else {
1754
- $reqs['PHP Version']['pass'] = false;
1755
- $pass = false;
1756
- }
1757
-
1758
- if (is_writable(WP_CONTENT_DIR)) {
1759
- $reqs['Backup Folder']['status'] = "writable";
1760
- $reqs['Backup Folder']['pass'] = true;
1761
- } else {
1762
- $reqs['Backup Folder']['status'] = "not writable";
1763
- $reqs['Backup Folder']['pass'] = false;
1764
- }
1765
-
1766
- $file_path = MWP_BACKUP_DIR;
1767
- $reqs['Backup Folder']['status'] .= ' (' . $file_path . ')';
1768
-
1769
- if ($func = $this->check_sys()) {
1770
- $reqs['Execute Function']['status'] = $func;
1771
- $reqs['Execute Function']['pass'] = true;
1772
- } else {
1773
- $reqs['Execute Function']['status'] = "not found";
1774
- $reqs['Execute Function']['info'] = "(will try PHP replacement)";
1775
- $reqs['Execute Function']['pass'] = false;
1776
- }
1777
-
1778
- $reqs['Zip']['status'] = $this->get_zip();
1779
- $reqs['Zip']['pass'] = true;
1780
- $reqs['Unzip']['status'] = $this->get_unzip();
1781
- $reqs['Unzip']['pass'] = true;
1782
-
1783
- $paths = $this->check_mysql_paths();
1784
-
1785
- if (!empty($paths['mysqldump'])) {
1786
- $reqs['MySQL Dump']['status'] = $paths['mysqldump'];
1787
- $reqs['MySQL Dump']['pass'] = true;
1788
- } else {
1789
- $reqs['MySQL Dump']['status'] = "not found";
1790
- $reqs['MySQL Dump']['info'] = "(will try PHP replacement)";
1791
- $reqs['MySQL Dump']['pass'] = false;
1792
- }
1793
-
1794
- $exec_time = ini_get('max_execution_time');
1795
- $reqs['Execution time']['status'] = $exec_time ? $exec_time . "s" : 'unknown';
1796
- $reqs['Execution time']['pass'] = true;
1797
-
1798
- $mem_limit = ini_get('memory_limit');
1799
- $reqs['Memory limit']['status'] = $mem_limit ? $mem_limit : 'unknown';
1800
- $reqs['Memory limit']['pass'] = true;
1801
-
1802
- $changed = $this->set_memory();
1803
- if($changed['execution_time']){
1804
- $exec_time = ini_get('max_execution_time');
1805
- $reqs['Execution time']['status'] .= $exec_time ? ' (will try '.$exec_time . 's)' : ' (unknown)';
1806
- }
1807
- if($changed['memory_limit']){
1808
- $mem_limit = ini_get('memory_limit');
1809
- $reqs['Memory limit']['status'] .= $mem_limit ? ' (will try '.$mem_limit.')' : ' (unknown)';
1810
- }
1811
-
1812
- if(defined('MWP_SHOW_LOG') && MWP_SHOW_LOG == true){
1813
- $md5 = get_option('mwp_log_md5');
1814
- if ($md5 !== false) {
1815
- global $mmb_plugin_url;
1816
- $md5 = "<a href='$mmb_plugin_url/log_$md5' target='_blank'>$md5</a>";
1817
- } else {
1818
- $md5 = "not created";
1819
- }
1820
- $reqs['Backup Log']['status'] = $md5;
1821
- $reqs['Backup Log']['pass'] = true;
1822
- }
1823
-
1824
- return $reqs;
1825
- }
1826
-
1827
- /**
1828
- * Uploads backup file from server to email.
1829
- * A lot of email service have limitation to 10mb.
1830
- *
1831
- * @param array $args arguments passed to the function
1832
- * [email] -> email address which backup should send to
1833
- * [task_name] -> name of backup task
1834
- * [file_path] -> absolute path of backup file on local server
1835
- * @return bool|array true is successful, array with error message if not
1836
- */
1837
- function email_backup($args) {
1838
- $email = $args['email'];
1839
-
1840
- if (!is_email($email)) {
1841
- return array(
1842
- 'error' => 'Your email (' . $email . ') is not correct'
1843
- );
1844
- }
1845
- $backup_file = $args['file_path'];
1846
- $task_name = isset($args['task_name']) ? $args['task_name'] : '';
1847
- if (file_exists($backup_file) && $email) {
1848
- $attachments = array(
1849
- $backup_file
1850
- );
1851
- $headers = 'From: ManageWP <no-reply@managewp.com>' . "\r\n";
1852
- $subject = "ManageWP - " . $task_name . " - " . $this->site_name;
1853
- ob_start();
1854
- $result = wp_mail($email, $subject, $subject, $headers, $attachments);
1855
- ob_end_clean();
1856
-
1857
- }
1858
-
1859
- if (!$result) {
1860
- return array(
1861
- 'error' => 'Email not sent. Maybe your backup is too big for email or email server is not available on your website.'
1862
- );
1863
- }
1864
- return true;
1865
- }
1866
-
1867
- /**
1868
- * Uploads backup file from server to remote sftp server.
1869
- *
1870
- * @param array $args arguments passed to the function
1871
- * [sftp_username] -> sftp username on remote server
1872
- * [sftp_password] -> sftp password on remote server
1873
- * [sftp_hostname] -> sftp hostname of remote host
1874
- * [sftp_remote_folder] -> folder on remote site which backup file should be upload to
1875
- * [sftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be upload to
1876
- * [sftp_passive] -> passive mode or not
1877
- * [sftp_ssl] -> ssl or not
1878
- * [sftp_port] -> number of port for ssl protocol
1879
- * [backup_file] -> absolute path of backup file on local server
1880
- * @return bool|array true is successful, array with error message if not
1881
- */
1882
- function sftp_backup($args) {
1883
- extract($args);
1884
- // file_put_contents("sftp_log.txt","sftp_backup",FILE_APPEND);
1885
- $port = $sftp_port ? $sftp_port : 22; //default port is 22
1886
- // file_put_contents("sftp_log.txt","sftp port:".$sftp_port,FILE_APPEND);
1887
- $sftp_hostname = $sftp_hostname?$sftp_hostname:"";
1888
- // file_put_contents("sftp_log.txt","sftp host:".$sftp_hostname,FILE_APPEND);
1889
- $sftp_username = $sftp_username?$sftp_username:"";
1890
- // file_put_contents("sftp_log.txt","sftp user:".$sftp_username,FILE_APPEND);
1891
- $sftp_password = $sftp_password?$sftp_password:"";
1892
- // file_put_contents("sftp_log.txt","sftp pass:".$sftp_password,FILE_APPEND);
1893
- // file_put_contents("sftp_log.txt","Creating NetSFTP",FILE_APPEND);
1894
- $sftp = new Net_SFTP($sftp_hostname,$port);
1895
- // file_put_contents("sftp_log.txt","Created NetSFTP",FILE_APPEND);
1896
- $remote = $sftp_remote_folder ? trim($sftp_remote_folder,"/")."/" : '';
1897
- if (!$sftp->login($sftp_username, $sftp_password)) {
1898
- file_put_contents("sftp_log.txt","sftp login failed in sftp_backup",FILE_APPEND);
1899
- return array(
1900
- 'error' => 'SFTP login failed for ' . $sftp_username . ', ' . $sftp_password,
1901
- 'partial' => 1
1902
- );
1903
- }
1904
- file_put_contents("sftp_log.txt","making remote dir",FILE_APPEND);
1905
- $sftp->mkdir($remote);
1906
- file_put_contents("sftp_log.txt","made remote dir",FILE_APPEND);
1907
- if ($sftp_site_folder) {
1908
- $remote .= '/' . $this->site_name;
1909
- }
1910
- $sftp->mkdir($remote);
1911
- file_put_contents("sftp_log.txt","making {$sftp_remote_folder} dir",FILE_APPEND);
1912
- $sftp->mkdir($sftp_remote_folder);
1913
- file_put_contents("sftp_log.txt","made {$sftp_remote_folder} dir",FILE_APPEND);
1914
- file_put_contents("sftp_log.txt","starting upload",FILE_APPEND);
1915
- $upload = $sftp->put( $remote.'/' . basename($backup_file),$backup_file, NET_SFTP_LOCAL_FILE);
1916
- file_put_contents("sftp_log.txt","finish upload",FILE_APPEND);
1917
- $sftp->disconnect();
1918
-
1919
- if ($upload === false) {
1920
- file_put_contents("sftp_log.txt","sftp upload failed",FILE_APPEND);
1921
- return array(
1922
- 'error' => 'Failed to upload file to SFTP. Please check your specified path.',
1923
- 'partial' => 1
1924
- );
1925
- }
1926
-
1927
- return true;
1928
- }
1929
-
1930
-
1931
-
1932
- /**
1933
- * Uploads backup file from server to remote ftp server.
1934
- *
1935
- * @param array $args arguments passed to the function
1936
- * [ftp_username] -> ftp username on remote server
1937
- * [ftp_password] -> ftp password on remote server
1938
- * [ftp_hostname] -> ftp hostname of remote host
1939
- * [ftp_remote_folder] -> folder on remote site which backup file should be upload to
1940
- * [ftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be upload to
1941
- * [ftp_passive] -> passive mode or not
1942
- * [ftp_ssl] -> ssl or not
1943
- * [ftp_port] -> number of port for ssl protocol
1944
- * [backup_file] -> absolute path of backup file on local server
1945
- * @return bool|array true is successful, array with error message if not
1946
- */
1947
- function ftp_backup($args) {
1948
- extract($args);
1949
-
1950
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
1951
- if ($ftp_ssl) {
1952
- if (function_exists('ftp_ssl_connect')) {
1953
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
1954
- if ($conn_id === false) {
1955
- return array(
1956
- 'error' => 'Failed to connect to ' . $ftp_hostname,
1957
- 'partial' => 1
1958
- );
1959
- }
1960
- } else {
1961
- return array(
1962
- 'error' => 'FTPS disabled: Please enable ftp_ssl_connect in PHP',
1963
- 'partial' => 1
1964
- );
1965
- }
1966
- } else {
1967
- if (function_exists('ftp_connect')) {
1968
- $conn_id = ftp_connect($ftp_hostname,$port);
1969
- if ($conn_id === false) {
1970
- return array(
1971
- 'error' => 'Failed to connect to ' . $ftp_hostname,
1972
- 'partial' => 1
1973
- );
1974
- }
1975
- } else {
1976
- return array(
1977
- 'error' => 'FTP disabled: Please enable ftp_connect in PHP',
1978
- 'partial' => 1
1979
- );
1980
- }
1981
- }
1982
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
1983
- if ($login === false) {
1984
- return array(
1985
- 'error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password,
1986
- 'partial' => 1
1987
- );
1988
- }
1989
-
1990
- if($ftp_passive){
1991
- @ftp_pasv($conn_id,true);
1992
- }
1993
-
1994
- @ftp_mkdir($conn_id, $ftp_remote_folder);
1995
- if ($ftp_site_folder) {
1996
- $ftp_remote_folder .= '/' . $this->site_name;
1997
- }
1998
- @ftp_mkdir($conn_id, $ftp_remote_folder);
1999
-
2000
- $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_BINARY);
2001
-
2002
- if ($upload === false) { //Try ascii
2003
- $upload = @ftp_put($conn_id, $ftp_remote_folder . '/' . basename($backup_file), $backup_file, FTP_ASCII);
2004
- }
2005
- @ftp_close($conn_id);
2006
-
2007
- if ($upload === false) {
2008
- return array(
2009
- 'error' => 'Failed to upload file to FTP. Please check your specified path.',
2010
- 'partial' => 1
2011
- );
2012
- }
2013
-
2014
- return true;
2015
- }
2016
-
2017
- /**
2018
- * Deletes backup file from remote ftp server.
2019
- *
2020
- * @param array $args arguments passed to the function
2021
- * [ftp_username] -> ftp username on remote server
2022
- * [ftp_password] -> ftp password on remote server
2023
- * [ftp_hostname] -> ftp hostname of remote host
2024
- * [ftp_remote_folder] -> folder on remote site which backup file should be deleted from
2025
- * [ftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be deleted from
2026
- * [backup_file] -> absolute path of backup file on local server
2027
- * @return void
2028
- */
2029
- function remove_ftp_backup($args) {
2030
- extract($args);
2031
-
2032
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
2033
- if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2034
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2035
- } else if (function_exists('ftp_connect')) {
2036
- $conn_id = ftp_connect($ftp_hostname,$port);
2037
- }
2038
-
2039
- if ($conn_id) {
2040
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2041
- if ($ftp_site_folder)
2042
- $ftp_remote_folder .= '/' . $this->site_name;
2043
-
2044
- if($ftp_passive){
2045
- @ftp_pasv($conn_id,true);
2046
- }
2047
-
2048
- $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $backup_file);
2049
-
2050
- ftp_close($conn_id);
2051
- }
2052
- }
2053
- /**
2054
- * Deletes backup file from remote sftp server.
2055
- *
2056
- * @param array $args arguments passed to the function
2057
- * [sftp_username] -> sftp username on remote server
2058
- * [sftp_password] -> sftp password on remote server
2059
- * [sftp_hostname] -> sftp hostname of remote host
2060
- * [sftp_remote_folder] -> folder on remote site which backup file should be deleted from
2061
- * [sftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be deleted from
2062
- * [backup_file] -> absolute path of backup file on local server
2063
- * @return void
2064
- */
2065
- function remove_sftp_backup($args) {
2066
- extract($args);
2067
- file_put_contents("sftp_log.txt","sftp remove_sftp_backup",FILE_APPEND);
2068
- $port = $sftp_port ? $sftp_port : 22; //default port is 21
2069
- $sftp_hostname = $sftp_hostname?$sftp_hostname:"";
2070
- $sftp_username = $sftp_username?$sftp_username:"";
2071
- $sftp_password = $sftp_password?$sftp_password:"";
2072
- $sftp = new Net_SFTP($sftp_hostname,$port);
2073
- if (!$sftp->login($sftp_username, $sftp_password)) {
2074
- file_put_contents("sftp_log.txt","sftp login failed in remove_sftp_backup",FILE_APPEND);
2075
- return false;
2076
- }
2077
- $remote = $sftp_remote_folder ? trim($sftp_remote_folder,"/")."/" :'';
2078
- // copies filename.local to filename.remote on the SFTP server
2079
- if(isset($backup_file) && isset($remote) && $backup_file!=="")
2080
- $upload = $sftp->delete( $remote . '/' . $backup_file);
2081
- $sftp->disconnect();
2082
- }
2083
-
2084
-
2085
- /**
2086
- * Downloads backup file from server from remote ftp server to root folder on local server.
2087
- *
2088
- * @param array $args arguments passed to the function
2089
- * [ftp_username] -> ftp username on remote server
2090
- * [ftp_password] -> ftp password on remote server
2091
- * [ftp_hostname] -> ftp hostname of remote host
2092
- * [ftp_remote_folder] -> folder on remote site which backup file should be downloaded from
2093
- * [ftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be downloaded from
2094
- * [backup_file] -> absolute path of backup file on local server
2095
- * @return string|array absolute path to downloaded file is successful, array with error message if not
2096
- */
2097
- function get_ftp_backup($args) {
2098
- extract($args);
2099
-
2100
- $port = $ftp_port ? $ftp_port : 21; //default port is 21
2101
- if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
2102
- $conn_id = ftp_ssl_connect($ftp_hostname,$port);
2103
-
2104
- } else if (function_exists('ftp_connect')) {
2105
- $conn_id = ftp_connect($ftp_hostname,$port);
2106
- if ($conn_id === false) {
2107
- return false;
2108
- }
2109
- }
2110
- $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
2111
- if ($login === false) {
2112
- return false;
2113
- }
2114
-
2115
- if ($ftp_site_folder)
2116
- $ftp_remote_folder .= '/' . $this->site_name;
2117
-
2118
- if($ftp_passive){
2119
- @ftp_pasv($conn_id,true);
2120
- }
2121
-
2122
- $temp = ABSPATH . 'mwp_temp_backup.zip';
2123
- $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
2124
- if ($get === false) {
2125
- return false;
2126
- }
2127
-
2128
- ftp_close($conn_id);
2129
-
2130
- return $temp;
2131
- }
2132
-
2133
-
2134
-
2135
- /**
2136
- * Downloads backup file from server from remote ftp server to root folder on local server.
2137
- *
2138
- * @param array $args arguments passed to the function
2139
- * [ftp_username] -> ftp username on remote server
2140
- * [ftp_password] -> ftp password on remote server
2141
- * [ftp_hostname] -> ftp hostname of remote host
2142
- * [ftp_remote_folder] -> folder on remote site which backup file should be downloaded from
2143
- * [ftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be downloaded from
2144
- * [backup_file] -> absolute path of backup file on local server
2145
- * @return string|array absolute path to downloaded file is successful, array with error message if not
2146
- */
2147
- function get_sftp_backup($args) {
2148
- extract($args);
2149
- file_put_contents("sftp_log.txt","get_sftp_backup",FILE_APPEND);
2150
-
2151
- $port = $sftp_port ? $sftp_port : 22; //default port is 21 $sftp_hostname = $sftp_hostname?$sftp_hostname:"";
2152
- file_put_contents("sftp_log.txt","sftp port:".$sftp_port,FILE_APPEND);
2153
- $sftp_username = $sftp_username?$sftp_username:"";
2154
- $sftp_password = $sftp_password?$sftp_password:"";
2155
- file_put_contents("sftp_log.txt","sftp host:".$sftp_hostname.";username:".$sftp_username.";password:".$sftp_password,FILE_APPEND);
2156
- $sftp = new Net_SFTP($sftp_hostname,$port);
2157
- if (!$sftp->login($sftp_username, $sftp_password)) {
2158
- file_put_contents("sftp_log.txt","sftp login failed in get_sftp_backup",FILE_APPEND);
2159
- return false;
2160
- }
2161
- $remote = $sftp_remote_folder ? trim($sftp_remote_folder,"/")."/" : '';
2162
-
2163
-
2164
- if ($ftp_site_folder)
2165
- $remote .= '/' . $this->site_name;
2166
-
2167
- $temp = ABSPATH . 'mwp_temp_backup.zip';
2168
- $get = $sftp->get($remote . '/' . $backup_file,$temp);
2169
- $sftp->disconnect();
2170
- if ($get === false) {
2171
- file_put_contents("sftp_log.txt","sftp get failed in get_sftp_backup",FILE_APPEND);
2172
- return false;
2173
- }
2174
-
2175
- return $temp;
2176
- }
2177
-
2178
- /**
2179
- * Uploads backup file from server to Dropbox.
2180
- *
2181
- * @param array $args arguments passed to the function
2182
- * [consumer_key] -> consumer key of ManageWP Dropbox application
2183
- * [consumer_secret] -> consumer secret of ManageWP Dropbox application
2184
- * [oauth_token] -> oauth token of user on ManageWP Dropbox application
2185
- * [oauth_token_secret] -> oauth token secret of user on ManageWP Dropbox application
2186
- * [dropbox_destination] -> folder on user's Dropbox account which backup file should be upload to
2187
- * [dropbox_site_folder] -> subfolder with site name in dropbox_destination which backup file should be upload to
2188
- * [backup_file] -> absolute path of backup file on local server
2189
- * @return bool|array true is successful, array with error message if not
2190
- */
2191
- function dropbox_backup($args) {
2192
- extract($args);
2193
-
2194
- global $mmb_plugin_dir;
2195
- require_once $mmb_plugin_dir . '/lib/dropbox.php';
2196
-
2197
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2198
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2199
-
2200
- if ($dropbox_site_folder == true)
2201
- $dropbox_destination .= '/' . $this->site_name . '/' . basename($backup_file);
2202
- else
2203
- $dropbox_destination .= '/' . basename($backup_file);
2204
-
2205
- try {
2206
- $dropbox->upload($backup_file, $dropbox_destination, true);
2207
- } catch (Exception $e) {
2208
- $this->_log($e->getMessage());
2209
- return array(
2210
- 'error' => $e->getMessage(),
2211
- 'partial' => 1
2212
- );
2213
- }
2214
-
2215
- return true;
2216
- }
2217
-
2218
- /**
2219
- * Deletes backup file from Dropbox to root folder on local server.
2220
- *
2221
- * @param array $args arguments passed to the function
2222
- * [consumer_key] -> consumer key of ManageWP Dropbox application
2223
- * [consumer_secret] -> consumer secret of ManageWP Dropbox application
2224
- * [oauth_token] -> oauth token of user on ManageWP Dropbox application
2225
- * [oauth_token_secret] -> oauth token secret of user on ManageWP Dropbox application
2226
- * [dropbox_destination] -> folder on user's Dropbox account which backup file should be downloaded from
2227
- * [dropbox_site_folder] -> subfolder with site name in dropbox_destination which backup file should be downloaded from
2228
- * [backup_file] -> absolute path of backup file on local server
2229
- * @return void
2230
- */
2231
- function remove_dropbox_backup($args) {
2232
- extract($args);
2233
-
2234
- global $mmb_plugin_dir;
2235
- require_once $mmb_plugin_dir . '/lib/dropbox.php';
2236
-
2237
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2238
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2239
-
2240
- if ($dropbox_site_folder == true)
2241
- $dropbox_destination .= '/' . $this->site_name;
2242
-
2243
- try {
2244
- $dropbox->fileopsDelete($dropbox_destination . '/' . $backup_file);
2245
- } catch (Exception $e) {
2246
- $this->_log($e->getMessage());
2247
- /*return array(
2248
- 'error' => $e->getMessage(),
2249
- 'partial' => 1
2250
- );*/
2251
- }
2252
-
2253
- //return true;
2254
- }
2255
-
2256
- /**
2257
- * Downloads backup file from Dropbox to root folder on local server.
2258
- *
2259
- * @param array $args arguments passed to the function
2260
- * [consumer_key] -> consumer key of ManageWP Dropbox application
2261
- * [consumer_secret] -> consumer secret of ManageWP Dropbox application
2262
- * [oauth_token] -> oauth token of user on ManageWP Dropbox application
2263
- * [oauth_token_secret] -> oauth token secret of user on ManageWP Dropbox application
2264
- * [dropbox_destination] -> folder on user's Dropbox account which backup file should be deleted from
2265
- * [dropbox_site_folder] -> subfolder with site name in dropbox_destination which backup file should be deleted from
2266
- * [backup_file] -> absolute path of backup file on local server
2267
- * @return bool|array absolute path to downloaded file is successful, array with error message if not
2268
- */
2269
- function get_dropbox_backup($args) {
2270
- extract($args);
2271
-
2272
- global $mmb_plugin_dir;
2273
- require_once $mmb_plugin_dir . '/lib/dropbox.php';
2274
-
2275
- $dropbox = new Dropbox($consumer_key, $consumer_secret);
2276
- $dropbox->setOAuthTokens($oauth_token, $oauth_token_secret);
2277
-
2278
- if ($dropbox_site_folder == true)
2279
- $dropbox_destination .= '/' . $this->site_name;
2280
-
2281
- $temp = ABSPATH . 'mwp_temp_backup.zip';
2282
-
2283
- try {
2284
- $file = $dropbox->download($dropbox_destination.'/'.$backup_file);
2285
- $handle = @fopen($temp, 'w');
2286
- $result = fwrite($handle,$file);
2287
- fclose($handle);
2288
-
2289
- if($result)
2290
- return $temp;
2291
- else
2292
- return false;
2293
- } catch (Exception $e) {
2294
- $this->_log($e->getMessage());
2295
- return array(
2296
- 'error' => $e->getMessage(),
2297
- 'partial' => 1
2298
- );
2299
- }
2300
- }
2301
-
2302
- /**
2303
- * Uploads backup file from server to Amazon S3.
2304
- *
2305
- * @param array $args arguments passed to the function
2306
- * [as3_bucket_region] -> Amazon S3 bucket region
2307
- * [as3_bucket] -> Amazon S3 bucket
2308
- * [as3_access_key] -> Amazon S3 access key
2309
- * [as3_secure_key] -> Amazon S3 secure key
2310
- * [as3_directory] -> folder on user's Amazon S3 account which backup file should be upload to
2311
- * [as3_site_folder] -> subfolder with site name in as3_directory which backup file should be upload to
2312
- * [backup_file] -> absolute path of backup file on local server
2313
- * @return bool|array true is successful, array with error message if not
2314
- */
2315
- function amazons3_backup($args) {
2316
- if ($this->mmb_function_exists('curl_init')) {
2317
- require_once('lib/s3.php');
2318
- extract($args);
2319
-
2320
- if ($as3_site_folder == true)
2321
- $as3_directory .= '/' . $this->site_name;
2322
-
2323
- $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
2324
- try{
2325
- $s3 = new mwpS3(trim($as3_access_key), trim(str_replace(' ', '+', $as3_secure_key)), false, $endpoint);
2326
- if ($s3->putObjectFile($backup_file, $as3_bucket, $as3_directory . '/' . basename($backup_file), mwpS3::ACL_PRIVATE)) {
2327
- return true;
2328
- } else {
2329
- return array(
2330
- 'error' => 'Failed to upload to Amazon S3. Please check your details and set upload/delete permissions on your bucket.',
2331
- 'partial' => 1
2332
- );
2333
- }
2334
- } catch (Exception $e) {
2335
- $err = $e->getMessage();
2336
- if($err){
2337
- return array(
2338
- 'error' => 'Failed to upload to AmazonS3 ('.$err.').'
2339
- );
2340
- } else {
2341
- return array(
2342
- 'error' => 'Failed to upload to Amazon S3.'
2343
- );
2344
- }
2345
- }
2346
-
2347
- } else {
2348
- return array(
2349
- 'error' => 'You cannot use Amazon S3 on your server. Please enable curl extension first.',
2350
- 'partial' => 1
2351
- );
2352
- }
2353
-
2354
- }
2355
-
2356
-
2357
- /**
2358
- * Deletes backup file from Amazon S3.
2359
- *
2360
- * @param array $args arguments passed to the function
2361
- * [as3_bucket_region] -> Amazon S3 bucket region
2362
- * [as3_bucket] -> Amazon S3 bucket
2363
- * [as3_access_key] -> Amazon S3 access key
2364
- * [as3_secure_key] -> Amazon S3 secure key
2365
- * [as3_directory] -> folder on user's Amazon S3 account which backup file should be deleted from
2366
- * [as3_site_folder] -> subfolder with site name in as3_directory which backup file should be deleted from
2367
- * [backup_file] -> absolute path of backup file on local server
2368
- * @return void
2369
- */
2370
- function remove_amazons3_backup($args) {
2371
- if ($this->mmb_function_exists('curl_init')) {
2372
- require_once('lib/s3.php');
2373
- extract($args);
2374
- if ($as3_site_folder == true)
2375
- $as3_directory .= '/' . $this->site_name;
2376
- $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
2377
- try {
2378
- $s3 = new mwpS3(trim($as3_access_key), trim(str_replace(' ', '+', $as3_secure_key)), false, $endpoint);
2379
- $s3->deleteObject($as3_bucket, $as3_directory . '/' . $backup_file);
2380
- } catch (Exception $e){
2381
-
2382
- }
2383
- }
2384
- }
2385
-
2386
- /**
2387
- * Downloads backup file from Amazon S3 to root folder on local server.
2388
- *
2389
- * @param array $args arguments passed to the function
2390
- * [as3_bucket_region] -> Amazon S3 bucket region
2391
- * [as3_bucket] -> Amazon S3 bucket
2392
- * [as3_access_key] -> Amazon S3 access key
2393
- * [as3_secure_key] -> Amazon S3 secure key
2394
- * [as3_directory] -> folder on user's Amazon S3 account which backup file should be downloaded from
2395
- * [as3_site_folder] -> subfolder with site name in as3_directory which backup file should be downloaded from
2396
- * [backup_file] -> absolute path of backup file on local server
2397
- * @return bool|array absolute path to downloaded file is successful, array with error message if not
2398
- */
2399
- function get_amazons3_backup($args) {
2400
- require_once('lib/s3.php');
2401
- extract($args);
2402
- $endpoint = isset($as3_bucket_region) ? $as3_bucket_region : 's3.amazonaws.com';
2403
- $temp = '';
2404
- try {
2405
- $s3 = new mwpS3($as3_access_key, str_replace(' ', '+', $as3_secure_key), false, $endpoint);
2406
- if ($as3_site_folder == true)
2407
- $as3_directory .= '/' . $this->site_name;
2408
-
2409
- $temp = ABSPATH . 'mwp_temp_backup.zip';
2410
- $s3->getObject($as3_bucket, $as3_directory . '/' . $backup_file, $temp);
2411
- } catch (Exception $e) {
2412
- return $temp;
2413
- }
2414
- return $temp;
2415
- }
2416
-
2417
- /**
2418
- * Uploads backup file from server to Google Drive.
2419
- *
2420
- * @param array $args arguments passed to the function
2421
- * [google_drive_token] -> user's Google drive token in json form
2422
- * [google_drive_directory] -> folder on user's Google Drive account which backup file should be upload to
2423
- * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be upload to
2424
- * [backup_file] -> absolute path of backup file on local server
2425
- * @return bool|array true is successful, array with error message if not
2426
- */
2427
- function google_drive_backup($args) {
2428
- extract($args);
2429
-
2430
- global $mmb_plugin_dir;
2431
- require_once("$mmb_plugin_dir/lib/google-api-client/Google_Client.php");
2432
- require_once("$mmb_plugin_dir/lib/google-api-client/contrib/Google_DriveService.php");
2433
-
2434
- $gdrive_client = new Google_Client();
2435
- $gdrive_client->setUseObjects(true);
2436
- $gdrive_client->setAccessToken($google_drive_token);
2437
-
2438
- $gdrive_service = new Google_DriveService($gdrive_client);
2439
-
2440
- try {
2441
- $about = $gdrive_service->about->get();
2442
- $root_folder_id = $about->getRootFolderId();
2443
- } catch (Exception $e) {
2444
- return array(
2445
- 'error' => $e->getMessage(),
2446
- );
2447
- }
2448
-
2449
- try {
2450
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$google_drive_directory' and '$root_folder_id' in parents and trashed = false"));
2451
- $files = $list_files->getItems();
2452
- } catch (Exception $e) {
2453
- return array(
2454
- 'error' => $e->getMessage(),
2455
- );
2456
- }
2457
- if (isset($files[0])) {
2458
- $managewp_folder = $files[0];
2459
- }
2460
-
2461
- if (!isset($managewp_folder)) {
2462
- try {
2463
- $_managewp_folder = new Google_DriveFile();
2464
- $_managewp_folder->setTitle($google_drive_directory);
2465
- $_managewp_folder->setMimeType('application/vnd.google-apps.folder');
2466
-
2467
- if ($root_folder_id != null) {
2468
- $parent = new Google_ParentReference();
2469
- $parent->setId($root_folder_id);
2470
- $_managewp_folder->setParents(array($parent));
2471
- }
2472
-
2473
- $managewp_folder = $gdrive_service->files->insert($_managewp_folder, array());
2474
- } catch (Exception $e) {
2475
- return array(
2476
- 'error' => $e->getMessage(),
2477
- );
2478
- }
2479
- }
2480
-
2481
- if ($google_drive_site_folder) {
2482
- try {
2483
- $subfolder_title = $this->site_name;
2484
- $managewp_folder_id = $managewp_folder->getId();
2485
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$subfolder_title' and '$managewp_folder_id' in parents and trashed = false"));
2486
- $files = $list_files->getItems();
2487
- } catch (Exception $e) {
2488
- return array(
2489
- 'error' => $e->getMessage(),
2490
- );
2491
- }
2492
- if (isset($files[0])) {
2493
- $backup_folder = $files[0];
2494
- } else {
2495
- try {
2496
- $_backup_folder = new Google_DriveFile();
2497
- $_backup_folder->setTitle($subfolder_title);
2498
- $_backup_folder->setMimeType('application/vnd.google-apps.folder');
2499
-
2500
- if (isset($managewp_folder)) {
2501
- $_backup_folder->setParents(array($managewp_folder));
2502
- }
2503
-
2504
- $backup_folder = $gdrive_service->files->insert($_backup_folder, array());
2505
- } catch (Exception $e) {
2506
- return array(
2507
- 'error' => $e->getMessage(),
2508
- );
2509
- }
2510
- }
2511
- } else {
2512
- $backup_folder = $managewp_folder;
2513
- }
2514
-
2515
- $file_path = explode('/', $backup_file);
2516
- $new_file = new Google_DriveFile();
2517
- $new_file->setTitle(end($file_path));
2518
- $new_file->setDescription('Backup file of site: ' . $this->site_name . '.');
2519
-
2520
- if ($backup_folder != null) {
2521
- $new_file->setParents(array($backup_folder));
2522
- }
2523
-
2524
- $tries = 1;
2525
-
2526
- while($tries <= 2) {
2527
- try {
2528
- $data = file_get_contents($backup_file);
2529
-
2530
- $createdFile = $gdrive_service->files->insert($new_file, array(
2531
- 'data' => $data,
2532
- ));
2533
-
2534
- break;
2535
- } catch (Exception $e) {
2536
- if ($e->getCode() >= 500 && $e->getCode() <= 504 && $mmb_gdrive_upload_tries <= 2) {
2537
- sleep(2);
2538
- $tries++;
2539
- } else {
2540
- return array(
2541
- 'error' => $e->getMessage(),
2542
- );
2543
- }
2544
- }
2545
- }
2546
-
2547
- return true;
2548
- }
2549
-
2550
- /**
2551
- * Deletes backup file from Google Drive.
2552
- *
2553
- * @param array $args arguments passed to the function
2554
- * [google_drive_token] -> user's Google drive token in json form
2555
- * [google_drive_directory] -> folder on user's Google Drive account which backup file should be deleted from
2556
- * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be deleted from
2557
- * [backup_file] -> absolute path of backup file on local server
2558
- * @return void
2559
- */
2560
- function remove_google_drive_backup($args) {
2561
- extract($args);
2562
-
2563
- global $mmb_plugin_dir;
2564
- require_once("$mmb_plugin_dir/lib/google-api-client/Google_Client.php");
2565
- require_once("$mmb_plugin_dir/lib/google-api-client/contrib/Google_DriveService.php");
2566
-
2567
- try {
2568
- $gdrive_client = new Google_Client();
2569
- $gdrive_client->setUseObjects(true);
2570
- $gdrive_client->setAccessToken($google_drive_token);
2571
- } catch (Exception $e) {
2572
- $this->_log($e->getMessage());
2573
- /*eturn array(
2574
- 'error' => $e->getMessage(),
2575
- );*/
2576
- }
2577
-
2578
- $gdrive_service = new Google_DriveService($gdrive_client);
2579
-
2580
- try {
2581
- $about = $gdrive_service->about->get();
2582
- $root_folder_id = $about->getRootFolderId();
2583
- } catch (Exception $e) {
2584
- $this->_log($e->getMessage());
2585
- /*return array(
2586
- 'error' => $e->getMessage(),
2587
- );*/
2588
- }
2589
-
2590
- try {
2591
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$google_drive_directory' and '$root_folder_id' in parents and trashed = false"));
2592
- $files = $list_files->getItems();
2593
- } catch (Exception $e) {
2594
- $this->_log($e->getMessage());
2595
- /*return array(
2596
- 'error' => $e->getMessage(),
2597
- );*/
2598
- }
2599
- if (isset($files[0])) {
2600
- $managewp_folder = $files[0];
2601
- } else {
2602
- $this->_log("This file does not exist.");
2603
- /*return array(
2604
- 'error' => "This file does not exist.",
2605
- );*/
2606
- }
2607
-
2608
- if ($google_drive_site_folder) {
2609
- try {
2610
- $subfolder_title = $this->site_name;
2611
- $managewp_folder_id = $managewp_folder->getId();
2612
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$subfolder_title' and '$managewp_folder_id' in parents and trashed = false"));
2613
- $files = $list_files->getItems();
2614
- } catch (Exception $e) {
2615
- $this->_log($e->getMessage());
2616
- /*return array(
2617
- 'error' => $e->getMessage(),
2618
- );*/
2619
- }
2620
- if (isset($files[0])) {
2621
- $backup_folder = $files[0];
2622
- }
2623
- } else {
2624
- $backup_folder = $managewp_folder;
2625
- }
2626
-
2627
- if (isset($backup_folder)) {
2628
- try {
2629
- $backup_folder_id = $backup_folder->getId();
2630
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$backup_file' and '$backup_folder_id' in parents and trashed = false"));
2631
- $files = $list_files->getItems();;
2632
- } catch (Exception $e) {
2633
- $this->_log($e->getMessage());
2634
- /*return array(
2635
- 'error' => $e->getMessage(),
2636
- );*/
2637
- }
2638
- if (isset($files[0])) {
2639
- try {
2640
- $gdrive_service->files->delete($files[0]->getId());
2641
- } catch (Exception $e) {
2642
- $this->_log($e->getMessage());
2643
- /*return array(
2644
- 'error' => $e->getMessage(),
2645
- );*/
2646
- }
2647
- } else {
2648
- $this->_log("This file does not exist.");
2649
- /*return array(
2650
- 'error' => "This file does not exist.",
2651
- );*/
2652
- }
2653
- } else {
2654
- $this->_log("This file does not exist.");
2655
- /*return array(
2656
- 'error' => "This file does not exist.",
2657
- );*/
2658
- }
2659
-
2660
- //return true;
2661
- }
2662
-
2663
- /**
2664
- * Downloads backup file from Google Drive to root folder on local server.
2665
- *
2666
- * @param array $args arguments passed to the function
2667
- * [google_drive_token] -> user's Google drive token in json form
2668
- * [google_drive_directory] -> folder on user's Google Drive account which backup file should be downloaded from
2669
- * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be downloaded from
2670
- * [backup_file] -> absolute path of backup file on local server
2671
- * @return bool|array absolute path to downloaded file is successful, array with error message if not
2672
- */
2673
- function get_google_drive_backup($args) {
2674
- extract($args);
2675
-
2676
- global $mmb_plugin_dir;
2677
- require_once("$mmb_plugin_dir/lib/google-api-client/Google_Client.php");
2678
- require_once("$mmb_plugin_dir/lib/google-api-client/contrib/Google_DriveService.php");
2679
-
2680
- try {
2681
- $gdrive_client = new Google_Client();
2682
- $gdrive_client->setUseObjects(true);
2683
- $gdrive_client->setAccessToken($google_drive_token);
2684
- } catch (Exception $e) {
2685
- return array(
2686
- 'error' => $e->getMessage(),
2687
- );
2688
- }
2689
-
2690
- $gdrive_service = new Google_DriveService($gdrive_client);
2691
-
2692
- try {
2693
- $about = $gdrive_service->about->get();
2694
- $root_folder_id = $about->getRootFolderId();
2695
- } catch (Exception $e) {
2696
- return array(
2697
- 'error' => $e->getMessage(),
2698
- );
2699
- }
2700
-
2701
- try {
2702
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$google_drive_directory' and '$root_folder_id' in parents and trashed = false"));
2703
- $files = $list_files->getItems();
2704
- } catch (Exception $e) {
2705
- return array(
2706
- 'error' => $e->getMessage(),
2707
- );
2708
- }
2709
- if (isset($files[0])) {
2710
- $managewp_folder = $files[0];
2711
- } else {
2712
- return array(
2713
- 'error' => "This file does not exist.",
2714
- );
2715
- }
2716
-
2717
- if ($google_drive_site_folder) {
2718
- try {
2719
- $subfolder_title = $this->site_name;
2720
- $managewp_folder_id = $managewp_folder->getId();
2721
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$subfolder_title' and '$managewp_folder_id' in parents and trashed = false"));
2722
- $files = $list_files->getItems();
2723
- } catch (Exception $e) {
2724
- return array(
2725
- 'error' => $e->getMessage(),
2726
- );
2727
- }
2728
- if (isset($files[0])) {
2729
- $backup_folder = $files[0];
2730
- }
2731
- } else {
2732
- $backup_folder = $managewp_folder;
2733
- }
2734
-
2735
- if (isset($backup_folder)) {
2736
- try {
2737
- $backup_folder_id = $backup_folder->getId();
2738
- $list_files = $gdrive_service->files->listFiles(array("q"=>"title='$backup_file' and '$backup_folder_id' in parents and trashed = false"));
2739
- $files = $list_files->getItems();
2740
- } catch (Exception $e) {
2741
- return array(
2742
- 'error' => $e->getMessage(),
2743
- );
2744
- }
2745
- if (isset($files[0])) {
2746
- try {
2747
- $download_url = $files[0]->getDownloadUrl();
2748
- if ($download_url) {
2749
- $request = new Google_HttpRequest($download_url, 'GET', null, null);
2750
- $http_request = Google_Client::$io->authenticatedRequest($request);
2751
- if ($http_request->getResponseHttpCode() == 200) {
2752
- $stream = $http_request->getResponseBody();
2753
- $local_destination = ABSPATH . 'mwp_temp_backup.zip';
2754
- $handle = @fopen($local_destination, 'w+');
2755
- $result = fwrite($handle, $stream);
2756
- fclose($handle);
2757
- if($result)
2758
- return $local_destination;
2759
- else
2760
- return array(
2761
- 'error' => "Write permission error.",
2762
- );
2763
- } else {
2764
- return array(
2765
- 'error' => "This file does not exist.",
2766
- );
2767
- }
2768
- } else {
2769
- return array(
2770
- 'error' => "This file does not exist.",
2771
- );
2772
- }
2773
- } catch (Exception $e) {
2774
- return array(
2775
- 'error' => $e->getMessage(),
2776
- );
2777
- }
2778
- } else {
2779
- return array(
2780
- 'error' => "This file does not exist.",
2781
- );
2782
- }
2783
- } else {
2784
- return array(
2785
- 'error' => "This file does not exist.",
2786
- );
2787
- }
2788
-
2789
- return false;
2790
- }
2791
-
2792
- /**
2793
- * Schedules the next execution of some backup task.
2794
- *
2795
- * @param string $type daily, weekly or monthly
2796
- * @param string $schedule format: task_time (if daily), task_time|task_day (if weekly), task_time|task_date (if monthly)
2797
- * @return bool|int timestamp if sucessful, false if not
2798
- */
2799
- function schedule_next($type, $schedule) {
2800
- $schedule = explode("|", $schedule);
2801
-
2802
- if (empty($schedule))
2803
- return false;
2804
- switch ($type) {
2805
- case 'daily':
2806
- if (isset($schedule[1]) && $schedule[1]) {
2807
- $delay_time = $schedule[1] * 60;
2808
- }
2809
-
2810
- $current_hour = date("H");
2811
- $schedule_hour = $schedule[0];
2812
- if ($current_hour >= $schedule_hour)
2813
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 1, date("Y"));
2814
- else
2815
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2816
- break;
2817
-
2818
- case 'weekly':
2819
- if (isset($schedule[2]) && $schedule[2]) {
2820
- $delay_time = $schedule[2] * 60;
2821
- }
2822
- $current_weekday = date('w');
2823
- $schedule_weekday = $schedule[1];
2824
- $current_hour = date("H");
2825
- $schedule_hour = $schedule[0];
2826
-
2827
- if ($current_weekday > $schedule_weekday)
2828
- $weekday_offset = 7 - ($week_day - $task_schedule[1]);
2829
- else
2830
- $weekday_offset = $schedule_weekday - $current_weekday;
2831
-
2832
- if (!$weekday_offset) { //today is scheduled weekday
2833
- if ($current_hour >= $schedule_hour)
2834
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + 7, date("Y"));
2835
- else
2836
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d"), date("Y"));
2837
- } else {
2838
- $time = mktime($schedule_hour, 0, 0, date("m"), date("d") + $weekday_offset, date("Y"));
2839
- }
2840
- break;
2841
-
2842
- case 'monthly':
2843
- if (isset($schedule[2]) && $schedule[2]) {
2844
- $delay_time = $schedule[2] * 60;
2845
- }
2846
- $current_monthday = date('j');
2847
- $schedule_monthday = $schedule[1];
2848
- $current_hour = date("H");
2849
- $schedule_hour = $schedule[0];
2850
-
2851
- if ($current_monthday > $schedule_monthday) {
2852
- $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2853
- } else if ($current_monthday < $schedule_monthday) {
2854
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2855
- } else if ($current_monthday == $schedule_monthday) {
2856
- if ($current_hour >= $schedule_hour)
2857
- $time = mktime($schedule_hour, 0, 0, date("m") + 1, $schedule_monthday, date("Y"));
2858
- else
2859
- $time = mktime($schedule_hour, 0, 0, date("m"), $schedule_monthday, date("Y"));
2860
- break;
2861
- }
2862
-
2863
- break;
2864
-
2865
- default:
2866
- break;
2867
- }
2868
-
2869
- if (isset($delay_time) && $delay_time) {
2870
- $time += $delay_time;
2871
- }
2872
-
2873
- return $time;
2874
- }
2875
-
2876
- /**
2877
- * Parse task arguments for info on master.
2878
- *
2879
- * @return mixed associative array with stats for every backup task or error if backup is manually deleted on server
2880
- */
2881
- function get_backup_stats() {
2882
- $stats = array();
2883
- $tasks = $this->tasks;
2884
- if (is_array($tasks) && !empty($tasks)) {
2885
- foreach ($tasks as $task_name => $info) {
2886
- if (is_array($info['task_results']) && !empty($info['task_results'])) {
2887
- foreach ($info['task_results'] as $key => $result) {
2888
- if (isset($result['server']) && !isset($result['error'])) {
2889
- if (isset($result['server']['file_path']) && !$info['task_args']['del_host_file']) {
2890
- if (!file_exists($result['server']['file_path'])) {
2891
- $info['task_results'][$key]['error'] = 'Backup created but manually removed from server.';
2892
- }
2893
- }
2894
- }
2895
- }
2896
- }
2897
- if (is_array($info['task_results']))
2898
- $stats[$task_name] = array_values($info['task_results']);
2899
- }
2900
- }
2901
- return $stats;
2902
- }
2903
-
2904
- /**
2905
- * Returns all backup tasks with information when the next schedule will be.
2906
- *
2907
- * @return mixed associative array with timestamp with next schedule for every backup task
2908
- */
2909
- function get_next_schedules() {
2910
- $stats = array();
2911
- $tasks = $this->tasks;
2912
- if (is_array($tasks) && !empty($tasks)) {
2913
- foreach ($tasks as $task_name => $info) {
2914
- $stats[$task_name] = isset($info['task_args']['next']) ? $info['task_args']['next'] : array();
2915
- }
2916
- }
2917
- return $stats;
2918
- }
2919
-
2920
- /**
2921
- * Deletes all old backups from local server.
2922
- * It depends on configuration on master (Number of backups to keep).
2923
- *
2924
- * @param string $task_name name of backup task
2925
- * @return bool|void true if there are backups for deletion, void if not
2926
- */
2927
- function remove_old_backups($task_name) {
2928
- //Check for previous failed backups first
2929
- $this->cleanup();
2930
-
2931
- //Remove by limit
2932
- $backups = $this->tasks;
2933
- if ($task_name == 'Backup Now') {
2934
- $num = 0;
2935
- } else {
2936
- $num = 1;
2937
- }
2938
-
2939
- if ((count($backups[$task_name]['task_results']) - $num) >= $backups[$task_name]['task_args']['limit']) {
2940
- //how many to remove ?
2941
- $remove_num = (count($backups[$task_name]['task_results']) - $num - $backups[$task_name]['task_args']['limit']) + 1;
2942
- for ($i = 0; $i < $remove_num; $i++) {
2943
- //Remove from the server
2944
- if (isset($backups[$task_name]['task_results'][$i]['server'])) {
2945
- @unlink($backups[$task_name]['task_results'][$i]['server']['file_path']);
2946
- }
2947
-
2948
- //Remove from ftp
2949
- if (isset($backups[$task_name]['task_results'][$i]['ftp']) && isset($backups[$task_name]['task_args']['account_info']['mwp_ftp'])) {
2950
- $ftp_file = $backups[$task_name]['task_results'][$i]['ftp'];
2951
- $args = $backups[$task_name]['task_args']['account_info']['mwp_ftp'];
2952
- $args['backup_file'] = $ftp_file;
2953
- $this->remove_ftp_backup($args);
2954
- }
2955
- if (isset($backups[$task_name]['task_results'][$i]['sftp']) && isset($backups[$task_name]['task_args']['account_info']['mwp_sftp'])) {
2956
- $ftp_file = $backups[$task_name]['task_results'][$i]['fstp'];
2957
- $args = $backups[$task_name]['task_args']['account_info']['mwp_sftp'];
2958
- $args['backup_file'] = $sftp_file;
2959
- $this->remove_sftp_backup($args);
2960
- }
2961
-
2962
- if (isset($backups[$task_name]['task_results'][$i]['amazons3']) && isset($backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'])) {
2963
- $amazons3_file = $backups[$task_name]['task_results'][$i]['amazons3'];
2964
- $args = $backups[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
2965
- $args['backup_file'] = $amazons3_file;
2966
- $this->remove_amazons3_backup($args);
2967
- }
2968
-
2969
- if (isset($backups[$task_name]['task_results'][$i]['dropbox']) && isset($backups[$task_name]['task_args']['account_info']['mwp_dropbox'])) {
2970
- //To do: dropbox remove
2971
- $dropbox_file = $backups[$task_name]['task_results'][$i]['dropbox'];
2972
- $args = $backups[$task_name]['task_args']['account_info']['mwp_dropbox'];
2973
- $args['backup_file'] = $dropbox_file;
2974
- $this->remove_dropbox_backup($args);
2975
- }
2976
-
2977
- if (isset($backups[$task_name]['task_results'][$i]['google_drive']) && isset($backups[$task_name]['task_args']['account_info']['mwp_google_drive'])) {
2978
- $google_drive_file = $backups[$task_name]['task_results'][$i]['google_drive'];
2979
- $args = $backups[$task_name]['task_args']['account_info']['mwp_google_drive'];
2980
- $args['backup_file'] = $google_drive_file;
2981
- $this->remove_google_drive_backup($args);
2982
- }
2983
-
2984
- //Remove database backup info
2985
- unset($backups[$task_name]['task_results'][$i]);
2986
- } //end foreach
2987
-
2988
- if (is_array($backups[$task_name]['task_results']))
2989
- $backups[$task_name]['task_results'] = array_values($backups[$task_name]['task_results']);
2990
- else
2991
- $backups[$task_name]['task_results']=array();
2992
-
2993
- $this->update_tasks($backups);
2994
-
2995
- return true;
2996
- }
2997
- }
2998
-
2999
- /**
3000
- * Deletes specified backup.
3001
- *
3002
- * @param array $args arguments passed to function
3003
- * [task_name] -> name of backup task
3004
- * [result_id] -> id of baskup task result, which should be restored
3005
- * [google_drive_token] -> json of Google Drive token, if it is remote destination
3006
- * @return bool true if successful, false if not
3007
- */
3008
- function delete_backup($args) {
3009
- if (empty($args))
3010
- return false;
3011
- extract($args);
3012
- $task_name = stripslashes($task_name);
3013
- if (isset($google_drive_token)) {
3014
- $this->tasks[$task_name]['task_args']['account_info']['mwp_google_drive']['google_drive_token'] = $google_drive_token;
3015
- }
3016
-
3017
- $tasks = $this->tasks;
3018
-
3019
- $task = $tasks[$task_name];
3020
- $backups = $task['task_results'];
3021
- $backup = $backups[$result_id];
3022
-
3023
- if (isset($backup['server'])) {
3024
- @unlink($backup['server']['file_path']);
3025
- }
3026
-
3027
- //Remove from ftp
3028
- if (isset($backup['ftp'])) {
3029
- $ftp_file = $backup['ftp'];
3030
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_ftp'];
3031
- $args['backup_file'] = $ftp_file;
3032
- $this->remove_ftp_backup($args);
3033
- }
3034
- if (isset($backup['sftp'])) {
3035
- $ftp_file = $backup['ftp'];
3036
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_sftp'];
3037
- $args['backup_file'] = $ftp_file;
3038
- $this->remove_sftp_backup($args);
3039
- }
3040
-
3041
- if (isset($backup['amazons3'])) {
3042
- $amazons3_file = $backup['amazons3'];
3043
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_amazon_s3'];
3044
- $args['backup_file'] = $amazons3_file;
3045
- $this->remove_amazons3_backup($args);
3046
- }
3047
-
3048
- if (isset($backup['dropbox'])) {
3049
- $dropbox_file = $backup['dropbox'];
3050
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_dropbox'];
3051
- $args['backup_file'] = $dropbox_file;
3052
- $this->remove_dropbox_backup($args);
3053
- }
3054
-
3055
- if (isset($backup['google_drive'])) {
3056
- $google_drive_file = $backup['google_drive'];
3057
- $args = $tasks[$task_name]['task_args']['account_info']['mwp_google_drive'];
3058
- $args['backup_file'] = $google_drive_file;
3059
- $this->remove_google_drive_backup($args);
3060
- }
3061
-
3062
- unset($backups[$result_id]);
3063
-
3064
- if (count($backups)) {
3065
- $tasks[$task_name]['task_results'] = $backups;
3066
- } else {
3067
- unset($tasks[$task_name]['task_results']);
3068
- }
3069
-
3070
- $this->update_tasks($tasks);
3071
- //update_option('mwp_backup_tasks', $tasks);
3072
- return true;
3073
- }
3074
-
3075
- /**
3076
- * Deletes all unneeded files produced by backup process.
3077
- *
3078
- * @return array array of deleted files
3079
- */
3080
- function cleanup() {
3081
- $tasks = $this->tasks;
3082
- $backup_folder = WP_CONTENT_DIR . '/' . md5('mmb-worker') . '/mwp_backups/';
3083
- $backup_folder_new = MWP_BACKUP_DIR . '/';
3084
- $files = glob($backup_folder . "*");
3085
- $new = glob($backup_folder_new . "*");
3086
-
3087
- //Failed db files first
3088
- $db_folder = MWP_DB_DIR . '/';
3089
- $db_files = glob($db_folder . "*");
3090
- if (is_array($db_files) && !empty($db_files)) {
3091
- foreach ($db_files as $file) {
3092
- @unlink($file);
3093
- }
3094
- @unlink(MWP_BACKUP_DIR.'/mwp_db/index.php');
3095
- @rmdir(MWP_DB_DIR);
3096
- }
3097
-
3098
- //clean_old folder?
3099
- if ((isset($files[0]) && basename($files[0]) == 'index.php' && count($files) == 1) || (empty($files))) {
3100
- if (!empty($files)) {
3101
- foreach ($files as $file) {
3102
- @unlink($file);
3103
- }
3104
- }
3105
- @rmdir(WP_CONTENT_DIR . '/' . md5('mmb-worker') . '/mwp_backups');
3106
- @rmdir(WP_CONTENT_DIR . '/' . md5('mmb-worker'));
3107
- }
3108
-
3109
- if (!empty($new)) {
3110
- foreach ($new as $b) {
3111
- $files[] = $b;
3112
- }
3113
- }
3114
- $deleted = array();
3115
-
3116
- if (is_array($files) && count($files)) {
3117
- $results = array();
3118
- if (!empty($tasks)) {
3119
- foreach ((array) $tasks as $task) {
3120
- if (isset($task['task_results']) && count($task['task_results'])) {
3121
- foreach ($task['task_results'] as $backup) {
3122
- if (isset($backup['server'])) {
3123
- $results[] = $backup['server']['file_path'];
3124
- }
3125
- }
3126
- }
3127
- }
3128
- }
3129
-
3130
- $num_deleted = 0;
3131
- foreach ($files as $file) {
3132
- if (!in_array($file, $results) && basename($file) != 'index.php') {
3133
- @unlink($file);
3134
- $deleted[] = basename($file);
3135
- $num_deleted++;
3136
- }
3137
- }
3138
- }
3139
-
3140
- return $deleted;
3141
- }
3142
-
3143
- /**
3144
- * Uploads to remote destination in the second step, invoked from master.
3145
- *
3146
- * @param array $args arguments passed to function
3147
- * [task_name] -> name of backup task
3148
- * @return array|void void if success, array with error message if not
3149
- */
3150
- function remote_backup_now($args) {
3151
- $this->set_memory();
3152
- if (!empty($args))
3153
- extract($args);
3154
-
3155
- $tasks = $this->tasks;
3156
- $task_name = stripslashes($task_name);
3157
- $task = $tasks[$task_name];
3158
-
3159
- if (!empty($task)) {
3160
- extract($task['task_args']);
3161
- }
3162
-
3163
- $results = $task['task_results'];
3164
-
3165
- if (is_array($results) && count($results)) {
3166
- $backup_file = $results[count($results) - 1]['server']['file_path'];
3167
- }
3168
-
3169
- if ($backup_file && file_exists($backup_file)) {
3170
- //FTP, Amazon S3, Dropbox or Google Drive
3171
- if (isset($account_info['mwp_ftp']) && !empty($account_info['mwp_ftp'])) {
3172
- $this->update_status($task_name, $this->statuses['ftp']);
3173
- $account_info['mwp_ftp']['backup_file'] = $backup_file;
3174
- $return = $this->ftp_backup($account_info['mwp_ftp']);
3175
- $this->wpdb_reconnect();
3176
-
3177
- if (!(is_array($return) && isset($return['error']))) {
3178
- $this->update_status($task_name, $this->statuses['ftp'], true);
3179
- $this->update_status($task_name, $this->statuses['finished'], true);
3180
- }
3181
- }
3182
-
3183
- if (isset($account_info['mwp_sftp']) && !empty($account_info['mwp_sftp'])) {
3184
- $this->update_status($task_name, $this->statuses['sftp']);
3185
- $account_info['mwp_sftp']['backup_file'] = $backup_file;
3186
- $return = $this->sftp_backup($account_info['mwp_sftp']);
3187
- $this->wpdb_reconnect();
3188
-
3189
- if (!(is_array($return) && isset($return['error']))) {
3190
- $this->update_status($task_name, $this->statuses['sftp'], true);
3191
- $this->update_status($task_name, $this->statuses['finished'], true);
3192
- }
3193
- }
3194
-
3195
- if (isset($account_info['mwp_amazon_s3']) && !empty($account_info['mwp_amazon_s3'])) {
3196
- $this->update_status($task_name, $this->statuses['s3']);
3197
- $account_info['mwp_amazon_s3']['backup_file'] = $backup_file;
3198
- $return = $this->amazons3_backup($account_info['mwp_amazon_s3']);
3199
- $this->wpdb_reconnect();
3200
-
3201
- if (!(is_array($return) && isset($return['error']))) {
3202
- $this->update_status($task_name, $this->statuses['s3'], true);
3203
- $this->update_status($task_name, $this->statuses['finished'], true);
3204
- }
3205
- }
3206
-
3207
- if (isset($account_info['mwp_dropbox']) && !empty($account_info['mwp_dropbox'])) {
3208
- $this->update_status($task_name, $this->statuses['dropbox']);
3209
- $account_info['mwp_dropbox']['backup_file'] = $backup_file;
3210
- $return = $this->dropbox_backup($account_info['mwp_dropbox']);
3211
- $this->wpdb_reconnect();
3212
-
3213
- if (!(is_array($return) && isset($return['error']))) {
3214
- $this->update_status($task_name, $this->statuses['dropbox'], true);
3215
- $this->update_status($task_name, $this->statuses['finished'], true);
3216
- }
3217
- }
3218
-
3219
- if (isset($account_info['mwp_email']) && !empty($account_info['mwp_email'])) {
3220
- $this->update_status($task_name, $this->statuses['email']);
3221
- $account_info['mwp_email']['task_name'] = $task_name;
3222
- $account_info['mwp_email']['file_path'] = $backup_file;
3223
- $return = $this->email_backup($account_info['mwp_email']);
3224
- $this->wpdb_reconnect();
3225
-
3226
- if (!(is_array($return) && isset($return['error']))) {
3227
- $this->update_status($task_name, $this->statuses['email'], true);
3228
- $this->update_status($task_name, $this->statuses['finished'], true);
3229
- }
3230
- }
3231
-
3232
- if (isset($account_info['mwp_google_drive']) && !empty($account_info['mwp_google_drive'])) {
3233
- $this->update_status($task_name, $this->statuses['google_drive']);
3234
- $account_info['mwp_google_drive']['backup_file'] = $backup_file;
3235
- $return = $this->google_drive_backup($account_info['mwp_google_drive']);
3236
- $this->wpdb_reconnect();
3237
-
3238
- if (!(is_array($return) && isset($return['error']))) {
3239
- $this->update_status($task_name, $this->statuses['google_drive'], true);
3240
- $this->update_status($task_name, $this->statuses['finished'], true);
3241
- }
3242
- }
3243
-
3244
- $tasks = $this->tasks;
3245
- @file_put_contents(MWP_BACKUP_DIR.'/mwp_db/index.php', '');
3246
- if ($return == true && $del_host_file) {
3247
- @unlink($backup_file);
3248
- unset($tasks[$task_name]['task_results'][count($tasks[$task_name]['task_results']) - 1]['server']);
3249
- }
3250
- $this->update_tasks($tasks);
3251
- } else {
3252
- $return = array(
3253
- 'error' => 'Backup file not found on your server. Please try again.'
3254
- );
3255
- }
3256
-
3257
- return $return;
3258
- }
3259
-
3260
- /**
3261
- * Checks if scheduled backup tasks should be executed.
3262
- *
3263
- * @param array $args arguments passed to function
3264
- * [task_name] -> name of backup task
3265
- * [task_id] -> id of backup task
3266
- * [$site_key] -> hash key of backup task
3267
- * [worker_version] -> version of worker
3268
- * [mwp_google_drive_refresh_token] -> should be Google Drive token be refreshed, true if it is remote destination of task
3269
- * @param string $url url on master where worker validate task
3270
- * @return string|array|boolean
3271
- */
3272
- function validate_task($args, $url) {
3273
- if (!class_exists('WP_Http')) {
3274
- include_once(ABSPATH . WPINC . '/class-http.php');
3275
- }
3276
-
3277
- $worker_upto_3_9_22 = (MMB_WORKER_VERSION <= '3.9.22'); // worker version is less or equals to 3.9.22
3278
- $params = array('timeout'=>100);
3279
- $params['body'] = $args;
3280
- $result = wp_remote_post($url, $params);
3281
-
3282
- if ($worker_upto_3_9_22) {
3283
- if (is_array($result) && $result['body'] == 'mwp_delete_task') {
3284
- //$tasks = $this->get_backup_settings();
3285
- $tasks = $this->tasks;
3286
- unset($tasks[$args['task_name']]);
3287
- $this->update_tasks($tasks);
3288
- $this->cleanup();
3289
- return 'deleted';
3290
- } elseif(is_array($result) && $result['body'] == 'mwp_pause_task'){
3291
- return 'paused';
3292
- } elseif(is_array($result) && substr($result['body'], 0, 8) == 'token - '){
3293
- return $result['body'];
3294
- }
3295
- } else {
3296
- if (is_array($result) && $result['body']) {
3297
- $response = unserialize($result['body']);
3298
- if ($response['message'] == 'mwp_delete_task') {
3299
- $tasks = $this->tasks;
3300
- unset($tasks[$args['task_name']]);
3301
- $this->update_tasks($tasks);
3302
- $this->cleanup();
3303
- return 'deleted';
3304
- } elseif ($response['message'] == 'mwp_pause_task') {
3305
- return 'paused';
3306
- } elseif ($response['message'] == 'mwp_do_task') {
3307
- return $response;
3308
- }
3309
- }
3310
- }
3311
-
3312
- return false;
3313
- }
3314
-
3315
- /**
3316
- * Updates status of backup task.
3317
- * Positive number if completed, negative if not.
3318
- *
3319
- * @param string $task_name name of backup task
3320
- * @param int $status status which tasks should be updated to
3321
- * (
3322
- * 0 - Backup started,
3323
- * 1 - DB dump,
3324
- * 2 - DB ZIP,
3325
- * 3 - Files ZIP,
3326
- * 4 - Amazon S3,
3327
- * 5 - Dropbox,
3328
- * 6 - FTP,
3329
- * 7 - Email,
3330
- * 8 - Google Drive,
3331
- * 100 - Finished
3332
- * )
3333
- * @param bool $completed completed or not
3334
- * @return void
3335
- */
3336
- function update_status($task_name, $status, $completed = false) {
3337
- if ($task_name != 'Backup Now') {
3338
- $tasks = $this->tasks;
3339
- $index = count($tasks[$task_name]['task_results']) - 1;
3340
- if (!is_array($tasks[$task_name]['task_results'][$index]['status'])) {
3341
- $tasks[$task_name]['task_results'][$index]['status'] = array();
3342
- }
3343
- if (!$completed) {
3344
- $tasks[$task_name]['task_results'][$index]['status'][] = (int) $status * (-1);
3345
- } else {
3346
- $status_index = count($tasks[$task_name]['task_results'][$index]['status']) - 1;
3347
- $tasks[$task_name]['task_results'][$index]['status'][$status_index] = abs($tasks[$task_name]['task_results'][$index]['status'][$status_index]);
3348
- }
3349
-
3350
- $this->update_tasks($tasks);
3351
- //update_option('mwp_backup_tasks',$tasks);
3352
- }
3353
- }
3354
-
3355
- /**
3356
- * Update $this->tasks attribute and save it to wp_options with key mwp_backup_tasks.
3357
- *
3358
- * @param mixed $tasks associative array with all tasks data
3359
- * @return void
3360
- */
3361
- function update_tasks($tasks) {
3362
- $this->tasks = $tasks;
3363
- update_option('mwp_backup_tasks', $tasks);
3364
- }
3365
-
3366
- /**
3367
- * Reconnects to database to avoid timeout problem after ZIP files.
3368
- *
3369
- * @return void
3370
- */
3371
- function wpdb_reconnect() {
3372
- global $wpdb;
3373
-
3374
- if(class_exists('wpdb') && function_exists('wp_set_wpdb_vars')){
3375
- @mysql_close($wpdb->dbh);
3376
- $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
3377
- wp_set_wpdb_vars();
3378
- if (function_exists('is_multisite')) {
3379
- if (is_multisite()) {
3380
- $wpdb->set_blog_id(get_current_blog_id());
3381
- }
3382
- }
3383
- }
3384
- }
3385
-
3386
- /**
3387
- * Replaces .htaccess file in process of restoring WordPress site.
3388
- *
3389
- * @param string $url url of current site
3390
- * @return void
3391
- */
3392
- function replace_htaccess($url) {
3393
- $file = @file_get_contents(ABSPATH.'.htaccess');
3394
- if ($file && strlen($file)) {
3395
- $args = parse_url($url);
3396
- $string = rtrim($args['path'], "/");
3397
- $regex = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
3398
- $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
3399
- $file = preg_replace($regex, $replace, $file);
3400
- @file_put_contents(ABSPATH.'.htaccess', $file);
3401
- }
3402
- }
3403
-
3404
- /**
3405
- * Removes cron for checking scheduled tasks, if there are not any scheduled task.
3406
- *
3407
- * @return void
3408
- */
3409
- function check_cron_remove() {
3410
- if(empty($this->tasks) || (count($this->tasks) == 1 && isset($this->tasks['Backup Now'])) ){
3411
- wp_clear_scheduled_hook('mwp_backup_tasks');
3412
- exit;
3413
- }
3414
- }
3415
-
3416
- /**
3417
- * Re-add tasks on website re-add.
3418
- *
3419
- * @param array $params arguments passed to function
3420
- * @return array $params without backups
3421
- */
3422
- public function readd_tasks($params = array()) {
3423
- global $mmb_core;
3424
-
3425
- if( empty($params) || !isset($params['backups']) )
3426
- return $params;
3427
-
3428
- $before = array();
3429
- $tasks = $params['backups'];
3430
- if( !empty($tasks) ){
3431
- $mmb_backup = new MMB_Backup();
3432
-
3433
- if( function_exists( 'wp_next_scheduled' ) ){
3434
- if ( !wp_next_scheduled('mwp_backup_tasks') ) {
3435
- wp_schedule_event( time(), 'tenminutes', 'mwp_backup_tasks' );
3436
- }
3437
- }
3438
-
3439
- foreach( $tasks as $task ){
3440
- $before[$task['task_name']] = array();
3441
-
3442
- if(isset($task['secure'])){
3443
- if($decrypted = $mmb_core->_secure_data($task['secure'])){
3444
- $decrypted = maybe_unserialize($decrypted);
3445
- if(is_array($decrypted)){
3446
- foreach($decrypted as $key => $val){
3447
- if(!is_numeric($key))
3448
- $task[$key] = $val;
3449
- }
3450
- unset($task['secure']);
3451
- } else
3452
- $task['secure'] = $decrypted;
3453
- }
3454
-
3455
- }
3456
- if (isset($task['account_info']) && is_array($task['account_info'])) { //only if sends from master first time(secure data)
3457
- $task['args']['account_info'] = $task['account_info'];
3458
- }
3459
-
3460
- $before[$task['task_name']]['task_args'] = $task['args'];
3461
- $before[$task['task_name']]['task_args']['next'] = $mmb_backup->schedule_next($task['args']['type'], $task['args']['schedule']);
3462
- }
3463
- }
3464
- update_option('mwp_backup_tasks', $before);
3465
-
3466
- unset($params['backups']);
3467
- return $params;
3468
- }
3469
-
3470
- }
3471
-
3472
- /*if( function_exists('add_filter') ) {
3473
- add_filter( 'mwp_website_add', 'MMB_Backup::readd_tasks' );
3474
- }*/
3475
-
3476
- if(!function_exists('get_all_files_from_dir')) {
3477
- /**
3478
- * Get all files in directory
3479
- *
3480
- * @param string $path Relative or absolute path to folder
3481
- * @param array $exclude List of excluded files or folders, relative to $path
3482
- * @return array List of all files in folder $path, exclude all files in $exclude array
3483
- */
3484
- function get_all_files_from_dir($path, $exclude = array()) {
3485
- if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
3486
- global $directory_tree, $ignore_array;
3487
- $directory_tree = array();
3488
- foreach ($exclude as $file) {
3489
- if (!in_array($file, array('.', '..'))) {
3490
- if ($file[0] === "/") $path = substr($file, 1);
3491
- $ignore_array[] = "$path/$file";
3492
- }
3493
- }
3494
- get_all_files_from_dir_recursive($path);
3495
- return $directory_tree;
3496
- }
3497
- }
3498
-
3499
- if (!function_exists('get_all_files_from_dir_recursive')) {
3500
- /**
3501
- * Get all files in directory,
3502
- * wrapped function which writes in global variable
3503
- * and exclued files or folders are read from global variable
3504
- *
3505
- * @param string $path Relative or absolute path to folder
3506
- * @return void
3507
- */
3508
- function get_all_files_from_dir_recursive($path) {
3509
- if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
3510
- global $directory_tree, $ignore_array;
3511
- $directory_tree_temp = array();
3512
- $dh = @opendir($path);
3513
-
3514
- while (false !== ($file = @readdir($dh))) {
3515
- if (!in_array($file, array('.', '..'))) {
3516
- if (!in_array("$path/$file", $ignore_array)) {
3517
- if (!is_dir("$path/$file")) {
3518
- $directory_tree[] = "$path/$file";
3519
- } else {
3520
- get_all_files_from_dir_recursive("$path/$file");
3521
- }
3522
- }
3523
- }
3524
- }
3525
- @closedir($dh);
3526
- }
3527
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
comment.class.php DELETED
@@ -1,252 +0,0 @@
1
- <?php
2
- /*************************************************************
3
- *
4
- * comment.class.php
5
- *
6
- * Get comments
7
- *
8
- *
9
- * Copyright (c) 2011 Prelovac Media
10
- * www.prelovac.com
11
- **************************************************************/
12
- if(basename($_SERVER['SCRIPT_FILENAME']) == "comment.class.php"):
13
- exit;
14
- endif;
15
- class MMB_Comment extends MMB_Core
16
- {
17
- function __construct()
18
- {
19
- parent::__construct();
20
- }
21
-
22
- function change_status($args)
23
- {
24
-
25
- global $wpdb;
26
- $comment_id = $args['comment_id'];
27
- $status = $args['status'];
28
-
29
- if ( 'approve' == $status )
30
- $status_sql = '1';
31
- elseif ( 'unapprove' == $status )
32
- $status_sql = '0';
33
- elseif ( 'spam' == $status )
34
- $status_sql = 'spam';
35
- elseif ( 'trash' == $status )
36
- $status_sql = 'trash';
37
- $sql = "update ".$wpdb->prefix."comments set comment_approved = '%s' where comment_ID = '%s'";
38
- $success = $wpdb->query($wpdb->prepare($sql, $status_sql, $comment_id));
39
-
40
-
41
- return $success;
42
- }
43
-
44
- function get_comments($args){
45
- global $wpdb;
46
-
47
- $where='';
48
-
49
- extract($args);
50
-
51
- if(!empty($filter_comments))
52
- {
53
- $where.=" AND (c.comment_author LIKE '%".mysql_real_escape_string($filter_comments)."%' OR c.comment_content LIKE '%".mysql_real_escape_string($filter_comments)."%')";
54
- }
55
- $comment_array = array();
56
- $comment_statuses = array('approved', 'pending', 'spam', 'trash');
57
- foreach ($args as $checkbox => $checkbox_val)
58
- {
59
- if($checkbox_val=="on") {
60
- $status_val = str_replace("mwp_get_comments_","",$checkbox);
61
- if($status_val == 'approved'){
62
- $status_val = 1;
63
- }elseif($status_val == 'pending'){
64
- $status_val = 0;
65
- }
66
- $comment_array[]="'".$status_val."'";
67
- }
68
- }
69
- if(!empty($comment_array))
70
- {
71
- $where.=" AND c.comment_approved IN (".implode(",",$comment_array).")";
72
- }
73
-
74
- $sql_query = "$wpdb->comments as c, $wpdb->posts as p WHERE c.comment_post_ID = p.ID ".$where;
75
-
76
- $comments_total = $wpdb->get_results("SELECT count(*) as total_comments FROM ".$sql_query);
77
- $total=$comments_total[0]->total_comments;
78
- $comments_approved = $this->comment_total();
79
-
80
- $query_comments = $wpdb->get_results("SELECT c.comment_ID, c.comment_post_ID, c.comment_author, c.comment_author_email, c.comment_author_url, c.comment_author_IP, c.comment_date, c.comment_content, c.comment_approved, c.comment_parent, p.post_title, p.post_type, p.guid FROM ".$sql_query." ORDER BY c.comment_date DESC LIMIT 500");
81
- $comments = array();
82
- foreach ( $query_comments as $comments_info )
83
- {
84
- $comment_total_approved = 0;
85
- if(isset($comments_approved[$comments_info->comment_post_ID]['approved'])){
86
- $comment_total_approved = $comments_approved[$comments_info->comment_post_ID]['approved'];
87
- }
88
- $comment_total_pending = 0;
89
- if(isset($comments_approved[$comments_info->comment_post_ID]['pending'])){
90
- $comment_total_pending = $comments_approved[$comments_info->comment_post_ID]['pending'];
91
- }
92
- $comment_parent_author = '';
93
- if($comments_info->comment_parent > 0){
94
- $select_parent_author = "SELECT comment_author FROM $wpdb->comments WHERE comment_ID = ".$comments_info->comment_parent;
95
- $select_parent_author_res = $wpdb->get_row($select_parent_author);
96
- $comment_parent_author = $select_parent_author_res->comment_author;
97
- }
98
-
99
- $comments[$comments_info->comment_ID] = array(
100
- "comment_post_ID" => $comments_info->comment_post_ID,
101
- "comment_author" => $comments_info->comment_author,
102
- "comment_author_email" => $comments_info->comment_author_email,
103
- "comment_author_url" => $comments_info->comment_author_url,
104
- "comment_author_IP" => $comments_info->comment_author_IP,
105
- "comment_date" => $comments_info->comment_date,
106
- "comment_content" => htmlspecialchars($comments_info->comment_content),
107
- "comment_approved" => $comments_info->comment_approved,
108
- "comment_parent" => $comments_info->comment_parent,
109
- "comment_parent_author" => $comment_parent_author,
110
- "post_title" => htmlspecialchars($comments_info->post_title),
111
- "post_type" => $comments_info->post_type,
112
- "guid" => $comments_info->guid,
113
- "comment_total_approved" => $comment_total_approved,
114
- "comment_total_pending" => $comment_total_pending,
115
- );
116
- }
117
-
118
- return array('comments' => $comments, 'total' => $total);
119
- }
120
-
121
- function comment_total(){
122
- global $wpdb;
123
- $totals = array();
124
- $select_total_approved = "SELECT COUNT(*) as total, p.ID FROM $wpdb->comments as c, $wpdb->posts as p WHERE c.comment_post_ID = p.ID AND c.comment_approved = 1 GROUP BY p.ID";
125
- $select_total_approved_res = $wpdb->get_results($select_total_approved);
126
-
127
- if(!empty($select_total_approved_res)){
128
- foreach($select_total_approved_res as $row){
129
- $totals[$row->ID]['approved'] = $row->total;
130
- }
131
- }
132
- $select_total_pending = "SELECT COUNT(*) as total, p.ID FROM $wpdb->comments as c, $wpdb->posts as p WHERE c.comment_post_ID = p.ID AND c.comment_approved = 0 GROUP BY p.ID";
133
- $select_total_pending_res = $wpdb->get_results($select_total_pending);
134
- if(!empty($select_total_pending_res)){
135
- foreach($select_total_pending_res as $row){
136
- $totals[$row->ID]['pending'] = $row->total;
137
- }
138
- }
139
-
140
- return $totals;
141
- }
142
-
143
- function action_comment($args){
144
- global $wpdb;
145
- extract($args);
146
- if($docomaction == 'approve'){
147
- $docomaction = '1';
148
- }else if($docomaction == 'unapprove' || $docomaction == 'untrash' || $docomaction == 'unspam'){
149
- $docomaction = '0';
150
- }
151
-
152
- if(!empty($comment_id)){
153
- if($docomaction == 'delete'){
154
- $update_query = "DELETE FROM $wpdb->comments WHERE comment_ID = ".$comment_id;
155
- $delete_query = "DELETE FROM $wpdb->commentmeta WHERE comment_id = ".$comment_id;
156
- $wpdb->query($delete_query);
157
- }else{
158
- $update_query = "UPDATE $wpdb->comments SET comment_approved = '".$docomaction."' WHERE comment_ID = ".$comment_id;
159
- }
160
- $wpdb->query($update_query);
161
-
162
- return 'Comment updated.';
163
- }else{
164
- return 'No ID...';
165
- }
166
- }
167
-
168
- function bulk_action_comments($args){
169
- global $wpdb;
170
- extract($args);
171
-
172
- if($docomaction=='delete'){
173
- $update_query_intro = "DELETE FROM $wpdb->comments WHERE comment_ID = ";
174
- }else{
175
- if($docomaction=='unapprove' || $docomaction == 'untrash' || $docomaction == 'unspam'){
176
- $docomaction = '0';
177
- }else if($docomaction == 'approve'){
178
- $docomaction = '1';
179
- }
180
- $update_query_intro = "UPDATE $wpdb->comments SET comment_approved = '".$docomaction."' WHERE comment_ID = ";
181
- }
182
- foreach($args as $key=>$val){
183
-
184
- if(!empty($val) && is_numeric($val))
185
- {
186
- if($docomaction=='delete'){
187
- $delete_query = "DELETE FROM $wpdb->commentmeta WHERE comment_id = ".$val;
188
- $wpdb->query($delete_query);
189
- }
190
- $update_query = $update_query_intro.$val;
191
-
192
- $wpdb->query($update_query);
193
- }
194
- }
195
- return "comments updated";
196
- }
197
-
198
- function reply_comment($args){
199
- global $wpdb, $current_user;
200
- extract($args);
201
- $comments = array();
202
-
203
- if(!empty($comment_id) && !empty($reply_text)){
204
- $admins = get_userdata($current_user->ID);
205
- $now = time();
206
- $insert_reply = "INSERT INTO $wpdb->comments(comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_author_IP, comment_date, comment_date_gmt, comment_content, comment_karma, comment_approved, comment_agent, comment_parent, user_id) VALUES(".$post_id.", '".$admins->user_login."', '".$admins->user_email."', '".$admins->user_url."', '".$_SERVER['REMOTE_ADDR']."', NOW(), NOW(), '%s', 0, 1, '".$_SERVER['HTTP_USER_AGENT']."', ".$comment_id.", ".$current_user->ID.")";
207
- $insert_reply_res = $wpdb->query($wpdb->prepare($insert_reply, base64_decode($reply_text)));
208
- $lastid = $wpdb->insert_id;
209
-
210
- $comments_approved = $this->comment_total();
211
-
212
- $comment_total_approved = 0;
213
- if(isset($comments_approved[$post_id]['approved'])){
214
- $comment_total_approved = $comments_approved[$post_id]['approved'];
215
- }
216
- $comment_total_pending = 0;
217
- if(isset($comments_approved[$post_id]['pending'])){
218
- $comment_total_pending = $comments_approved[$post_id]['pending'];
219
- }
220
-
221
- $comment_parent_author = '';
222
- if($comment_id > 0){
223
- $select_parent_author = "SELECT c.comment_author, p.post_title, p.post_type, p.guid FROM $wpdb->comments as c, $wpdb->posts as p WHERE c.comment_post_ID = p.ID AND c.comment_ID = ".$comment_id;
224
- $select_parent_author_res = $wpdb->get_row($select_parent_author);
225
- $comment_parent_author = $select_parent_author_res->comment_author;
226
- }
227
-
228
- $comments[$lastid] = array(
229
- "comment_post_ID" => $post_id,
230
- "comment_author" => $admins->user_login,
231
- "comment_author_email" => $admins->user_email,
232
- "comment_author_url" => $admins->user_url,
233
- "comment_author_IP" => $_SERVER['REMOTE_ADDR'],
234
- "comment_date" => $now,
235
- "comment_content" => htmlspecialchars($reply_text),
236
- "comment_approved" => '1',
237
- "comment_parent" => $comment_id,
238
- "comment_parent_author" => $comment_parent_author,
239
- "post_title" => htmlspecialchars($select_parent_author_res->post_title),
240
- "post_type" => $select_parent_author_res->post_type,
241
- "guid" => $select_parent_author_res->guid,
242
- "comment_total_approved" => $comment_total_approved,
243
- "comment_total_pending" => $comment_total_pending,
244
- );
245
-
246
-
247
- }
248
- return $comments;
249
- }
250
-
251
- }
252
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
core.class.php DELETED
@@ -1,918 +0,0 @@
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
- if(basename($_SERVER['SCRIPT_FILENAME']) == "core.class.php"):
13
- exit;
14
- endif;
15
- class MMB_Core extends MMB_Helper
16
- {
17
- var $name;
18
- var $slug;
19
- var $settings;
20
- var $remote_client;
21
- var $comment_instance;
22
- var $plugin_instance;
23
- var $theme_instance;
24
- var $wp_instance;
25
- var $post_instance;
26
- var $stats_instance;
27
- var $search_instance;
28
- var $links_instance;
29
- var $user_instance;
30
- var $security_instance;
31
- var $backup_instance;
32
- var $installer_instance;
33
- var $mmb_multisite;
34
- var $network_admin_install;
35
- private $action_call;
36
- private $action_params;
37
- private $mmb_pre_init_actions;
38
- private $mmb_pre_init_filters;
39
- private $mmb_init_actions;
40
-
41
-
42
- function __construct()
43
- {
44
- global $mmb_plugin_dir, $wpmu_version, $blog_id, $_mmb_plugin_actions, $_mmb_item_filter, $_mmb_options;
45
-
46
- $_mmb_plugin_actions = array();
47
- $_mmb_options = get_option('wrksettings');
48
- $_mmb_options = !empty($_mmb_options) ? $_mmb_options : array();
49
-
50
- $this->name = 'Manage Multiple Blogs';
51
- $this->action_call = null;
52
- $this->action_params = null;
53
-
54
- if ( function_exists('is_multisite') ) {
55
- if ( is_multisite() ) {
56
- $this->mmb_multisite = $blog_id;
57
- $this->network_admin_install = get_option('mmb_network_admin_install');
58
- }
59
- } else if (!empty($wpmu_version)) {
60
- $this->mmb_multisite = $blog_id;
61
- $this->network_admin_install = get_option('mmb_network_admin_install');
62
- } else {
63
- $this->mmb_multisite = false;
64
- $this->network_admin_install = null;
65
- }
66
-
67
- // admin notices
68
- if ( !get_option('_worker_public_key') ){
69
- if( $this->mmb_multisite ){
70
- if( is_network_admin() && $this->network_admin_install == '1'){
71
- add_action('network_admin_notices', array( &$this, 'network_admin_notice' ));
72
- } else if( $this->network_admin_install != '1' ){
73
- $parent_key = $this->get_parent_blog_option('_worker_public_key');
74
- if(empty($parent_key))
75
- add_action('admin_notices', array( &$this, 'admin_notice' ));
76
- }
77
- } else {
78
- add_action('admin_notices', array( &$this, 'admin_notice' ));
79
- }
80
- }
81
-
82
- // default filters
83
- //$this->mmb_pre_init_filters['get_stats']['mmb_stats_filter'][] = array('MMB_Stats', 'pre_init_stats'); // called with class name, use global $mmb_core inside the function instead of $this
84
- $this->mmb_pre_init_filters['get_stats']['mmb_stats_filter'][] = 'mmb_pre_init_stats';
85
-
86
- $_mmb_item_filter['pre_init_stats'] = array( 'core_update', 'hit_counter', 'comments', 'backups', 'posts', 'drafts', 'scheduled' );
87
- $_mmb_item_filter['get'] = array( 'updates', 'errors' );
88
-
89
- $this->mmb_pre_init_actions = array(
90
- 'backup_req' => 'mmb_get_backup_req',
91
- );
92
-
93
- $this->mmb_init_actions = array(
94
- 'do_upgrade' => 'mmb_do_upgrade',
95
- 'get_stats' => 'mmb_stats_get',
96
- 'remove_site' => 'mmb_remove_site',
97
- 'backup_clone' => 'mmb_backup_now',
98
- 'restore' => 'mmb_restore_now',
99
- 'optimize_tables' => 'mmb_optimize_tables',
100
- 'check_wp_version' => 'mmb_wp_checkversion',
101
- 'create_post' => 'mmb_post_create',
102
- 'update_worker' => 'mmb_update_worker_plugin',
103
- 'change_comment_status' => 'mmb_change_comment_status',
104
- 'change_post_status' => 'mmb_change_post_status',
105
- 'get_comment_stats' => 'mmb_comment_stats_get',
106
- 'install_addon' => 'mmb_install_addon',
107
- 'get_links' => 'mmb_get_links',
108
- 'add_link' => 'mmb_add_link',
109
- 'delete_link' => 'mmb_delete_link',
110
- 'delete_links' => 'mmb_delete_links',
111
- 'get_comments' => 'mmb_get_comments',
112
- 'action_comment' => 'mmb_action_comment',
113
- 'bulk_action_comments' => 'mmb_bulk_action_comments',
114
- 'replyto_comment' => 'mmb_reply_comment',
115
- 'add_user' => 'mmb_add_user',
116
- 'email_backup' => 'mmb_email_backup',
117
- 'check_backup_compat' => 'mmb_check_backup_compat',
118
- 'scheduled_backup' => 'mmb_scheduled_backup',
119
- 'run_task' => 'mmb_run_task_now',
120
- 'execute_php_code' => 'mmb_execute_php_code',
121
- 'delete_backup' => 'mmm_delete_backup',
122
- 'remote_backup_now' => 'mmb_remote_backup_now',
123
- 'set_notifications' => 'mmb_set_notifications',
124
- 'clean_orphan_backups' => 'mmb_clean_orphan_backups',
125
- 'get_users' => 'mmb_get_users',
126
- 'edit_users' => 'mmb_edit_users',
127
- 'get_posts' => 'mmb_get_posts',
128
- 'delete_post' => 'mmb_delete_post',
129
- 'delete_posts' => 'mmb_delete_posts',
130
- 'edit_posts' => 'mmb_edit_posts',
131
- 'get_pages' => 'mmb_get_pages',
132
- 'delete_page' => 'mmb_delete_page',
133
- 'get_plugins_themes' => 'mmb_get_plugins_themes',
134
- 'edit_plugins_themes' => 'mmb_edit_plugins_themes',
135
- 'worker_brand' => 'mmb_worker_brand',
136
- 'maintenance' => 'mmb_maintenance_mode',
137
- 'get_dbname' => 'mmb_get_dbname',
138
- 'security_check' => 'mbb_security_check',
139
- 'security_fix_folder_listing'=> 'mbb_security_fix_folder_listing',
140
- 'security_fix_php_reporting'=> 'mbb_security_fix_php_reporting',
141
- 'security_fix_database_reporting'=> 'mbb_security_fix_database_reporting',
142
- 'security_fix_wp_version'=> 'mbb_security_fix_wp_version',
143
- 'security_fix_admin_username'=>'mbb_security_fix_admin_username',
144
- 'security_fix_htaccess_permission'=>'mbb_security_fix_htaccess_permission',
145
- 'security_fix_scripts_styles'=>'mbb_security_fix_scripts_styles',
146
- 'security_fix_file_permission'=>'mbb_security_fix_file_permission',
147
- 'security_fix_all' =>'mbb_security_fix_all',
148
- 'get_autoupdate_plugins_themes' => 'mmb_get_autoupdate_plugins_themes',
149
- 'edit_autoupdate_plugins_themes' => 'mmb_edit_autoupdate_plugins_themes',
150
-
151
- );
152
-
153
- $mwp_worker_brand = get_option("mwp_worker_brand");
154
- //!$mwp_worker_brand['hide_managed_remotely']
155
- if ($mwp_worker_brand == false || (is_array($mwp_worker_brand) && !array_key_exists('hide_managed_remotely', $mwp_worker_brand))) {
156
- add_action('rightnow_end', array( &$this, 'add_right_now_info' ));
157
- }
158
- if ($mwp_worker_brand != false && is_array($mwp_worker_brand) && isset($mwp_worker_brand['text_for_client']) && ($mwp_worker_brand['email_or_link'] != 0)) {
159
- add_action('admin_init', array($this, 'enqueue_scripts'));
160
- add_action('admin_init', array($this, 'enqueue_styles'));
161
- add_action('admin_menu', array($this, 'add_support_page'));
162
- add_action('admin_head', array($this, 'support_page_script'));
163
- add_action('admin_footer', array($this, 'support_page_dialog'));
164
- add_action('admin_init', array($this, 'send_email_to_admin'));
165
- }
166
- add_action( 'plugins_loaded', array( &$this, 'dissalow_text_editor' ) );
167
-
168
- add_action('admin_init', array(&$this,'admin_actions'));
169
- add_action('init', array( &$this, 'mmb_remote_action'), 9999);
170
- add_action('setup_theme', 'mmb_run_backup_action', 1);
171
- add_action('plugins_loaded', 'mmb_authenticate', 1);
172
- add_action('setup_theme', 'mmb_parse_request');
173
- add_action('set_auth_cookie', array( &$this, 'mmb_set_auth_cookie'));
174
- add_action('set_logged_in_cookie', array( &$this, 'mmb_set_logged_in_cookie'));
175
-
176
-
177
- }
178
-
179
- function mmb_remote_action(){
180
- if($this->action_call != null){
181
- $params = isset($this->action_params) && $this->action_params != null ? $this->action_params : array();
182
- call_user_func($this->action_call, $params);
183
- }
184
- }
185
-
186
- function register_action_params( $action = false, $params = array() ){
187
-
188
- if(isset($this->mmb_pre_init_actions[$action]) && function_exists($this->mmb_pre_init_actions[$action])){
189
- call_user_func($this->mmb_pre_init_actions[$action], $params);
190
- }
191
-
192
- if(isset($this->mmb_init_actions[$action]) && function_exists($this->mmb_init_actions[$action])){
193
- $this->action_call = $this->mmb_init_actions[$action];
194
- $this->action_params = $params;
195
-
196
- if( isset($this->mmb_pre_init_filters[$action]) && !empty($this->mmb_pre_init_filters[$action])){
197
- global $mmb_filters;
198
-
199
- foreach($this->mmb_pre_init_filters[$action] as $_name => $_functions){
200
- if(!empty($_functions)){
201
- $data = array();
202
-
203
- foreach($_functions as $_k => $_callback){
204
- if(is_array($_callback) && method_exists($_callback[0], $_callback[1]) ){
205
- $data = call_user_func( $_callback, $params );
206
- } elseif (is_string($_callback) && function_exists( $_callback )){
207
- $data = call_user_func( $_callback, $params );
208
- }
209
- $mmb_filters[$_name] = isset($mmb_filters[$_name]) && !empty($mmb_filters[$_name]) ? array_merge($mmb_filters[$_name], $data) : $data;
210
- add_filter( $_name, create_function( '$a' , 'global $mmb_filters; return array_merge($a, $mmb_filters["'.$_name.'"]);') );
211
- }
212
- }
213
-
214
- }
215
- }
216
- return true;
217
- }
218
- return false;
219
- }
220
-
221
- /**
222
- * Add notice to network admin dashboard for security reasons
223
- *
224
- */
225
- function network_admin_notice()
226
- {
227
- global $status, $page, $s;
228
- $context = $status;
229
- $plugin = 'worker/init.php';
230
- $nonce = wp_create_nonce('deactivate-plugin_' . $plugin);
231
- $actions = 'plugins.php?action=deactivate&amp;plugin='.urlencode($plugin).'&amp;plugin_status=' . $context . '&amp;paged=' . $page.'&amp;s=' . $s. '&amp;_wpnonce=' .$nonce ;
232
- echo '<div class="error" style="text-align: center;"><p style="color: red; font-size: 14px; font-weight: bold;">ManageWP Notice</p><p>
233
- Please <a href="https://managewp.com" target="_blank">add this site and your network blogs</a>, with your network administrator username, to your ManageWP account. <a target="_blank" href="https://managewp.com/features">What is ManageWP?</a> <br ><br > Otherwise, click to <a href="'.$actions.'">deactivate ManageWP plugin</a></em>.
234
- </p></div>';
235
- }
236
-
237
-
238
- /**
239
- * Add notice to admin dashboard for security reasons
240
- *
241
- */
242
- function admin_notice()
243
- {
244
- global $status, $page, $s;
245
- $context = $status;
246
- $plugin = 'worker/init.php';
247
- $nonce = wp_create_nonce('deactivate-plugin_' . $plugin);
248
- $actions = 'plugins.php?action=deactivate&amp;plugin='.urlencode($plugin).'&amp;plugin_status=' . $context . '&amp;paged=' . $page.'&amp;s=' . $s. '&amp;_wpnonce=' .$nonce ;
249
- $deactivation = 'click to <a href="'.$actions.'">deactivate ManageWP plugin</a>';
250
- if($this->mmb_multisite && $this->network_admin_install != '1'){
251
- $deactivation = "deactivate ManageWP plugin";
252
- }
253
- echo '<div class="error" style="text-align: center;"><p style="color: red; font-size: 14px; font-weight: bold;">ManageWP Notice</p><p>
254
- Please <a href="https://managewp.com" target="_blank">add this site</a> to your ManageWP account. <a target="_blank" href="https://managewp.com/features">What is ManageWP?</a> <br ><br >
255
- <em>Otherwise, '.$deactivation.'</em>.
256
- </p></div>';
257
- }
258
-
259
- /**
260
- * Add an item into the Right Now Dashboard widget
261
- * to inform that the blog can be managed remotely
262
- *
263
- */
264
- function add_right_now_info()
265
- {
266
- $mwp_worker_brand = get_option('mwp_worker_brand');
267
- echo '<div class="mmb-slave-info">';
268
- if($mwp_worker_brand && isset($mwp_worker_brand['remotely_managed_text'])){
269
- /*$url = isset($mwp_worker_brand['author_url']) ? $mwp_worker_brand['author_url'] : null;
270
- if($url) {
271
- $scheme = parse_url($mwp_worker_brand['author_url'], PHP_URL_SCHEME);
272
- if(empty($scheme)) {
273
- $url = 'http://' . $url;
274
- }
275
- }
276
- if($url) {
277
- $managedBy = '<a target="_blank" href="'.htmlspecialchars($url).'">'
278
- .htmlspecialchars($mwp_worker_brand['author'])
279
- .'</a>';
280
- } else {
281
- $managedBy = htmlspecialchars($mwp_worker_brand['author']);
282
- }
283
- echo sprintf('<p>This site is managed by %s.</p>', $managedBy);*/
284
- echo '<p>'.$mwp_worker_brand['remotely_managed_text'].'</p>';
285
- }else{
286
- echo '<p>This site can be managed remotely.</p>';
287
- }
288
- echo '</div>';
289
- }
290
-
291
- function enqueue_scripts()
292
- {
293
- wp_enqueue_script('jquery');
294
- wp_enqueue_script('jquery-ui-core');
295
- wp_enqueue_script('jquery-ui-dialog');
296
- }
297
-
298
- function enqueue_styles()
299
- {
300
- wp_enqueue_style('wp-jquery-ui');
301
- wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css');
302
- }
303
-
304
- function send_email_to_admin(){
305
- if(!isset($_POST['support_mwp_message'])) {
306
- return;
307
- }
308
- global $current_user;
309
- if (empty($_POST['support_mwp_message'])) {
310
- $this->mwp_send_ajax_response(false, "Please enter a message.");
311
- }
312
- $mwp_worker_brand = get_option('mwp_worker_brand');
313
- if(empty($mwp_worker_brand['admin_email'])) {
314
- $this->mwp_send_ajax_response(false, "Unable to send email to admin.");
315
- }
316
- $subject = 'New ticket for site '.get_bloginfo('url');
317
- $message = <<<EOF
318
- Hi,
319
- User with a username {$current_user->user_login} has a new question:
320
- {$_POST['support_mwp_message']}
321
- EOF;
322
- $has_been_sent = wp_mail($mwp_worker_brand['admin_email'], $subject, $message);
323
- if(!$has_been_sent) {
324
- $this->mwp_send_ajax_response(false, "Unable to send email. Please try again.");
325
- }
326
- $this->mwp_send_ajax_response(true, "Message successfully sent.");
327
- }
328
-
329
- function mwp_send_ajax_response($success = true, $message = '')
330
- {
331
- $response = json_encode(array(
332
- 'success' => $success,
333
- 'message' => $message,
334
- ));
335
- print $response;
336
- exit;
337
- }
338
-
339
- function support_page_dialog()
340
- {
341
- $mwp_worker_brand = get_option('mwp_worker_brand');
342
- if($mwp_worker_brand && isset($mwp_worker_brand['text_for_client']) && ($mwp_worker_brand['text_for_client'] != ''))
343
- {
344
- $notification_text = $mwp_worker_brand['text_for_client'];
345
- }
346
- ?>
347
- <div id="support_dialog" style="display: none;">
348
- <div>
349
- <p><?php echo $notification_text; ?></p>
350
- </div>
351
- <div style="margin: 19px 0 0;">
352
- <?php
353
- if($mwp_worker_brand['email_or_link'] == 1)
354
- {
355
- ?>
356
- <form method="post" id="support_form">
357
- <textarea name="support_mwp_message" id="support_message" style="width:500px;height:150px;display:block;margin-left:auto;margin-right:auto;"></textarea>
358
- <button type="submit" class="button-primary" style="display:block;margin:20px auto 7px auto;border:1px solid #a1a1a1;padding:0px 31px;border-radius: 4px;">Send</button>
359
- </form>
360
- <div id="support_response_id" style="margin-top: 14px"></div>
361
- <style>
362
- .ui-widget-content{
363
- z-index: 300002;
364
- }
365
- .ui-widget-overlay {
366
- background-repeat: repeat;
367
- }
368
- </style>
369
- </div>
370
- <?php
371
- }
372
- else
373
- {
374
- }
375
- echo '</div>';
376
- }
377
-
378
- function support_page_script()
379
- {
380
- ?>
381
- <script type="text/javascript">
382
- jQuery(document).ready(function ($) {
383
- var $dialog = $('#support_dialog');
384
- var $form = $('#support_form');
385
- var $messageContainer = $('#support_response_id');
386
- $form.submit(function (e) {
387
- e.preventDefault();
388
- var data = $(this).serialize();
389
- $.ajax({
390
- type: "POST",
391
- url: 'index.php',
392
- dataType: 'json',
393
- data: data,
394
- success: function (data, textStatus, jqXHR) {
395
- if(data.success) {
396
- $form.slideUp();
397
- }
398
- $messageContainer.html(data.message);
399
- },
400
- error: function (jqXHR, textStatus, errorThrown){
401
- $messageContainer.html('An error occurred, please try again.');
402
- }
403
- });
404
- });
405
- $('.toplevel_page_mwp-support').click(function (e) {
406
- e.preventDefault();
407
- $form.show();
408
- $messageContainer.empty();
409
- $dialog.dialog({
410
- draggable: false,
411
- resizable: false,
412
- modal: true,
413
- width: '530px',
414
- height: 'auto',
415
- title: 'Contact Support',
416
- close: function(){
417
- $('#support_response_id').html('');
418
- $( this ).dialog( "destroy" );
419
- }
420
- });
421
- });
422
- });
423
- </script>
424
- <?php
425
- }
426
-
427
- /**
428
- * Add Support page on Top Menu
429
- *
430
- */
431
- function add_support_page()
432
- {
433
- $mwp_worker_brand = get_option('mwp_worker_brand');
434
- if ($mwp_worker_brand && isset($mwp_worker_brand['text_for_client']) && ($mwp_worker_brand['text_for_client'] != '')) {
435
- add_menu_page(__('Support', 'wp-support'), __('Support', 'wp-support'), 'read', 'mwp-support', array(&$this, 'support_function'), '');
436
- }
437
- }
438
-
439
- /**
440
- * Support page handler
441
- *
442
- */
443
- function support_function()
444
- {
445
- }
446
-
447
-
448
- /**
449
- * Remove editor from plugins&themes submenu page
450
- *
451
- */
452
- function dissalow_text_editor(){
453
- $mwp_worker_brand = get_option('mwp_worker_brand');
454
- if($mwp_worker_brand && isset($mwp_worker_brand['dissalow_edit']) && ($mwp_worker_brand['dissalow_edit'] == 'checked')){
455
- define('DISALLOW_FILE_EDIT',true);
456
- define('DISALLOW_FILE_MODS',true);
457
- }
458
- }
459
-
460
- /**
461
- * Get parent blog options
462
- *
463
- */
464
- private function get_parent_blog_option( $option_name = '' )
465
- {
466
- global $wpdb;
467
- $option = $wpdb->get_var( $wpdb->prepare( "SELECT `option_value` FROM {$wpdb->base_prefix}options WHERE option_name = %s LIMIT 1", $option_name ) );
468
- return $option;
469
- }
470
-
471
- /**
472
- * Gets an instance of the Comment class
473
- *
474
- */
475
- function get_comment_instance()
476
- {
477
- if (!isset($this->comment_instance)) {
478
- $this->comment_instance = new MMB_Comment();
479
- }
480
-
481
- return $this->comment_instance;
482
- }
483
-
484
- /**
485
- * Gets an instance of the Plugin class
486
- *
487
- */
488
- function get_plugin_instance()
489
- {
490
- if (!isset($this->plugin_instance)) {
491
- $this->plugin_instance = new MMB_Plugin();
492
- }
493
-
494
- return $this->plugin_instance;
495
- }
496
-
497
- /**
498
- * Gets an instance of the Theme class
499
- *
500
- */
501
- function get_theme_instance()
502
- {
503
- if (!isset($this->theme_instance)) {
504
- $this->theme_instance = new MMB_Theme();
505
- }
506
-
507
- return $this->theme_instance;
508
- }
509
-
510
-
511
- /**
512
- * Gets an instance of MMB_Post class
513
- *
514
- */
515
- function get_post_instance()
516
- {
517
- if (!isset($this->post_instance)) {
518
- $this->post_instance = new MMB_Post();
519
- }
520
-
521
- return $this->post_instance;
522
- }
523
-
524
- /**
525
- * Gets an instance of Blogroll class
526
- *
527
- */
528
- function get_blogroll_instance()
529
- {
530
- if (!isset($this->blogroll_instance)) {
531
- $this->blogroll_instance = new MMB_Blogroll();
532
- }
533
-
534
- return $this->blogroll_instance;
535
- }
536
-
537
-
538
-
539
- /**
540
- * Gets an instance of the WP class
541
- *
542
- */
543
- function get_wp_instance()
544
- {
545
- if (!isset($this->wp_instance)) {
546
- $this->wp_instance = new MMB_WP();
547
- }
548
-
549
- return $this->wp_instance;
550
- }
551
-
552
- /**
553
- * Gets an instance of User
554
- *
555
- */
556
- function get_user_instance()
557
- {
558
- if (!isset($this->user_instance)) {
559
- $this->user_instance = new MMB_User();
560
- }
561
-
562
- return $this->user_instance;
563
- }
564
- /**
565
- * Gets an instance of Security
566
- *
567
- */
568
- function get_security_instance()
569
- {
570
- if (!isset($this->security_instance)) {
571
- $this->security_instance = new MMB_Security();
572
- }
573
-
574
- return $this->security_instance;
575
- }
576
-
577
-
578
- /**
579
- * Gets an instance of stats class
580
- *
581
- */
582
- function get_stats_instance()
583
- {
584
- if (!isset($this->stats_instance)) {
585
- $this->stats_instance = new MMB_Stats();
586
- }
587
- return $this->stats_instance;
588
- }
589
- /**
590
- * Gets an instance of search class
591
- *
592
- */
593
- function get_search_instance()
594
- {
595
- if (!isset($this->search_instance)) {
596
- $this->search_instance = new MMB_Search();
597
- }
598
- //return $this->search_instance;
599
- return $this->search_instance;
600
- }
601
- /**
602
- * Gets an instance of stats class
603
- *
604
- */
605
- function get_backup_instance()
606
- {
607
- if (!isset($this->backup_instance)) {
608
- $this->backup_instance = new MMB_Backup();
609
- }
610
-
611
- return $this->backup_instance;
612
- }
613
-
614
- /**
615
- * Gets an instance of links class
616
- *
617
- */
618
- function get_link_instance()
619
- {
620
- if (!isset($this->link_instance)) {
621
- $this->link_instance = new MMB_Link();
622
- }
623
-
624
- return $this->link_instance;
625
- }
626
-
627
- function get_installer_instance()
628
- {
629
- if (!isset($this->installer_instance)) {
630
- $this->installer_instance = new MMB_Installer();
631
- }
632
- return $this->installer_instance;
633
- }
634
-
635
- /**
636
- * Plugin install callback function
637
- * Check PHP version
638
- */
639
- function install() {
640
-
641
- global $wpdb, $_wp_using_ext_object_cache, $current_user;
642
- $_wp_using_ext_object_cache = false;
643
-
644
- //delete plugin options, just in case
645
- if ($this->mmb_multisite != false) {
646
- $network_blogs = $wpdb->get_results("select `blog_id`, `site_id` from `{$wpdb->blogs}`");
647
- if(!empty($network_blogs)){
648
- if( is_network_admin() ){
649
- update_option('mmb_network_admin_install', 1);
650
- foreach($network_blogs as $details){
651
- if($details->site_id == $details->blog_id)
652
- update_blog_option($details->blog_id, 'mmb_network_admin_install', 1);
653
- else
654
- update_blog_option($details->blog_id, 'mmb_network_admin_install', -1);
655
-
656
- delete_blog_option($blog_id, '_worker_nossl_key');
657
- delete_blog_option($blog_id, '_worker_public_key');
658
- delete_blog_option($blog_id, '_action_message_id');
659
- }
660
- } else {
661
- update_option('mmb_network_admin_install', -1);
662
- delete_option('_worker_nossl_key');
663
- delete_option('_worker_public_key');
664
- delete_option('_action_message_id');
665
- }
666
- }
667
- } else {
668
- delete_option('_worker_nossl_key');
669
- delete_option('_worker_public_key');
670
- delete_option('_action_message_id');
671
- }
672
-
673
- //delete_option('mwp_backup_tasks');
674
- delete_option('mwp_notifications');
675
- delete_option('mwp_worker_brand');
676
- delete_option('mwp_pageview_alerts');
677
- }
678
-
679
- /**
680
- * Saves the (modified) options into the database
681
- *
682
- */
683
- function save_options( $options = array() ){
684
- global $_mmb_options;
685
-
686
- $_mmb_options = array_merge( $_mmb_options, $options );
687
- update_option('wrksettings', $options);
688
- }
689
-
690
- /**
691
- * Deletes options for communication with master
692
- *
693
- */
694
- function uninstall( $deactivate = false )
695
- {
696
- global $current_user, $wpdb, $_wp_using_ext_object_cache;
697
- $_wp_using_ext_object_cache = false;
698
-
699
- if ($this->mmb_multisite != false) {
700
- $network_blogs = $wpdb->get_col("select `blog_id` from `{$wpdb->blogs}`");
701
- if(!empty($network_blogs)){
702
- if( is_network_admin() ){
703
- if( $deactivate ) {
704
- delete_option('mmb_network_admin_install');
705
- foreach($network_blogs as $blog_id){
706
- delete_blog_option($blog_id, 'mmb_network_admin_install');
707
- delete_blog_option($blog_id, '_worker_nossl_key');
708
- delete_blog_option($blog_id, '_worker_public_key');
709
- delete_blog_option($blog_id, '_action_message_id');
710
- delete_blog_option($blog_id, 'mwp_maintenace_mode');
711
- //delete_blog_option($blog_id, 'mwp_backup_tasks');
712
- delete_blog_option($blog_id, 'mwp_notifications');
713
- delete_blog_option($blog_id, 'mwp_worker_brand');
714
- delete_blog_option($blog_id, 'mwp_pageview_alerts');
715
- delete_blog_option($blog_id, 'mwp_pageview_alerts');
716
- }
717
- }
718
- } else {
719
- if( $deactivate )
720
- delete_option('mmb_network_admin_install');
721
-
722
- delete_option('_worker_nossl_key');
723
- delete_option('_worker_public_key');
724
- delete_option('_action_message_id');
725
- }
726
- }
727
- } else {
728
- delete_option('_worker_nossl_key');
729
- delete_option('_worker_public_key');
730
- delete_option('_action_message_id');
731
- }
732
-
733
- //Delete options
734
- delete_option('mwp_maintenace_mode');
735
- //delete_option('mwp_backup_tasks');
736
- delete_option('mwp_notifications');
737
- delete_option('mwp_worker_brand');
738
- delete_option('mwp_pageview_alerts');
739
- wp_clear_scheduled_hook('mwp_backup_tasks');
740
- wp_clear_scheduled_hook('mwp_notifications');
741
- wp_clear_scheduled_hook('mwp_datasend');
742
- }
743
-
744
-
745
- /**
746
- * Constructs a url (for ajax purpose)
747
- *
748
- * @param mixed $base_page
749
- */
750
- function construct_url($params = array(), $base_page = 'index.php')
751
- {
752
- $url = "$base_page?_wpnonce=" . wp_create_nonce($this->slug);
753
- foreach ($params as $key => $value) {
754
- $url .= "&$key=$value";
755
- }
756
-
757
- return $url;
758
- }
759
-
760
- /**
761
- * Worker update
762
- *
763
- */
764
- function update_worker_plugin($params)
765
- {
766
- extract($params);
767
- if ($download_url) {
768
- @include_once ABSPATH . 'wp-admin/includes/file.php';
769
- @include_once ABSPATH . 'wp-admin/includes/misc.php';
770
- @include_once ABSPATH . 'wp-admin/includes/template.php';
771
- @include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
772
- @include_once ABSPATH . 'wp-admin/includes/screen.php';
773
-
774
- if (!$this->is_server_writable()) {
775
- return array(
776
- 'error' => 'Failed, please <a target="_blank" href="http://managewp.com/user-guide/faq/my-pluginsthemes-fail-to-update-or-i-receive-a-yellow-ftp-warning">add FTP details for automatic upgrades.</a>'
777
- );
778
- }
779
-
780
- ob_start();
781
- @unlink(dirname(__FILE__));
782
- $upgrader = new Plugin_Upgrader();
783
- $result = $upgrader->run(array(
784
- 'package' => $download_url,
785
- 'destination' => WP_PLUGIN_DIR,
786
- 'clear_destination' => true,
787
- 'clear_working' => true,
788
- 'hook_extra' => array(
789
- 'plugin' => 'worker/init.php'
790
- )
791
- ));
792
- ob_end_clean();
793
- if (is_wp_error($result) || !$result) {
794
- return array(
795
- 'error' => 'ManageWP Worker plugin could not be updated.'
796
- );
797
- } else {
798
- return array(
799
- 'success' => 'ManageWP Worker plugin successfully updated.'
800
- );
801
- }
802
- }
803
- return array(
804
- 'error' => 'Bad download path for worker installation file.'
805
- );
806
- }
807
-
808
- /**
809
- * Automatically logs in when called from Master
810
- *
811
- */
812
- function automatic_login()
813
- {
814
- $where = isset($_GET['mwp_goto']) ? $_GET['mwp_goto'] : false;
815
- $username = isset($_GET['username']) ? $_GET['username'] : '';
816
- $auto_login = isset($_GET['auto_login']) ? $_GET['auto_login'] : 0;
817
-
818
- if( !function_exists('is_user_logged_in') )
819
- include_once( ABSPATH.'wp-includes/pluggable.php' );
820
-
821
- if (( $auto_login && strlen(trim($username)) && !is_user_logged_in() ) || (isset($this->mmb_multisite) && $this->mmb_multisite )) {
822
- $signature = base64_decode($_GET['signature']);
823
- $message_id = trim($_GET['message_id']);
824
-
825
- $auth = $this->authenticate_message($where . $message_id, $signature, $message_id);
826
- if ($auth === true) {
827
-
828
- if (!headers_sent())
829
- header('P3P: CP="CAO PSA OUR"');
830
-
831
- if(!defined('MMB_USER_LOGIN'))
832
- define('MMB_USER_LOGIN', true);
833
-
834
- $siteurl = function_exists('get_site_option') ? get_site_option( 'siteurl' ) : get_option('siteurl');
835
- $user = $this->mmb_get_user_info($username);
836
- wp_set_current_user($user->ID);
837
-
838
- if(!defined('COOKIEHASH') || (isset($this->mmb_multisite) && $this->mmb_multisite) )
839
- wp_cookie_constants();
840
-
841
- wp_set_auth_cookie($user->ID);
842
- @mmb_worker_header();
843
-
844
- if((isset($this->mmb_multisite) && $this->mmb_multisite ) || isset($_REQUEST['mwpredirect'])){
845
- if(function_exists('wp_safe_redirect') && function_exists('admin_url')){
846
- wp_safe_redirect(admin_url($where));
847
- exit();
848
- }
849
- }
850
- } else {
851
- wp_die($auth['error']);
852
- }
853
- } elseif( is_user_logged_in() ) {
854
- @mmb_worker_header();
855
- if(isset($_REQUEST['mwpredirect'])){
856
- if(function_exists('wp_safe_redirect') && function_exists('admin_url')){
857
- wp_safe_redirect(admin_url($where));
858
- exit();
859
- }
860
- }
861
- }
862
- }
863
-
864
- function mmb_set_auth_cookie( $auth_cookie ){
865
- if(!defined('MMB_USER_LOGIN'))
866
- return false;
867
-
868
- if( !defined('COOKIEHASH') )
869
- wp_cookie_constants();
870
-
871
- $_COOKIE['wordpress_'.COOKIEHASH] = $auth_cookie;
872
-
873
- }
874
- function mmb_set_logged_in_cookie( $logged_in_cookie ){
875
- if(!defined('MMB_USER_LOGIN'))
876
- return false;
877
-
878
- if( !defined('COOKIEHASH') )
879
- wp_cookie_constants();
880
-
881
- $_COOKIE['wordpress_logged_in_'.COOKIEHASH] = $logged_in_cookie;
882
- }
883
-
884
- function admin_actions(){
885
- add_filter('all_plugins', array($this, 'worker_replace'));
886
- }
887
-
888
- function worker_replace($all_plugins){
889
- $replace = get_option("mwp_worker_brand");
890
- if(is_array($replace)){
891
- if($replace['name'] || $replace['desc'] || $replace['author'] || $replace['author_url']){
892
- $all_plugins['worker/init.php']['Name'] = $replace['name'];
893
- $all_plugins['worker/init.php']['Title'] = $replace['name'];
894
- $all_plugins['worker/init.php']['Description'] = $replace['desc'];
895
- $all_plugins['worker/init.php']['AuthorURI'] = $replace['author_url'];
896
- $all_plugins['worker/init.php']['Author'] = $replace['author'];
897
- $all_plugins['worker/init.php']['AuthorName'] = $replace['author'];
898
- $all_plugins['worker/init.php']['PluginURI'] = '';
899
- }
900
-
901
- if($replace['hide']){
902
- if (!function_exists('get_plugins')) {
903
- include_once(ABSPATH . 'wp-admin/includes/plugin.php');
904
- }
905
- $activated_plugins = get_option('active_plugins');
906
- if (!$activated_plugins)
907
- $activated_plugins = array();
908
- if(in_array('worker/init.php',$activated_plugins))
909
- unset($all_plugins['worker/init.php']);
910
- }
911
- }
912
-
913
-
914
- return $all_plugins;
915
- }
916
-
917
- }
918
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
functions.php ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ function mwp_autoload($class)
4
+ {
5
+ if (substr($class, 0, 8) === 'Dropbox_'
6
+ || substr($class, 0, 8) === 'Symfony_'
7
+ || substr($class, 0, 8) === 'Monolog_'
8
+ || substr($class, 0, 5) === 'Gelf_'
9
+ || substr($class, 0, 4) === 'MWP_'
10
+ || substr($class, 0, 4) === 'MMB_'
11
+ || substr($class, 0, 3) === 'S3_'
12
+ ) {
13
+ $file = dirname(__FILE__).'/src/'.str_replace('_', '/', $class).'.php';
14
+ if (file_exists($file)) {
15
+ include_once $file;
16
+ }
17
+ }
18
+ }
19
+
20
+ function mwp_register_autoload_google()
21
+ {
22
+ static $registered;
23
+
24
+ if ($registered) {
25
+ return;
26
+ } else {
27
+ $registered = true;
28
+ }
29
+
30
+ if (version_compare(PHP_VERSION, '5.3', '<')) {
31
+ spl_autoload_register('mwp_autoload_google');
32
+ } else {
33
+ spl_autoload_register('mwp_autoload_google', true, true);
34
+ }
35
+ }
36
+
37
+ function mwp_autoload_google($class)
38
+ {
39
+ if (substr($class, 0, 7) === 'Google_') {
40
+ $file = dirname(__FILE__).'/src/'.str_replace('_', '/', $class).'.php';
41
+ if (file_exists($file)) {
42
+ include_once $file;
43
+ }
44
+ }
45
+ }
46
+
47
+ function mwp_container()
48
+ {
49
+ static $container;
50
+
51
+ if ($container === null) {
52
+ $parameters = get_option('mwp_container_parameters', array());
53
+ $container = new MMB_Container($parameters);
54
+ }
55
+
56
+ return $container;
57
+ }
58
+
59
+ /**
60
+ * @return Monolog_Psr_LoggerInterface
61
+ */
62
+ function mwp_logger()
63
+ {
64
+ static $mwp_logger;
65
+ if (!get_option('mwp_debug_enable', false)) {
66
+ if ($mwp_logger === null) {
67
+ $mwp_logger = new Monolog_Logger('worker', array(new Monolog_Handler_NullHandler()));
68
+ }
69
+
70
+ return $mwp_logger;
71
+ }
72
+ if ($mwp_logger instanceof Monolog_Logger) {
73
+ return $mwp_logger;
74
+ }
75
+ if ($mwp_logger === null) {
76
+ $mwp_logger = true;
77
+ $logger = mwp_container()->getLogger();
78
+ Monolog_Registry::addLogger($logger, 'worker');
79
+
80
+ $errorHandler = new Monolog_ErrorHandler($logger);
81
+ $errorHandler->registerErrorHandler();
82
+ $errorHandler->registerExceptionHandler();
83
+ $errorHandler->registerFatalHandler(null, 1024);
84
+ }
85
+
86
+ return Monolog_Registry::getInstance('worker');
87
+ }
88
+
89
+ /**
90
+ * @param $appKey
91
+ * @param $appSecret
92
+ * @param $token
93
+ * @param $tokenSecret
94
+ *
95
+ * @return Dropbox_Client
96
+ */
97
+ function mwp_dropbox_oauth1_factory($appKey, $appSecret, $token, $tokenSecret)
98
+ {
99
+ $oauthToken ='OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.$appKey.'", oauth_token="'.$token.'", oauth_signature="'.$appSecret.'&'.$tokenSecret.'"';
100
+ $client = new Dropbox_Client($oauthToken, $token);
101
+
102
+ return $client;
103
+ }
104
+
105
+ function mwp_format_memory_limit($limit)
106
+ {
107
+ if ((string) (int) $limit === (string) $limit) {
108
+ // The number is numeric.
109
+ return mwp_format_bytes($limit);
110
+ }
111
+
112
+ $units = strtolower(substr($limit, -1));
113
+
114
+ if (!in_array($units, array('b', 'k', 'm', 'g'))) {
115
+ // Invalid size unit.
116
+ return $limit;
117
+ }
118
+
119
+ $number = substr($limit, 0, -1);
120
+
121
+ if ((string) (int) $number !== $number) {
122
+ // The number isn't numeric.
123
+ return $number;
124
+ }
125
+
126
+ switch ($units) {
127
+ case 'g':
128
+ return $number.' GB';
129
+ case 'm':
130
+ return $number.' MB';
131
+ case 'k':
132
+ return $number.' KB';
133
+ case 'b':
134
+ default:
135
+ return $number.' B';
136
+ }
137
+ }
138
+
139
+
140
+ function mwp_format_bytes($bytes)
141
+ {
142
+ $bytes = (int) $bytes;
143
+
144
+ if ($bytes > 1024 * 1024 * 1024) {
145
+ return round($bytes / 1024 / 1024 / 1024, 2).' GB';
146
+ } elseif ($bytes > 1024 * 1024) {
147
+ return round($bytes / 1024 / 1024, 2).' MB';
148
+ } elseif ($bytes > 1024) {
149
+ return round($bytes / 1024, 2).' KB';
150
+ }
151
+
152
+ return $bytes.' B';
153
+ }
154
+
155
+ function mwp_log_warnings()
156
+ {
157
+ // If mbstring.func_overload is set, it changes the behavior of the standard string functions in
158
+ // ways that makes external libraries like Dropbox break.
159
+ $mbstring_func_overload = ini_get("mbstring.func_overload");
160
+ if ($mbstring_func_overload & 2 == 2) {
161
+ mwp_logger()->warning('"mbstring.func_overload" changes the behavior of the standard string functions in ways that makes external libraries like Dropbox break');
162
+ }
163
+
164
+ if (strlen((string) PHP_INT_MAX) < 19) {
165
+ // Looks like we're running on a 32-bit build of PHP. This could cause problems because some of the numbers
166
+ // we use (file sizes, quota, etc) can be larger than 32-bit ints can handle.
167
+ mwp_logger()->warning("Some external libraries rely on 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=".((string) PHP_INT_MAX).").");
168
+ }
169
+ }
170
+
171
+ function search_posts_by_term($params = false)
172
+ {
173
+
174
+ global $wpdb, $current_user;
175
+
176
+ $search_type = trim($params['search_type']);
177
+ $search_term = strtolower(trim($params['search_term']));
178
+ switch ($search_type) {
179
+ case 'page_post':
180
+ $num_posts = 10;
181
+ $num_content_char = 30;
182
+
183
+ $term_orig = trim($params['search_term']);
184
+
185
+ $term_base = addslashes(trim($params['search_term']));
186
+
187
+ $query = "SELECT *
188
+ FROM $wpdb->posts
189
+ WHERE $wpdb->posts.post_status = 'publish'
190
+ AND ($wpdb->posts.post_title LIKE '%$term_base%'
191
+ OR $wpdb->posts.post_content LIKE '%$term_base%')
192
+ ORDER BY $wpdb->posts.post_modified DESC
193
+ LIMIT 0, $num_posts
194
+ ";
195
+
196
+ $posts_array = $wpdb->get_results($query);
197
+
198
+ $ret_posts = array();
199
+
200
+ foreach ($posts_array as $post) {
201
+ //highlight searched term
202
+
203
+ if (substr_count(strtolower($post->post_title), strtolower($term_orig))) {
204
+ $str_position_start = strpos(strtolower($post->post_title), strtolower($term_orig));
205
+
206
+ $post->post_title = substr($post->post_title, 0, $str_position_start).'<b>'.
207
+ substr($post->post_title, $str_position_start, strlen($term_orig)).'</b>'.
208
+ substr($post->post_title, $str_position_start + strlen($term_orig));
209
+
210
+ }
211
+ $post->post_content = html_entity_decode($post->post_content);
212
+
213
+ $post->post_content = strip_tags($post->post_content);
214
+
215
+
216
+ if (substr_count(strtolower($post->post_content), strtolower($term_orig))) {
217
+ $str_position_start = strpos(strtolower($post->post_content), strtolower($term_orig));
218
+
219
+ $start = $str_position_start > $num_content_char ? $str_position_start - $num_content_char : 0;
220
+ $first_len = $str_position_start > $num_content_char ? $num_content_char : $str_position_start;
221
+
222
+ $start_substring = $start > 0 ? '...' : '';
223
+ $post->post_content = $start_substring.substr($post->post_content, $start, $first_len).'<b>'.
224
+ substr($post->post_content, $str_position_start, strlen($term_orig)).'</b>'.
225
+ substr($post->post_content, $str_position_start + strlen($term_orig), $num_content_char).'...';
226
+
227
+
228
+ } else {
229
+ $post->post_content = substr($post->post_content, 0, 50).'...';
230
+ }
231
+
232
+ $ret_posts[] = array(
233
+ 'ID' => $post->ID,
234
+ 'post_permalink' => get_permalink($post->ID),
235
+ 'post_date' => $post->post_date,
236
+ 'post_title' => $post->post_title,
237
+ 'post_content' => $post->post_content,
238
+ 'post_modified' => $post->post_modified,
239
+ 'comment_count' => $post->comment_count,
240
+ );
241
+ }
242
+ mmb_response($ret_posts, true);
243
+ break;
244
+
245
+ case 'plugin':
246
+ $plugins = get_option('active_plugins');
247
+
248
+ if (!function_exists('get_plugin_data')) {
249
+ include_once(ABSPATH.'/wp-admin/includes/plugin.php');
250
+ }
251
+
252
+ $have_plugin = array();
253
+ foreach ($plugins as $plugin) {
254
+ $pl = WP_PLUGIN_DIR.'/'.$plugin;
255
+ $pl_extended = get_plugin_data($pl);
256
+ $pl_name = $pl_extended['Name'];
257
+ if (strpos(strtolower($pl_name), $search_term) > -1) {
258
+
259
+ $have_plugin[] = $pl_name;
260
+ }
261
+ }
262
+ if ($have_plugin) {
263
+ mmb_response($have_plugin, true);
264
+ } else {
265
+ mmb_response('Not found', false);
266
+ }
267
+ break;
268
+ case 'theme':
269
+ $theme = strtolower(get_option('stylesheet'));
270
+ $tm = ABSPATH.'wp-content/themes/'.$theme.'/style.css';
271
+ $tm_extended = get_theme_data($tm);
272
+ $tm_name = $tm_extended['Name'];
273
+ $have_theme = array();
274
+ if (strpos(strtolower($tm_name), $search_term) > -1) {
275
+ $have_theme[] = $tm_name;
276
+ mmb_response($have_theme, true);
277
+ } else {
278
+ mmb_response('Not found', false);
279
+ }
280
+ break;
281
+ default:
282
+ mmb_response('Not found', false);
283
+ }
284
+ }
285
+
286
+ function mmb_add_action($action = false, $callback = false)
287
+ {
288
+ if (!$action || !$callback) {
289
+ return;
290
+ }
291
+
292
+ global $mmb_actions;
293
+
294
+ if (!is_callable($callback)) {
295
+ wp_die('The provided argument is not a valid callback');
296
+ }
297
+
298
+ if (isset($mmb_actions[$action])) {
299
+ wp_die('Cannot redeclare ManageWP action "'.$action.'".');
300
+ }
301
+
302
+ $mmb_actions[$action] = $callback;
303
+ }
304
+
305
+ function mmb_get_extended_info($stats)
306
+ {
307
+ $params = get_option('mmb_stats_filter');
308
+ $filter = isset($params['plugins']['cleanup']) ? $params['plugins']['cleanup'] : array();
309
+ $stats['num_revisions'] = mmb_num_revisions($filter['revisions']);
310
+ //$stats['num_revisions'] = 5;
311
+ $stats['overhead'] = mmb_handle_overhead(false);
312
+ $stats['num_spam_comments'] = mmb_num_spam_comments();
313
+
314
+ return $stats;
315
+ }
316
+
317
+ /* Revisions */
318
+ function cleanup_delete_worker($params = array())
319
+ {
320
+ $revision_params = get_option('mmb_stats_filter');
321
+ $revision_filter = isset($revision_params['plugins']['cleanup']) ? $revision_params['plugins']['cleanup'] : array();
322
+
323
+ $params_array = explode('_', $params['actions']);
324
+ $return_array = array();
325
+
326
+ foreach ($params_array as $param) {
327
+ switch ($param) {
328
+ case 'revision':
329
+ if (mmb_delete_all_revisions($revision_filter['revisions'])) {
330
+ $return_array['revision'] = 'OK';
331
+ } else {
332
+ $return_array['revision_error'] = 'OK, nothing to do';
333
+ }
334
+ break;
335
+ case 'overhead':
336
+ if (mmb_handle_overhead(true)) {
337
+ $return_array['overhead'] = 'OK';
338
+ } else {
339
+ $return_array['overhead_error'] = 'OK, nothing to do';
340
+ }
341
+ break;
342
+ case 'comment':
343
+ if (mmb_delete_spam_comments()) {
344
+ $return_array['comment'] = 'OK';
345
+ } else {
346
+ $return_array['comment_error'] = 'OK, nothing to do';
347
+ }
348
+ break;
349
+ default:
350
+ break;
351
+ }
352
+
353
+ }
354
+
355
+ unset($params);
356
+
357
+ mmb_response($return_array, true);
358
+ }
359
+
360
+ function mmb_num_revisions($filter)
361
+ {
362
+ global $wpdb;
363
+
364
+ $allRevisions = $wpdb->get_results("SELECT ID, post_name FROM {$wpdb->posts} WHERE post_type = 'revision'", ARRAY_A);
365
+
366
+ $revisionsToDelete = 0;
367
+ $revisionsToKeepCount = array();
368
+
369
+ if (isset($filter['num_to_keep']) && !empty($filter['num_to_keep'])) {
370
+ $num_rev = str_replace("r_", "", $filter['num_to_keep']);
371
+
372
+ foreach ($allRevisions as $revision) {
373
+ $revisionsToKeepCount[$revision['post_name']] = isset($revisionsToKeepCount[$revision['post_name']])
374
+ ? $revisionsToKeepCount[$revision['post_name']] + 1
375
+ : 1;
376
+
377
+ if ($revisionsToKeepCount[$revision['post_name']] > $num_rev) {
378
+ ++$revisionsToDelete;
379
+ }
380
+ }
381
+ } else {
382
+ $revisionsToDelete = count($allRevisions);
383
+ }
384
+
385
+ return $revisionsToDelete;
386
+ }
387
+
388
+ function mmb_select_all_revisions()
389
+ {
390
+ global $wpdb;
391
+ $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'revision'";
392
+ $revisions = $wpdb->get_results($sql);
393
+
394
+ return $revisions;
395
+ }
396
+
397
+ function mmb_delete_all_revisions($filter)
398
+ {
399
+ global $wpdb;
400
+ $where = '';
401
+ $keep = isset($filter['num_to_keep']) ? $filter['num_to_keep'] : false;
402
+ if ($keep) {
403
+ $num_rev = str_replace("r_", "", $keep);
404
+ $allRevisions = $wpdb->get_results("SELECT ID, post_name FROM {$wpdb->posts} WHERE post_type = 'revision' ORDER BY post_date DESC", ARRAY_A);
405
+ $revisionsToKeep = array(0 => 0);
406
+ $revisionsToKeepCount = array();
407
+
408
+ foreach ($allRevisions as $revision) {
409
+ $revisionsToKeepCount[$revision['post_name']] = isset($revisionsToKeepCount[$revision['post_name']])
410
+ ? $revisionsToKeepCount[$revision['post_name']] + 1
411
+ : 1;
412
+
413
+ if ($revisionsToKeepCount[$revision['post_name']] <= $num_rev) {
414
+ $revisionsToKeep[] = $revision['ID'];
415
+ }
416
+ }
417
+
418
+ $notInQuery = join(', ', $revisionsToKeep);
419
+
420
+ $where = "AND a.ID NOT IN ({$notInQuery})";
421
+ }
422
+
423
+ $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' {$where}";
424
+
425
+ $revisions = $wpdb->query($sql);
426
+
427
+ return $revisions;
428
+ }
429
+
430
+ function mmb_handle_overhead($clear = false)
431
+ {
432
+ /** @var wpdb $wpdb */
433
+ global $wpdb;
434
+ $query = 'SHOW TABLE STATUS';
435
+ $tables = $wpdb->get_results($query, ARRAY_A);
436
+ $total_gain = 0;
437
+ $table_string = '';
438
+ foreach ($tables as $table) {
439
+ if (isset($table['Engine']) && $table['Engine'] === 'MyISAM') {
440
+ if ($wpdb->base_prefix != $wpdb->prefix) {
441
+ if (preg_match('/^'.$wpdb->prefix.'*/Ui', $table['Name'])) {
442
+ if ($table['Data_free'] > 0) {
443
+ $total_gain += $table['Data_free'] / 1024;
444
+ $table_string .= $table['Name'].",";
445
+ }
446
+ }
447
+ } else {
448
+ if (preg_match('/^'.$wpdb->prefix.'[0-9]{1,20}_*/Ui', $table['Name'])) {
449
+ continue;
450
+ } else {
451
+ if ($table['Data_free'] > 0) {
452
+ $total_gain += $table['Data_free'] / 1024;
453
+ $table_string .= $table['Name'].",";
454
+ }
455
+ }
456
+ }
457
+ // @todo check if the cleanup was successful, if not, set a flag always skip innodb cleanup
458
+ //} elseif (isset($table['Engine']) && $table['Engine'] == 'InnoDB') {
459
+ // $innodb_file_per_table = $wpdb->get_results("SHOW VARIABLES LIKE 'innodb_file_per_table'");
460
+ // if (isset($innodb_file_per_table[0]->Value) && $innodb_file_per_table[0]->Value === "ON") {
461
+ // if ($table['Data_free'] > 0) {
462
+ // $total_gain += $table['Data_free'] / 1024;
463
+ // $table_string .= $table['Name'].",";
464
+ // }
465
+ // }
466
+ }
467
+ }
468
+
469
+ if ($clear) {
470
+ $table_string = substr($table_string, 0, strlen($table_string) - 1); //remove last ,
471
+ $table_string = rtrim($table_string);
472
+ $query = "OPTIMIZE TABLE $table_string";
473
+ $optimize = $wpdb->query($query);
474
+
475
+ return (bool)$optimize;
476
+ } else {
477
+ return round($total_gain, 3);
478
+ }
479
+ }
480
+
481
+
482
+ /* Spam Comments */
483
+ function mmb_num_spam_comments()
484
+ {
485
+ global $wpdb;
486
+ $sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = 'spam'";
487
+ $num_spams = $wpdb->get_var($sql);
488
+
489
+ return $num_spams;
490
+ }
491
+
492
+ function mmb_delete_spam_comments()
493
+ {
494
+ global $wpdb;
495
+ $spam = 1;
496
+ $total = 0;
497
+ while (!empty($spam)) {
498
+ $getCommentIds = "SELECT comment_ID FROM $wpdb->comments WHERE comment_approved = 'spam' LIMIT 200";
499
+ $spam = $wpdb->get_results($getCommentIds);
500
+ foreach ($spam as $comment) {
501
+ wp_delete_comment($comment->comment_ID, true);
502
+ }
503
+ $total += count($spam);
504
+ if (!empty($spam)) {
505
+ usleep(100000);
506
+ }
507
+ }
508
+
509
+ return $total;
510
+ }
511
+
512
+ function mmb_get_spam_comments()
513
+ {
514
+ global $wpdb;
515
+ $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'";
516
+ $spams = $wpdb->get_results($sql);
517
+
518
+ return $spams;
519
+ }
520
+
521
+ function mwp_is_nio_shell_available()
522
+ {
523
+ static $check;
524
+ if(isset($check)){
525
+ return $check;
526
+ }
527
+ try {
528
+ $process = new Symfony_Process_Process("cd .", dirname(__FILE__), array(), null, 1);
529
+ $process->run();
530
+ $check = $process->isSuccessful();
531
+ } catch (Exception $e) {
532
+ $check = false;
533
+ }
534
+ return $check;
535
+ }
536
+
537
+ function mwp_is_shell_available()
538
+ {
539
+ if (mwp_is_safe_mode()) {
540
+ return false;
541
+ }
542
+ if (!function_exists('proc_open') || !function_exists('escapeshellarg')) {
543
+ return false;
544
+ }
545
+
546
+ if (extension_loaded('suhosin') && $suhosin = ini_get('suhosin.executor.func.blacklist')) {
547
+ $suhosin = explode(',', $suhosin);
548
+ $blacklist = array_map('trim', $suhosin);
549
+ $blacklist = array_map('strtolower', $blacklist);
550
+ if (in_array('proc_open', $blacklist)) {
551
+ return false;
552
+ }
553
+ }
554
+
555
+ if (!mwp_is_nio_shell_available()) {
556
+ return false;
557
+ }
558
+
559
+ return true;
560
+ }
561
+
562
+ function mwp_is_safe_mode()
563
+ {
564
+ $value = ini_get("safe_mode");
565
+ if ((int) $value === 0 || strtolower($value) === "off") {
566
+ return false;
567
+ }
568
+
569
+ return true;
570
+ }
helper.class.php DELETED
@@ -1,562 +0,0 @@
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
- define('MWP_SHOW_LOG', false);
14
-
15
- class MMB_Helper
16
- {
17
- /**
18
- * A helper function to log data
19
- *
20
- * @param mixed $mixed
21
- */
22
- function _log($mixed)
23
- {
24
- if(defined('MWP_SHOW_LOG') && MWP_SHOW_LOG == true){
25
- if (is_array($mixed)) {
26
- $mixed = print_r($mixed, 1);
27
- } else if (is_object($mixed)) {
28
- ob_start();
29
- var_dump($mixed);
30
- $mixed = ob_get_clean();
31
- }
32
-
33
- $md5 = get_option('mwp_log_md5');
34
- if ($md5 === false) {
35
- $md5 = md5(date('jS F Y h:i:s A'));
36
- update_option('mwp_log_md5', $md5);
37
- }
38
- $handle = fopen(dirname(__FILE__) . '/log_'.$md5, 'a');
39
- fwrite($handle, $mixed . PHP_EOL);
40
- fclose($handle);
41
- }
42
- }
43
-
44
- function _escape(&$array)
45
- {
46
- global $wpdb;
47
-
48
- if (!is_array($array)) {
49
- return ($wpdb->escape($array));
50
- } else {
51
- foreach ((array) $array as $k => $v) {
52
- if (is_array($v)) {
53
- $this->_escape($array[$k]);
54
- } else if (is_object($v)) {
55
- //skip
56
- } else {
57
- $array[$k] = $wpdb->escape($v);
58
- }
59
- }
60
- }
61
- }
62
-
63
- /**
64
- * Initializes the file system
65
- *
66
- */
67
- function init_filesystem()
68
- {
69
- global $wp_filesystem;
70
-
71
- if (!$wp_filesystem || !is_object($wp_filesystem)) {
72
- WP_Filesystem();
73
- }
74
-
75
- if (!is_object($wp_filesystem))
76
- return FALSE;
77
-
78
- return TRUE;
79
- }
80
-
81
- /**
82
- *
83
- * Check if function exists or not on `suhosin` black list
84
- *
85
- */
86
-
87
- function mmb_get_user_info( $user_info = false, $info = 'login' ){
88
-
89
- if($user_info === false)
90
- return false;
91
-
92
- if( strlen( trim( $user_info ) ) == 0)
93
- return false;
94
-
95
-
96
- global $wp_version;
97
- if (version_compare($wp_version, '3.2.2', '<=')){
98
- return get_userdatabylogin( $user_info );
99
- } else {
100
- return get_user_by( $info, $user_info );
101
- }
102
- }
103
-
104
- /**
105
- *
106
- * Call action item filters
107
- *
108
- */
109
-
110
- function mmb_parse_action_params( $key = '', $params = null, $call_object = null ){
111
-
112
- global $_mmb_item_filter;
113
- $call_object = $call_object !== null ? $call_object : $this;
114
- $return = array();
115
-
116
- if(isset($_mmb_item_filter[$key]) && !empty($_mmb_item_filter[$key])){
117
- if( isset($params['item_filter']) && !empty($params['item_filter'])){
118
- foreach($params['item_filter'] as $_items){
119
- if(!empty($_items)){
120
- foreach($_items as $_item){
121
- if(isset($_item[0]) && in_array($_item[0], $_mmb_item_filter[$key])){
122
- $_item[1] = isset($_item[1]) ? $_item[1] : array();
123
- $return = call_user_func(array( &$call_object, 'get_'.$_item[0]), $return, $_item[1]);
124
- }
125
- }
126
- }
127
- }
128
- }
129
- }
130
-
131
- return $return;
132
- }
133
-
134
- /**
135
- *
136
- * Check if function exists or not on `suhosin` black list
137
- *
138
- */
139
-
140
- function mmb_function_exists($function_callback){
141
-
142
- if(!function_exists($function_callback))
143
- return false;
144
-
145
- $disabled = explode(', ', @ini_get('disable_functions'));
146
- if (in_array($function_callback, $disabled))
147
- return false;
148
-
149
- if (extension_loaded('suhosin')) {
150
- $suhosin = @ini_get("suhosin.executor.func.blacklist");
151
- if (empty($suhosin) == false) {
152
- $suhosin = explode(',', $suhosin);
153
- $blacklist = array_map('trim', $suhosin);
154
- $blacklist = array_map('strtolower', $blacklist);
155
- if(in_array($function_callback, $blacklist))
156
- return false;
157
- }
158
- }
159
- return true;
160
- }
161
-
162
- /**
163
- * Gets transient based on WP version
164
- *
165
- * @global string $wp_version
166
- * @param string $option_name
167
- * @return mixed
168
- */
169
-
170
- function mmb_set_transient($option_name = false, $data = false){
171
-
172
- if (!$option_name || !$data) {
173
- return false;
174
- }
175
- if($this->mmb_multisite)
176
- return $this->mmb_set_sitemeta_transient($option_name, $data);
177
-
178
- global $wp_version;
179
-
180
- if (version_compare($wp_version, '2.7.9', '<=')) {
181
- update_option($option_name, $data);
182
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
183
- update_option('_transient_' . $option_name, $data);
184
- } else {
185
- update_option('_site_transient_' . $option_name, $data);
186
- }
187
-
188
- }
189
- function mmb_get_transient($option_name)
190
- {
191
- if (trim($option_name) == '') {
192
- return FALSE;
193
- }
194
- if($this->mmb_multisite)
195
- return $this->mmb_get_sitemeta_transient($option_name);
196
-
197
- global $wp_version;
198
-
199
- $transient = array();
200
-
201
- if (version_compare($wp_version, '2.7.9', '<=')) {
202
- return get_option($option_name);
203
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
204
- $transient = get_option('_transient_' . $option_name);
205
- return apply_filters("transient_".$option_name, $transient);
206
- } else {
207
- $transient = get_option('_site_transient_' . $option_name);
208
- return apply_filters("site_transient_".$option_name, $transient);
209
- }
210
- }
211
-
212
- function mmb_delete_transient($option_name)
213
- {
214
- if (trim($option_name) == '') {
215
- return FALSE;
216
- }
217
-
218
- global $wp_version;
219
-
220
- if (version_compare($wp_version, '2.7.9', '<=')) {
221
- delete_option($option_name);
222
- } else if (version_compare($wp_version, '2.9.9', '<=')) {
223
- delete_option('_transient_' . $option_name);
224
- } else {
225
- delete_option('_site_transient_' . $option_name);
226
- }
227
- }
228
-
229
- function mmb_get_sitemeta_transient($option_name){
230
- global $wpdb;
231
- $option_name = '_site_transient_'. $option_name;
232
-
233
- $result = $wpdb->get_var( $wpdb->prepare("SELECT `meta_value` FROM `{$wpdb->sitemeta}` WHERE meta_key = %s AND `site_id` = %s", $option_name, $this->mmb_multisite));
234
- $result = maybe_unserialize($result);
235
- return $result;
236
- }
237
-
238
- function mmb_set_sitemeta_transient($option_name, $option_value){
239
- global $wpdb;
240
- $option_name = '_site_transient_'. $option_name;
241
-
242
- if($this->mmb_get_sitemeta_transient($option_name)){
243
- $result = $wpdb->update( $wpdb->sitemeta,
244
- array(
245
- 'meta_value' => maybe_serialize($option_value)
246
- ),
247
- array(
248
- 'meta_key' => $option_name,
249
- 'site_id' => $this->mmb_multisite
250
- )
251
- );
252
- }else {
253
- $result = $wpdb->insert( $wpdb->sitemeta,
254
- array(
255
- 'meta_key' => $option_name,
256
- 'meta_value' => maybe_serialize($option_value),
257
- 'site_id' => $this->mmb_multisite
258
- )
259
- );
260
- }
261
- return $result;
262
- }
263
-
264
- function delete_temp_dir($directory)
265
- {
266
- if (substr($directory, -1) == "/") {
267
- $directory = substr($directory, 0, -1);
268
- }
269
- if (!file_exists($directory) || !is_dir($directory)) {
270
- return false;
271
- } elseif (!is_readable($directory)) {
272
- return false;
273
- } else {
274
- $directoryHandle = opendir($directory);
275
-
276
- while ($contents = readdir($directoryHandle)) {
277
- if ($contents != '.' && $contents != '..') {
278
- $path = $directory . "/" . $contents;
279
-
280
- if (is_dir($path)) {
281
- $this->delete_temp_dir($path);
282
- } else {
283
- unlink($path);
284
- }
285
- }
286
- }
287
- closedir($directoryHandle);
288
- rmdir($directory);
289
- return true;
290
- }
291
- }
292
-
293
- function set_worker_message_id($message_id = false)
294
- {
295
- if ($message_id) {
296
- add_option('_action_message_id', $message_id) or update_option('_action_message_id', $message_id);
297
- return $message_id;
298
- }
299
- return false;
300
- }
301
-
302
- function get_worker_message_id()
303
- {
304
- return (int) get_option('_action_message_id');
305
- }
306
-
307
- function set_master_public_key($public_key = false)
308
- {
309
- if ($public_key && !get_option('_worker_public_key')) {
310
- add_option('_worker_public_key', base64_encode($public_key));
311
- return true;
312
- }
313
- return false;
314
- }
315
-
316
- function get_master_public_key()
317
- {
318
- if (!get_option('_worker_public_key'))
319
- return false;
320
- return base64_decode(get_option('_worker_public_key'));
321
- }
322
-
323
-
324
- function get_random_signature()
325
- {
326
- if (!get_option('_worker_nossl_key'))
327
- return false;
328
- return base64_decode(get_option('_worker_nossl_key'));
329
- }
330
-
331
- function set_random_signature($random_key = false)
332
- {
333
- if ($random_key && !get_option('_worker_nossl_key')) {
334
- add_option('_worker_nossl_key', base64_encode($random_key));
335
- return true;
336
- }
337
- return false;
338
- }
339
-
340
-
341
- function authenticate_message($data = false, $signature = false, $message_id = false)
342
- {
343
- if (!$data && !$signature) {
344
- return array(
345
- 'error' => 'Authentication failed.'
346
- );
347
- }
348
-
349
- $current_message = $this->get_worker_message_id();
350
-
351
- if ((int) $current_message >= (int) $message_id)
352
- return array(
353
- 'error' => 'Invalid message recieved. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
354
- );
355
-
356
- $pl_key = $this->get_master_public_key();
357
- if (!$pl_key) {
358
- return array(
359
- 'error' => 'Authentication failed. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
360
- );
361
- }
362
-
363
- if (function_exists('openssl_verify') && !$this->get_random_signature()) {
364
- $verify = openssl_verify($data, $signature, $pl_key);
365
- if ($verify == 1) {
366
- $message_id = $this->set_worker_message_id($message_id);
367
- return true;
368
- } else if ($verify == 0) {
369
- return array(
370
- 'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
371
- );
372
- } else {
373
- return array(
374
- 'error' => 'Command not successful! Please try again.'
375
- );
376
- }
377
- } else if ($this->get_random_signature()) {
378
- if (md5($data . $this->get_random_signature()) === $signature) {
379
- $message_id = $this->set_worker_message_id($message_id);
380
- return true;
381
- }
382
- return array(
383
- 'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
384
- );
385
- }
386
- // no rand key - deleted in get_stat maybe
387
- else
388
- return array(
389
- 'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
390
- );
391
- }
392
-
393
- function get_secure_hash(){
394
-
395
- $pl_key = $this->get_master_public_key();
396
- if ( empty($pl_key) )
397
- $pl_key = $this->get_random_signature();
398
-
399
- if( !empty($pl_key) )
400
- return md5(base64_encode($pl_key));
401
-
402
- return false;
403
- }
404
-
405
- function _secure_data($data = false){
406
- if($data == false)
407
- return false;
408
-
409
- $pl_key = $this->get_master_public_key();
410
- if (!$pl_key)
411
- return false;
412
-
413
- $secure = '';
414
- if( function_exists('openssl_public_decrypt') && !$this->get_random_signature() ){
415
- if(is_array($data) && !empty($data)){
416
- foreach($data as $input){
417
- openssl_public_decrypt($input, $decrypted, $pl_key);
418
- $secure .= $decrypted;
419
- }
420
- } else if ( is_string( $data ) ) {
421
- openssl_public_decrypt($data, $decrypted, $pl_key);
422
- $secure = $decrypted;
423
- } else {
424
- $secure = $data;
425
- }
426
- return $secure;
427
- }
428
- return false;
429
-
430
- }
431
-
432
- function encrypt_data( $data = false, $single = false ){
433
- if( empty($data) )
434
- return $data;
435
-
436
- $pl_key = $this->get_master_public_key();
437
- if ( !$pl_key )
438
- return false;
439
-
440
- $data = serialize( $data );
441
- $crypted = '';
442
- if( function_exists('openssl_public_encrypt') && !$this->get_random_signature() ){
443
- $length = strlen( $data );
444
- if( $length > 100 ){
445
- for($i = 0; $i <= $length + 100; $i = $i+100){
446
- $input = substr($data, $i, 100);
447
- openssl_public_encrypt($input, $crypt, $pl_key);
448
- $crypted .= base64_encode($crypt).'::';
449
- }
450
- } else
451
- openssl_public_encrypt($input, $crypted, $pl_key);
452
- } else {
453
- $crypted = base64_encode($data);
454
- }
455
-
456
- return $crypted;
457
-
458
- }
459
-
460
- function check_if_user_exists($username = false)
461
- {
462
- global $wpdb;
463
- if ($username) {
464
- if( !function_exists('username_exists') )
465
- include_once(ABSPATH . WPINC . '/registration.php');
466
-
467
- include_once(ABSPATH . 'wp-includes/pluggable.php');
468
-
469
- if (username_exists($username) == null) {
470
- return false;
471
- }
472
-
473
- $user = (array) $this->mmb_get_user_info( $username );
474
- if ((isset($user[$wpdb->prefix . 'user_level']) && $user[$wpdb->prefix . 'user_level'] == 10) || isset($user[$wpdb->prefix . 'capabilities']['administrator']) ||
475
- (isset($user['caps']['administrator']) && $user['caps']['administrator'] == 1)){
476
- return true;
477
- }
478
- return false;
479
- }
480
- return false;
481
- }
482
-
483
- function refresh_updates()
484
- {
485
- if (rand(1, 3) == '2') {
486
- require_once(ABSPATH . WPINC . '/update.php');
487
- wp_update_plugins();
488
- wp_update_themes();
489
- wp_version_check();
490
- }
491
- }
492
-
493
- function remove_http($url = '')
494
- {
495
- if ($url == 'http://' OR $url == 'https://') {
496
- return $url;
497
- }
498
- return preg_replace('/^(http|https)\:\/\/(www.)?/i', '', $url);
499
-
500
- }
501
-
502
- function mmb_get_error($error_object)
503
- {
504
- if (!is_wp_error($error_object)) {
505
- return $error_object != '' ? $error_object : '';
506
- } else {
507
- $errors = array();
508
- if(!empty($error_object->error_data)) {
509
- foreach ($error_object->error_data as $error_key => $error_string) {
510
- $errors[] = str_replace('_', ' ', ucfirst($error_key)) . ': ' . $error_string;
511
- }
512
- } elseif (!empty($error_object->errors)){
513
- foreach ($error_object->errors as $error_key => $err) {
514
- $errors[] = 'Error: '.str_replace('_', ' ', strtolower($error_key));
515
- }
516
- }
517
- return implode('<br />', $errors);
518
- }
519
- }
520
-
521
- function is_server_writable(){
522
-
523
- if((!defined('FTP_HOST') || !defined('FTP_USER') || !defined('FTP_PASS')) && (get_filesystem_method(array(), false) != 'direct'))
524
- return false;
525
- else
526
- return true;
527
- }
528
-
529
- function mmb_download_url($url, $file_name)
530
- {
531
- if (function_exists('fopen') && function_exists('ini_get') && ini_get('allow_url_fopen') == true && ($destination = @fopen($file_name, 'wb')) && ($source = @fopen($url, "r")) ) {
532
-
533
- while ($a = @fread($source, 1024* 1024)) {
534
- @fwrite($destination, $a);
535
- }
536
-
537
- fclose($source);
538
- fclose($destination);
539
- } else
540
- if (!fsockopen_download($url, $file_name))
541
- die('Error downloading file ' . $url);
542
- return $file_name;
543
- }
544
-
545
- function return_bytes($val) {
546
- $val = trim($val);
547
- $last = strtolower($val[strlen($val)-1]);
548
- switch($last) {
549
- // The 'G' modifier is available since PHP 5.1.0
550
- case 'g':
551
- $val *= 1024;
552
- case 'm':
553
- $val *= 1024;
554
- case 'k':
555
- $val *= 1024;
556
- }
557
-
558
- return $val;
559
- }
560
-
561
- }
562
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
init.php CHANGED
@@ -1,1520 +1,2043 @@
1
- <?php
2
- /*
3
- Plugin Name: ManageWP - Worker
4
- Plugin URI: http://managewp.com/
5
- Description: Manage Multiple WordPress sites from one dashboard. Visit <a href="https://managewp.com">ManageWP.com</a> to sign up.
6
- Author: ManageWP
7
- Version: 3.9.28
8
- Author URI: http://managewp.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
- if(basename($_SERVER['SCRIPT_FILENAME']) == "init.php"):
22
- exit;
23
- endif;
24
- if(!defined('MMB_WORKER_VERSION'))
25
- define('MMB_WORKER_VERSION', '3.9.28');
26
-
27
- if ( !defined('MMB_XFRAME_COOKIE')){
28
- $siteurl = function_exists( 'get_site_option' ) ? get_site_option( 'siteurl' ) : get_option( 'siteurl' );
29
- define('MMB_XFRAME_COOKIE', $xframe = 'wordpress_'.md5($siteurl).'_xframe');
30
- }
31
- global $wpdb, $mmb_plugin_dir, $mmb_plugin_url, $wp_version, $mmb_filters, $_mmb_item_filter;
32
- if (version_compare(PHP_VERSION, '5.0.0', '<')) // min version 5 supported
33
- exit("<p>ManageWP Worker plugin requires PHP 5 or higher.</p>");
34
-
35
- $mmb_wp_version = $wp_version;
36
- $mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
37
- $mmb_plugin_url = WP_PLUGIN_URL . '/' . basename(dirname(__FILE__));
38
-
39
- require_once("$mmb_plugin_dir/helper.class.php");
40
- require_once("$mmb_plugin_dir/core.class.php");
41
- require_once("$mmb_plugin_dir/post.class.php");
42
- require_once("$mmb_plugin_dir/comment.class.php");
43
- require_once("$mmb_plugin_dir/stats.class.php");
44
- require_once("$mmb_plugin_dir/backup.class.php");
45
- require_once("$mmb_plugin_dir/installer.class.php");
46
- require_once("$mmb_plugin_dir/link.class.php");
47
- require_once("$mmb_plugin_dir/user.class.php");
48
- require_once("$mmb_plugin_dir/security.class.php");
49
- require_once("$mmb_plugin_dir/api.php");
50
-
51
- require_once("$mmb_plugin_dir/plugins/search/search.php");
52
- require_once("$mmb_plugin_dir/plugins/cleanup/cleanup.php");
53
-
54
- require_once("$mmb_plugin_dir/widget.class.php");
55
-
56
- if(!function_exists( 'json_decode' ) && !function_exists( 'json_encode' )){
57
- global $mmb_plugin_dir;
58
- require_once ($mmb_plugin_dir.'/lib/json/JSON.php' );
59
-
60
- function json_decode($json_object, $assoc = false) {
61
- $json = $assoc == true ? new Services_JSON(SERVICES_JSON_LOOSE_TYPE) : new Services_JSON();
62
- return $json->decode($json_object);
63
- }
64
-
65
- function json_encode($object_data) {
66
- $json = new Services_JSON();
67
- return $json->encode($object_data);
68
- }
69
- }
70
-
71
- if( !function_exists ( 'mmb_parse_data' )) {
72
- function mmb_parse_data( $data = array() ){
73
- if( empty($data) )
74
- return $data;
75
-
76
- $data = (array) $data;
77
- if( isset($data['params']) )
78
- $data['params'] = mmb_filter_params( $data['params'] );
79
-
80
- $postkeys = array('action', 'params', 'id', 'signature', 'setting' );
81
-
82
- if( !empty($data) ){
83
- foreach($data as $key => $items){
84
- if( !in_array($key, $postkeys) )
85
- unset($data[$key]);
86
- }
87
- }
88
- return $data;
89
- }
90
- }
91
-
92
- if( !function_exists ( 'mmb_filter_params' )) {
93
- function mmb_filter_params( $array = array() ){
94
-
95
- $filter = array( 'current_user', 'wpdb' );
96
- $return = array();
97
- foreach ($array as $key => $val) {
98
- if( !is_int($key) && in_array($key, $filter) )
99
- continue;
100
-
101
- if( is_array( $val ) ) {
102
- $return[$key] = mmb_filter_params( $val );
103
- } else {
104
- $return[$key] = $val;
105
- }
106
- }
107
-
108
- return $return;
109
- }
110
- }
111
- if( !function_exists ( 'hex2bin' )) {
112
- function hex2bin($h){
113
- if (!is_string($h)) return null;
114
- $r='';
115
- for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
116
- return $r;
117
- }
118
- }
119
- if( !function_exists('mmb_authenticate')) {
120
- function mmb_authenticate() {
121
- global $_mwp_data, $_mwp_auth, $mmb_core;
122
- if (!isset($HTTP_RAW_POST_DATA)) {
123
- $HTTP_RAW_POST_DATA = file_get_contents('php://input');
124
- }
125
- if(substr($HTTP_RAW_POST_DATA, 0, 7) == "action="){
126
- $HTTP_RAW_POST_DATA = str_replace("action=", "", $HTTP_RAW_POST_DATA);
127
- }
128
- $_mwp_data = base64_decode($HTTP_RAW_POST_DATA);
129
- if (!$_mwp_data){
130
- return;
131
- }
132
- $_mwp_data = mmb_parse_data( @unserialize($_mwp_data) );
133
-
134
- if(empty($_mwp_data['action'])) {
135
- return;
136
- }
137
-
138
- if (!$mmb_core->check_if_user_exists($_mwp_data['params']['username'])) {
139
- mmb_response('Username <b>' . $_mwp_data['params']['username'] . '</b> does not have administrator capabilities. Please check the Admin username.', false);
140
- }
141
-
142
- if($_mwp_data['action'] === 'add_site') {
143
- $_mwp_auth = true;
144
- return;
145
- } else {
146
- $_mwp_auth = $mmb_core->authenticate_message($_mwp_data['action'] . $_mwp_data['id'], $_mwp_data['signature'], $_mwp_data['id']);
147
- }
148
-
149
- if($_mwp_auth !== true) {
150
- mmb_response($_mwp_auth['error'], false);
151
- }
152
-
153
- if(isset($_mwp_data['params']['username']) && !is_user_logged_in()){
154
- $user = function_exists('get_user_by') ? get_user_by('login', $_mwp_data['params']['username']) : get_userdatabylogin( $_mwp_data['params']['username'] );
155
- wp_set_current_user($user->ID);
156
- if(@getenv('IS_WPE'))
157
- wp_set_auth_cookie($user->ID);
158
- }
159
- if(!defined("WP_ADMIN"))
160
- define(WP_ADMIN,true);
161
- }
162
- }
163
-
164
- if( !function_exists ( 'mmb_parse_request' )) {
165
- function mmb_parse_request(){
166
- global $mmb_core, $wp_db_version, $wpmu_version, $_wp_using_ext_object_cache, $_mwp_data, $_mwp_auth;
167
- if(empty($_mwp_auth)) {
168
- MMB_Stats::set_hit_count();
169
- return;
170
- }
171
- ob_start();
172
- $_wp_using_ext_object_cache = false;
173
- @set_time_limit(1200);
174
-
175
- if ($_mwp_data['action'] === 'add_site') {
176
- mmb_add_site($_mwp_data['params']);
177
- mmb_response('You should never see this.', false);
178
- }
179
-
180
- /* in case database upgrade required, do database backup and perform upgrade ( wordpress wp_upgrade() function ) */
181
- if( strlen(trim($wp_db_version)) && !defined('ACX_PLUGIN_DIR') ){
182
- if ( get_option('db_version') != $wp_db_version ) {
183
- /* in multisite network, please update database manualy */
184
- if (empty($wpmu_version) || (function_exists('is_multisite') && !is_multisite())){
185
- if( ! function_exists('wp_upgrade'))
186
- include_once(ABSPATH.'wp-admin/includes/upgrade.php');
187
-
188
- ob_clean();
189
- @wp_upgrade();
190
- @do_action('after_db_upgrade');
191
- ob_end_clean();
192
- }
193
- }
194
- }
195
-
196
- if(isset($_mwp_data['params']['secure'])){
197
- if($decrypted = $mmb_core->_secure_data($_mwp_data['params']['secure'])){
198
- $decrypted = maybe_unserialize($decrypted);
199
- if(is_array($decrypted)){
200
- foreach($decrypted as $key => $val){
201
- if(!is_numeric($key))
202
- $_mwp_data['params'][$key] = $val;
203
- }
204
- unset($_mwp_data['params']['secure']);
205
- } else $_mwp_data['params']['secure'] = $decrypted;
206
- }
207
- }
208
-
209
- if( isset($_mwp_data['setting']) ){
210
- $mmb_core->save_options( $_mwp_data['setting'] );
211
- }
212
-
213
- if( !$mmb_core->register_action_params( $_mwp_data['action'], $_mwp_data['params'] ) ){
214
- global $_mmb_plugin_actions;
215
- $_mmb_plugin_actions[$_mwp_data['action']] = $_mwp_data['params'];
216
- }
217
- ob_end_clean();
218
- }
219
- }
220
- /* Main response function */
221
- if( !function_exists ( 'mmb_response' )) {
222
-
223
- function mmb_response($response = false, $success = true)
224
- {
225
- $return = array();
226
-
227
- if ((is_array($response) && empty($response)) || (!is_array($response) && strlen($response) == 0))
228
- $return['error'] = 'Empty response.';
229
- else if ($success)
230
- $return['success'] = $response;
231
- else
232
- $return['error'] = $response;
233
-
234
- if( !headers_sent() ){
235
- header('HTTP/1.0 200 OK');
236
- header('Content-Type: text/plain');
237
- }
238
- exit("<MWPHEADER>" . base64_encode(serialize($return))."<ENDMWPHEADER>");
239
- }
240
- }
241
-
242
-
243
-
244
- if( !function_exists ( 'mmb_add_site' )) {
245
- function mmb_add_site($params) {
246
- global $mmb_core;
247
- $num = extract($params);
248
-
249
- if ($num) {
250
- if (!get_option('_action_message_id') && !get_option('_worker_public_key')) {
251
- $public_key = base64_decode($public_key);
252
-
253
- if (function_exists('openssl_verify')) {
254
- $verify = openssl_verify($action . $id, base64_decode($signature), $public_key);
255
- if ($verify == 1) {
256
- $mmb_core->set_master_public_key($public_key);
257
- $mmb_core->set_worker_message_id($id);
258
-
259
-
260
-
261
- $mmb_core->get_stats_instance();
262
- if(isset($notifications) && is_array($notifications) && !empty($notifications)){
263
- $mmb_core->stats_instance->set_notifications($notifications);
264
- }
265
- if(isset($brand) && is_array($brand) && !empty($brand)){
266
- update_option('mwp_worker_brand', $brand);
267
- }
268
-
269
- if( isset( $add_settigns ) && is_array($add_settigns) && !empty( $add_settigns ) )
270
- apply_filters( 'mwp_website_add', $add_settigns );
271
-
272
- mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
273
- } else if ($verify == 0) {
274
-
275
- //mmb_response('Site could not be added. OpenSSL verification error: "'.openssl_error_string().'". Contact your hosting support to check the OpenSSL configuration.', false);
276
-
277
- } else {
278
- mmb_response('Command not successful. Please try again.', false);
279
- }
280
- }
281
-
282
- if (!get_option('_worker_nossl_key')) {
283
- srand();
284
-
285
- $random_key = md5(base64_encode($public_key) . rand(0, getrandmax()));
286
-
287
- $mmb_core->set_random_signature($random_key);
288
- $mmb_core->set_worker_message_id($id);
289
- $mmb_core->set_master_public_key($public_key);
290
-
291
-
292
- $mmb_core->get_stats_instance();
293
- if(is_array($notifications) && !empty($notifications)){
294
- $mmb_core->stats_instance->set_notifications($notifications);
295
- }
296
-
297
- if(is_array($brand) && !empty($brand)){
298
- update_option('mwp_worker_brand',$brand);
299
- }
300
-
301
- mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
302
- } else
303
- mmb_response('Handshake not successful. Please deactivate, then activate ManageWP Worker plugin on your site, and re-add this site to your dashboard.', false);
304
-
305
- } else {
306
- mmb_response('Handshake not successful. Please deactivate, then activate ManageWP Worker plugin on your site, and re-add this site to your dashboard.', false);
307
- }
308
- } else {
309
- mmb_response('Invalid parameters received. Please try again.', false);
310
- }
311
- }
312
- }
313
-
314
- if( !function_exists ( 'mmb_remove_site' )) {
315
- function mmb_remove_site($params)
316
- {
317
- extract($params);
318
- global $mmb_core;
319
- $mmb_core->uninstall( $deactivate );
320
-
321
- include_once(ABSPATH . 'wp-admin/includes/plugin.php');
322
- $plugin_slug = basename(dirname(__FILE__)) . '/' . basename(__FILE__);
323
-
324
- if ($deactivate) {
325
- deactivate_plugins($plugin_slug, true);
326
- }
327
-
328
- if (!is_plugin_active($plugin_slug))
329
- mmb_response(array(
330
- 'deactivated' => 'Site removed successfully. <br /><br />ManageWP Worker plugin successfully deactivated.'
331
- ), true);
332
- else
333
- mmb_response(array(
334
- 'removed_data' => 'Site removed successfully. <br /><br /><b>ManageWP Worker plugin was not deactivated.</b>'
335
- ), true);
336
-
337
- }
338
- }
339
- if( !function_exists ( 'mmb_stats_get' )) {
340
- function mmb_stats_get($params)
341
- {
342
- global $mmb_core;
343
- $mmb_core->get_stats_instance();
344
- mmb_response($mmb_core->stats_instance->get($params), true);
345
- }
346
- }
347
-
348
- if( !function_exists ( 'mmb_worker_header' )) {
349
- function mmb_worker_header()
350
- { global $mmb_core, $current_user;
351
-
352
- if(!headers_sent()){
353
- if(isset($current_user->ID))
354
- $expiration = time() + apply_filters('auth_cookie_expiration', 10800, $current_user->ID, false);
355
- else
356
- $expiration = time() + 10800;
357
-
358
- setcookie(MMB_XFRAME_COOKIE, md5(MMB_XFRAME_COOKIE), $expiration, COOKIEPATH, COOKIE_DOMAIN, false, true);
359
- $_COOKIE[MMB_XFRAME_COOKIE] = md5(MMB_XFRAME_COOKIE);
360
- }
361
- }
362
- }
363
-
364
- if( !function_exists ( 'mmb_pre_init_stats' )) {
365
- function mmb_pre_init_stats( $params )
366
- {
367
- global $mmb_core;
368
- $mmb_core->get_stats_instance();
369
- return $mmb_core->stats_instance->pre_init_stats($params);
370
- }
371
- }
372
-
373
- if( !function_exists ( 'mwp_datasend' )) {
374
- function mwp_datasend( $params = array() )
375
- {
376
- global $mmb_core, $_mmb_item_filter, $_mmb_options;
377
- if( isset($_mmb_options['datacron']) ){
378
-
379
- $_mmb_remoteurl = get_option('home');
380
- $_mmb_remoteown = isset($_mmb_options['dataown']) && !empty($_mmb_options['dataown']) ? $_mmb_options['dataown'] : false;
381
-
382
- if( empty($_mmb_remoteown) )
383
- return;
384
-
385
- $_mmb_item_filter['pre_init_stats'] = array( 'core_update', 'hit_counter', 'comments', 'backups', 'posts', 'drafts', 'scheduled' );
386
- $_mmb_item_filter['get'] = array( 'updates', 'errors' );
387
- $mmb_core->get_stats_instance();
388
-
389
- $filter = array(
390
- 'refresh' => 'transient',
391
- 'item_filter' => array(
392
- 'get_stats' => array(
393
- array('updates', array('plugins' => true, 'themes' => true, 'premium' => true )),
394
- array('core_update', array('core' => true )),
395
- array('posts', array('numberposts' => 5 )),
396
- array('drafts', array('numberposts' => 5 )),
397
- array('scheduled', array('numberposts' => 5 )),
398
- array('hit_counter'),
399
- array('comments', array('numberposts' => 5 )),
400
- array('backups'),
401
- 'plugins' => array('cleanup' => array(
402
- 'overhead' => array(),
403
- 'revisions' => array( 'num_to_keep' => 'r_5'),
404
- 'spam' => array(),
405
- )
406
- ),
407
- ),
408
- )
409
- );
410
-
411
- $pre_init_data = $mmb_core->stats_instance->pre_init_stats($filter);
412
- $init_data = $mmb_core->stats_instance->get($filter);
413
-
414
- $data = array_merge($init_data, $pre_init_data);
415
- $hash = $mmb_core->get_secure_hash();
416
-
417
- $datasend['datasend'] = $mmb_core->encrypt_data($data);
418
- $datasend['sitehome'] = base64_encode($_mmb_remoteown.'[]'.$_mmb_remoteurl);
419
- $datasend['sitehash'] = md5($hash.$_mmb_remoteown.$_mmb_remoteurl);
420
- if ( !class_exists('WP_Http') )
421
- include_once(ABSPATH . WPINC . '/class-http.php');
422
-
423
- $remote = array();
424
- $remote['body'] = $datasend;
425
-
426
- $result = wp_remote_post($_mmb_options['datacron'], $remote);
427
- if(!is_wp_error($result)){
428
- if(isset($result['body']) && !empty($result['body'])){
429
- $settings = @unserialize($result['body']);
430
- /* rebrand worker or set default */
431
- $brand = '';
432
- if($settings['worker_brand']){
433
- $brand = $settings['worker_brand'];
434
- }
435
- update_option("mwp_worker_brand",$brand);
436
- /* change worker version */
437
- $w_version = $settings['worker_updates']['version'];
438
- $w_url = $settings['worker_updates']['url'];
439
- if(version_compare(MMB_WORKER_VERSION, $w_version, '<')){
440
- //automatic update
441
- $mmb_core->update_worker_plugin(array("download_url" => $w_url));
442
- }
443
- }
444
- }else{
445
- //$mmb_core->_log($result);
446
- }
447
-
448
- }
449
- }
450
- }
451
-
452
- //post
453
- if( !function_exists ( 'mmb_post_create' )) {
454
- function mmb_post_create($params)
455
- {
456
- global $mmb_core;
457
- $mmb_core->get_post_instance();
458
- $return = $mmb_core->post_instance->create($params);
459
- if (is_int($return))
460
- mmb_response($return, true);
461
- else{
462
- if(isset($return['error'])){
463
- mmb_response($return['error'], false);
464
- } else {
465
- mmb_response($return, false);
466
- }
467
- }
468
- }
469
- }
470
-
471
- if( !function_exists ( 'mmb_change_post_status' )) {
472
- function mmb_change_post_status($params)
473
- {
474
- global $mmb_core;
475
- $mmb_core->get_post_instance();
476
- $return = $mmb_core->post_instance->change_status($params);
477
- //mmb_response($return, true);
478
-
479
- }
480
- }
481
-
482
- //comments
483
- if( !function_exists ( 'mmb_change_comment_status' )) {
484
- function mmb_change_comment_status($params)
485
- {
486
- global $mmb_core;
487
- $mmb_core->get_comment_instance();
488
- $return = $mmb_core->comment_instance->change_status($params);
489
- //mmb_response($return, true);
490
- if ($return){
491
- $mmb_core->get_stats_instance();
492
- mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
493
- }else
494
- mmb_response('Comment not updated', false);
495
- }
496
-
497
- }
498
- if( !function_exists ( 'mmb_comment_stats_get' )) {
499
- function mmb_comment_stats_get($params)
500
- {
501
- global $mmb_core;
502
- $mmb_core->get_stats_instance();
503
- mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
504
- }
505
- }
506
-
507
- if( !function_exists ( 'mmb_backup_now' )) {
508
- //backup
509
- function mmb_backup_now($params)
510
- {
511
- global $mmb_core;
512
-
513
- $mmb_core->get_backup_instance();
514
- $return = $mmb_core->backup_instance->backup($params);
515
-
516
- if (is_array($return) && array_key_exists('error', $return))
517
- mmb_response($return['error'], false);
518
- else {
519
- mmb_response($return, true);
520
- }
521
- }
522
- }
523
-
524
- if( !function_exists ( 'mmb_run_task_now' )) {
525
- function mmb_run_task_now($params)
526
- {
527
- global $mmb_core;
528
- $mmb_core->get_backup_instance();
529
-
530
- $task_name = isset($params['task_name']) ? $params['task_name'] : false;
531
- $google_drive_token = isset($params['google_drive_token']) ? $params['google_drive_token'] : false;
532
-
533
- if ($task_name) {
534
- $return = $mmb_core->backup_instance->task_now($task_name, $google_drive_token);
535
- if (is_array($return) && array_key_exists('error', $return))
536
- mmb_response($return['error'], false);
537
- else {
538
- mmb_response($return, true);
539
- }
540
- } else {
541
- mmb_response("Task name is not provided.", false);
542
- }
543
-
544
- }
545
- }
546
-
547
- if( !function_exists ( 'mmb_email_backup' )) {
548
- function mmb_email_backup($params)
549
- {
550
- global $mmb_core;
551
- $mmb_core->get_backup_instance();
552
- $return = $mmb_core->backup_instance->email_backup($params);
553
-
554
- if (is_array($return) && array_key_exists('error', $return))
555
- mmb_response($return['error'], false);
556
- else {
557
- mmb_response($return, true);
558
- }
559
- }
560
- }
561
-
562
- if( !function_exists ( 'mmb_check_backup_compat' )) {
563
- function mmb_check_backup_compat($params)
564
- {
565
- global $mmb_core;
566
- $mmb_core->get_backup_instance();
567
- $return = $mmb_core->backup_instance->check_backup_compat($params);
568
-
569
- if (is_array($return) && array_key_exists('error', $return))
570
- mmb_response($return['error'], false);
571
- else {
572
- mmb_response($return, true);
573
- }
574
- }
575
- }
576
-
577
- if( !function_exists ( 'mmb_get_backup_req' )) {
578
- function mmb_get_backup_req( $params )
579
- {
580
- global $mmb_core;
581
- $mmb_core->get_stats_instance();
582
- $return = $mmb_core->stats_instance->get_backup_req($params);
583
-
584
- mmb_response($return, true);
585
- }
586
- }
587
-
588
- // Fires when Backup Now, or some backup task is saved.
589
- if( !function_exists ( 'mmb_scheduled_backup' )) {
590
- function mmb_scheduled_backup($params)
591
- {
592
- global $mmb_core;
593
- $mmb_core->get_backup_instance();
594
- $return = $mmb_core->backup_instance->set_backup_task($params);
595
- mmb_response($return, $return);
596
- }
597
- }
598
-
599
- if( !function_exists ( 'mmm_delete_backup' )) {
600
- function mmm_delete_backup($params)
601
- {
602
- global $mmb_core;
603
- $mmb_core->get_backup_instance();
604
- $return = $mmb_core->backup_instance->delete_backup($params);
605
- mmb_response($return, $return);
606
- }
607
- }
608
-
609
- if( !function_exists ( 'mmb_optimize_tables' )) {
610
- function mmb_optimize_tables($params)
611
- {
612
- global $mmb_core;
613
- $mmb_core->get_backup_instance();
614
- $return = $mmb_core->backup_instance->optimize_tables();
615
- if ($return)
616
- mmb_response($return, true);
617
- else
618
- mmb_response(false, false);
619
- }
620
- }
621
- if( !function_exists ( 'mmb_restore_now' )) {
622
- function mmb_restore_now($params)
623
- {
624
- global $mmb_core;
625
- $mmb_core->get_backup_instance();
626
- $return = $mmb_core->backup_instance->restore($params);
627
- if (is_array($return) && array_key_exists('error', $return))
628
- mmb_response($return['error'], false);
629
- else
630
- mmb_response($return, true);
631
-
632
- }
633
- }
634
-
635
- if( !function_exists ( 'mmb_remote_backup_now' )) {
636
- function mmb_remote_backup_now($params)
637
- {
638
- global $mmb_core;
639
- $backup_instance = $mmb_core->get_backup_instance();
640
- $return = $mmb_core->backup_instance->remote_backup_now($params);
641
- if (is_array($return) && array_key_exists('error', $return))
642
- mmb_response($return['error'], false);
643
- else
644
- mmb_response($return, true);
645
- }
646
- }
647
-
648
-
649
- if( !function_exists ( 'mmb_clean_orphan_backups' )) {
650
- function mmb_clean_orphan_backups()
651
- {
652
- global $mmb_core;
653
- $backup_instance = $mmb_core->get_backup_instance();
654
- $return = $mmb_core->backup_instance->cleanup();
655
- if(is_array($return))
656
- mmb_response($return, true);
657
- else
658
- mmb_response($return, false);
659
- }
660
- }
661
-
662
- function mmb_run_backup_action() {
663
- if(isset($_POST['mmb_backup_nonce']))
664
- if (!wp_verify_nonce($_POST['mmb_backup_nonce'], 'mmb-backup-nonce')) return false;
665
- $public_key = get_option('_worker_public_key');
666
- if (!isset($_POST['public_key']) || $public_key !== $_POST['public_key']) return false;
667
- $args = @json_decode(stripslashes($_POST['args']), true);
668
- if (!$args) return false;
669
- $cron_action = isset($_POST['backup_cron_action']) ? $_POST['backup_cron_action'] : false;
670
- if ($cron_action) {
671
- do_action($cron_action, $args);
672
- }
673
- //unset($_POST['public_key']);
674
- unset($_POST['mmb_backup_nonce']);
675
- unset($_POST['args']);
676
- unset($_POST['backup_cron_action']);
677
- return true;
678
- }
679
-
680
- add_filter( 'mwp_website_add', 'mmb_readd_backup_task' );
681
-
682
- if (!function_exists('mmb_readd_backup_task')) {
683
- function mmb_readd_backup_task($params = array()) {
684
- global $mmb_core;
685
- $backup_instance = $mmb_core->get_backup_instance();
686
- $settings = $backup_instance->readd_tasks($params);
687
- return $settings;
688
- }
689
- }
690
-
691
- if( !function_exists ( 'mmb_update_worker_plugin' )) {
692
- function mmb_update_worker_plugin($params)
693
- {
694
- global $mmb_core;
695
- mmb_response($mmb_core->update_worker_plugin($params), true);
696
- }
697
- }
698
-
699
- if( !function_exists ( 'mmb_wp_checkversion' )) {
700
- function mmb_wp_checkversion($params)
701
- {
702
- include_once(ABSPATH . 'wp-includes/version.php');
703
- global $mmb_wp_version, $mmb_core;
704
- mmb_response($mmb_wp_version, true);
705
- }
706
- }
707
- if( !function_exists ( 'mmb_search_posts_by_term' )) {
708
- function mmb_search_posts_by_term($params)
709
- {
710
- global $mmb_core;
711
- $mmb_core->get_search_instance();
712
-
713
- $search_type = trim($params['search_type']);
714
- $search_term = strtolower(trim($params['search_term']));
715
-
716
- switch ($search_type){
717
- case 'page_post':
718
- $return = $mmb_core->search_instance->search_posts_by_term($params);
719
- if($return){
720
- $return = serialize($return);
721
- mmb_response($return, true);
722
- }else{
723
- mmb_response('No posts found', false);
724
- }
725
- break;
726
-
727
- case 'plugin':
728
- $plugins = get_option('active_plugins');
729
-
730
- $have_plugin = false;
731
- foreach ($plugins as $plugin) {
732
- if(strpos($plugin, $search_term)>-1){
733
- $have_plugin = true;
734
- }
735
- }
736
- if($have_plugin){
737
- mmb_response(serialize($plugin), true);
738
- }else{
739
- mmb_response(false, false);
740
- }
741
- break;
742
- case 'theme':
743
- $theme = strtolower(get_option('template'));
744
- if(strpos($theme, $search_term)>-1){
745
- mmb_response($theme, true);
746
- }else{
747
- mmb_response(false, false);
748
- }
749
- break;
750
- default: mmb_response(false, false);
751
- }
752
- $return = $mmb_core->search_instance->search_posts_by_term($params);
753
-
754
-
755
-
756
- if ($return_if_true) {
757
- mmb_response($return_value, true);
758
- } else {
759
- mmb_response($return_if_false, false);
760
- }
761
- }
762
- }
763
-
764
- if( !function_exists ( 'mmb_install_addon' )) {
765
- function mmb_install_addon($params)
766
- {
767
- global $mmb_core;
768
- $mmb_core->get_installer_instance();
769
- $return = $mmb_core->installer_instance->install_remote_file($params);
770
- mmb_response($return, true);
771
-
772
- }
773
- }
774
-
775
- if( !function_exists ( 'mmb_do_upgrade' )) {
776
- function mmb_do_upgrade($params)
777
- {
778
- global $mmb_core, $mmb_upgrading;
779
- $mmb_core->get_installer_instance();
780
- $return = $mmb_core->installer_instance->do_upgrade($params);
781
- mmb_response($return, true);
782
-
783
- }
784
- }
785
-
786
- if( !function_exists ('mmb_get_links')) {
787
- function mmb_get_links($params)
788
- {
789
- global $mmb_core;
790
- $mmb_core->get_link_instance();
791
- $return = $mmb_core->link_instance->get_links($params);
792
- if (is_array($return) && array_key_exists('error', $return))
793
- mmb_response($return['error'], false);
794
- else {
795
- mmb_response($return, true);
796
- }
797
- }
798
- }
799
-
800
- if( !function_exists ( 'mmb_add_link' )) {
801
- function mmb_add_link($params)
802
- {
803
- global $mmb_core;
804
- $mmb_core->get_link_instance();
805
- $return = $mmb_core->link_instance->add_link($params);
806
- if (is_array($return) && array_key_exists('error', $return))
807
-
808
- mmb_response($return['error'], false);
809
- else {
810
- mmb_response($return, true);
811
- }
812
-
813
- }
814
- }
815
-
816
- if( !function_exists ('mmb_delete_link')) {
817
- function mmb_delete_link($params)
818
- {
819
- global $mmb_core;
820
- $mmb_core->get_link_instance();
821
-
822
- $return = $mmb_core->link_instance->delete_link($params);
823
- if (is_array($return) && array_key_exists('error', $return))
824
- mmb_response($return['error'], false);
825
- else {
826
- mmb_response($return, true);
827
- }
828
- }
829
- }
830
-
831
- if( !function_exists ('mmb_delete_links')) {
832
- function mmb_delete_links($params)
833
- {
834
- global $mmb_core;
835
- $mmb_core->get_link_instance();
836
-
837
- $return = $mmb_core->link_instance->delete_links($params);
838
- if (is_array($return) && array_key_exists('error', $return))
839
- mmb_response($return['error'], false);
840
- else {
841
- mmb_response($return, true);
842
- }
843
- }
844
- }
845
-
846
- if( !function_exists ('mmb_get_comments')) {
847
- function mmb_get_comments($params)
848
- {
849
- global $mmb_core;
850
- $mmb_core->get_comment_instance();
851
- $return = $mmb_core->comment_instance->get_comments($params);
852
- if (is_array($return) && array_key_exists('error', $return))
853
- mmb_response($return['error'], false);
854
- else {
855
- mmb_response($return, true);
856
- }
857
- }
858
- }
859
-
860
- if( !function_exists ('mmb_action_comment')) {
861
- function mmb_action_comment($params)
862
- {
863
- global $mmb_core;
864
- $mmb_core->get_comment_instance();
865
-
866
- $return = $mmb_core->comment_instance->action_comment($params);
867
- if (is_array($return) && array_key_exists('error', $return))
868
- mmb_response($return['error'], false);
869
- else {
870
- mmb_response($return, true);
871
- }
872
- }
873
- }
874
-
875
- if( !function_exists ('mmb_bulk_action_comments')) {
876
- function mmb_bulk_action_comments($params)
877
- {
878
- global $mmb_core;
879
- $mmb_core->get_comment_instance();
880
-
881
- $return = $mmb_core->comment_instance->bulk_action_comments($params);
882
- if (is_array($return) && array_key_exists('error', $return))
883
- mmb_response($return['error'], false);
884
- else {
885
- mmb_response($return, true);
886
- }
887
- }
888
- }
889
-
890
- if( !function_exists ('mmb_reply_comment')) {
891
- function mmb_reply_comment($params)
892
- {
893
- global $mmb_core;
894
- $mmb_core->get_comment_instance();
895
-
896
- $return = $mmb_core->comment_instance->reply_comment($params);
897
- if (is_array($return) && array_key_exists('error', $return))
898
- mmb_response($return['error'], false);
899
- else {
900
- mmb_response($return, true);
901
- }
902
- }
903
- }
904
-
905
- if( !function_exists ( 'mmb_add_user' )) {
906
- function mmb_add_user($params)
907
- {
908
- global $mmb_core;
909
- $mmb_core->get_user_instance();
910
- $return = $mmb_core->user_instance->add_user($params);
911
- if (is_array($return) && array_key_exists('error', $return))
912
-
913
- mmb_response($return['error'], false);
914
- else {
915
- mmb_response($return, true);
916
- }
917
-
918
- }
919
- }
920
-
921
- if( !function_exists ( 'mbb_security_check' )) {
922
- function mbb_security_check($params)
923
- {
924
- global $mmb_core;
925
- $mmb_core->get_security_instance();
926
- $return = $mmb_core->security_instance->security_check($params);
927
- if (is_array($return) && array_key_exists('error', $return))
928
- mmb_response($return['error'], false);
929
- else {
930
- mmb_response($return, true);
931
- }
932
-
933
- }
934
- }
935
-
936
- if( !function_exists ( 'mbb_security_fix_folder_listing' )) {
937
- function mbb_security_fix_folder_listing($params)
938
- {
939
- global $mmb_core;
940
- $mmb_core->get_security_instance();
941
- $return = $mmb_core->security_instance->security_fix_dir_listing($params);
942
- if (is_array($return) && array_key_exists('error', $return))
943
- mmb_response($return['error'], false);
944
- else {
945
- mmb_response($return, true);
946
- }
947
-
948
- }
949
- }
950
-
951
- if( !function_exists ( 'mbb_security_fix_php_reporting' )) {
952
- function mbb_security_fix_php_reporting($params)
953
- {
954
- global $mmb_core;
955
- $mmb_core->get_security_instance();
956
- $return = $mmb_core->security_instance->security_fix_php_reporting($params);
957
- if (is_array($return) && array_key_exists('error', $return))
958
- mmb_response($return['error'], false);
959
- else {
960
- mmb_response($return, true);
961
- }
962
-
963
- }
964
- }
965
-
966
- if( !function_exists ( 'mbb_security_fix_database_reporting' )) {
967
- function mbb_security_fix_database_reporting($params)
968
- {
969
- global $mmb_core;
970
- $mmb_core->get_security_instance();
971
- $return = $mmb_core->security_instance->security_fix_database_reporting($params);
972
- if (is_array($return) && array_key_exists('error', $return))
973
- mmb_response($return['error'], false);
974
- else {
975
- mmb_response($return, true);
976
- }
977
-
978
- }
979
- }
980
-
981
- //security_fix_wp_version
982
-
983
- if( !function_exists ( 'mbb_security_fix_wp_version' )) {
984
- function mbb_security_fix_wp_version($params)
985
- {
986
- global $mmb_core;
987
- $mmb_core->get_security_instance();
988
- $return = $mmb_core->security_instance->security_fix_wp_version($params);
989
- if (is_array($return) && array_key_exists('error', $return))
990
- mmb_response($return['error'], false);
991
- else {
992
- mmb_response($return, true);
993
- }
994
-
995
- }
996
- }
997
-
998
- //mbb_security_fix_admin_username
999
-
1000
- if( !function_exists ( 'mbb_security_fix_admin_username' )) {
1001
- function mbb_security_fix_admin_username($params)
1002
- {
1003
- global $mmb_core;
1004
- $mmb_core->get_security_instance();
1005
- $return = $mmb_core->security_instance->security_fix_admin_username($params);
1006
- if (is_array($return) && array_key_exists('error', $return))
1007
- mmb_response($return['error'], false);
1008
- else {
1009
- mmb_response($return, true);
1010
- }
1011
-
1012
- }
1013
- }
1014
-
1015
- if( !function_exists ( 'mbb_security_fix_scripts_styles' )) {
1016
- function mbb_security_fix_scripts_styles($params)
1017
- {
1018
- global $mmb_core;
1019
- $mmb_core->get_security_instance();
1020
- $return = $mmb_core->security_instance->security_fix_scripts_styles($params);
1021
- if (is_array($return) && array_key_exists('error', $return))
1022
- mmb_response($return['error'], false);
1023
- else {
1024
- mmb_response($return, true);
1025
- }
1026
-
1027
- }
1028
- }
1029
-
1030
- //mbb_security_fix_file_permission
1031
- if( !function_exists ( 'mbb_security_fix_file_permission' )) {
1032
- function mbb_security_fix_file_permission($params)
1033
- {
1034
- global $mmb_core;
1035
- $mmb_core->get_security_instance();
1036
- $return = $mmb_core->security_instance->security_fix_permissions($params);
1037
- if (is_array($return) && array_key_exists('error', $return))
1038
- mmb_response($return['error'], false);
1039
- else {
1040
- mmb_response($return, true);
1041
- }
1042
-
1043
- }
1044
- }
1045
-
1046
- //mbb_security_fix_all
1047
- if( !function_exists ( 'mbb_security_fix_all' )) {
1048
- function mbb_security_fix_all($params)
1049
- {
1050
- global $mmb_core;
1051
- $mmb_core->get_security_instance();
1052
- $return = $mmb_core->security_instance->security_fix_all($params);
1053
- if (is_array($return) && array_key_exists('error', $return))
1054
- mmb_response($return['error'], false);
1055
- else {
1056
- mmb_response($return, true);
1057
- }
1058
- }
1059
- }
1060
-
1061
- //mbb_security_fix_htaccess_permission
1062
-
1063
- if( !function_exists ( 'mbb_security_fix_htaccess_permission' )) {
1064
- function mbb_security_fix_htaccess_permission($params)
1065
- {
1066
- global $mmb_core;
1067
- $mmb_core->get_security_instance();
1068
- $return = $mmb_core->security_instance->security_fix_htaccess_permission($params);
1069
- if (is_array($return) && array_key_exists('error', $return))
1070
- mmb_response($return['error'], false);
1071
- else {
1072
- mmb_response($return, true);
1073
- }
1074
-
1075
- }
1076
- }
1077
-
1078
- if( !function_exists ('mmb_get_users')) {
1079
- function mmb_get_users($params)
1080
- {
1081
- global $mmb_core;
1082
- $mmb_core->get_user_instance();
1083
- $return = $mmb_core->user_instance->get_users($params);
1084
- if (is_array($return) && array_key_exists('error', $return))
1085
- mmb_response($return['error'], false);
1086
- else {
1087
- mmb_response($return, true);
1088
- }
1089
- }
1090
- }
1091
-
1092
- if( !function_exists ('mmb_edit_users')) {
1093
- function mmb_edit_users($params)
1094
- {
1095
- global $mmb_core;
1096
- $mmb_core->get_user_instance();
1097
- $users = $mmb_core->user_instance->edit_users($params);
1098
- $response = 'User updated.';
1099
- $check_error = false;
1100
- foreach ($users as $username => $user) {
1101
- $check_error = array_key_exists('error', $user);
1102
- if($check_error){
1103
- $response = $username.': '.$user['error'];
1104
- }
1105
- }
1106
- mmb_response($response, !$check_error);
1107
- }
1108
- }
1109
-
1110
- if( !function_exists ('mmb_get_posts')) {
1111
- function mmb_get_posts($params)
1112
- {
1113
- global $mmb_core;
1114
- $mmb_core->get_post_instance();
1115
-
1116
- $return = $mmb_core->post_instance->get_posts($params);
1117
- if (is_array($return) && array_key_exists('error', $return))
1118
- mmb_response($return['error'], false);
1119
- else {
1120
- mmb_response($return, true);
1121
- }
1122
- }
1123
- }
1124
-
1125
- if( !function_exists ('mmb_delete_post')) {
1126
- function mmb_delete_post($params)
1127
- {
1128
- global $mmb_core;
1129
- $mmb_core->get_post_instance();
1130
-
1131
- $return = $mmb_core->post_instance->delete_post($params);
1132
- if (is_array($return) && array_key_exists('error', $return))
1133
- mmb_response($return['error'], false);
1134
- else {
1135
- mmb_response($return, true);
1136
- }
1137
- }
1138
- }
1139
-
1140
- if( !function_exists ('mmb_delete_posts')) {
1141
- function mmb_delete_posts($params)
1142
- {
1143
- global $mmb_core;
1144
- $mmb_core->get_post_instance();
1145
-
1146
- $return = $mmb_core->post_instance->delete_posts($params);
1147
- if (is_array($return) && array_key_exists('error', $return))
1148
- mmb_response($return['error'], false);
1149
- else {
1150
- mmb_response($return, true);
1151
- }
1152
- }
1153
- }
1154
-
1155
-
1156
-
1157
- if( !function_exists ('mmb_edit_posts')) {
1158
- function mmb_edit_posts($params)
1159
- {
1160
- global $mmb_core;
1161
- $mmb_core->get_posts_instance();
1162
- $return = $mmb_core->posts_instance->edit_posts($params);
1163
- mmb_response($return, true);
1164
- }
1165
- }
1166
-
1167
- if( !function_exists ('mmb_get_pages')) {
1168
- function mmb_get_pages($params)
1169
- {
1170
- global $mmb_core;
1171
- $mmb_core->get_post_instance();
1172
-
1173
- $return = $mmb_core->post_instance->get_pages($params);
1174
- if (is_array($return) && array_key_exists('error', $return))
1175
- mmb_response($return['error'], false);
1176
- else {
1177
- mmb_response($return, true);
1178
- }
1179
- }
1180
- }
1181
-
1182
- if( !function_exists ('mmb_delete_page')) {
1183
- function mmb_delete_page($params)
1184
- {
1185
- global $mmb_core;
1186
- $mmb_core->get_post_instance();
1187
-
1188
- $return = $mmb_core->post_instance->delete_page($params);
1189
- if (is_array($return) && array_key_exists('error', $return))
1190
- mmb_response($return['error'], false);
1191
- else {
1192
- mmb_response($return, true);
1193
- }
1194
- }
1195
- }
1196
-
1197
- if( !function_exists ( 'mmb_iframe_plugins_fix' )) {
1198
- function mmb_iframe_plugins_fix($update_actions)
1199
- {
1200
- foreach($update_actions as $key => $action)
1201
- {
1202
- $update_actions[$key] = str_replace('target="_parent"','',$action);
1203
- }
1204
-
1205
- return $update_actions;
1206
-
1207
- }
1208
- }
1209
- if( !function_exists ( 'mmb_execute_php_code' )) {
1210
- function mmb_execute_php_code($params)
1211
- {
1212
- ob_start();
1213
- eval($params['code']);
1214
- $return = ob_get_flush();
1215
- mmb_response(print_r($return, true), true);
1216
- }
1217
- }
1218
-
1219
- if( !function_exists ( 'mmb_set_notifications' )) {
1220
- function mmb_set_notifications($params)
1221
- {
1222
- global $mmb_core;
1223
- $mmb_core->get_stats_instance();
1224
- $return = $mmb_core->stats_instance->set_notifications($params);
1225
- if (is_array($return) && array_key_exists('error', $return))
1226
- mmb_response($return['error'], false);
1227
- else {
1228
- mmb_response($return, true);
1229
- }
1230
-
1231
- }
1232
- }
1233
-
1234
- if( !function_exists ('mmb_get_dbname')) {
1235
- function mmb_get_dbname($params)
1236
- {
1237
- global $mmb_core;
1238
- $mmb_core->get_stats_instance();
1239
-
1240
- $return = $mmb_core->stats_instance->get_active_db();
1241
- if (is_array($return) && array_key_exists('error', $return))
1242
- mmb_response($return['error'], false);
1243
- else {
1244
- mmb_response($return, true);
1245
- }
1246
- }
1247
- }
1248
-
1249
- if( !function_exists('mmb_more_reccurences') ){
1250
- //Backup Tasks
1251
- add_filter('cron_schedules', 'mmb_more_reccurences');
1252
- function mmb_more_reccurences($schedules) {
1253
- $schedules['halfminute'] = array('interval' => 30, 'display' => 'Once in a half minute');
1254
- $schedules['minutely'] = array('interval' => 60, 'display' => 'Once in a minute');
1255
- $schedules['fiveminutes'] = array('interval' => 300, 'display' => 'Once every five minutes');
1256
- $schedules['tenminutes'] = array('interval' => 600, 'display' => 'Once every ten minutes');
1257
- $schedules['sixhours'] = array('interval' => 21600, 'display' => 'Every six hours');
1258
- $schedules['fourhours'] = array('interval' => 14400, 'display' => 'Every four hours');
1259
- $schedules['threehours'] = array('interval' => 10800, 'display' => 'Every three hours');
1260
-
1261
- return $schedules;
1262
- }
1263
- }
1264
-
1265
- add_action('mwp_backup_tasks', 'mwp_check_backup_tasks');
1266
-
1267
- if( !function_exists('mwp_check_backup_tasks') ){
1268
- function mwp_check_backup_tasks() {
1269
- global $mmb_core, $_wp_using_ext_object_cache;
1270
- $_wp_using_ext_object_cache = false;
1271
- $mmb_core->get_backup_instance();
1272
- $mmb_core->backup_instance->check_backup_tasks();
1273
- }
1274
- }
1275
-
1276
- // Remote upload in the second request.
1277
- // add_action('mmb_scheduled_remote_upload', 'mmb_call_scheduled_remote_upload');
1278
- add_action('mmb_remote_upload', 'mmb_call_scheduled_remote_upload');
1279
-
1280
- if( !function_exists('mmb_call_scheduled_remote_upload') ){
1281
- function mmb_call_scheduled_remote_upload($args) {
1282
- global $mmb_core, $_wp_using_ext_object_cache;
1283
- $_wp_using_ext_object_cache = false;
1284
-
1285
- $mmb_core->get_backup_instance();
1286
- if (isset($args['task_name'])) {
1287
- $mmb_core->backup_instance->remote_backup_now($args);
1288
- }
1289
- }
1290
- }
1291
-
1292
- // if (!wp_next_scheduled('mwp_notifications')) {
1293
- // wp_schedule_event( time(), 'twicedaily', 'mwp_notifications' );
1294
- // }
1295
- // add_action('mwp_notifications', 'mwp_check_notifications');
1296
-
1297
- if (!wp_next_scheduled('mwp_datasend')) {
1298
- wp_schedule_event( time(), 'threehours', 'mwp_datasend' );
1299
- }
1300
-
1301
- add_action('mwp_datasend', 'mwp_datasend');
1302
-
1303
- if( !function_exists('mwp_check_notifications') ){
1304
- function mwp_check_notifications() {
1305
- global $mmb_core, $_wp_using_ext_object_cache;
1306
- $_wp_using_ext_object_cache = false;
1307
-
1308
- $mmb_core->get_stats_instance();
1309
- $mmb_core->stats_instance->check_notifications();
1310
- }
1311
- }
1312
-
1313
-
1314
- if( !function_exists('mmb_get_plugins_themes') ){
1315
- function mmb_get_plugins_themes($params) {
1316
- global $mmb_core;
1317
- $mmb_core->get_installer_instance();
1318
- $return = $mmb_core->installer_instance->get($params);
1319
- mmb_response($return, true);
1320
- }
1321
- }
1322
-
1323
-
1324
- if( !function_exists('mmb_get_autoupdate_plugins_themes') ){
1325
- function mmb_get_autoupdate_plugins_themes($params) {
1326
- $return = MWP_Updater::getSettings($params);
1327
- mmb_response($return, true);
1328
- }
1329
- }
1330
-
1331
- if( !function_exists('mmb_edit_plugins_themes') ){
1332
- function mmb_edit_plugins_themes($params) {
1333
- global $mmb_core;
1334
- $mmb_core->get_installer_instance();
1335
- $return = $mmb_core->installer_instance->edit($params);
1336
- mmb_response($return, true);
1337
- }
1338
- }
1339
-
1340
- if( !function_exists('mmb_edit_autoupdate_plugins_themes') ){
1341
- function mmb_edit_autoupdate_plugins_themes($params) {
1342
- $return = MWP_Updater::setSettings($params);
1343
- mmb_response($return, true);
1344
- }
1345
- }
1346
-
1347
- if( !function_exists('mmb_worker_brand')){
1348
- function mmb_worker_brand($params) {
1349
- update_option("mwp_worker_brand",$params['brand']);
1350
- mmb_response(true, true);
1351
- }
1352
- }
1353
-
1354
- if( !function_exists('mmb_maintenance_mode')){
1355
- function mmb_maintenance_mode( $params ) {
1356
- global $wp_object_cache;
1357
-
1358
- $default = get_option('mwp_maintenace_mode');
1359
- $params = empty($default) ? $params : array_merge($default, $params);
1360
- update_option("mwp_maintenace_mode", $params);
1361
-
1362
- if(!empty($wp_object_cache))
1363
- @$wp_object_cache->flush();
1364
- mmb_response(true, true);
1365
- }
1366
- }
1367
-
1368
- if( !function_exists('mmb_plugin_actions') ){
1369
- function mmb_plugin_actions() {
1370
- global $mmb_actions, $mmb_core;
1371
-
1372
- if(!empty($mmb_actions)){
1373
- global $_mmb_plugin_actions;
1374
- if(!empty($_mmb_plugin_actions)){
1375
- $failed = array();
1376
- foreach($_mmb_plugin_actions as $action => $params){
1377
- if(isset($mmb_actions[$action]))
1378
- call_user_func($mmb_actions[$action], $params);
1379
- else
1380
- $failed[] = $action;
1381
- }
1382
- if(!empty($failed)){
1383
- $f = implode(', ', $failed);
1384
- $s = count($f) > 1 ? 'Actions "' . $f . '" do' : 'Action "' . $f . '" does';
1385
- mmb_response($s.' not exist. Please update your Worker plugin.', false);
1386
- }
1387
-
1388
- }
1389
- }
1390
-
1391
- global $pagenow, $current_user, $mmode;
1392
- if( !is_admin() && !in_array($pagenow, array( 'wp-login.php' ))){
1393
- $mmode = get_option('mwp_maintenace_mode');
1394
- if( !empty($mmode) ){
1395
- if(isset($mmode['active']) && $mmode['active'] == true){
1396
- if(isset($current_user->data) && !empty($current_user->data) && isset($mmode['hidecaps']) && !empty($mmode['hidecaps'])){
1397
- $usercaps = array();
1398
- if(isset($current_user->caps) && !empty($current_user->caps)){
1399
- $usercaps = $current_user->caps;
1400
- }
1401
- foreach($mmode['hidecaps'] as $cap => $hide){
1402
- if(!$hide)
1403
- continue;
1404
-
1405
- foreach($usercaps as $ucap => $val){
1406
- if($ucap == $cap){
1407
- ob_end_clean();
1408
- ob_end_flush();
1409
- die($mmode['template']);
1410
- }
1411
- }
1412
- }
1413
- } else
1414
- die($mmode['template']);
1415
- }
1416
- }
1417
- }
1418
-
1419
- if (file_exists(dirname(__FILE__) . '/log')) {
1420
- unlink(dirname(__FILE__) . '/log');
1421
- }
1422
- }
1423
- }
1424
-
1425
- $mmb_core = new MMB_Core();
1426
-
1427
- if(isset($_GET['auto_login']))
1428
- $mmb_core->automatic_login();
1429
-
1430
- require_once dirname(__FILE__) . '/updater.php';
1431
- MWP_Updater::register();
1432
-
1433
- if (function_exists('register_activation_hook'))
1434
- register_activation_hook( __FILE__ , array( $mmb_core, 'install' ));
1435
-
1436
- if (function_exists('register_deactivation_hook'))
1437
- register_deactivation_hook(__FILE__, array( $mmb_core, 'uninstall' ));
1438
-
1439
- if (function_exists('add_action'))
1440
- add_action('init', 'mmb_plugin_actions', 99999);
1441
-
1442
- if (function_exists('add_filter'))
1443
- add_filter('install_plugin_complete_actions','mmb_iframe_plugins_fix');
1444
-
1445
- if(!function_exists('mwb_edit_redirect_override')){
1446
- function mwb_edit_redirect_override($location = false, $comment_id = false){
1447
- if(isset($_COOKIE[MMB_XFRAME_COOKIE])){
1448
- $location = get_site_url().'/wp-admin/edit-comments.php';
1449
- }
1450
- return $location;
1451
- }
1452
- }
1453
- if (function_exists('add_filter'))
1454
- add_filter('comment_edit_redirect', 'mwb_edit_redirect_override');
1455
-
1456
- if( isset($_COOKIE[MMB_XFRAME_COOKIE]) ){
1457
- remove_action( 'admin_init', 'send_frame_options_header');
1458
- remove_action( 'login_init', 'send_frame_options_header');
1459
- }
1460
- function mwp_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1461
- {
1462
- $errorId = 'mwp_error_' . md5($errfile . $errline);
1463
- $error = sprintf("%s\nError [%s]: %s\nIn file: %s:%s", date('Y-m-d H:i:s'), $errno, $errstr, $errfile, $errline);
1464
- set_transient($errorId, $error, 3600);
1465
- }
1466
-
1467
- function mwp_fatal_error_handler()
1468
- {
1469
- $isError = false;
1470
- if ($error = error_get_last()) {
1471
- switch ($error['type']) {
1472
- case E_ERROR:
1473
- case E_CORE_ERROR:
1474
- case E_COMPILE_ERROR:
1475
- case E_USER_ERROR:
1476
- $isError = true;
1477
- break;
1478
- }
1479
- }
1480
- if ($isError) {
1481
- mwp_error_handler($error['type'], $error['message'], $error['file'], $error['line'], array());
1482
- }
1483
- }
1484
-
1485
-
1486
- if (get_option('mwp_debug_enable')) {
1487
- set_error_handler('mwp_error_handler');
1488
- register_shutdown_function('mwp_fatal_error_handler');
1489
- }
1490
-
1491
- if (get_option('mwp_remove_php_reporting') == 'T')
1492
- {
1493
- @error_reporting(0);
1494
- @ini_set('display_errors', 'off');
1495
- @ini_set('display_startup_errors', "off");
1496
- }
1497
-
1498
- if (get_option('mwp_remove_wp_version') == 'T')
1499
- {
1500
- remove_action('wp_head', 'wp_generator');
1501
- remove_filter('wp_head', 'wp_generator');
1502
- }
1503
- if (get_option('managewp_remove_styles_version') == 'T')
1504
- {
1505
- global $wp_styles;
1506
- if (!is_a($wp_styles, 'WP_Styles'))
1507
- return;
1508
-
1509
- foreach ($wp_styles->registered as $handle => $style)
1510
- $wp_styles->registered[$handle]->ver = null;
1511
- }
1512
- if (get_option('managewp_remove_scripts_version') == 'T')
1513
- {
1514
- global $wp_scripts;
1515
- if (!is_a($wp_scripts, 'WP_Scripts'))
1516
- return;
1517
-
1518
- foreach ($wp_scripts->registered as $handle => $script)
1519
- $wp_scripts->registered[$handle]->ver = null;
1520
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*
3
+ Plugin Name: ManageWP - Worker
4
+ Plugin URI: https://managewp.com
5
+ Description: ManageWP Worker plugin allows you to manage your WordPress sites from one dashboard. Visit <a href="https://managewp.com">ManageWP.com</a> for more information.
6
+ Version: 3.9.29
7
+ Author: ManageWP
8
+ Author URI: https://managewp.com
9
+ License: GPL2
10
+ */
11
+
12
+ /*************************************************************
13
+ * init.php
14
+ * Initialize the communication with master
15
+ * Copyright (c) 2011 Prelovac Media
16
+ * www.prelovac.com
17
+ **************************************************************/
18
+ if (!defined('ABSPATH')) {
19
+ exit;
20
+ }
21
+
22
+ if (!defined('MMB_WORKER_VERSION')) {
23
+ define('MMB_WORKER_VERSION', '3.9.29');
24
+ }
25
+
26
+ $GLOBALS['MMB_WORKER_VERSION'] = '3.9.29';
27
+ $GLOBALS['MMB_WORKER_REVISION'] = '2014-08-27 00:00:00';
28
+
29
+ /**
30
+ * Reserved memory for fatal error handling execution context.
31
+ */
32
+ $GLOBALS['mwp_reserved_memory'] = str_repeat(' ', 1024 * 20);
33
+ /**
34
+ * If we ever get only partially upgraded due to a server error or misconfiguration,
35
+ * attempt to disable the plugin and notify the site's administrator via email.
36
+ */
37
+ function mwp_fail_safe()
38
+ {
39
+ $GLOBALS['mwp_reserved_memory'] = null;
40
+
41
+ $lastError = error_get_last();
42
+
43
+ if (!$lastError || $lastError['type'] !== E_ERROR) {
44
+ return;
45
+ }
46
+
47
+ $activePlugins = get_option('active_plugins');
48
+ $workerIndex = array_search(plugin_basename(__FILE__), $activePlugins);
49
+ if ($workerIndex === false) {
50
+ // Plugin is not yet enabled, possibly in activation context.
51
+ return;
52
+ }
53
+
54
+ $errorSource = realpath($lastError['file']);
55
+ // We might be in eval() context.
56
+ if (!$errorSource) {
57
+ return;
58
+ }
59
+
60
+ // The only fatal error that we would get would be a 'Class 'X' not found in ...', so look out only for those messages.
61
+ if (!preg_match('/^Class \'[^\']+\' not found$/', $lastError['message'])) {
62
+ return;
63
+ }
64
+
65
+ // Only look for files that belong to this plugin.
66
+ $pluginBase = realpath(dirname(__FILE__));
67
+ if (strpos($errorSource, $pluginBase) !== 0) {
68
+ return;
69
+ }
70
+
71
+ unset($activePlugins[$workerIndex]);
72
+ // Reset indexes.
73
+ $activePlugins = array_values($activePlugins);
74
+ update_option('active_plugins', $activePlugins);
75
+
76
+ // We probably won't have access to the wp_mail function.
77
+ $mailFn = function_exists('wp_mail') ? 'wp_mail' : 'mail';
78
+ $siteUrl = get_option('siteurl');
79
+ $title = sprintf("ManageWP Worker deactivated on %s", $siteUrl);
80
+ $reason = "You received this e-mail because you are listed as the site's administrator.";
81
+ $to = get_option('admin_email');
82
+ $brand = get_option('mwp_worker_brand');
83
+ if (!empty($brand['admin_email'])) {
84
+ $to = $brand['admin_email'];
85
+ $reason = "You received this e-mail because you are listed as the site's manager.";
86
+ }
87
+ $body = sprintf("Due to an unsuccessful (possibly automatic) update, the ManageWP Worker plugin has deactivated itself on your site %s.
88
+
89
+ This was done as a precaution to prevent any problems to your site. %s
90
+
91
+ We apologize for the inconvenience. Please reinstall the plugin manually and re-add the website to your ManageWP dashboard.", $siteUrl, $reason);
92
+ $mailFn($to.',support@managewp.com', $title, $body);
93
+
94
+ // If we're inside a cron scope, don't attempt to hide this error.
95
+ if (defined('DOING_CRON') && DOING_CRON) {
96
+ return;
97
+ }
98
+
99
+ // If we're inside a normal request scope, we apologize. Retry the request so user doesn't have to see an ugly error page.
100
+ if (!empty($_SERVER['REQUEST_URI'])) {
101
+ $siteUrl .= $_SERVER['REQUEST_URI'];
102
+ }
103
+ if (headers_sent()) {
104
+ // The headers are probably sent if the PHP configuration has the 'display_errors' directive enabled. In that case try a meta redirect.
105
+ echo sprintf('<meta http-equiv="refresh" content="0; url=%s">', htmlspecialchars($siteUrl, ENT_QUOTES));
106
+ } else {
107
+ header('Location: '.htmlspecialchars($siteUrl, ENT_QUOTES));
108
+ }
109
+ exit;
110
+ }
111
+
112
+ register_shutdown_function('mwp_fail_safe');
113
+
114
+ require_once dirname(__FILE__).'/functions.php';
115
+
116
+ if (!defined('MMB_XFRAME_COOKIE')) {
117
+ $siteurl = function_exists('get_site_option') ? get_site_option('siteurl') : get_option('siteurl');
118
+ define('MMB_XFRAME_COOKIE', $xframe = 'wordpress_'.md5($siteurl).'_xframe');
119
+ }
120
+
121
+ global $wpdb, $mmb_plugin_dir, $mmb_plugin_url, $wp_version, $mmb_filters, $_mmb_item_filter;
122
+ if (version_compare(PHP_VERSION, '5.2.0', '<')) // min version 5 supported
123
+ {
124
+ exit("<p>ManageWP Worker plugin requires PHP 5.2 or higher.</p>");
125
+ }
126
+
127
+ if (version_compare(PHP_VERSION, '5.3', '<')) {
128
+ spl_autoload_register('mwp_autoload');
129
+ } else {
130
+ // The prepend parameter was added in PHP 5.3.0
131
+ spl_autoload_register('mwp_autoload', true, true);
132
+ }
133
+
134
+ // Will register the logger as the error handler.
135
+ mwp_logger();
136
+
137
+ $mmb_wp_version = $wp_version;
138
+ $mmb_plugin_dir = WP_PLUGIN_DIR.'/'.basename(dirname(__FILE__));
139
+ $mmb_plugin_url = WP_PLUGIN_URL.'/'.basename(dirname(__FILE__));
140
+
141
+ define('MWP_SHOW_LOG', false);
142
+ // <stats.class.php>
143
+ add_filter('mwp_website_add', 'MMB_Stats::readd_alerts');
144
+ // <backup.class.php>
145
+ define('MWP_BACKUP_DIR', WP_CONTENT_DIR.'/managewp/backups');
146
+ define('MWP_DB_DIR', MWP_BACKUP_DIR.'/mwp_db');
147
+
148
+ mmb_add_action('search_posts_by_term', 'search_posts_by_term');
149
+ add_filter('mmb_stats_filter', 'mmb_get_extended_info');
150
+ mmb_add_action('cleanup_delete', 'cleanup_delete_worker');
151
+
152
+ // <widget.class.php>
153
+ $mwp_worker_brand = get_option("mwp_worker_brand");
154
+ $worker_brand = 0;
155
+ if (is_array($mwp_worker_brand)) {
156
+ if ($mwp_worker_brand['name'] || $mwp_worker_brand['desc'] || $mwp_worker_brand['author'] || $mwp_worker_brand['author_url']) {
157
+ $worker_brand = 1;
158
+ }
159
+ }
160
+ if (!$worker_brand) {
161
+ add_action('widgets_init', create_function('', 'return register_widget("MMB_Widget");'));
162
+ }
163
+
164
+ if (!function_exists('mmb_parse_data')) {
165
+ function mmb_parse_data($data = array())
166
+ {
167
+ if (empty($data)) {
168
+ return $data;
169
+ }
170
+
171
+ $data = (array) $data;
172
+ if (isset($data['params'])) {
173
+ $data['params'] = mmb_filter_params($data['params']);
174
+ }
175
+
176
+ $postkeys = array('action', 'params', 'id', 'signature', 'setting', 'add_site_signature_id', 'add_site_signature');
177
+
178
+ if (!empty($data)) {
179
+ foreach ($data as $key => $items) {
180
+ if (!in_array($key, $postkeys)) {
181
+ unset($data[$key]);
182
+ }
183
+ }
184
+ }
185
+
186
+ return $data;
187
+ }
188
+ }
189
+
190
+ if (!function_exists('mmb_filter_params')) {
191
+ function mmb_filter_params($array = array())
192
+ {
193
+
194
+ $filter = array('current_user', 'wpdb');
195
+ $return = array();
196
+ foreach ($array as $key => $val) {
197
+ if (!is_int($key) && in_array($key, $filter)) {
198
+ continue;
199
+ }
200
+
201
+ if (is_array($val)) {
202
+ $return[$key] = mmb_filter_params($val);
203
+ } else {
204
+ $return[$key] = $val;
205
+ }
206
+ }
207
+
208
+ return $return;
209
+ }
210
+ }
211
+ if (!function_exists('mmb_authenticate')) {
212
+ function mmb_authenticate()
213
+ {
214
+ global $_mwp_data, $_mwp_auth, $mmb_core, $HTTP_RAW_POST_DATA;
215
+ if (!isset($HTTP_RAW_POST_DATA)) {
216
+ $HTTP_RAW_POST_DATA = file_get_contents('php://input');
217
+ }
218
+ $compat = false;
219
+ $compatActive = false;
220
+ $contentType = empty($_SERVER['CONTENT_TYPE']) ? false : $_SERVER['CONTENT_TYPE'];
221
+
222
+ if ($compat && empty($_SERVER['HTTP_MWP_ACTION']) && $contentType === 'application/json') {
223
+ $compatActive = true;
224
+ }
225
+
226
+ if (empty($_SERVER['HTTP_MWP_ACTION']) && !$compatActive) {
227
+ return;
228
+ }
229
+ $_mwp_data = json_decode($HTTP_RAW_POST_DATA, true);
230
+
231
+ if (!$_mwp_data) {
232
+ return;
233
+ }
234
+ $_mwp_data = mmb_parse_data($_mwp_data);
235
+
236
+ if ($compatActive) {
237
+ if (empty($_mwp_data['action'])) {
238
+ return;
239
+ }
240
+ $_mwp_data['signature'] = base64_decode($_mwp_data['signature']);
241
+ } else {
242
+ $_mwp_data['action'] = $_SERVER['HTTP_MWP_ACTION'];
243
+ $_mwp_data['id'] = isset($_SERVER['HTTP_MWP_MESSAGE_ID']) ? $_SERVER['HTTP_MWP_MESSAGE_ID'] : "";
244
+ $_mwp_data['signature'] = isset($_SERVER['HTTP_MWP_SIGNATURE']) ? base64_decode($_SERVER['HTTP_MWP_SIGNATURE']) : '';
245
+ }
246
+
247
+ $usernameUsed = array_key_exists('username', $_mwp_data['params']) ? $_mwp_data['params']['username'] : null;
248
+ if (empty($_mwp_data['params']['username']) || !$mmb_core->check_if_user_exists($_mwp_data['params']['username'])) {
249
+ $filter = array(
250
+ 'user_roles' => array(
251
+ 'administrator'
252
+ ),
253
+ 'username'=>'',
254
+ 'username_filter'=>'',
255
+ );
256
+ $users = $mmb_core->get_user_instance()->get_users($filter);
257
+
258
+ if (empty($users['users'])) {
259
+ mmb_response('We could not find an administrator user to use. Please contact support.', false);
260
+ }
261
+
262
+ $_mwp_data['params']['username'] = $users['users'][0]['user_login'];
263
+ }
264
+
265
+ if (isset($_mwp_data['params']['username']) && !is_user_logged_in()) {
266
+ $user = function_exists('get_user_by') ? get_user_by('login', $_mwp_data['params']['username']) : get_user_by('login', $_mwp_data['params']['username']);
267
+ }
268
+
269
+ if ($_mwp_data['action'] === 'add_site') {
270
+ $_mwp_auth = mwp_add_site_verify_signature($_mwp_data, $usernameUsed);
271
+ if(isset($user)){
272
+ $GLOBALS['mwp_user_id'] = $user->ID;
273
+ }
274
+
275
+ return;
276
+ } else {
277
+ $_mwp_auth = $mmb_core->authenticate_message($_mwp_data['action'].$_mwp_data['id'], $_mwp_data['signature'], $_mwp_data['id']);
278
+ }
279
+
280
+ if ($_mwp_auth !== true) {
281
+ mmb_response($_mwp_auth['error'], false);
282
+ }
283
+
284
+
285
+ //$this->w3tc_flush();
286
+
287
+ if (isset($user)) {
288
+ wp_set_current_user($user->ID);
289
+ if (@getenv('IS_WPE')) {
290
+ wp_set_auth_cookie($user->ID);
291
+ }
292
+ }
293
+
294
+
295
+ /*if (!defined('WP_ADMIN')) {
296
+ define('WP_ADMIN', true);
297
+ }*/
298
+
299
+ if(defined('ALTERNATE_WP_CRON') && !defined('DOING_AJAX') && ALTERNATE_WP_CRON === true ){
300
+ define('DOING_AJAX', true);
301
+ }
302
+ }
303
+ }
304
+
305
+ if (!function_exists("mwp_add_site_verify_signature")) {
306
+ function mwp_add_site_verify_signature($_mwp_data, $posted_username = null)
307
+ {
308
+ global $mmb_plugin_dir;
309
+
310
+ $nonce = new MWP_Security_HashNonce();
311
+ $nonce->setValue($_mwp_data['id']);
312
+ if (!$nonce->verify()) {
313
+ $_mwp_auth = array(
314
+ 'error' => 'Invalid nonce used. Please contact support'
315
+ );
316
+ mmb_response($_mwp_auth['error'], false);
317
+ } else {
318
+
319
+ if (!empty($_mwp_data['add_site_signature']) && !empty($_mwp_data['add_site_signature_id'])) {
320
+ $signature = base64_decode($_mwp_data['add_site_signature']);
321
+ $signature_id = $_mwp_data['add_site_signature_id'];
322
+ $plaintext = array();
323
+ $plaintext['setting'] = $_mwp_data['setting'];
324
+ $plaintext['params'] = $_mwp_data['params'];
325
+ if (isset($posted_username)) {
326
+ $plaintext['params']['username'] = $posted_username;
327
+ }
328
+ if (file_exists($mmb_plugin_dir.'/publickeys/'.$signature_id.'.pub')) {
329
+ $plaintext = json_encode($plaintext);
330
+ require_once dirname(__FILE__).'/src/PHPSecLib/Crypt/RSA.php';
331
+ $rsa = new Crypt_RSA();
332
+ $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
333
+ $rsa->loadKey(file_get_contents($mmb_plugin_dir.'/publickeys/'.$signature_id.'.pub')); // public key
334
+ $_mwp_auth = $rsa->verify($plaintext, $signature);
335
+ } else {
336
+ $_mwp_auth = false; // we don't have key
337
+ }
338
+ } else {
339
+ $_mwp_auth = false;
340
+ }
341
+
342
+ if ($_mwp_auth !== true) {
343
+ $_mwp_auth = array(
344
+ 'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
345
+ );
346
+ mmb_response($_mwp_auth['error'], false);
347
+ }
348
+ }
349
+
350
+ return $_mwp_auth;
351
+ }
352
+ }
353
+
354
+ if (!function_exists('mmb_parse_request')) {
355
+ function mmb_parse_request()
356
+ {
357
+ global $mmb_core, $wp_db_version, $wpmu_version, $_wp_using_ext_object_cache, $_mwp_data, $_mwp_auth;
358
+ if (empty($_mwp_auth)) {
359
+ MMB_Stats::set_hit_count();
360
+
361
+ return;
362
+ }
363
+ ob_start();
364
+ $_wp_using_ext_object_cache = false;
365
+ @set_time_limit(1200);
366
+
367
+ if (isset($_mwp_data['setting'])) {
368
+ if(array_key_exists("dataown",$_mwp_data['setting'])){
369
+ $oldconfiguration = array("dataown" => $_mwp_data['setting']['dataown']);
370
+ $mmb_core->save_options($oldconfiguration);
371
+ unset($_mwp_data['setting']['dataown']);
372
+ }
373
+
374
+ $configurationService = new MWP_Configuration_Service();
375
+ $configuration = new MWP_Configuration_Conf($_mwp_data['setting']);
376
+ $configurationService->saveConfiguration($configuration);
377
+ }
378
+
379
+ if ($_mwp_data['action'] === 'add_site') {
380
+ mmb_add_site($_mwp_data['params']);
381
+ mmb_response('You should never see this.', false);
382
+ }
383
+
384
+ /* in case database upgrade required, do database backup and perform upgrade ( wordpress wp_upgrade() function ) */
385
+ if (strlen(trim($wp_db_version)) && !defined('ACX_PLUGIN_DIR')) {
386
+ if (get_option('db_version') != $wp_db_version) {
387
+ /* in multisite network, please update database manualy */
388
+ if (empty($wpmu_version) || (function_exists('is_multisite') && !is_multisite())) {
389
+ if (!function_exists('wp_upgrade')) {
390
+ include_once(ABSPATH.'wp-admin/includes/upgrade.php');
391
+ }
392
+
393
+ ob_clean();
394
+ @wp_upgrade();
395
+ @do_action('after_db_upgrade');
396
+ ob_end_clean();
397
+ }
398
+ }
399
+ }
400
+
401
+ if (isset($_mwp_data['params']['secure'])) {
402
+ if (is_array($_mwp_data['params']['secure'])) {
403
+ $secureParams = $_mwp_data['params']['secure'];
404
+ foreach ($secureParams as $key => $value) {
405
+ $secureParams[$key] = base64_decode($value);
406
+ }
407
+ $_mwp_data['params']['secure'] = $secureParams;
408
+ } else {
409
+ $_mwp_data['params']['secure'] = base64_decode($_mwp_data['params']['secure']);
410
+ }
411
+ if ($decrypted = $mmb_core->_secure_data($_mwp_data['params']['secure'])) {
412
+ $decrypted = maybe_unserialize($decrypted);
413
+ if (is_array($decrypted)) {
414
+ foreach ($decrypted as $key => $val) {
415
+ if (!is_numeric($key)) {
416
+ $_mwp_data['params'][$key] = $val;
417
+ }
418
+ }
419
+ unset($_mwp_data['params']['secure']);
420
+ } else {
421
+ $_mwp_data['params']['secure'] = $decrypted;
422
+ }
423
+ }
424
+
425
+ if (!$decrypted && $mmb_core->get_random_signature() !== false) {
426
+ require_once dirname(__FILE__).'/src/PHPSecLib/Crypt/AES.php';
427
+ $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB);
428
+ $cipher->setKey($mmb_core->get_random_signature());
429
+ $decrypted = $cipher->decrypt($_mwp_data['params']['secure']);
430
+ $_mwp_data['params']['account_info'] = json_decode($decrypted, true);
431
+ }
432
+
433
+ }
434
+
435
+ $logData = array(
436
+ 'action' => $_mwp_data['action'],
437
+ 'action_parameters' => $_mwp_data['params'],
438
+ 'action_settings' => $_mwp_data['setting'],
439
+ );
440
+
441
+ if (!empty( $_mwp_data['setting'])) {
442
+ $logData['settings'] = $_mwp_data['setting'];
443
+ }
444
+
445
+ mwp_logger()->debug('Master request: "{action}"', $logData);
446
+
447
+ if (!$mmb_core->register_action_params($_mwp_data['action'], $_mwp_data['params'])) {
448
+ global $_mmb_plugin_actions;
449
+ $_mmb_plugin_actions[$_mwp_data['action']] = $_mwp_data['params'];
450
+ }
451
+
452
+ ob_end_clean();
453
+ }
454
+ }
455
+ /* Main response function */
456
+ if (!function_exists('mmb_response')) {
457
+
458
+ function mmb_response($response = false, $success = true)
459
+ {
460
+ $return = array();
461
+
462
+ if ((is_array($response) && empty($response)) || (!is_array($response) && strlen($response) == 0)) {
463
+ $return['error'] = 'Empty response.';
464
+ } else {
465
+ if ($success) {
466
+ $return['success'] = $response;
467
+ } else {
468
+ $return['error'] = $response;
469
+ }
470
+ }
471
+
472
+ if (!headers_sent()) {
473
+ header('HTTP/1.0 200 OK');
474
+ header('Content-Type: text/plain');
475
+ }
476
+
477
+ mwp_logger()->debug('Master response: {action_response_status}', array(
478
+ 'action_response_status' => $success ? 'success' : 'error',
479
+ 'action_response' => $return,
480
+ 'headers_sent' => headers_sent(),
481
+ ));
482
+
483
+ exit("<MWPHEADER>".base64_encode(serialize($return))."<ENDMWPHEADER>");
484
+ }
485
+ }
486
+
487
+
488
+ if (!function_exists('mmb_add_site')) {
489
+ function mmb_add_site($params)
490
+ {
491
+ global $mmb_core;
492
+ $num = extract($params);
493
+
494
+ if ($num) {
495
+ if (!get_option('_worker_public_key')) {
496
+ $public_key = base64_decode($public_key);
497
+
498
+ if (function_exists('openssl_verify')) {
499
+ $verify = openssl_verify($action.$id, base64_decode($signature), $public_key);
500
+ if ($verify == 1) {
501
+ $mmb_core->set_master_public_key($public_key);
502
+ //$mmb_core->set_worker_message_id($id);
503
+
504
+
505
+ $mmb_core->get_stats_instance();
506
+ if (isset($notifications) && is_array($notifications) && !empty($notifications)) {
507
+ $mmb_core->stats_instance->set_notifications($notifications);
508
+ }
509
+ if (isset($brand) && is_array($brand) && !empty($brand)) {
510
+ update_option('mwp_worker_brand', $brand);
511
+ }
512
+
513
+ if (isset($add_settigns) && is_array($add_settigns) && !empty($add_settigns)) {
514
+ apply_filters('mwp_website_add', $add_settigns);
515
+ }
516
+
517
+ mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
518
+ } else {
519
+ if ($verify == 0) {
520
+
521
+ //mmb_response('Site could not be added. OpenSSL verification error: "'.openssl_error_string().'". Contact your hosting support to check the OpenSSL configuration.', false);
522
+
523
+ } else {
524
+ mmb_response('Command not successful. Please try again.', false);
525
+ }
526
+ }
527
+ }
528
+
529
+ if (!get_option('_worker_nossl_key')) {
530
+ srand();
531
+
532
+ $random_key = md5(base64_encode($public_key).rand(0, getrandmax()));
533
+
534
+ $mmb_core->set_random_signature($random_key);
535
+ //$mmb_core->set_worker_message_id($id);
536
+ $mmb_core->set_master_public_key($public_key);
537
+
538
+
539
+ $mmb_core->get_stats_instance();
540
+ if (is_array($notifications) && !empty($notifications)) {
541
+ $mmb_core->stats_instance->set_notifications($notifications);
542
+ }
543
+
544
+ if (is_array($brand) && !empty($brand)) {
545
+ update_option('mwp_worker_brand', $brand);
546
+ }
547
+
548
+ mmb_response($mmb_core->stats_instance->get_initial_stats(), true);
549
+ } else {
550
+ mmb_response('Sorry, we were unable to communicate with your website. Please deactivate, then activate ManageWP Worker plugin on your website and try again or contact our support.', false);
551
+ }
552
+
553
+ } else {
554
+ mmb_response('Sorry, we were unable to communicate with your website. Please deactivate, then activate ManageWP Worker plugin on your website and try again or contact our support.', false);
555
+ }
556
+ } else {
557
+ mmb_response('Invalid parameters received. Please try again.', false);
558
+ }
559
+ }
560
+ }
561
+
562
+ if (!function_exists('mmb_remove_site')) {
563
+ function mmb_remove_site($params)
564
+ {
565
+ extract($params);
566
+ global $mmb_core;
567
+ $mmb_core->uninstall($deactivate);
568
+
569
+ include_once(ABSPATH.'wp-admin/includes/plugin.php');
570
+ $plugin_slug = basename(dirname(__FILE__)).'/'.basename(__FILE__);
571
+
572
+ if ($deactivate) {
573
+ deactivate_plugins($plugin_slug, true);
574
+ } else {
575
+ // Prolong the worker deactivation upon site removal.
576
+ update_option('mmb_worker_activation_time', time());
577
+ }
578
+
579
+ if (!is_plugin_active($plugin_slug)) {
580
+ mmb_response(
581
+ array(
582
+ 'deactivated' => 'Site removed successfully. <br /><br />ManageWP Worker plugin successfully deactivated.'
583
+ ),
584
+ true
585
+ );
586
+ } else {
587
+ mmb_response(
588
+ array(
589
+ 'removed_data' => 'Site removed successfully. <br /><br /><b>ManageWP Worker plugin was not deactivated.</b>'
590
+ ),
591
+ true
592
+ );
593
+ }
594
+
595
+ }
596
+ }
597
+ if (!function_exists('mmb_stats_get')) {
598
+ function mmb_stats_get($params)
599
+ {
600
+ global $mmb_core;
601
+ $mmb_core->get_stats_instance();
602
+ mmb_response($mmb_core->stats_instance->get($params), true);
603
+ }
604
+ }
605
+
606
+ if (!function_exists('mmb_worker_header')) {
607
+ function mmb_worker_header()
608
+ {
609
+ global $mmb_core, $current_user;
610
+
611
+ if (!headers_sent()) {
612
+ if (isset($current_user->ID)) {
613
+ $expiration = time() + apply_filters('auth_cookie_expiration', 10800, $current_user->ID, false);
614
+ } else {
615
+ $expiration = time() + 10800;
616
+ }
617
+
618
+ setcookie(MMB_XFRAME_COOKIE, md5(MMB_XFRAME_COOKIE), $expiration, COOKIEPATH, COOKIE_DOMAIN, false, true);
619
+ $_COOKIE[MMB_XFRAME_COOKIE] = md5(MMB_XFRAME_COOKIE);
620
+ }
621
+ }
622
+ }
623
+
624
+ if (!function_exists('mmb_pre_init_stats')) {
625
+ function mmb_pre_init_stats($params)
626
+ {
627
+ global $mmb_core;
628
+ $mmb_core->get_stats_instance();
629
+
630
+ return $mmb_core->stats_instance->pre_init_stats($params);
631
+ }
632
+ }
633
+
634
+ if (!function_exists('mwp_datasend')) {
635
+ function mwp_datasend($params = array())
636
+ {
637
+ global $mmb_core, $_mmb_item_filter, $_mmb_options;
638
+
639
+
640
+ $_mmb_remoteurl = get_option('home');
641
+ $_mmb_remoteown = isset($_mmb_options['dataown']) && !empty($_mmb_options['dataown']) ? $_mmb_options['dataown'] : false;
642
+
643
+ if (empty($_mmb_remoteown)) {
644
+ return;
645
+ }
646
+
647
+ $_mmb_item_filter['pre_init_stats'] = array('core_update', 'hit_counter', 'comments', 'backups', 'posts', 'drafts', 'scheduled');
648
+ $_mmb_item_filter['get'] = array('updates', 'errors');
649
+ $mmb_core->get_stats_instance();
650
+
651
+ $filter = array(
652
+ 'refresh' => 'transient',
653
+ 'item_filter' => array(
654
+ 'get_stats' => array(
655
+ array('updates', array('plugins' => true, 'themes' => true, 'premium' => true)),
656
+ array('core_update', array('core' => true)),
657
+ array('posts', array('numberposts' => 5)),
658
+ array('drafts', array('numberposts' => 5)),
659
+ array('scheduled', array('numberposts' => 5)),
660
+ array('hit_counter'),
661
+ array('comments', array('numberposts' => 5)),
662
+ array('backups'),
663
+ 'plugins' => array(
664
+ 'cleanup' => array(
665
+ 'overhead' => array(),
666
+ 'revisions' => array('num_to_keep' => 'r_5'),
667
+ 'spam' => array(),
668
+ )
669
+ ),
670
+ ),
671
+ )
672
+ );
673
+
674
+ $pre_init_data = $mmb_core->stats_instance->pre_init_stats($filter);
675
+ $init_data = $mmb_core->stats_instance->get($filter);
676
+
677
+ $data = array_merge($init_data, $pre_init_data);
678
+ $data['server_ip'] = $_SERVER['SERVER_ADDR'];
679
+ $data['uhost'] = php_uname('n');
680
+ $hash = $mmb_core->get_secure_hash();
681
+
682
+ if (mwp_datasend_trigger($data)) { // adds trigger to check if really need to send something
683
+ $configurationService = new MWP_Configuration_Service();
684
+ $configuration = $configurationService->getConfiguration();
685
+
686
+ set_transient("mwp_cache_notifications", $data);
687
+ set_transient("mwp_cache_notifications_time", time());
688
+
689
+ $datasend['datasend'] = $mmb_core->encrypt_data($data);
690
+ $datasend['sitehome'] = base64_encode($_mmb_remoteown.'[]'.$_mmb_remoteurl);
691
+ $datasend['sitehash'] = md5($hash.$_mmb_remoteown.$_mmb_remoteurl);
692
+ $datasend['setting_checksum_order'] = implode(",", array_keys($configuration->getVariables()));
693
+ $datasend['setting_checksum'] = md5(json_encode($configuration->toArray()));
694
+ if (!class_exists('WP_Http')) {
695
+ include_once(ABSPATH.WPINC.'/class-http.php');
696
+ }
697
+
698
+ $remote = array();
699
+ $remote['body'] = $datasend;
700
+
701
+ $result = wp_remote_post($configuration->getMasterCronUrl(), $remote);
702
+ if (!is_wp_error($result)) {
703
+ if (isset($result['body']) && !empty($result['body'])) {
704
+ $settings = @unserialize($result['body']);
705
+ /* rebrand worker or set default */
706
+ $brand = '';
707
+ if ($settings['worker_brand']) {
708
+ $brand = $settings['worker_brand'];
709
+ }
710
+ update_option("mwp_worker_brand", $brand);
711
+ /* change worker version */
712
+ $w_version = $settings['worker_updates']['version'];
713
+ $w_url = $settings['worker_updates']['url'];
714
+ if (version_compare($GLOBALS['MMB_WORKER_VERSION'], $w_version, '<')) {
715
+ //automatic update
716
+ $mmb_core->update_worker_plugin(array("download_url" => $w_url));
717
+ }
718
+
719
+ if (!empty($settings['mwp_worker_configuration'])) {
720
+ require_once dirname(__FILE__).'/src/PHPSecLib/Crypt/RSA.php';
721
+ $rsa = new Crypt_RSA();
722
+ $keyName = $configuration->getKeyName();
723
+ $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
724
+ $rsa->loadKey(file_get_contents(dirname(__FILE__)."/publickeys/$keyName.pub")); // public key
725
+ $signature = base64_decode($settings['mwp_worker_configuration_signature']);
726
+ if ($rsa->verify(json_encode($settings['mwp_worker_configuration']), $signature)) {
727
+ $configuration = new MWP_Configuration_Conf($settings['mwp_worker_configuration']);
728
+ $configurationService->saveConfiguration($configuration);
729
+ }
730
+ }
731
+ }
732
+ } else {
733
+ //$mmb_core->_log($result);
734
+ }
735
+
736
+ }
737
+
738
+ }
739
+
740
+ }
741
+
742
+ if (!function_exists("mwp_datasend_trigger")) {
743
+ // trigger function, returns true if notifications should be sent
744
+ function mwp_datasend_trigger($stats)
745
+ {
746
+
747
+ $configurationService = new MWP_Configuration_Service();
748
+ $configuration = $configurationService->getConfiguration();
749
+
750
+ $cachedData = get_transient("mwp_cache_notifications");
751
+ $cacheTime = (int) get_transient("mwp_cache_notifications_time");
752
+
753
+ $returnValue = false;
754
+ if (false == $cachedData || empty($configuration)) {
755
+ $returnValue = true;
756
+ }
757
+ /**
758
+ * Cache lifetime check
759
+ */
760
+ if (!$returnValue) {
761
+ $now = time();
762
+ if ($now - $configuration->getNotiCacheLifeTime() >= $cacheTime) {
763
+ $returnValue = true;
764
+ }
765
+ }
766
+
767
+ /**
768
+ * Themes difference check section
769
+ * First check if array differ in size. If same size,then check values difference
770
+ */
771
+ if (!$returnValue && empty($stats['upgradable_themes']) != empty($cachedData['upgradable_themes'])) {
772
+ $returnValue = true;
773
+ }
774
+ if (!$returnValue && !empty($stats['upgradable_themes'])) {
775
+ $themesArr = mwp_std_to_array($stats['upgradable_themes']);
776
+ $cachedThemesArr = mwp_std_to_array($cachedData['upgradable_themes']);
777
+ if ($themesArr != $cachedThemesArr) {
778
+ $returnValue = true;
779
+ }
780
+ }
781
+
782
+ /**
783
+ * Plugins difference check section
784
+ * First check if array differ in size. If same size,then check values difference
785
+ */
786
+ if (!$returnValue && empty($stats['upgradable_plugins']) != empty($cachedData['upgradable_plugins'])) {
787
+ $returnValue = true;
788
+ }
789
+
790
+ if (!$returnValue && !empty($stats['upgradable_plugins'])) { //we have hear stdclass
791
+ $pluginsArr = mwp_std_to_array($stats['upgradable_plugins']);
792
+ $cachedPluginsArr = mwp_std_to_array($cachedData['upgradable_plugins']);
793
+ if ($pluginsArr != $cachedPluginsArr) {
794
+ $returnValue = true;
795
+ }
796
+ }
797
+
798
+ /**
799
+ * Premium difference check section
800
+ * First check if array differ in size. If same size,then check values difference
801
+ */
802
+ if (!$returnValue && empty($stats['premium_updates']) != empty($cachedData['premium_updates'])) {
803
+ $returnValue = true;
804
+ }
805
+ if (!$returnValue && !empty($stats['premium_updates'])) {
806
+ $premiumArr = mwp_std_to_array($stats['premium_updates']);
807
+ $cachedPremiumArr = mwp_std_to_array($cachedData['premium_updates']);
808
+ if ($premiumArr != $cachedPremiumArr) {
809
+ $returnValue = true;
810
+ }
811
+ }
812
+ /**
813
+ * Comments
814
+ * Check if we have configs first, then check trasholds
815
+ */
816
+ if (!$returnValue && (int) $stats['num_spam_comments'] >= $configuration->getNotiTresholdSpamComments() && $stats['num_spam_comments'] != (int) $cachedData['num_spam_comments']) {
817
+ $returnValue = true;
818
+ }
819
+ if (!$returnValue && (int) $stats['num_spam_comments'] < (int) $cachedData['num_spam_comments']) {
820
+ $returnValue = true;
821
+ }
822
+
823
+ if (!$returnValue && !empty($stats['comments'])) {
824
+ if (!empty($stats['comments']['pending']) && count($stats['comments']['pending']) >= $configuration->getNotiTresholdPendingComments()) {
825
+ $pendingArr = mwp_std_to_array($stats['comments']['pending']);
826
+ $cachedPendingArr = mwp_std_to_array($cachedData['comments']['pending']);
827
+ if ($pendingArr != $cachedPendingArr) {
828
+ $returnValue = true;
829
+ }
830
+ }
831
+
832
+ if (!empty($stats['comments']['approved']) && count($stats['comments']['approved']) >= $configuration->getNotiTresholdApprovedComments()) {
833
+ $approvedArr = mwp_std_to_array($stats['comments']['approved']);
834
+ $cachedApprovedArr = mwp_std_to_array($cachedData['comments']['approved']);
835
+ if ($approvedArr != $cachedApprovedArr) {
836
+ $returnValue = true;
837
+ }
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Drafts, posts
843
+ */
844
+
845
+ if (!$returnValue && !empty($stats['drafts']) && count($stats['drafts']) >= $configuration->getNotiTresholdDrafts()) {
846
+ if (count($stats['drafts']) > $configuration->getNotiTresholdDrafts() && empty($cachedData['drafts'])) {
847
+ $returnValue = true;
848
+ } else {
849
+ $draftsArr = mwp_std_to_array($stats['drafts']);
850
+ $cachedDraftsArr = mwp_std_to_array($cachedData['drafts']);
851
+ if ($draftsArr != $cachedDraftsArr) {
852
+ $returnValue = true;
853
+ }
854
+ }
855
+
856
+ }
857
+
858
+ if (!$returnValue && !empty($stats['posts']) && count($stats['posts']) >= $configuration->getNotiTresholdPosts()) {
859
+ if (count($stats['posts']) > $configuration->getNotiTresholdPosts() && empty($cachedData['posts'])) {
860
+ $returnValue = true;
861
+ } else {
862
+ $postsArr = mwp_std_to_array($stats['posts']);
863
+ $cachedPostsArr = mwp_std_to_array($cachedData['posts']);
864
+ if ($postsArr != $cachedPostsArr) {
865
+ $returnValue = true;
866
+ }
867
+ }
868
+ }
869
+
870
+ /**
871
+ * Core updates & backups
872
+ */
873
+ if (!$returnValue && empty($stats['core_updates']) != empty($cachedData['core_updates'])) {
874
+ $returnValue = true;
875
+ }
876
+ if (!$returnValue && !empty($stats['core_updates'])) {
877
+ $coreArr = mwp_std_to_array($stats['core_updates']);
878
+ $cachedCoreArr = mwp_std_to_array($cachedData['core_updates']);
879
+ if ($coreArr != $cachedCoreArr) {
880
+ $returnValue = true;
881
+ }
882
+ }
883
+
884
+ if (!$returnValue && empty($stats['mwp_backups']) != empty($cachedData['mwp_backups'])) {
885
+ $returnValue = true;
886
+ }
887
+ if (!$returnValue && !empty($stats['mwp_backups'])) {
888
+ $backupArr = mwp_std_to_array($stats['mwp_backups']);
889
+ $cachedBackupArr = mwp_std_to_array($cachedData['mwp_backups']);
890
+ if ($backupArr != $cachedBackupArr) {
891
+ $returnValue = true;
892
+ }
893
+ }
894
+
895
+ return $returnValue;
896
+ }
897
+ }
898
+
899
+ if (!function_exists("mwp_std_to_array")) {
900
+ function mwp_std_to_array($obj)
901
+ {
902
+ if (is_object($obj)) {
903
+ $objArr = clone $obj;
904
+ } else {
905
+ $objArr = $obj;
906
+ }
907
+ if (!empty($objArr)) {
908
+ foreach ($objArr as &$element) {
909
+ if ($element instanceof stdClass || is_array($element)) {
910
+ $element = mwp_std_to_array($element);
911
+ }
912
+ }
913
+ $objArr = (array) $objArr;
914
+ }
915
+
916
+ return $objArr;
917
+ }
918
+ }
919
+
920
+
921
+ //post
922
+ if (!function_exists('mmb_post_create')) {
923
+ function mmb_post_create($params)
924
+ {
925
+ global $mmb_core;
926
+ $mmb_core->get_post_instance();
927
+ $return = $mmb_core->post_instance->create($params);
928
+ if (is_int($return)) {
929
+ mmb_response($return, true);
930
+ } else {
931
+ if (isset($return['error'])) {
932
+ mmb_response($return['error'], false);
933
+ } else {
934
+ mmb_response($return, false);
935
+ }
936
+ }
937
+ }
938
+ }
939
+
940
+ if (!function_exists('mmb_change_post_status')) {
941
+ function mmb_change_post_status($params)
942
+ {
943
+ global $mmb_core;
944
+ $mmb_core->get_post_instance();
945
+ $return = $mmb_core->post_instance->change_status($params);
946
+ if (is_wp_error($return)){
947
+ mmb_response($return->get_error_message(), false);
948
+ } elseif (empty($return)) {
949
+ mmb_response("Post status can not be changed", false);
950
+ } else {
951
+ mmb_response($return, true);
952
+ }
953
+ }
954
+ }
955
+
956
+ //comments
957
+ if (!function_exists('mmb_change_comment_status')) {
958
+ function mmb_change_comment_status($params)
959
+ {
960
+ global $mmb_core;
961
+ $mmb_core->get_comment_instance();
962
+ $return = $mmb_core->comment_instance->change_status($params);
963
+ //mmb_response($return, true);
964
+ if ($return) {
965
+ $mmb_core->get_stats_instance();
966
+ mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
967
+ } else {
968
+ mmb_response('Comment not updated', false);
969
+ }
970
+ }
971
+
972
+ }
973
+ if (!function_exists('mmb_comment_stats_get')) {
974
+ function mmb_comment_stats_get($params)
975
+ {
976
+ global $mmb_core;
977
+ $mmb_core->get_stats_instance();
978
+ mmb_response($mmb_core->stats_instance->get_comments_stats($params), true);
979
+ }
980
+ }
981
+
982
+ if (!function_exists('mmb_backup_now')) {
983
+ //backup
984
+ function mmb_backup_now($params)
985
+ {
986
+ global $mmb_core;
987
+
988
+ $mmb_core->get_backup_instance();
989
+ $return = $mmb_core->backup_instance->backup($params);
990
+
991
+ if (is_array($return) && array_key_exists('error', $return)) {
992
+ mmb_response($return['error'], false);
993
+ } else {
994
+ mmb_response($return, true);
995
+ }
996
+ }
997
+ }
998
+
999
+ if (!function_exists('mwp_ping_backup')) {
1000
+ //ping backup
1001
+ function mwp_ping_backup($params)
1002
+ {
1003
+ global $mmb_core;
1004
+
1005
+ $mmb_core->get_backup_instance();
1006
+ $return = $mmb_core->backup_instance->ping_backup($params);
1007
+
1008
+ if (is_array($return) && array_key_exists('error', $return)) {
1009
+ mmb_response($return['error'], false);
1010
+ } else {
1011
+ mmb_response($return, true);
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ if (!function_exists('mmb_run_task_now')) {
1017
+ function mmb_run_task_now($params)
1018
+ {
1019
+ global $mmb_core;
1020
+ $mmb_core->get_backup_instance();
1021
+
1022
+ $task_name = isset($params['task_name']) ? $params['task_name'] : false;
1023
+ $google_drive_token = isset($params['google_drive_token']) ? $params['google_drive_token'] : false;
1024
+
1025
+ if ($task_name) {
1026
+ $return = $mmb_core->backup_instance->task_now($task_name, $google_drive_token);
1027
+ if (is_array($return) && array_key_exists('error', $return)) {
1028
+ mmb_response($return['error'], false);
1029
+ } else {
1030
+ mmb_response($return, true);
1031
+ }
1032
+ } else {
1033
+ mmb_response("Task name is not provided.", false);
1034
+ }
1035
+
1036
+ }
1037
+ }
1038
+
1039
+ if (!function_exists('mmb_email_backup')) {
1040
+ function mmb_email_backup($params)
1041
+ {
1042
+ global $mmb_core;
1043
+ $mmb_core->get_backup_instance();
1044
+ $return = $mmb_core->backup_instance->email_backup($params);
1045
+
1046
+ if (is_array($return) && array_key_exists('error', $return)) {
1047
+ mmb_response($return['error'], false);
1048
+ } else {
1049
+ mmb_response($return, true);
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ if (!function_exists('mmb_check_backup_compat')) {
1055
+ function mmb_check_backup_compat($params)
1056
+ {
1057
+ global $mmb_core;
1058
+ $mmb_core->get_backup_instance();
1059
+ $return = $mmb_core->backup_instance->check_backup_compat($params);
1060
+
1061
+ if (is_array($return) && array_key_exists('error', $return)) {
1062
+ mmb_response($return['error'], false);
1063
+ } else {
1064
+ mmb_response($return, true);
1065
+ }
1066
+ }
1067
+ }
1068
+
1069
+ if (!function_exists('mmb_get_backup_req')) {
1070
+ function mmb_get_backup_req($params)
1071
+ {
1072
+ global $mmb_core;
1073
+ $mmb_core->get_stats_instance();
1074
+ $return = $mmb_core->stats_instance->get_backup_req($params);
1075
+
1076
+ mmb_response($return, true);
1077
+ }
1078
+ }
1079
+
1080
+ // Fires when Backup Now, or some backup task is saved.
1081
+ if (!function_exists('mmb_scheduled_backup')) {
1082
+ function mmb_scheduled_backup($params)
1083
+ {
1084
+ global $mmb_core;
1085
+ $mmb_core->get_backup_instance();
1086
+ $return = $mmb_core->backup_instance->set_backup_task($params);
1087
+ mmb_response($return, $return);
1088
+ }
1089
+ }
1090
+
1091
+ if (!function_exists('mmm_delete_backup')) {
1092
+ function mmm_delete_backup($params)
1093
+ {
1094
+ global $mmb_core;
1095
+ $mmb_core->get_backup_instance();
1096
+ $return = $mmb_core->backup_instance->delete_backup($params);
1097
+ mmb_response($return, $return);
1098
+ }
1099
+ }
1100
+
1101
+ if (!function_exists('mmb_optimize_tables')) {
1102
+ function mmb_optimize_tables($params)
1103
+ {
1104
+ global $mmb_core;
1105
+ $mmb_core->get_backup_instance();
1106
+ $return = $mmb_core->backup_instance->optimize_tables();
1107
+ if ($return) {
1108
+ mmb_response($return, true);
1109
+ } else {
1110
+ mmb_response(false, false);
1111
+ }
1112
+ }
1113
+ }
1114
+ if (!function_exists('mmb_restore_now')) {
1115
+ function mmb_restore_now($params)
1116
+ {
1117
+ global $mmb_core;
1118
+ $mmb_core->get_backup_instance();
1119
+ $return = $mmb_core->backup_instance->restore($params);
1120
+ if (is_array($return) && array_key_exists('error', $return)) {
1121
+ mmb_response($return['error'], false);
1122
+ } else {
1123
+ mmb_response($return, true);
1124
+ }
1125
+
1126
+ }
1127
+ }
1128
+
1129
+ if (!function_exists('mmb_remote_backup_now')) {
1130
+ function mmb_remote_backup_now($params)
1131
+ {
1132
+ global $mmb_core;
1133
+ $backup_instance = $mmb_core->get_backup_instance();
1134
+ $return = $mmb_core->backup_instance->remote_backup_now($params);
1135
+ if (is_array($return) && array_key_exists('error', $return)) {
1136
+ mmb_response($return['error'], false);
1137
+ } else {
1138
+ mmb_response($return, true);
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+
1144
+ if (!function_exists('mmb_clean_orphan_backups')) {
1145
+ function mmb_clean_orphan_backups()
1146
+ {
1147
+ global $mmb_core;
1148
+ $backup_instance = $mmb_core->get_backup_instance();
1149
+ $return = $mmb_core->backup_instance->cleanup();
1150
+ if (is_array($return)) {
1151
+ mmb_response($return, true);
1152
+ } else {
1153
+ mmb_response($return, false);
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ function mmb_run_forked_action()
1159
+ {
1160
+
1161
+ $usernameUsed = array_key_exists('username', $_POST) ? $_POST : null;
1162
+ if ($usernameUsed && !is_user_logged_in()) {
1163
+ $user = function_exists('get_user_by') ? get_user_by('login', $_POST['username']) : get_user_by('login', $_POST['username']);
1164
+ }
1165
+
1166
+ if (isset($user)) {
1167
+ wp_set_current_user($user->ID);
1168
+ if (@getenv('IS_WPE')) {
1169
+ wp_set_auth_cookie($user->ID);
1170
+ }
1171
+ }
1172
+ if (!isset($_POST['mmb_fork_nonce']) || (isset($_POST['mmb_fork_nonce']) && !wp_verify_nonce($_POST['mmb_fork_nonce'], 'mmb-fork-nonce'))) {
1173
+ return false;
1174
+ }
1175
+
1176
+ $public_key = get_option('_worker_public_key');
1177
+ if (!isset($_POST['public_key']) || $public_key !== $_POST['public_key']) {
1178
+ return false;
1179
+ }
1180
+ $args = @json_decode(stripslashes($_POST['args']), true);
1181
+ $args['forked'] = true;
1182
+
1183
+ if (!isset($args)) {
1184
+ return false;
1185
+ }
1186
+ $cron_action = isset($_POST['mwp_forked_action']) ? $_POST['mwp_forked_action'] : false;
1187
+ if ($cron_action) {
1188
+ do_action($cron_action, $args);
1189
+ }
1190
+ //unset($_POST['public_key']);
1191
+ unset($_POST['mmb_fork_nonce']);
1192
+ unset($_POST['args']);
1193
+ unset($_POST['mwp_forked_action']);
1194
+
1195
+ return true;
1196
+ }
1197
+
1198
+ add_filter('mwp_website_add', 'mmb_readd_backup_task');
1199
+
1200
+ if (!function_exists('mmb_readd_backup_task')) {
1201
+ function mmb_readd_backup_task($params = array())
1202
+ {
1203
+ global $mmb_core;
1204
+ $backup_instance = $mmb_core->get_backup_instance();
1205
+ $settings = $backup_instance->readd_tasks($params);
1206
+
1207
+ return $settings;
1208
+ }
1209
+ }
1210
+
1211
+ if (!function_exists('mmb_update_worker_plugin')) {
1212
+ function mmb_update_worker_plugin($params)
1213
+ {
1214
+ global $mmb_core;
1215
+ mmb_response($mmb_core->update_worker_plugin($params), true);
1216
+ }
1217
+ }
1218
+
1219
+ if (!function_exists('mmb_wp_checkversion')) {
1220
+ function mmb_wp_checkversion($params)
1221
+ {
1222
+ include_once(ABSPATH.'wp-includes/version.php');
1223
+ global $mmb_wp_version, $mmb_core;
1224
+ mmb_response($mmb_wp_version, true);
1225
+ }
1226
+ }
1227
+ if (!function_exists('mmb_search_posts_by_term')) {
1228
+ function mmb_search_posts_by_term($params)
1229
+ {
1230
+ global $mmb_core;
1231
+ $mmb_core->get_search_instance();
1232
+
1233
+ $search_type = trim($params['search_type']);
1234
+ $search_term = strtolower(trim($params['search_term']));
1235
+
1236
+ switch ($search_type) {
1237
+ case 'page_post':
1238
+ $return = $mmb_core->search_instance->search_posts_by_term($params);
1239
+ if ($return) {
1240
+ $return = serialize($return);
1241
+ mmb_response($return, true);
1242
+ } else {
1243
+ mmb_response('No posts found', false);
1244
+ }
1245
+ break;
1246
+
1247
+ case 'plugin':
1248
+ $plugins = get_option('active_plugins');
1249
+
1250
+ $have_plugin = false;
1251
+ foreach ($plugins as $plugin) {
1252
+ if (strpos($plugin, $search_term) > -1) {
1253
+ $have_plugin = true;
1254
+ }
1255
+ }
1256
+ if ($have_plugin) {
1257
+ mmb_response(serialize($plugin), true);
1258
+ } else {
1259
+ mmb_response(false, false);
1260
+ }
1261
+ break;
1262
+ case 'theme':
1263
+ $theme = strtolower(get_option('template'));
1264
+ if (strpos($theme, $search_term) > -1) {
1265
+ mmb_response($theme, true);
1266
+ } else {
1267
+ mmb_response(false, false);
1268
+ }
1269
+ break;
1270
+ default:
1271
+ mmb_response(false, false);
1272
+ }
1273
+ $return = $mmb_core->search_instance->search_posts_by_term($params);
1274
+
1275
+
1276
+ if ($return_if_true) {
1277
+ mmb_response($return_value, true);
1278
+ } else {
1279
+ mmb_response($return_if_false, false);
1280
+ }
1281
+ }
1282
+ }
1283
+
1284
+ if (!function_exists('mmb_install_addon')) {
1285
+ function mmb_install_addon($params)
1286
+ {
1287
+ global $mmb_core;
1288
+ $mmb_core->get_installer_instance();
1289
+ $return = $mmb_core->installer_instance->install_remote_file($params);
1290
+ mmb_response($return, true);
1291
+
1292
+ }
1293
+ }
1294
+
1295
+ if (!function_exists('mmb_install_addons')) {
1296
+ function mmb_install_addons($params)
1297
+ {
1298
+ global $mmb_core;
1299
+ $mmb_core->get_installer_instance();
1300
+ $return = $mmb_core->installer_instance->install_remote_files($params);
1301
+ mmb_response($return, true);
1302
+
1303
+ }
1304
+ }
1305
+
1306
+ if (!function_exists('mmb_do_upgrade')) {
1307
+ function mmb_do_upgrade($params)
1308
+ {
1309
+ global $mmb_core, $mmb_upgrading;
1310
+ $mmb_core->get_installer_instance();
1311
+ $return = $mmb_core->installer_instance->do_upgrade($params);
1312
+ mmb_response($return, true);
1313
+
1314
+ }
1315
+ }
1316
+
1317
+ if (!function_exists('mmb_get_links')) {
1318
+ function mmb_get_links($params)
1319
+ {
1320
+ global $mmb_core;
1321
+ $mmb_core->get_link_instance();
1322
+ $return = $mmb_core->link_instance->get_links($params);
1323
+ if (is_array($return) && array_key_exists('error', $return)) {
1324
+ mmb_response($return['error'], false);
1325
+ } else {
1326
+ mmb_response($return, true);
1327
+ }
1328
+ }
1329
+ }
1330
+
1331
+ if (!function_exists('mmb_add_link')) {
1332
+ function mmb_add_link($params)
1333
+ {
1334
+ global $mmb_core;
1335
+ $mmb_core->get_link_instance();
1336
+ $return = $mmb_core->link_instance->add_link($params);
1337
+ if (is_array($return) && array_key_exists('error', $return)) {
1338
+ mmb_response($return['error'], false);
1339
+ } else {
1340
+ mmb_response($return, true);
1341
+ }
1342
+
1343
+ }
1344
+ }
1345
+
1346
+ if (!function_exists('mmb_delete_link')) {
1347
+ function mmb_delete_link($params)
1348
+ {
1349
+ global $mmb_core;
1350
+ $mmb_core->get_link_instance();
1351
+
1352
+ $return = $mmb_core->link_instance->delete_link($params);
1353
+ if (is_array($return) && array_key_exists('error', $return)) {
1354
+ mmb_response($return['error'], false);
1355
+ } else {
1356
+ mmb_response($return, true);
1357
+ }
1358
+ }
1359
+ }
1360
+
1361
+ if (!function_exists('mmb_delete_links')) {
1362
+ function mmb_delete_links($params)
1363
+ {
1364
+ global $mmb_core;
1365
+ $mmb_core->get_link_instance();
1366
+
1367
+ $return = $mmb_core->link_instance->delete_links($params);
1368
+ if (is_array($return) && array_key_exists('error', $return)) {
1369
+ mmb_response($return['error'], false);
1370
+ } else {
1371
+ mmb_response($return, true);
1372
+ }
1373
+ }
1374
+ }
1375
+
1376
+ if (!function_exists('mmb_get_comments')) {
1377
+ function mmb_get_comments($params)
1378
+ {
1379
+ global $mmb_core;
1380
+ $mmb_core->get_comment_instance();
1381
+ $return = $mmb_core->comment_instance->get_comments($params);
1382
+ if (is_array($return) && array_key_exists('error', $return)) {
1383
+ mmb_response($return['error'], false);
1384
+ } else {
1385
+ mmb_response($return, true);
1386
+ }
1387
+ }
1388
+ }
1389
+
1390
+ if (!function_exists('mmb_action_comment')) {
1391
+ function mmb_action_comment($params)
1392
+ {
1393
+ global $mmb_core;
1394
+ $mmb_core->get_comment_instance();
1395
+
1396
+ $return = $mmb_core->comment_instance->action_comment($params);
1397
+ if (is_array($return) && array_key_exists('error', $return)) {
1398
+ mmb_response($return['error'], false);
1399
+ } else {
1400
+ mmb_response($return, true);
1401
+ }
1402
+ }
1403
+ }
1404
+
1405
+ if (!function_exists('mmb_bulk_action_comments')) {
1406
+ function mmb_bulk_action_comments($params)
1407
+ {
1408
+ global $mmb_core;
1409
+ $mmb_core->get_comment_instance();
1410
+
1411
+ $return = $mmb_core->comment_instance->bulk_action_comments($params);
1412
+ if (is_array($return) && array_key_exists('error', $return)) {
1413
+ mmb_response($return['error'], false);
1414
+ } else {
1415
+ mmb_response($return, true);
1416
+ }
1417
+ }
1418
+ }
1419
+
1420
+ if (!function_exists('mmb_reply_comment')) {
1421
+ function mmb_reply_comment($params)
1422
+ {
1423
+ global $mmb_core;
1424
+ $mmb_core->get_comment_instance();
1425
+
1426
+ $return = $mmb_core->comment_instance->reply_comment($params);
1427
+ if (is_array($return) && array_key_exists('error', $return)) {
1428
+ mmb_response($return['error'], false);
1429
+ } else {
1430
+ mmb_response($return, true);
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ if (!function_exists('mmb_add_user')) {
1436
+ function mmb_add_user($params)
1437
+ {
1438
+ global $mmb_core;
1439
+ $mmb_core->get_user_instance();
1440
+ $return = $mmb_core->user_instance->add_user($params);
1441
+ if (is_array($return) && array_key_exists('error', $return)) {
1442
+ mmb_response($return['error'], false);
1443
+ } else {
1444
+ mmb_response($return, true);
1445
+ }
1446
+
1447
+ }
1448
+ }
1449
+
1450
+ if (!function_exists('mbb_security_check')) {
1451
+ function mbb_security_check($params)
1452
+ {
1453
+ global $mmb_core;
1454
+ $mmb_core->get_security_instance();
1455
+ $return = $mmb_core->security_instance->security_check($params);
1456
+ if (is_array($return) && array_key_exists('error', $return)) {
1457
+ mmb_response($return['error'], false);
1458
+ } else {
1459
+ mmb_response($return, true);
1460
+ }
1461
+
1462
+ }
1463
+ }
1464
+
1465
+ if (!function_exists('mbb_security_fix_folder_listing')) {
1466
+ function mbb_security_fix_folder_listing($params)
1467
+ {
1468
+ global $mmb_core;
1469
+ $mmb_core->get_security_instance();
1470
+ $return = $mmb_core->security_instance->security_fix_dir_listing($params);
1471
+ if (is_array($return) && array_key_exists('error', $return)) {
1472
+ mmb_response($return['error'], false);
1473
+ } else {
1474
+ mmb_response($return, true);
1475
+ }
1476
+
1477
+ }
1478
+ }
1479
+
1480
+ if (!function_exists('mbb_security_fix_php_reporting')) {
1481
+ function mbb_security_fix_php_reporting($params)
1482
+ {
1483
+ global $mmb_core;
1484
+ $mmb_core->get_security_instance();
1485
+ $return = $mmb_core->security_instance->security_fix_php_reporting($params);
1486
+ if (is_array($return) && array_key_exists('error', $return)) {
1487
+ mmb_response($return['error'], false);
1488
+ } else {
1489
+ mmb_response($return, true);
1490
+ }
1491
+
1492
+ }
1493
+ }
1494
+
1495
+ if (!function_exists('mbb_security_fix_database_reporting')) {
1496
+ function mbb_security_fix_database_reporting($params)
1497
+ {
1498
+ global $mmb_core;
1499
+ $mmb_core->get_security_instance();
1500
+ $return = $mmb_core->security_instance->security_fix_database_reporting($params);
1501
+ if (is_array($return) && array_key_exists('error', $return)) {
1502
+ mmb_response($return['error'], false);
1503
+ } else {
1504
+ mmb_response($return, true);
1505
+ }
1506
+
1507
+ }
1508
+ }
1509
+
1510
+ //security_fix_wp_version
1511
+
1512
+ if (!function_exists('mbb_security_fix_wp_version')) {
1513
+ function mbb_security_fix_wp_version($params)
1514
+ {
1515
+ global $mmb_core;
1516
+ $mmb_core->get_security_instance();
1517
+ $return = $mmb_core->security_instance->security_fix_wp_version($params);
1518
+ if (is_array($return) && array_key_exists('error', $return)) {
1519
+ mmb_response($return['error'], false);
1520
+ } else {
1521
+ mmb_response($return, true);
1522
+ }
1523
+
1524
+ }
1525
+ }
1526
+
1527
+ //mbb_security_fix_admin_username
1528
+
1529
+ if (!function_exists('mbb_security_fix_admin_username')) {
1530
+ function mbb_security_fix_admin_username($params)
1531
+ {
1532
+ global $mmb_core;
1533
+ $mmb_core->get_security_instance();
1534
+ $return = $mmb_core->security_instance->security_fix_admin_username($params);
1535
+ if (is_array($return) && array_key_exists('error', $return)) {
1536
+ mmb_response($return['error'], false);
1537
+ } else {
1538
+ mmb_response($return, true);
1539
+ }
1540
+
1541
+ }
1542
+ }
1543
+
1544
+ if (!function_exists('mbb_security_fix_scripts_styles')) {
1545
+ function mbb_security_fix_scripts_styles($params)
1546
+ {
1547
+ global $mmb_core;
1548
+ $mmb_core->get_security_instance();
1549
+ $return = $mmb_core->security_instance->security_fix_scripts_styles($params);
1550
+ if (is_array($return) && array_key_exists('error', $return)) {
1551
+ mmb_response($return['error'], false);
1552
+ } else {
1553
+ mmb_response($return, true);
1554
+ }
1555
+
1556
+ }
1557
+ }
1558
+
1559
+ //mbb_security_fix_file_permission
1560
+ if (!function_exists('mbb_security_fix_file_permission')) {
1561
+ function mbb_security_fix_file_permission($params)
1562
+ {
1563
+ global $mmb_core;
1564
+ $mmb_core->get_security_instance();
1565
+ $return = $mmb_core->security_instance->security_fix_permissions($params);
1566
+ if (is_array($return) && array_key_exists('error', $return)) {
1567
+ mmb_response($return['error'], false);
1568
+ } else {
1569
+ mmb_response($return, true);
1570
+ }
1571
+
1572
+ }
1573
+ }
1574
+
1575
+ //mbb_security_fix_all
1576
+ if (!function_exists('mbb_security_fix_all')) {
1577
+ function mbb_security_fix_all($params)
1578
+ {
1579
+ global $mmb_core;
1580
+ $mmb_core->get_security_instance();
1581
+ $return = $mmb_core->security_instance->security_fix_all($params);
1582
+ if (is_array($return) && array_key_exists('error', $return)) {
1583
+ mmb_response($return['error'], false);
1584
+ } else {
1585
+ mmb_response($return, true);
1586
+ }
1587
+ }
1588
+ }
1589
+
1590
+ //mbb_security_fix_htaccess_permission
1591
+
1592
+ if (!function_exists('mbb_security_fix_htaccess_permission')) {
1593
+ function mbb_security_fix_htaccess_permission($params)
1594
+ {
1595
+ global $mmb_core;
1596
+ $mmb_core->get_security_instance();
1597
+ $return = $mmb_core->security_instance->security_fix_htaccess_permission($params);
1598
+ if (is_array($return) && array_key_exists('error', $return)) {
1599
+ mmb_response($return['error'], false);
1600
+ } else {
1601
+ mmb_response($return, true);
1602
+ }
1603
+
1604
+ }
1605
+ }
1606
+
1607
+ if (!function_exists('mmb_get_users')) {
1608
+ function mmb_get_users($params)
1609
+ {
1610
+ global $mmb_core;
1611
+ $mmb_core->get_user_instance();
1612
+ $return = $mmb_core->user_instance->get_users($params);
1613
+ if (is_array($return) && array_key_exists('error', $return)) {
1614
+ mmb_response($return['error'], false);
1615
+ } else {
1616
+ mmb_response($return, true);
1617
+ }
1618
+ }
1619
+ }
1620
+
1621
+ if (!function_exists('mmb_edit_users')) {
1622
+ function mmb_edit_users($params)
1623
+ {
1624
+ global $mmb_core;
1625
+ $mmb_core->get_user_instance();
1626
+ $users = $mmb_core->user_instance->edit_users($params);
1627
+ $response = 'User updated.';
1628
+ $check_error = false;
1629
+ foreach ($users as $username => $user) {
1630
+ $check_error = array_key_exists('error', $user);
1631
+ if ($check_error) {
1632
+ $response = $username.': '.$user['error'];
1633
+ }
1634
+ }
1635
+ mmb_response($response, !$check_error);
1636
+ }
1637
+ }
1638
+
1639
+ if (!function_exists('mmb_get_posts')) {
1640
+ function mmb_get_posts($params)
1641
+ {
1642
+ global $mmb_core;
1643
+ $mmb_core->get_post_instance();
1644
+
1645
+ $return = $mmb_core->post_instance->get_posts($params);
1646
+ if (is_array($return) && array_key_exists('error', $return)) {
1647
+ mmb_response($return['error'], false);
1648
+ } else {
1649
+ mmb_response($return, true);
1650
+ }
1651
+ }
1652
+ }
1653
+
1654
+ if (!function_exists('mmb_delete_post')) {
1655
+ function mmb_delete_post($params)
1656
+ {
1657
+ global $mmb_core;
1658
+ $mmb_core->get_post_instance();
1659
+
1660
+ $return = $mmb_core->post_instance->delete_post($params);
1661
+ if (is_array($return) && array_key_exists('error', $return)) {
1662
+ mmb_response($return['error'], false);
1663
+ } else {
1664
+ mmb_response($return, true);
1665
+ }
1666
+ }
1667
+ }
1668
+
1669
+ if (!function_exists('mmb_delete_posts')) {
1670
+ function mmb_delete_posts($params)
1671
+ {
1672
+ global $mmb_core;
1673
+ $mmb_core->get_post_instance();
1674
+
1675
+ $return = $mmb_core->post_instance->delete_posts($params);
1676
+ if (is_array($return) && array_key_exists('error', $return)) {
1677
+ mmb_response($return['error'], false);
1678
+ } else {
1679
+ mmb_response($return, true);
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+
1685
+ if (!function_exists('mmb_edit_posts')) {
1686
+ function mmb_edit_posts($params)
1687
+ {
1688
+ global $mmb_core;
1689
+ $mmb_core->get_posts_instance();
1690
+ $return = $mmb_core->posts_instance->edit_posts($params);
1691
+ mmb_response($return, true);
1692
+ }
1693
+ }
1694
+
1695
+ if (!function_exists('mmb_get_pages')) {
1696
+ function mmb_get_pages($params)
1697
+ {
1698
+ global $mmb_core;
1699
+ $mmb_core->get_post_instance();
1700
+
1701
+ $return = $mmb_core->post_instance->get_pages($params);
1702
+ if (is_array($return) && array_key_exists('error', $return)) {
1703
+ mmb_response($return['error'], false);
1704
+ } else {
1705
+ mmb_response($return, true);
1706
+ }
1707
+ }
1708
+ }
1709
+
1710
+ if (!function_exists('mmb_delete_page')) {
1711
+ function mmb_delete_page($params)
1712
+ {
1713
+ global $mmb_core;
1714
+ $mmb_core->get_post_instance();
1715
+
1716
+ $return = $mmb_core->post_instance->delete_page($params);
1717
+ if (is_array($return) && array_key_exists('error', $return)) {
1718
+ mmb_response($return['error'], false);
1719
+ } else {
1720
+ mmb_response($return, true);
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ if (!function_exists('mmb_iframe_plugins_fix')) {
1726
+ function mmb_iframe_plugins_fix($update_actions)
1727
+ {
1728
+ foreach ($update_actions as $key => $action) {
1729
+ $update_actions[$key] = str_replace('target="_parent"', '', $action);
1730
+ }
1731
+
1732
+ return $update_actions;
1733
+
1734
+ }
1735
+ }
1736
+ if (!function_exists('mmb_execute_php_code')) {
1737
+ function mmb_execute_php_code($params)
1738
+ {
1739
+ ob_start();
1740
+ eval($params['code']);
1741
+ $return = ob_get_flush();
1742
+ mmb_response(print_r($return, true), true);
1743
+ }
1744
+ }
1745
+
1746
+ if (!function_exists('mmb_set_notifications')) {
1747
+ function mmb_set_notifications($params)
1748
+ {
1749
+ global $mmb_core;
1750
+ $mmb_core->get_stats_instance();
1751
+ $return = $mmb_core->stats_instance->set_notifications($params);
1752
+ if (is_array($return) && array_key_exists('error', $return)) {
1753
+ mmb_response($return['error'], false);
1754
+ } else {
1755
+ mmb_response($return, true);
1756
+ }
1757
+
1758
+ }
1759
+ }
1760
+
1761
+ if (!function_exists('mmb_get_dbname')) {
1762
+ function mmb_get_dbname($params)
1763
+ {
1764
+ global $mmb_core;
1765
+ $mmb_core->get_stats_instance();
1766
+
1767
+ $return = $mmb_core->stats_instance->get_active_db();
1768
+ if (is_array($return) && array_key_exists('error', $return)) {
1769
+ mmb_response($return['error'], false);
1770
+ } else {
1771
+ mmb_response($return, true);
1772
+ }
1773
+ }
1774
+ }
1775
+
1776
+ if (!function_exists('mmb_more_reccurences')) {
1777
+ //Backup Tasks
1778
+ add_filter('cron_schedules', 'mmb_more_reccurences');
1779
+ function mmb_more_reccurences($schedules)
1780
+ {
1781
+ $schedules['halfminute'] = array('interval' => 30, 'display' => 'Once in a half minute');
1782
+ $schedules['minutely'] = array('interval' => 60, 'display' => 'Once in a minute');
1783
+ $schedules['fiveminutes'] = array('interval' => 300, 'display' => 'Once every five minutes');
1784
+ $schedules['tenminutes'] = array('interval' => 600, 'display' => 'Once every ten minutes');
1785
+ $schedules['sixhours'] = array('interval' => 21600, 'display' => 'Every six hours');
1786
+ $schedules['fourhours'] = array('interval' => 14400, 'display' => 'Every four hours');
1787
+ $schedules['threehours'] = array('interval' => 10800, 'display' => 'Every three hours');
1788
+
1789
+ return $schedules;
1790
+ }
1791
+ }
1792
+
1793
+ add_action('mwp_backup_tasks', 'mwp_check_backup_tasks');
1794
+
1795
+ if (!function_exists('mwp_check_backup_tasks')) {
1796
+ function mwp_check_backup_tasks()
1797
+ {
1798
+ global $mmb_core, $_wp_using_ext_object_cache;
1799
+ $_wp_using_ext_object_cache = false;
1800
+ $mmb_core->get_backup_instance();
1801
+ $mmb_core->backup_instance->check_backup_tasks();
1802
+ }
1803
+ }
1804
+
1805
+ // Remote upload in the second request.
1806
+ // add_action('mmb_scheduled_remote_upload', 'mmb_call_scheduled_remote_upload');
1807
+ add_action('mmb_remote_upload', 'mmb_call_scheduled_remote_upload');
1808
+
1809
+ if (!function_exists('mmb_call_scheduled_remote_upload')) {
1810
+ function mmb_call_scheduled_remote_upload($args)
1811
+ {
1812
+ global $mmb_core, $_wp_using_ext_object_cache;
1813
+ $_wp_using_ext_object_cache = false;
1814
+
1815
+ $mmb_core->get_backup_instance();
1816
+ if (isset($args['task_name'])) {
1817
+ $mmb_core->backup_instance->remote_backup_now($args);
1818
+ }
1819
+ }
1820
+ }
1821
+
1822
+ // if (!wp_next_scheduled('mwp_notifications')) {
1823
+ // wp_schedule_event( time(), 'twicedaily', 'mwp_notifications' );
1824
+ // }
1825
+ // add_action('mwp_notifications', 'mwp_check_notifications');
1826
+
1827
+ if (!wp_next_scheduled('mwp_datasend')) {
1828
+ wp_schedule_event(time(), 'threehours', 'mwp_datasend');
1829
+ }
1830
+
1831
+ add_action('mwp_datasend', 'mwp_datasend');
1832
+
1833
+ if (!function_exists('mwp_check_notifications')) {
1834
+ function mwp_check_notifications()
1835
+ {
1836
+ global $mmb_core, $_wp_using_ext_object_cache;
1837
+ $_wp_using_ext_object_cache = false;
1838
+
1839
+ $mmb_core->get_stats_instance();
1840
+ $mmb_core->stats_instance->check_notifications();
1841
+ }
1842
+ }
1843
+
1844
+
1845
+ if (!function_exists('mmb_get_plugins_themes')) {
1846
+ function mmb_get_plugins_themes($params)
1847
+ {
1848
+ global $mmb_core;
1849
+ $mmb_core->get_installer_instance();
1850
+ $return = $mmb_core->installer_instance->get($params);
1851
+ mmb_response($return, true);
1852
+ }
1853
+ }
1854
+
1855
+
1856
+ if (!function_exists('mmb_get_autoupdate_plugins_themes')) {
1857
+ function mmb_get_autoupdate_plugins_themes($params)
1858
+ {
1859
+ $return = MMB_Updater::getSettings($params);
1860
+ mmb_response($return, true);
1861
+ }
1862
+ }
1863
+
1864
+ if (!function_exists('mmb_edit_plugins_themes')) {
1865
+ function mmb_edit_plugins_themes($params)
1866
+ {
1867
+ global $mmb_core;
1868
+ $mmb_core->get_installer_instance();
1869
+ $return = $mmb_core->installer_instance->edit($params);
1870
+ mmb_response($return, true);
1871
+ }
1872
+ }
1873
+
1874
+ if (!function_exists('mmb_edit_autoupdate_plugins_themes')) {
1875
+ function mmb_edit_autoupdate_plugins_themes($params)
1876
+ {
1877
+ $return = MMB_Updater::setSettings($params);
1878
+ mmb_response($return, true);
1879
+ }
1880
+ }
1881
+
1882
+ if (!function_exists('mmb_worker_brand')) {
1883
+ function mmb_worker_brand($params)
1884
+ {
1885
+ update_option("mwp_worker_brand", $params['brand']);
1886
+ mmb_response(true, true);
1887
+ }
1888
+ }
1889
+
1890
+ if (!function_exists('mmb_maintenance_mode')) {
1891
+ function mmb_maintenance_mode($params)
1892
+ {
1893
+ global $wp_object_cache;
1894
+
1895
+ $default = get_option('mwp_maintenace_mode');
1896
+ $params = empty($default) ? $params : array_merge($default, $params);
1897
+ update_option("mwp_maintenace_mode", $params);
1898
+
1899
+ if (!empty($wp_object_cache)) {
1900
+ @$wp_object_cache->flush();
1901
+ }
1902
+ mmb_response(true, true);
1903
+ }
1904
+ }
1905
+
1906
+ if (!function_exists('mmb_plugin_actions')) {
1907
+ function mmb_plugin_actions()
1908
+ {
1909
+ global $mmb_actions, $mmb_core;
1910
+
1911
+ if (!empty($mmb_actions)) {
1912
+ global $_mmb_plugin_actions;
1913
+ if (!empty($_mmb_plugin_actions)) {
1914
+ $failed = array();
1915
+ foreach ($_mmb_plugin_actions as $action => $params) {
1916
+ if (isset($mmb_actions[$action])) {
1917
+ call_user_func($mmb_actions[$action], $params);
1918
+ } else {
1919
+ $failed[] = $action;
1920
+ }
1921
+ }
1922
+ if (!empty($failed)) {
1923
+ $f = implode(', ', $failed);
1924
+ $s = count($f) > 1 ? 'Actions "'.$f.'" do' : 'Action "'.$f.'" does';
1925
+ mmb_response($s.' not exist. Please update your Worker plugin.', false);
1926
+ }
1927
+
1928
+ }
1929
+ }
1930
+
1931
+ global $pagenow, $current_user, $mmode;
1932
+ if (!is_admin() && !in_array($pagenow, array('wp-login.php'))) {
1933
+ $mmode = get_option('mwp_maintenace_mode');
1934
+ if (!empty($mmode)) {
1935
+ if (isset($mmode['active']) && $mmode['active'] == true) {
1936
+ if (isset($current_user->data) && !empty($current_user->data) && isset($mmode['hidecaps']) && !empty($mmode['hidecaps'])) {
1937
+ $usercaps = array();
1938
+ if (isset($current_user->caps) && !empty($current_user->caps)) {
1939
+ $usercaps = $current_user->caps;
1940
+ }
1941
+ foreach ($mmode['hidecaps'] as $cap => $hide) {
1942
+ if (!$hide) {
1943
+ continue;
1944
+ }
1945
+
1946
+ foreach ($usercaps as $ucap => $val) {
1947
+ if ($ucap == $cap) {
1948
+ ob_end_clean();
1949
+ ob_end_flush();
1950
+ die($mmode['template']);
1951
+ }
1952
+ }
1953
+ }
1954
+ } else {
1955
+ die($mmode['template']);
1956
+ }
1957
+ }
1958
+ }
1959
+ }
1960
+
1961
+ if (file_exists(dirname(__FILE__).'/log')) {
1962
+ unlink(dirname(__FILE__).'/log');
1963
+ }
1964
+ }
1965
+ }
1966
+
1967
+ $mmb_core = new MMB_Core();
1968
+
1969
+ if (isset($_GET['auto_login'])) {
1970
+ $mmb_core->automatic_login();
1971
+ }
1972
+
1973
+ MMB_Updater::register();
1974
+
1975
+ if (function_exists('register_activation_hook')) {
1976
+ register_activation_hook(__FILE__, array($mmb_core, 'install'));
1977
+ }
1978
+
1979
+ if (function_exists('register_deactivation_hook')) {
1980
+ register_deactivation_hook(__FILE__, array($mmb_core, 'uninstall'));
1981
+ }
1982
+
1983
+ if (function_exists('add_action')) {
1984
+ add_action('init', 'mmb_plugin_actions', 99999);
1985
+ }
1986
+
1987
+ if (function_exists('add_filter')) {
1988
+ add_filter('install_plugin_complete_actions', 'mmb_iframe_plugins_fix');
1989
+ }
1990
+
1991
+ if (!function_exists('mwb_edit_redirect_override')) {
1992
+ function mwb_edit_redirect_override($location = false, $comment_id = false)
1993
+ {
1994
+ if (isset($_COOKIE[MMB_XFRAME_COOKIE])) {
1995
+ $location = get_site_url().'/wp-admin/edit-comments.php';
1996
+ }
1997
+
1998
+ return $location;
1999
+ }
2000
+ }
2001
+ if (function_exists('add_filter')) {
2002
+ add_filter('comment_edit_redirect', 'mwb_edit_redirect_override');
2003
+ }
2004
+
2005
+ if (isset($_COOKIE[MMB_XFRAME_COOKIE])) {
2006
+ remove_action('admin_init', 'send_frame_options_header');
2007
+ remove_action('login_init', 'send_frame_options_header');
2008
+ }
2009
+
2010
+ if (get_option('mwp_remove_php_reporting') == 'T') {
2011
+ @error_reporting(0);
2012
+ @ini_set('display_errors', 'off');
2013
+ @ini_set('display_startup_errors', "off");
2014
+ }
2015
+
2016
+ if (get_option('mwp_remove_wp_version') == 'T') {
2017
+ remove_action('wp_head', 'wp_generator');
2018
+ remove_filter('wp_head', 'wp_generator');
2019
+ }
2020
+ if (get_option('managewp_remove_styles_version') == 'T') {
2021
+ global $wp_styles;
2022
+ if (!is_a($wp_styles, 'WP_Styles')) {
2023
+ return;
2024
+ }
2025
+
2026
+ foreach ($wp_styles->registered as $handle => $style) {
2027
+ $wp_styles->registered[$handle]->ver = null;
2028
+ }
2029
+ }
2030
+ if (get_option('managewp_remove_scripts_version') == 'T') {
2031
+ global $wp_scripts;
2032
+ if (!is_a($wp_scripts, 'WP_Scripts')) {
2033
+ return;
2034
+ }
2035
+
2036
+ foreach ($wp_scripts->registered as $handle => $script) {
2037
+ $wp_scripts->registered[$handle]->ver = null;
2038
+ }
2039
+ }
2040
+
2041
+ if (wp_next_scheduled('mwp_backup_tasks')) {
2042
+ wp_clear_scheduled_hook( 'mwp_backup_tasks' );
2043
+ }
lib/PHPSecLib/Crypt/AES.php DELETED
@@ -1,540 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of AES.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * If {@link Crypt_AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
12
- * {@link Crypt_AES::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits
13
- * it'll be null-padded to 160-bits and 160 bits will be the key length until {@link Crypt_Rijndael::setKey() setKey()}
14
- * is called, again, at which point, it'll be recalculated.
15
- *
16
- * Since Crypt_AES extends Crypt_Rijndael, some functions are available to be called that, in the context of AES, don't
17
- * make a whole lot of sense. {@link Crypt_AES::setBlockLength() setBlockLength()}, for instance. Calling that function,
18
- * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
19
- *
20
- * Here's a short example of how to use this library:
21
- * <code>
22
- * <?php
23
- * include('Crypt/AES.php');
24
- *
25
- * $aes = new Crypt_AES();
26
- *
27
- * $aes->setKey('abcdefghijklmnop');
28
- *
29
- * $size = 10 * 1024;
30
- * $plaintext = '';
31
- * for ($i = 0; $i < $size; $i++) {
32
- * $plaintext.= 'a';
33
- * }
34
- *
35
- * echo $aes->decrypt($aes->encrypt($plaintext));
36
- * ?>
37
- * </code>
38
- *
39
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
40
- * of this software and associated documentation files (the "Software"), to deal
41
- * in the Software without restriction, including without limitation the rights
42
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43
- * copies of the Software, and to permit persons to whom the Software is
44
- * furnished to do so, subject to the following conditions:
45
- *
46
- * The above copyright notice and this permission notice shall be included in
47
- * all copies or substantial portions of the Software.
48
- *
49
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
55
- * THE SOFTWARE.
56
- *
57
- * @category Crypt
58
- * @package Crypt_AES
59
- * @author Jim Wigginton <terrafrost@php.net>
60
- * @copyright MMVIII Jim Wigginton
61
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
62
- * @link http://phpseclib.sourceforge.net
63
- */
64
-
65
- /**
66
- * Include Crypt_Rijndael
67
- */
68
- if (!class_exists('Crypt_Rijndael')) {
69
- require_once 'Rijndael.php';
70
- }
71
-
72
- /**#@+
73
- * @access public
74
- * @see Crypt_AES::encrypt()
75
- * @see Crypt_AES::decrypt()
76
- */
77
- /**
78
- * Encrypt / decrypt using the Counter mode.
79
- *
80
- * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
81
- *
82
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
83
- */
84
- define('CRYPT_AES_MODE_CTR', -1);
85
- /**
86
- * Encrypt / decrypt using the Electronic Code Book mode.
87
- *
88
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
89
- */
90
- define('CRYPT_AES_MODE_ECB', 1);
91
- /**
92
- * Encrypt / decrypt using the Code Book Chaining mode.
93
- *
94
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
95
- */
96
- define('CRYPT_AES_MODE_CBC', 2);
97
- /**
98
- * Encrypt / decrypt using the Cipher Feedback mode.
99
- *
100
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
101
- */
102
- define('CRYPT_AES_MODE_CFB', 3);
103
- /**
104
- * Encrypt / decrypt using the Cipher Feedback mode.
105
- *
106
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
107
- */
108
- define('CRYPT_AES_MODE_OFB', 4);
109
- /**#@-*/
110
-
111
- /**#@+
112
- * @access private
113
- * @see Crypt_AES::Crypt_AES()
114
- */
115
- /**
116
- * Toggles the internal implementation
117
- */
118
- define('CRYPT_AES_MODE_INTERNAL', 1);
119
- /**
120
- * Toggles the mcrypt implementation
121
- */
122
- define('CRYPT_AES_MODE_MCRYPT', 2);
123
- /**#@-*/
124
-
125
- /**
126
- * Pure-PHP implementation of AES.
127
- *
128
- * @author Jim Wigginton <terrafrost@php.net>
129
- * @version 0.1.0
130
- * @access public
131
- * @package Crypt_AES
132
- */
133
- class Crypt_AES extends Crypt_Rijndael {
134
- /**
135
- * mcrypt resource for encryption
136
- *
137
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
138
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
139
- *
140
- * @see Crypt_AES::encrypt()
141
- * @var String
142
- * @access private
143
- */
144
- var $enmcrypt;
145
-
146
- /**
147
- * mcrypt resource for decryption
148
- *
149
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
150
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
151
- *
152
- * @see Crypt_AES::decrypt()
153
- * @var String
154
- * @access private
155
- */
156
- var $demcrypt;
157
-
158
- /**
159
- * mcrypt resource for CFB mode
160
- *
161
- * @see Crypt_AES::encrypt()
162
- * @see Crypt_AES::decrypt()
163
- * @var String
164
- * @access private
165
- */
166
- var $ecb;
167
-
168
- /**
169
- * Default Constructor.
170
- *
171
- * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
172
- * CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC. If not explictly set, CRYPT_AES_MODE_CBC will be used.
173
- *
174
- * @param optional Integer $mode
175
- * @return Crypt_AES
176
- * @access public
177
- */
178
- function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
179
- {
180
- if ( !defined('CRYPT_AES_MODE') ) {
181
- switch (true) {
182
- case extension_loaded('mcrypt') && in_array('rijndael-128', mcrypt_list_algorithms()):
183
- define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT);
184
- break;
185
- default:
186
- define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL);
187
- }
188
- }
189
-
190
- switch ( CRYPT_AES_MODE ) {
191
- case CRYPT_AES_MODE_MCRYPT:
192
- switch ($mode) {
193
- case CRYPT_AES_MODE_ECB:
194
- $this->paddable = true;
195
- $this->mode = MCRYPT_MODE_ECB;
196
- break;
197
- case CRYPT_AES_MODE_CTR:
198
- // ctr doesn't have a constant associated with it even though it appears to be fairly widely
199
- // supported. in lieu of knowing just how widely supported it is, i've, for now, opted not to
200
- // include a compatibility layer. the layer has been implemented but, for now, is commented out.
201
- $this->mode = 'ctr';
202
- //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
203
- break;
204
- case CRYPT_AES_MODE_CFB:
205
- $this->mode = 'ncfb';
206
- break;
207
- case CRYPT_AES_MODE_OFB:
208
- $this->mode = MCRYPT_MODE_NOFB;
209
- break;
210
- case CRYPT_AES_MODE_CBC:
211
- default:
212
- $this->paddable = true;
213
- $this->mode = MCRYPT_MODE_CBC;
214
- }
215
-
216
- break;
217
- default:
218
- switch ($mode) {
219
- case CRYPT_AES_MODE_ECB:
220
- $this->paddable = true;
221
- $this->mode = CRYPT_RIJNDAEL_MODE_ECB;
222
- break;
223
- case CRYPT_AES_MODE_CTR:
224
- $this->mode = CRYPT_RIJNDAEL_MODE_CTR;
225
- break;
226
- case CRYPT_AES_MODE_CFB:
227
- $this->mode = CRYPT_RIJNDAEL_MODE_CFB;
228
- break;
229
- case CRYPT_AES_MODE_OFB:
230
- $this->mode = CRYPT_RIJNDAEL_MODE_OFB;
231
- break;
232
- case CRYPT_AES_MODE_CBC:
233
- default:
234
- $this->paddable = true;
235
- $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
236
- }
237
- }
238
-
239
- if (CRYPT_AES_MODE == CRYPT_AES_MODE_INTERNAL) {
240
- parent::Crypt_Rijndael($this->mode);
241
- }
242
-
243
- }
244
-
245
- /**
246
- * Dummy function
247
- *
248
- * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
249
- *
250
- * @access public
251
- * @param Integer $length
252
- */
253
- function setBlockLength($length)
254
- {
255
- return;
256
- }
257
-
258
- /**
259
- * Sets the initialization vector. (optional)
260
- *
261
- * SetIV is not required when CRYPT_RIJNDAEL_MODE_ECB is being used. If not explictly set, it'll be assumed
262
- * to be all zero's.
263
- *
264
- * @access public
265
- * @param String $iv
266
- */
267
- function setIV($iv)
268
- {
269
- parent::setIV($iv);
270
- if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
271
- $this->changed = true;
272
- }
273
- }
274
-
275
- /**
276
- * Encrypts a message.
277
- *
278
- * $plaintext will be padded with up to 16 additional bytes. Other AES implementations may or may not pad in the
279
- * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
280
- * URL:
281
- *
282
- * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
283
- *
284
- * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
285
- * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
286
- * length.
287
- *
288
- * @see Crypt_AES::decrypt()
289
- * @access public
290
- * @param String $plaintext
291
- */
292
- function encrypt($plaintext)
293
- {
294
- if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
295
- $this->_mcryptSetup();
296
-
297
- // re: http://phpseclib.sourceforge.net/cfb-demo.phps
298
- // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
299
- // rewritten CFB implementation the above outputs the same thing twice.
300
- if ($this->mode == 'ncfb' && $this->continuousBuffer) {
301
- $iv = &$this->encryptIV;
302
- $pos = &$this->enbuffer['pos'];
303
- $len = strlen($plaintext);
304
- $ciphertext = '';
305
- $i = 0;
306
- if ($pos) {
307
- $orig_pos = $pos;
308
- $max = 16 - $pos;
309
- if ($len >= $max) {
310
- $i = $max;
311
- $len-= $max;
312
- $pos = 0;
313
- } else {
314
- $i = $len;
315
- $pos+= $len;
316
- $len = 0;
317
- }
318
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
319
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
320
- $this->enbuffer['enmcrypt_init'] = true;
321
- }
322
- if ($len >= 16) {
323
- if ($this->enbuffer['enmcrypt_init'] === false || $len > 280) {
324
- if ($this->enbuffer['enmcrypt_init'] === true) {
325
- mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
326
- $this->enbuffer['enmcrypt_init'] = false;
327
- }
328
- $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 16));
329
- $iv = substr($ciphertext, -16);
330
- $len%= 16;
331
- } else {
332
- while ($len >= 16) {
333
- $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 16);
334
- $ciphertext.= $iv;
335
- $len-= 16;
336
- $i+= 16;
337
- }
338
- }
339
- }
340
-
341
- if ($len) {
342
- $iv = mcrypt_generic($this->ecb, $iv);
343
- $block = $iv ^ substr($plaintext, -$len);
344
- $iv = substr_replace($iv, $block, 0, $len);
345
- $ciphertext.= $block;
346
- $pos = $len;
347
- }
348
-
349
- return $ciphertext;
350
- }
351
-
352
- if ($this->paddable) {
353
- $plaintext = $this->_pad($plaintext);
354
- }
355
-
356
- $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
357
-
358
- if (!$this->continuousBuffer) {
359
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
360
- }
361
-
362
- return $ciphertext;
363
- }
364
-
365
- return parent::encrypt($plaintext);
366
- }
367
-
368
- /**
369
- * Decrypts a message.
370
- *
371
- * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
372
- *
373
- * @see Crypt_AES::encrypt()
374
- * @access public
375
- * @param String $ciphertext
376
- */
377
- function decrypt($ciphertext)
378
- {
379
- if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
380
- $this->_mcryptSetup();
381
-
382
- if ($this->mode == 'ncfb' && $this->continuousBuffer) {
383
- $iv = &$this->decryptIV;
384
- $pos = &$this->debuffer['pos'];
385
- $len = strlen($ciphertext);
386
- $plaintext = '';
387
- $i = 0;
388
- if ($pos) {
389
- $orig_pos = $pos;
390
- $max = 16 - $pos;
391
- if ($len >= $max) {
392
- $i = $max;
393
- $len-= $max;
394
- $pos = 0;
395
- } else {
396
- $i = $len;
397
- $pos+= $len;
398
- $len = 0;
399
- }
400
- // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
401
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
402
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
403
- }
404
- if ($len >= 16) {
405
- $cb = substr($ciphertext, $i, $len - $len % 16);
406
- $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
407
- $iv = substr($cb, -16);
408
- $len%= 16;
409
- }
410
- if ($len) {
411
- $iv = mcrypt_generic($this->ecb, $iv);
412
- $plaintext.= $iv ^ substr($ciphertext, -$len);
413
- $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
414
- $pos = $len;
415
- }
416
-
417
- return $plaintext;
418
- }
419
-
420
- if ($this->paddable) {
421
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
422
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
423
- $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 15) & 0xFFFFFFF0, chr(0));
424
- }
425
-
426
- $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
427
-
428
- if (!$this->continuousBuffer) {
429
- mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
430
- }
431
-
432
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
433
- }
434
-
435
- return parent::decrypt($ciphertext);
436
- }
437
-
438
- /**
439
- * Setup mcrypt
440
- *
441
- * Validates all the variables.
442
- *
443
- * @access private
444
- */
445
- function _mcryptSetup()
446
- {
447
- if (!$this->changed) {
448
- return;
449
- }
450
-
451
- if (!$this->explicit_key_length) {
452
- // this just copied from Crypt_Rijndael::_setup()
453
- $length = strlen($this->key) >> 2;
454
- if ($length > 8) {
455
- $length = 8;
456
- } else if ($length < 4) {
457
- $length = 4;
458
- }
459
- $this->Nk = $length;
460
- $this->key_size = $length << 2;
461
- }
462
-
463
- switch ($this->Nk) {
464
- case 4: // 128
465
- $this->key_size = 16;
466
- break;
467
- case 5: // 160
468
- case 6: // 192
469
- $this->key_size = 24;
470
- break;
471
- case 7: // 224
472
- case 8: // 256
473
- $this->key_size = 32;
474
- }
475
-
476
- $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, chr(0));
477
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($this->iv, 0, 16), 16, chr(0));
478
-
479
- if (!isset($this->enmcrypt)) {
480
- $mode = $this->mode;
481
- //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
482
-
483
- $this->demcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
484
- $this->enmcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
485
-
486
- if ($mode == 'ncfb') {
487
- $this->ecb = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
488
- }
489
-
490
- } // else should mcrypt_generic_deinit be called?
491
-
492
- mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
493
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
494
-
495
- if ($this->mode == 'ncfb') {
496
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
497
- }
498
-
499
- $this->changed = false;
500
- }
501
-
502
- /**
503
- * Treat consecutive "packets" as if they are a continuous buffer.
504
- *
505
- * The default behavior.
506
- *
507
- * @see Crypt_Rijndael::disableContinuousBuffer()
508
- * @access public
509
- */
510
- function enableContinuousBuffer()
511
- {
512
- parent::enableContinuousBuffer();
513
-
514
- if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
515
- $this->enbuffer['enmcrypt_init'] = true;
516
- $this->debuffer['demcrypt_init'] = true;
517
- }
518
- }
519
-
520
- /**
521
- * Treat consecutive packets as if they are a discontinuous buffer.
522
- *
523
- * The default behavior.
524
- *
525
- * @see Crypt_Rijndael::enableContinuousBuffer()
526
- * @access public
527
- */
528
- function disableContinuousBuffer()
529
- {
530
- parent::disableContinuousBuffer();
531
-
532
- if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
533
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
534
- mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
535
- }
536
- }
537
- }
538
-
539
- // vim: ts=4:sw=4:et:
540
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/Blowfish.php DELETED
@@ -1,1468 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of Blowfish.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * Useful resources are as follows:
12
- *
13
- * - {@link http://en.wikipedia.org/wiki/Blowfish Wikipedia description of Blowfish}
14
- *
15
- * Here's a short example of how to use this library:
16
- * <code>
17
- * <?php
18
- * include('Crypt/Blowfish.php');
19
- *
20
- * $blowfish = new Crypt_Blowfish();
21
- *
22
- * $blowfish->setKey('12345678901234567890123456789012');
23
- *
24
- * $plaintext = str_repeat('a', 1024);
25
- *
26
- * echo $blowfish->decrypt($blowfish->encrypt($plaintext));
27
- * ?>
28
- * </code>
29
- *
30
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
31
- * of this software and associated documentation files (the "Software"), to deal
32
- * in the Software without restriction, including without limitation the rights
33
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34
- * copies of the Software, and to permit persons to whom the Software is
35
- * furnished to do so, subject to the following conditions:
36
- *
37
- * The above copyright notice and this permission notice shall be included in
38
- * all copies or substantial portions of the Software.
39
- *
40
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
46
- * THE SOFTWARE.
47
- *
48
- * @category Crypt
49
- * @package Crypt_Blowfish
50
- * @author Jim Wigginton <terrafrost@php.net>
51
- * @author Hans-Juergen Petrich <petrich@tronic-media.com>
52
- * @copyright MMVII Jim Wigginton
53
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
54
- * @version 1.0
55
- * @link http://phpseclib.sourceforge.net
56
- */
57
-
58
- /**#@+
59
- * @access public
60
- * @see Crypt_Blowfish::encrypt()
61
- * @see Crypt_Blowfish::decrypt()
62
- */
63
- /**
64
- * Encrypt / decrypt using the Counter mode.
65
- *
66
- * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
67
- *
68
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
69
- */
70
- define('CRYPT_BLOWFISH_MODE_CTR', -1);
71
- /**
72
- * Encrypt / decrypt using the Electronic Code Book mode.
73
- *
74
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
75
- */
76
- define('CRYPT_BLOWFISH_MODE_ECB', 1);
77
- /**
78
- * Encrypt / decrypt using the Code Book Chaining mode.
79
- *
80
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
81
- */
82
- define('CRYPT_BLOWFISH_MODE_CBC', 2);
83
- /**
84
- * Encrypt / decrypt using the Cipher Feedback mode.
85
- *
86
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
87
- */
88
- define('CRYPT_BLOWFISH_MODE_CFB', 3);
89
- /**
90
- * Encrypt / decrypt using the Cipher Feedback mode.
91
- *
92
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
93
- */
94
- define('CRYPT_BLOWFISH_MODE_OFB', 4);
95
- /**#@-*/
96
-
97
- /**#@+
98
- * @access private
99
- * @see Crypt_Blowfish::Crypt_Blowfish()
100
- */
101
- /**
102
- * Toggles the internal implementation
103
- */
104
- define('CRYPT_BLOWFISH_MODE_INTERNAL', 1);
105
- /**
106
- * Toggles the mcrypt implementation
107
- */
108
- define('CRYPT_BLOWFISH_MODE_MCRYPT', 2);
109
- /**#@-*/
110
-
111
- /**
112
- * Pure-PHP implementation of Blowfish.
113
- *
114
- * @author Jim Wigginton <terrafrost@php.net>
115
- * @author Hans-Juergen Petrich <petrich@tronic-media.com>
116
- * @version 1.0
117
- * @access public
118
- * @package Crypt_Blowfish
119
- */
120
- class Crypt_Blowfish {
121
- /**
122
- * The Key as String
123
- *
124
- * @see Crypt_Blowfish::setKey()
125
- * @var Array
126
- * @access private
127
- */
128
- var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
129
-
130
- /**
131
- * The Encryption Mode
132
- *
133
- * @see Crypt_Blowfish::Crypt_Blowfish()
134
- * @var Integer
135
- * @access private
136
- */
137
- var $mode;
138
-
139
- /**
140
- * Continuous Buffer status
141
- *
142
- * @see Crypt_Blowfish::enableContinuousBuffer()
143
- * @var Boolean
144
- * @access private
145
- */
146
- var $continuousBuffer = false;
147
-
148
- /**
149
- * Padding status
150
- *
151
- * @see Crypt_Blowfish::enablePadding()
152
- * @var Boolean
153
- * @access private
154
- */
155
- var $padding = true;
156
-
157
- /**
158
- * The Initialization Vector
159
- *
160
- * @see Crypt_Blowfish::setIV()
161
- * @var String
162
- * @access private
163
- */
164
- var $iv = "\0\0\0\0\0\0\0\0";
165
-
166
- /**
167
- * A "sliding" Initialization Vector
168
- *
169
- * @see Crypt_Blowfish::enableContinuousBuffer()
170
- * @var String
171
- * @access private
172
- */
173
- var $encryptIV = "\0\0\0\0\0\0\0\0";
174
-
175
- /**
176
- * A "sliding" Initialization Vector
177
- *
178
- * @see Crypt_Blowfish::enableContinuousBuffer()
179
- * @var String
180
- * @access private
181
- */
182
- var $decryptIV = "\0\0\0\0\0\0\0\0";
183
-
184
- /**
185
- * mcrypt resource for encryption
186
- *
187
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
188
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
189
- *
190
- * @see Crypt_Blowfish::encrypt()
191
- * @var String
192
- * @access private
193
- */
194
- var $enmcrypt;
195
-
196
- /**
197
- * mcrypt resource for decryption
198
- *
199
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
200
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
201
- *
202
- * @see Crypt_Blowfish::decrypt()
203
- * @var String
204
- * @access private
205
- */
206
- var $demcrypt;
207
-
208
- /**
209
- * Does the enmcrypt resource need to be (re)initialized?
210
- *
211
- * @see Crypt_Blowfish::setKey()
212
- * @see Crypt_Blowfish::setIV()
213
- * @var Boolean
214
- * @access private
215
- */
216
- var $enchanged = true;
217
-
218
- /**
219
- * Does the demcrypt resource need to be (re)initialized?
220
- *
221
- * @see Crypt_Blowfish::setKey()
222
- * @see Crypt_Blowfish::setIV()
223
- * @var Boolean
224
- * @access private
225
- */
226
- var $dechanged = true;
227
-
228
- /**
229
- * Is the mode one that is paddable?
230
- *
231
- * @see Crypt_Blowfish::Crypt_Blowfish()
232
- * @var Boolean
233
- * @access private
234
- */
235
- var $paddable = false;
236
-
237
- /**
238
- * Encryption buffer for CTR, OFB and CFB modes
239
- *
240
- * @see Crypt_Blowfish::encrypt()
241
- * @var Array
242
- * @access private
243
- */
244
- var $enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
245
-
246
- /**
247
- * Decryption buffer for CTR, OFB and CFB modes
248
- *
249
- * @see Crypt_Blowfish::decrypt()
250
- * @var Array
251
- * @access private
252
- */
253
- var $debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
254
-
255
- /**
256
- * mcrypt resource for CFB mode
257
- *
258
- * @see Crypt_Blowfish::encrypt()
259
- * @see Crypt_Blowfish::decrypt()
260
- * @var String
261
- * @access private
262
- */
263
- var $ecb;
264
-
265
- /**
266
- * Performance-optimized callback function for en/decrypt()
267
- *
268
- * @var Callback
269
- * @access private
270
- */
271
- var $inline_crypt;
272
-
273
- /**
274
- * The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each
275
- *
276
- * S-Box 1
277
- *
278
- * @access private
279
- * @var array
280
- */
281
- var $sbox0 = array (
282
- 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
283
- 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
284
- 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
285
- 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
286
- 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
287
- 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
288
- 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
289
- 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
290
- 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
291
- 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
292
- 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
293
- 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
294
- 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
295
- 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
296
- 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
297
- 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
298
- 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
299
- 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
300
- 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
301
- 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
302
- 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
303
- 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
304
- 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
305
- 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
306
- 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
307
- 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
308
- 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
309
- 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
310
- 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
311
- 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
312
- 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
313
- 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
314
- );
315
-
316
- /**
317
- * S-Box 1
318
- *
319
- * @access private
320
- * @var array
321
- */
322
- var $sbox1 = array(
323
- 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
324
- 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
325
- 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
326
- 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
327
- 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
328
- 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
329
- 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
330
- 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
331
- 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
332
- 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
333
- 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
334
- 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
335
- 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
336
- 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
337
- 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
338
- 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
339
- 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
340
- 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
341
- 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
342
- 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
343
- 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
344
- 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
345
- 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
346
- 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
347
- 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
348
- 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
349
- 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
350
- 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
351
- 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
352
- 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
353
- 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
354
- 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
355
- );
356
-
357
- /**
358
- * S-Box 2
359
- *
360
- * @access private
361
- * @var array
362
- */
363
- var $sbox2 = array(
364
- 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
365
- 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
366
- 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
367
- 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
368
- 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
369
- 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
370
- 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
371
- 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
372
- 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
373
- 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
374
- 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
375
- 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
376
- 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
377
- 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
378
- 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
379
- 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
380
- 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
381
- 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
382
- 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
383
- 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
384
- 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
385
- 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
386
- 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
387
- 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
388
- 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
389
- 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
390
- 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
391
- 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
392
- 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
393
- 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
394
- 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
395
- 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
396
- );
397
-
398
- /**
399
- * S-Box 3
400
- *
401
- * @access private
402
- * @var array
403
- */
404
- var $sbox3 = array(
405
- 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
406
- 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
407
- 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
408
- 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
409
- 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
410
- 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
411
- 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
412
- 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
413
- 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
414
- 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
415
- 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
416
- 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
417
- 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
418
- 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
419
- 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
420
- 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
421
- 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
422
- 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
423
- 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
424
- 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
425
- 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
426
- 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
427
- 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
428
- 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
429
- 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
430
- 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
431
- 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
432
- 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
433
- 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
434
- 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
435
- 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
436
- 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
437
- );
438
-
439
- /**
440
- * P-Array consists of 18 32-bit subkeys
441
- *
442
- * @var array $parray
443
- * @access private
444
- */
445
- var $parray = array(
446
- 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
447
- 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
448
- 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
449
- );
450
-
451
- /**
452
- * The BCTX-working Array
453
- *
454
- * Holds the expanded key [p] and the key-depended s-boxes [sb]
455
- *
456
- * @var array $bctx
457
- * @access private
458
- */
459
- var $bctx = array();
460
-
461
- /**
462
- * Default Constructor.
463
- *
464
- * Determines whether or not the mcrypt extension should be used.
465
- * If not explictly set, CRYPT_BLOWFISH_MODE_CBC will be used.
466
- *
467
- * @param optional Integer $mode
468
- * @access public
469
- */
470
- function Crypt_Blowfish($mode = CRYPT_BLOWFISH_MODE_CBC)
471
- {
472
- if ( !defined('CRYPT_BLOWFISH_MODE') ) {
473
- switch (true) {
474
- case extension_loaded('mcrypt') && in_array('blowfish', mcrypt_list_algorithms()):
475
- define('CRYPT_BLOWFISH_MODE', CRYPT_BLOWFISH_MODE_MCRYPT);
476
- break;
477
- default:
478
- define('CRYPT_BLOWFISH_MODE', CRYPT_BLOWFISH_MODE_INTERNAL);
479
- }
480
- }
481
-
482
- switch ( CRYPT_BLOWFISH_MODE ) {
483
- case CRYPT_BLOWFISH_MODE_MCRYPT:
484
- switch ($mode) {
485
- case CRYPT_BLOWFISH_MODE_ECB:
486
- $this->paddable = true;
487
- $this->mode = MCRYPT_MODE_ECB;
488
- break;
489
- case CRYPT_BLOWFISH_MODE_CTR:
490
- $this->mode = 'ctr';
491
- break;
492
- case CRYPT_BLOWFISH_MODE_CFB:
493
- $this->mode = 'ncfb';
494
- $this->ecb = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_ECB, '');
495
- break;
496
- case CRYPT_BLOWFISH_MODE_OFB:
497
- $this->mode = MCRYPT_MODE_NOFB;
498
- break;
499
- case CRYPT_BLOWFISH_MODE_CBC:
500
- default:
501
- $this->paddable = true;
502
- $this->mode = MCRYPT_MODE_CBC;
503
- }
504
- $this->enmcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', $this->mode, '');
505
- $this->demcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', $this->mode, '');
506
-
507
- break;
508
- default:
509
- switch ($mode) {
510
- case CRYPT_BLOWFISH_MODE_ECB:
511
- case CRYPT_BLOWFISH_MODE_CBC:
512
- $this->paddable = true;
513
- $this->mode = $mode;
514
- break;
515
- case CRYPT_BLOWFISH_MODE_CTR:
516
- case CRYPT_BLOWFISH_MODE_CFB:
517
- case CRYPT_BLOWFISH_MODE_OFB:
518
- $this->mode = $mode;
519
- break;
520
- default:
521
- $this->paddable = true;
522
- $this->mode = CRYPT_BLOWFISH_MODE_CBC;
523
- }
524
- $this->inline_crypt_setup();
525
- }
526
- }
527
-
528
- /**
529
- * Sets the key.
530
- *
531
- * Keys can be of any length. Blowfish, itself, requires the use of a key between 32 and max. 448-bits long.
532
- * If the key is less than 32-bits we NOT fill the key to 32bit but let the key as it is to be compatible
533
- * with mcrypt because mcrypt act this way with blowfish key's < 32 bits.
534
- *
535
- * If the key is more than 448-bits, we trim the excess bits.
536
- *
537
- * If the key is not explicitly set, or empty, it'll be assumed a 128 bits key to be all null bytes.
538
- *
539
- * @access public
540
- * @param String $key
541
- */
542
- function setKey($key)
543
- {
544
- $keylength = strlen($key);
545
-
546
- if (!$keylength) {
547
- $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
548
- }
549
- elseif ($keylength > 56) {
550
- $key = substr($key, 0, 56);
551
- }
552
-
553
- $this->key = $key;
554
-
555
- $this->enchanged = true;
556
- $this->dechanged = true;
557
-
558
- if (CRYPT_BLOWFISH_MODE == CRYPT_BLOWFISH_MODE_MCRYPT) {
559
- return;
560
- }
561
-
562
- /* key-expanding p[] and S-Box building sb[] */
563
- $this->bctx = array(
564
- 'p' => array(),
565
- 'sb' => array(
566
- $this->sbox0,
567
- $this->sbox1,
568
- $this->sbox2,
569
- $this->sbox3
570
- )
571
- );
572
-
573
- // unpack binary string in unsigned chars
574
- $key = array_values(unpack('C*', $key));
575
- $keyl = count($key);
576
- for ($j = 0, $i = 0; $i < 18; ++$i) {
577
- // xor P1 with the first 32-bits of the key, xor P2 with the second 32-bits ...
578
- for ($data = 0, $k = 0; $k < 4; ++$k) {
579
- $data = ($data << 8) | $key[$j];
580
- if (++$j >= $keyl) {
581
- $j = 0;
582
- }
583
- }
584
- $this->bctx['p'][] = $this->parray[$i] ^ $data;
585
- }
586
-
587
- // encrypt the zero-string, replace P1 and P2 with the encrypted data,
588
- // encrypt P3 and P4 with the new P1 and P2, do it with all P-array and subkeys
589
- $datal = 0;
590
- $datar = 0;
591
- for ($i = 0; $i < 18; $i += 2) {
592
- $this->_encryptBlock($datal, $datar);
593
- $this->bctx['p'][$i ] = $datal;
594
- $this->bctx['p'][$i + 1] = $datar;
595
- }
596
- for ($i = 0; $i < 4; ++$i) {
597
- for ($j = 0; $j < 256; $j += 2) {
598
- $this->_encryptBlock($datal, $datar);
599
- $this->bctx['sb'][$i][$j ] = $datal;
600
- $this->bctx['sb'][$i][$j + 1] = $datar;
601
- }
602
- }
603
- }
604
-
605
- /**
606
- * Encrypt the block.
607
- *
608
- * @access private
609
- * @param int $Xl left uInt32 part of the block
610
- * @param int $Xr right uInt32 part of the block
611
- * @return void
612
- */
613
- function _encryptBlock(&$Xl, &$Xr)
614
- {
615
- $p = $this->bctx['p'];
616
- $sb_0 = $this->bctx['sb'][0];
617
- $sb_1 = $this->bctx['sb'][1];
618
- $sb_2 = $this->bctx['sb'][2];
619
- $sb_3 = $this->bctx['sb'][3];
620
- $l = $Xl;
621
- $r = $Xr;
622
-
623
- $i = -1;
624
- while ($i < 15) {
625
- $l^= $p[++$i];
626
- $r^= ($sb_0[$l >> 24 & 0xff] +
627
- $sb_1[$l >> 16 & 0xff] ^
628
- $sb_2[$l >> 8 & 0xff]) +
629
- $sb_3[$l & 0xff];
630
-
631
- $r^= $p[++$i];
632
- $l^= ($sb_0[$r >> 24 & 0xff] +
633
- $sb_1[$r >> 16 & 0xff] ^
634
- $sb_2[$r >> 8 & 0xff]) +
635
- $sb_3[$r & 0xff];
636
-
637
- }
638
- $Xr = $l ^ $p[16];
639
- $Xl = $r ^ $p[17];
640
- }
641
-
642
- /**
643
- * Sets the password.
644
- *
645
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
646
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
647
- * $hash, $salt, $count
648
- *
649
- * @param String $password
650
- * @param optional String $method
651
- * @access public
652
- */
653
- function setPassword($password, $method = 'pbkdf2')
654
- {
655
- $key = '';
656
-
657
- switch ($method) {
658
- default: // 'pbkdf2'
659
- list(, , $hash, $salt, $count) = func_get_args();
660
- if (!isset($hash)) {
661
- $hash = 'sha1';
662
- }
663
- // WPA and WPA2 use the SSID as the salt
664
- if (!isset($salt)) {
665
- $salt = 'phpseclib/salt';
666
- }
667
- // RFC2898#section-4.2 uses 1,000 iterations by default
668
- // WPA and WPA2 use 4,096.
669
- if (!isset($count)) {
670
- $count = 1000;
671
- }
672
-
673
- if (!class_exists('Crypt_Hash')) {
674
- require_once('Crypt/Hash.php');
675
- }
676
-
677
- $i = 1;
678
- while (strlen($key) < 56) {
679
- //$dk.= $this->_pbkdf($password, $salt, $count, $i++);
680
- $hmac = new Crypt_Hash();
681
- $hmac->setHash($hash);
682
- $hmac->setKey($password);
683
- $f = $u = $hmac->hash($salt . pack('N', $i++));
684
- for ($j = 2; $j <= $count; $j++) {
685
- $u = $hmac->hash($u);
686
- $f^= $u;
687
- }
688
- $key.= $f;
689
- }
690
- }
691
-
692
- $this->setKey($key);
693
- }
694
-
695
- /**
696
- * Sets the initialization vector. (optional)
697
- *
698
- * SetIV is not required when CRYPT_BLOWFISH_MODE_ECB is being used. If not explictly set, it'll be assumed
699
- * to be all null bytes.
700
- *
701
- * @access public
702
- * @param String $iv
703
- */
704
- function setIV($iv)
705
- {
706
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
707
- $this->enchanged = true;
708
- $this->dechanged = true;
709
- }
710
-
711
- /**
712
- * Encrypts a message.
713
- *
714
- * $plaintext will be padded with up to 8 additional bytes. Other Blowfish implementations may or may not pad in the
715
- * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
716
- * URL:
717
- *
718
- * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
719
- *
720
- * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
721
- * strlen($plaintext) will still need to be a multiple of 8, however, arbitrary values can be added to make it that
722
- * length.
723
- *
724
- * @see Crypt_Blowfish::decrypt()
725
- * @access public
726
- * @param String $plaintext
727
- */
728
- function encrypt($plaintext)
729
- {
730
- if ( CRYPT_BLOWFISH_MODE == CRYPT_BLOWFISH_MODE_MCRYPT ) {
731
- if ($this->paddable) {
732
- $plaintext = $this->_pad($plaintext);
733
- }
734
-
735
- if ($this->enchanged) {
736
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
737
- if ($this->mode == 'ncfb') {
738
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
739
- }
740
- $this->enchanged = false;
741
- }
742
-
743
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
744
- $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
745
- } else {
746
- $iv = &$this->encryptIV;
747
- $pos = &$this->enbuffer['pos'];
748
- $len = strlen($plaintext);
749
- $ciphertext = '';
750
- $i = 0;
751
- if ($pos) {
752
- $orig_pos = $pos;
753
- $max = 8 - $pos;
754
- if ($len >= $max) {
755
- $i = $max;
756
- $len-= $max;
757
- $pos = 0;
758
- } else {
759
- $i = $len;
760
- $pos+= $len;
761
- $len = 0;
762
- }
763
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
764
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
765
- $this->enbuffer['enmcrypt_init'] = true;
766
- }
767
- if ($len >= 8) {
768
- if ($this->enbuffer['enmcrypt_init'] === false || $len > 600) {
769
- if ($this->enbuffer['enmcrypt_init'] === true) {
770
- mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
771
- $this->enbuffer['enmcrypt_init'] = false;
772
- }
773
- $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 8));
774
- $iv = substr($ciphertext, -8);
775
- $len%= 8;
776
- } else {
777
- while ($len >= 8) {
778
- $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 8);
779
- $ciphertext.= $iv;
780
- $len-= 8;
781
- $i+= 8;
782
- }
783
- }
784
- }
785
- if ($len) {
786
- $iv = mcrypt_generic($this->ecb, $iv);
787
- $block = $iv ^ substr($plaintext, -$len);
788
- $iv = substr_replace($iv, $block, 0, $len);
789
- $ciphertext.= $block;
790
- $pos = $len;
791
- }
792
- return $ciphertext;
793
- }
794
-
795
- if (!$this->continuousBuffer) {
796
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
797
- }
798
-
799
- return $ciphertext;
800
- }
801
-
802
- if (empty($this->bctx)) {
803
- $this->setKey($this->key);
804
- }
805
-
806
- $inline = $this->inline_crypt;
807
- return $inline('encrypt', $this, $plaintext);
808
- }
809
-
810
- /**
811
- * Decrypts a message.
812
- *
813
- * If strlen($ciphertext) is not a multiple of 8, null bytes will be added to the end of the string until it is.
814
- *
815
- * @see Crypt_Blowfish::encrypt()
816
- * @access public
817
- * @param String $ciphertext
818
- */
819
- function decrypt($ciphertext)
820
- {
821
- if ( CRYPT_BLOWFISH_MODE == CRYPT_BLOWFISH_MODE_MCRYPT ) {
822
- if ($this->paddable) {
823
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
824
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
825
- $ciphertext = str_pad($ciphertext, strlen($ciphertext) + (8 - strlen($ciphertext) % 8) % 8, chr(0));
826
- }
827
-
828
- if ($this->dechanged) {
829
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
830
- if ($this->mode == 'ncfb') {
831
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
832
- }
833
- $this->dechanged = false;
834
- }
835
-
836
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
837
- $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
838
- } else {
839
- $iv = &$this->decryptIV;
840
- $pos = &$this->debuffer['pos'];
841
- $len = strlen($ciphertext);
842
- $plaintext = '';
843
- $i = 0;
844
- if ($pos) {
845
- $orig_pos = $pos;
846
- $max = 8 - $pos;
847
- if ($len >= $max) {
848
- $i = $max;
849
- $len-= $max;
850
- $pos = 0;
851
- } else {
852
- $i = $len;
853
- $pos+= $len;
854
- $len = 0;
855
- }
856
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
857
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
858
- }
859
- if ($len >= 8) {
860
- $cb = substr($ciphertext, $i, $len - $len % 8);
861
- $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
862
- $iv = substr($cb, -8);
863
- $len%= 8;
864
- }
865
- if ($len) {
866
- $iv = mcrypt_generic($this->ecb, $iv);
867
- $plaintext.= $iv ^ substr($ciphertext, -$len);
868
- $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
869
- $pos = $len;
870
- }
871
- return $plaintext;
872
- }
873
-
874
- if (!$this->continuousBuffer) {
875
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
876
- }
877
-
878
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
879
- }
880
-
881
- if (empty($this->bctx)) {
882
- $this->setKey($this->key);
883
- }
884
-
885
- $inline = $this->inline_crypt;
886
- return $inline('decrypt', $this, $ciphertext);
887
- }
888
-
889
- /**
890
- * Treat consecutive "packets" as if they are a continuous buffer.
891
- *
892
- * @see Crypt_Blowfish::disableContinuousBuffer()
893
- * @access public
894
- */
895
- function enableContinuousBuffer()
896
- {
897
- $this->continuousBuffer = true;
898
- }
899
-
900
- /**
901
- * Treat consecutive packets as if they are a discontinuous buffer.
902
- *
903
- * The default behavior.
904
- *
905
- * @see Crypt_Blowfish::enableContinuousBuffer()
906
- * @access public
907
- */
908
- function disableContinuousBuffer()
909
- {
910
- $this->continuousBuffer = false;
911
- $this->encryptIV = $this->iv;
912
- $this->decryptIV = $this->iv;
913
- $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
914
- $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
915
-
916
- if (CRYPT_BLOWFISH_MODE == CRYPT_BLOWFISH_MODE_MCRYPT) {
917
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
918
- mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
919
- }
920
- }
921
-
922
- /**
923
- * Pad "packets".
924
- *
925
- * Blowfish works by encrypting 8 bytes at a time. If you ever need to encrypt or decrypt something that's not
926
- * a multiple of 8, it becomes necessary to pad the input so that it's length is a multiple of eight.
927
- *
928
- * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
929
- * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
930
- * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
931
- * transmitted separately)
932
- *
933
- * @see Crypt_Blowfish::disablePadding()
934
- * @access public
935
- */
936
- function enablePadding()
937
- {
938
- $this->padding = true;
939
- }
940
-
941
- /**
942
- * Do not pad packets.
943
- *
944
- * @see Crypt_Blowfish::enablePadding()
945
- * @access public
946
- */
947
- function disablePadding()
948
- {
949
- $this->padding = false;
950
- }
951
-
952
- /**
953
- * Pads a string
954
- *
955
- * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
956
- *
957
- * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
958
- * and padding will, hence forth, be enabled.
959
- *
960
- * @see Crypt_Blowfish::_unpad()
961
- * @access private
962
- */
963
- function _pad($text)
964
- {
965
- $length = strlen($text);
966
-
967
- if (!$this->padding) {
968
- if ($length % 8 == 0) {
969
- return $text;
970
- } else {
971
- user_error("The plaintext's length ($length) is not a multiple of the block size (8)");
972
- $this->padding = true;
973
- }
974
- }
975
-
976
- $pad = 8 - ($length % 8);
977
-
978
- return str_pad($text, $length + $pad, chr($pad));
979
- }
980
-
981
- /**
982
- * Unpads a string
983
- *
984
- * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
985
- * and false will be returned.
986
- *
987
- * @see Crypt_Blowfish::_pad()
988
- * @access private
989
- */
990
- function _unpad($text)
991
- {
992
- if (!$this->padding) {
993
- return $text;
994
- }
995
-
996
- $length = ord($text[strlen($text) - 1]);
997
-
998
- if (!$length || $length > 8) {
999
- return false;
1000
- }
1001
-
1002
- return substr($text, 0, -$length);
1003
- }
1004
-
1005
- /**
1006
- * String Shift
1007
- *
1008
- * Inspired by array_shift
1009
- *
1010
- * @param String $string
1011
- * @return String
1012
- * @access private
1013
- */
1014
- function _string_shift(&$string)
1015
- {
1016
- $substr = substr($string, 0, 8);
1017
- $string = substr($string, 8);
1018
- return $substr;
1019
- }
1020
-
1021
- /**
1022
- * Generate CTR XOR encryption key
1023
- *
1024
- * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1025
- * plaintext / ciphertext in CTR mode.
1026
- *
1027
- * @see Crypt_Blowfish::decrypt()
1028
- * @see Crypt_Blowfish::encrypt()
1029
- * @access public
1030
- * @param String $iv
1031
- */
1032
- function _generate_xor(&$iv)
1033
- {
1034
- $xor = $iv;
1035
- for ($j = 4; $j <= 8; $j+=4) {
1036
- $temp = substr($iv, -$j, 4);
1037
- switch ($temp) {
1038
- case "\xFF\xFF\xFF\xFF":
1039
- $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1040
- break;
1041
- case "\x7F\xFF\xFF\xFF":
1042
- $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1043
- break 2;
1044
- default:
1045
- extract(unpack('Ncount', $temp));
1046
- $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1047
- break 2;
1048
- }
1049
- }
1050
-
1051
- return $xor;
1052
- }
1053
-
1054
- /**
1055
- * Creates performance-optimized function for de/encrypt(), storing it in $this->inline_crypt
1056
- *
1057
- * @access private
1058
- */
1059
- function inline_crypt_setup()
1060
- {/*{{{*/
1061
- $lambda_functions =& Crypt_Blowfish::get_lambda_functions();
1062
- $block_size = 8;
1063
- $mode = $this->mode;
1064
- $code_hash = "$mode";
1065
-
1066
- if (!isset($lambda_functions[$code_hash])) {
1067
- $init_cryptBlock = '
1068
- extract($self->bctx["p"], EXTR_PREFIX_ALL, "p");
1069
- extract($self->bctx["sb"], EXTR_PREFIX_ALL, "sb");
1070
- ';
1071
-
1072
- // Generating encrypt code:
1073
- $_encryptBlock = '
1074
- $in = unpack("N*", $in);
1075
- $l = $in[1];
1076
- $r = $in[2];
1077
- ';
1078
- for ($i = 0; $i < 16; $i+= 2) {
1079
- $_encryptBlock.= '
1080
- $l^= $p_'.($i).';
1081
- $r^= ($sb_0[$l >> 24 & 0xff] +
1082
- $sb_1[$l >> 16 & 0xff] ^
1083
- $sb_2[$l >> 8 & 0xff]) +
1084
- $sb_3[$l & 0xff];
1085
-
1086
- $r^= $p_'.($i + 1).';
1087
- $l^= ($sb_0[$r >> 24 & 0xff] +
1088
- $sb_1[$r >> 16 & 0xff] ^
1089
- $sb_2[$r >> 8 & 0xff]) +
1090
- $sb_3[$r & 0xff];
1091
- ';
1092
- }
1093
- $_encryptBlock.= '
1094
- $in = pack("N*", $r ^ $p_17, $l ^ $p_16);
1095
- ';
1096
-
1097
- // Generating decrypt code:
1098
- $_decryptBlock = '
1099
- $in = unpack("N*", $in);
1100
- $l = $in[1];
1101
- $r = $in[2];
1102
- ';
1103
-
1104
- for ($i = 17; $i > 2; $i-= 2) {
1105
- $_decryptBlock.= '
1106
- $l^= $p_'.($i).';
1107
- $r^= ($sb_0[$l >> 24 & 0xff] +
1108
- $sb_1[$l >> 16 & 0xff] ^
1109
- $sb_2[$l >> 8 & 0xff]) +
1110
- $sb_3[$l & 0xff];
1111
-
1112
- $r^= $p_'.($i - 1).';
1113
- $l^= ($sb_0[$r >> 24 & 0xff] +
1114
- $sb_1[$r >> 16 & 0xff] ^
1115
- $sb_2[$r >> 8 & 0xff]) +
1116
- $sb_3[$r & 0xff];
1117
- ';
1118
- }
1119
-
1120
- $_decryptBlock.= '
1121
- $in = pack("N*", $r ^ $p_0, $l ^ $p_1);
1122
- ';
1123
-
1124
- // Generating mode of operation code:
1125
- switch ($mode) {
1126
- case CRYPT_BLOWFISH_MODE_ECB:
1127
- $encrypt = '
1128
- $ciphertext = "";
1129
- $text = $self->_pad($text);
1130
- $plaintext_len = strlen($text);
1131
-
1132
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1133
- $in = substr($text, $i, '.$block_size.');
1134
- '.$_encryptBlock.'
1135
- $ciphertext.= $in;
1136
- }
1137
- return $ciphertext;
1138
- ';
1139
-
1140
- $decrypt = '
1141
- $plaintext = "";
1142
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1143
- $ciphertext_len = strlen($text);
1144
-
1145
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1146
- $in = substr($text, $i, '.$block_size.');
1147
- '.$_decryptBlock.'
1148
- $plaintext.= $in;
1149
- }
1150
-
1151
- return $self->_unpad($plaintext);
1152
- ';
1153
- break;
1154
- case CRYPT_BLOWFISH_MODE_CBC:
1155
- $encrypt = '
1156
- $ciphertext = "";
1157
- $text = $self->_pad($text);
1158
- $plaintext_len = strlen($text);
1159
-
1160
- $in = $self->encryptIV;
1161
-
1162
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1163
- $in = substr($text, $i, '.$block_size.') ^ $in;
1164
- '.$_encryptBlock.'
1165
- $ciphertext.= $in;
1166
- }
1167
-
1168
- if ($self->continuousBuffer) {
1169
- $self->encryptIV = $in;
1170
- }
1171
-
1172
- return $ciphertext;
1173
- ';
1174
-
1175
- $decrypt = '
1176
- $plaintext = "";
1177
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1178
- $ciphertext_len = strlen($text);
1179
-
1180
- $iv = $self->decryptIV;
1181
-
1182
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1183
- $in = $block = substr($text, $i, '.$block_size.');
1184
- '.$_decryptBlock.'
1185
- $plaintext.= $in ^ $iv;
1186
- $iv = $block;
1187
- }
1188
-
1189
- if ($self->continuousBuffer) {
1190
- $self->decryptIV = $iv;
1191
- }
1192
-
1193
- return $self->_unpad($plaintext);
1194
- ';
1195
- break;
1196
- case CRYPT_BLOWFISH_MODE_CTR:
1197
- $encrypt = '
1198
- $ciphertext = "";
1199
- $plaintext_len = strlen($text);
1200
- $xor = $self->encryptIV;
1201
- $buffer = &$self->enbuffer;
1202
-
1203
- if (strlen($buffer["encrypted"])) {
1204
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1205
- $block = substr($text, $i, '.$block_size.');
1206
- if (strlen($block) > strlen($buffer["encrypted"])) {
1207
- $in = $self->_generate_xor($xor);
1208
- '.$_encryptBlock.'
1209
- $buffer["encrypted"].= $in;
1210
- }
1211
- $key = $self->_string_shift($buffer["encrypted"]);
1212
- $ciphertext.= $block ^ $key;
1213
- }
1214
- } else {
1215
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1216
- $block = substr($text, $i, '.$block_size.');
1217
- $in = $self->_generate_xor($xor);
1218
- '.$_encryptBlock.'
1219
- $key = $in;
1220
- $ciphertext.= $block ^ $key;
1221
- }
1222
- }
1223
- if ($self->continuousBuffer) {
1224
- $self->encryptIV = $xor;
1225
- if ($start = $plaintext_len % '.$block_size.') {
1226
- $buffer["encrypted"] = substr($key, $start) . $buffer["encrypted"];
1227
- }
1228
- }
1229
-
1230
- return $ciphertext;
1231
- ';
1232
-
1233
- $decrypt = '
1234
- $plaintext = "";
1235
- $ciphertext_len = strlen($text);
1236
- $xor = $self->decryptIV;
1237
- $buffer = &$self->debuffer;
1238
-
1239
- if (strlen($buffer["ciphertext"])) {
1240
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1241
- $block = substr($text, $i, '.$block_size.');
1242
- if (strlen($block) > strlen($buffer["ciphertext"])) {
1243
- $in = $self->_generate_xor($xor);
1244
- '.$_encryptBlock.'
1245
- $buffer["ciphertext"].= $in;
1246
- }
1247
- $key = $self->_string_shift($buffer["ciphertext"]);
1248
- $plaintext.= $block ^ $key;
1249
- }
1250
- } else {
1251
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1252
- $block = substr($text, $i, '.$block_size.');
1253
- $in = $self->_generate_xor($xor);
1254
- '.$_encryptBlock.'
1255
- $key = $in;
1256
- $plaintext.= $block ^ $key;
1257
- }
1258
- }
1259
- if ($self->continuousBuffer) {
1260
- $self->decryptIV = $xor;
1261
- if ($start = $ciphertext_len % '.$block_size.') {
1262
- $buffer["ciphertext"] = substr($key, $start) . $buffer["ciphertext"];
1263
- }
1264
- }
1265
- return $plaintext;
1266
- ';
1267
- break;
1268
- case CRYPT_BLOWFISH_MODE_CFB:
1269
- $encrypt = '
1270
- $ciphertext = "";
1271
- $buffer = &$self->enbuffer;
1272
-
1273
- if ($self->continuousBuffer) {
1274
- $iv = &$self->encryptIV;
1275
- $pos = &$buffer["pos"];
1276
- } else {
1277
- $iv = $self->encryptIV;
1278
- $pos = 0;
1279
- }
1280
- $len = strlen($text);
1281
- $i = 0;
1282
- if ($pos) {
1283
- $orig_pos = $pos;
1284
- $max = '.$block_size.' - $pos;
1285
- if ($len >= $max) {
1286
- $i = $max;
1287
- $len-= $max;
1288
- $pos = 0;
1289
- } else {
1290
- $i = $len;
1291
- $pos+= $len;
1292
- $len = 0;
1293
- }
1294
- $ciphertext = substr($iv, $orig_pos) ^ $text;
1295
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
1296
- }
1297
- while ($len >= '.$block_size.') {
1298
- $in = $iv;
1299
- '.$_encryptBlock.';
1300
- $iv = $in ^ substr($text, $i, '.$block_size.');
1301
- $ciphertext.= $iv;
1302
- $len-= '.$block_size.';
1303
- $i+= '.$block_size.';
1304
- }
1305
- if ($len) {
1306
- $in = $iv;
1307
- '.$_encryptBlock.'
1308
- $iv = $in;
1309
- $block = $iv ^ substr($text, $i);
1310
- $iv = substr_replace($iv, $block, 0, $len);
1311
- $ciphertext.= $block;
1312
- $pos = $len;
1313
- }
1314
- return $ciphertext;
1315
- ';
1316
-
1317
- $decrypt = '
1318
- $plaintext = "";
1319
- $buffer = &$self->debuffer;
1320
-
1321
- if ($self->continuousBuffer) {
1322
- $iv = &$self->decryptIV;
1323
- $pos = &$buffer["pos"];
1324
- } else {
1325
- $iv = $self->decryptIV;
1326
- $pos = 0;
1327
- }
1328
- $len = strlen($text);
1329
- $i = 0;
1330
- if ($pos) {
1331
- $orig_pos = $pos;
1332
- $max = '.$block_size.' - $pos;
1333
- if ($len >= $max) {
1334
- $i = $max;
1335
- $len-= $max;
1336
- $pos = 0;
1337
- } else {
1338
- $i = $len;
1339
- $pos+= $len;
1340
- $len = 0;
1341
- }
1342
- $plaintext = substr($iv, $orig_pos) ^ $text;
1343
- $iv = substr_replace($iv, substr($text, 0, $i), $orig_pos, $i);
1344
- }
1345
- while ($len >= '.$block_size.') {
1346
- $in = $iv;
1347
- '.$_encryptBlock.'
1348
- $iv = $in;
1349
- $cb = substr($text, $i, '.$block_size.');
1350
- $plaintext.= $iv ^ $cb;
1351
- $iv = $cb;
1352
- $len-= '.$block_size.';
1353
- $i+= '.$block_size.';
1354
- }
1355
- if ($len) {
1356
- $in = $iv;
1357
- '.$_encryptBlock.'
1358
- $iv = $in;
1359
- $plaintext.= $iv ^ substr($text, $i);
1360
- $iv = substr_replace($iv, substr($text, $i), 0, $len);
1361
- $pos = $len;
1362
- }
1363
-
1364
- return $plaintext;
1365
- ';
1366
- break;
1367
- case CRYPT_BLOWFISH_MODE_OFB:
1368
- $encrypt = '
1369
- $ciphertext = "";
1370
- $plaintext_len = strlen($text);
1371
- $xor = $self->encryptIV;
1372
- $buffer = &$self->enbuffer;
1373
-
1374
- if (strlen($buffer["xor"])) {
1375
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1376
- $block = substr($text, $i, '.$block_size.');
1377
- if (strlen($block) > strlen($buffer["xor"])) {
1378
- $in = $xor;
1379
- '.$_encryptBlock.'
1380
- $xor = $in;
1381
- $buffer["xor"].= $xor;
1382
- }
1383
- $key = $self->_string_shift($buffer["xor"]);
1384
- $ciphertext.= $block ^ $key;
1385
- }
1386
- } else {
1387
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1388
- $in = $xor;
1389
- '.$_encryptBlock.'
1390
- $xor = $in;
1391
- $ciphertext.= substr($text, $i, '.$block_size.') ^ $xor;
1392
- }
1393
- $key = $xor;
1394
- }
1395
- if ($self->continuousBuffer) {
1396
- $self->encryptIV = $xor;
1397
- if ($start = $plaintext_len % '.$block_size.') {
1398
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
1399
- }
1400
- }
1401
- return $ciphertext;
1402
- ';
1403
-
1404
- $decrypt = '
1405
- $plaintext = "";
1406
- $ciphertext_len = strlen($text);
1407
- $xor = $self->decryptIV;
1408
- $buffer = &$self->debuffer;
1409
-
1410
- if (strlen($buffer["xor"])) {
1411
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1412
- $block = substr($text, $i, '.$block_size.');
1413
- if (strlen($block) > strlen($buffer["xor"])) {
1414
- $in = $xor;
1415
- '.$_encryptBlock.'
1416
- $xor = $in;
1417
- $buffer["xor"].= $xor;
1418
- }
1419
- $key = $self->_string_shift($buffer["xor"]);
1420
- $plaintext.= $block ^ $key;
1421
- }
1422
- } else {
1423
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1424
- $in = $xor;
1425
- '.$_encryptBlock.'
1426
- $xor = $in;
1427
- $plaintext.= substr($text, $i, '.$block_size.') ^ $xor;
1428
- }
1429
- $key = $xor;
1430
- }
1431
- if ($self->continuousBuffer) {
1432
- $self->decryptIV = $xor;
1433
- if ($start = $ciphertext_len % '.$block_size.') {
1434
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
1435
- }
1436
- }
1437
- return $plaintext;
1438
- ';
1439
- break;
1440
- }
1441
- $fnc_head = '$action, &$self, $text';
1442
- $fnc_body = $init_cryptBlock . 'if ($action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }';
1443
-
1444
- if (function_exists('create_function') && is_callable('create_function')) {
1445
- $lambda_functions[$code_hash] = create_function($fnc_head, $fnc_body);
1446
- } else {
1447
- eval('function ' . ($lambda_functions[$code_hash] = 'f' . md5(microtime())) . '(' . $fnc_head . ') { ' . $fnc_body . ' }');
1448
- }
1449
- }
1450
- $this->inline_crypt = $lambda_functions[$code_hash];
1451
- }/*}}}*/
1452
-
1453
- /**
1454
- * Holds the lambda_functions table (classwide)
1455
- *
1456
- * @see inline_crypt_setup()
1457
- * @return Array
1458
- * @access private
1459
- */
1460
- function &get_lambda_functions()
1461
- {
1462
- static $functions = array();
1463
- return $functions;
1464
- }
1465
- }
1466
-
1467
- // vim: ts=4:sw=4:et:
1468
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/DES.php DELETED
@@ -1,2536 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of DES.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * Useful resources are as follows:
12
- *
13
- * - {@link http://en.wikipedia.org/wiki/DES_supplementary_material Wikipedia: DES supplementary material}
14
- * - {@link http://www.itl.nist.gov/fipspubs/fip46-2.htm FIPS 46-2 - (DES), Data Encryption Standard}
15
- * - {@link http://www.cs.eku.edu/faculty/styer/460/Encrypt/JS-DES.html JavaScript DES Example}
16
- *
17
- * Here's a short example of how to use this library:
18
- * <code>
19
- * <?php
20
- * include('Crypt/DES.php');
21
- *
22
- * $des = new Crypt_DES();
23
- *
24
- * $des->setKey('abcdefgh');
25
- *
26
- * $size = 10 * 1024;
27
- * $plaintext = '';
28
- * for ($i = 0; $i < $size; $i++) {
29
- * $plaintext.= 'a';
30
- * }
31
- *
32
- * echo $des->decrypt($des->encrypt($plaintext));
33
- * ?>
34
- * </code>
35
- *
36
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
37
- * of this software and associated documentation files (the "Software"), to deal
38
- * in the Software without restriction, including without limitation the rights
39
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
40
- * copies of the Software, and to permit persons to whom the Software is
41
- * furnished to do so, subject to the following conditions:
42
- *
43
- * The above copyright notice and this permission notice shall be included in
44
- * all copies or substantial portions of the Software.
45
- *
46
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
49
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
51
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
52
- * THE SOFTWARE.
53
- *
54
- * @category Crypt
55
- * @package Crypt_DES
56
- * @author Jim Wigginton <terrafrost@php.net>
57
- * @copyright MMVII Jim Wigginton
58
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
59
- * @link http://phpseclib.sourceforge.net
60
- */
61
-
62
- /**#@+
63
- * @access private
64
- * @see Crypt_DES::_prepareKey()
65
- * @see Crypt_DES::_processBlock()
66
- */
67
- /**
68
- * Contains array_reverse($keys[CRYPT_DES_DECRYPT])
69
- */
70
- define('CRYPT_DES_ENCRYPT', 0);
71
- /**
72
- * Contains array_reverse($keys[CRYPT_DES_ENCRYPT])
73
- */
74
- define('CRYPT_DES_DECRYPT', 1);
75
- /**
76
- * Contains $keys[CRYPT_DES_ENCRYPT] as 1-dim array
77
- */
78
- define('CRYPT_DES_ENCRYPT_1DIM', 2);
79
- /**
80
- * Contains $keys[CRYPT_DES_DECRYPT] as 1-dim array
81
- */
82
- define('CRYPT_DES_DECRYPT_1DIM', 3);
83
- /**#@-*/
84
-
85
- /**#@+
86
- * @access public
87
- * @see Crypt_DES::encrypt()
88
- * @see Crypt_DES::decrypt()
89
- */
90
- /**
91
- * Encrypt / decrypt using the Counter mode.
92
- *
93
- * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
94
- *
95
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
96
- */
97
- define('CRYPT_DES_MODE_CTR', -1);
98
- /**
99
- * Encrypt / decrypt using the Electronic Code Book mode.
100
- *
101
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
102
- */
103
- define('CRYPT_DES_MODE_ECB', 1);
104
- /**
105
- * Encrypt / decrypt using the Code Book Chaining mode.
106
- *
107
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
108
- */
109
- define('CRYPT_DES_MODE_CBC', 2);
110
- /**
111
- * Encrypt / decrypt using the Cipher Feedback mode.
112
- *
113
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
114
- */
115
- define('CRYPT_DES_MODE_CFB', 3);
116
- /**
117
- * Encrypt / decrypt using the Cipher Feedback mode.
118
- *
119
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
120
- */
121
- define('CRYPT_DES_MODE_OFB', 4);
122
- /**#@-*/
123
-
124
- /**#@+
125
- * @access private
126
- * @see Crypt_DES::Crypt_DES()
127
- */
128
- /**
129
- * Toggles the internal implementation
130
- */
131
- define('CRYPT_DES_MODE_INTERNAL', 1);
132
- /**
133
- * Toggles the mcrypt implementation
134
- */
135
- define('CRYPT_DES_MODE_MCRYPT', 2);
136
- /**#@-*/
137
-
138
- /**
139
- * Pure-PHP implementation of DES.
140
- *
141
- * @author Jim Wigginton <terrafrost@php.net>
142
- * @version 0.1.0
143
- * @access public
144
- * @package Crypt_DES
145
- */
146
- class Crypt_DES {
147
- /**
148
- * The Key Schedule
149
- *
150
- * @see Crypt_DES::setKey()
151
- * @var Array
152
- * @access private
153
- */
154
- var $keys = "\0\0\0\0\0\0\0\0";
155
-
156
- /**
157
- * The Encryption Mode
158
- *
159
- * @see Crypt_DES::Crypt_DES()
160
- * @var Integer
161
- * @access private
162
- */
163
- var $mode;
164
-
165
- /**
166
- * Continuous Buffer status
167
- *
168
- * @see Crypt_DES::enableContinuousBuffer()
169
- * @var Boolean
170
- * @access private
171
- */
172
- var $continuousBuffer = false;
173
-
174
- /**
175
- * Padding status
176
- *
177
- * @see Crypt_DES::enablePadding()
178
- * @var Boolean
179
- * @access private
180
- */
181
- var $padding = true;
182
-
183
- /**
184
- * The Initialization Vector
185
- *
186
- * @see Crypt_DES::setIV()
187
- * @var String
188
- * @access private
189
- */
190
- var $iv = "\0\0\0\0\0\0\0\0";
191
-
192
- /**
193
- * A "sliding" Initialization Vector
194
- *
195
- * @see Crypt_DES::enableContinuousBuffer()
196
- * @var String
197
- * @access private
198
- */
199
- var $encryptIV = "\0\0\0\0\0\0\0\0";
200
-
201
- /**
202
- * A "sliding" Initialization Vector
203
- *
204
- * @see Crypt_DES::enableContinuousBuffer()
205
- * @var String
206
- * @access private
207
- */
208
- var $decryptIV = "\0\0\0\0\0\0\0\0";
209
-
210
- /**
211
- * mcrypt resource for encryption
212
- *
213
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
214
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
215
- *
216
- * @see Crypt_DES::encrypt()
217
- * @var String
218
- * @access private
219
- */
220
- var $enmcrypt;
221
-
222
- /**
223
- * mcrypt resource for decryption
224
- *
225
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
226
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
227
- *
228
- * @see Crypt_DES::decrypt()
229
- * @var String
230
- * @access private
231
- */
232
- var $demcrypt;
233
-
234
- /**
235
- * Does the enmcrypt resource need to be (re)initialized?
236
- *
237
- * @see Crypt_DES::setKey()
238
- * @see Crypt_DES::setIV()
239
- * @var Boolean
240
- * @access private
241
- */
242
- var $enchanged = true;
243
-
244
- /**
245
- * Does the demcrypt resource need to be (re)initialized?
246
- *
247
- * @see Crypt_DES::setKey()
248
- * @see Crypt_DES::setIV()
249
- * @var Boolean
250
- * @access private
251
- */
252
- var $dechanged = true;
253
-
254
- /**
255
- * Is the mode one that is paddable?
256
- *
257
- * @see Crypt_DES::Crypt_DES()
258
- * @var Boolean
259
- * @access private
260
- */
261
- var $paddable = false;
262
-
263
- /**
264
- * Encryption buffer for CTR, OFB and CFB modes
265
- *
266
- * @see Crypt_DES::encrypt()
267
- * @var Array
268
- * @access private
269
- */
270
- var $enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
271
-
272
- /**
273
- * Decryption buffer for CTR, OFB and CFB modes
274
- *
275
- * @see Crypt_DES::decrypt()
276
- * @var Array
277
- * @access private
278
- */
279
- var $debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
280
-
281
- /**
282
- * mcrypt resource for CFB mode
283
- *
284
- * @see Crypt_DES::encrypt()
285
- * @see Crypt_DES::decrypt()
286
- * @var String
287
- * @access private
288
- */
289
- var $ecb;
290
-
291
- /**
292
- * Performance-optimized callback function for en/decrypt()
293
- *
294
- * @var Callback
295
- * @access private
296
- */
297
- var $inline_crypt;
298
-
299
- /**
300
- * Holds whether performance-optimized $inline_crypt should be used or not.
301
- *
302
- * @var Boolean
303
- * @access private
304
- */
305
- var $use_inline_crypt = false;
306
-
307
- /**
308
- * Shuffle table.
309
- *
310
- * For each byte value index, the entry holds an 8-byte string
311
- * with each byte containing all bits in the same state as the
312
- * corresponding bit in the index value.
313
- *
314
- * @see Crypt_DES::_processBlock()
315
- * @see Crypt_DES::_prepareKey()
316
- * @var Array
317
- * @access private
318
- */
319
- var $shuffle = array(
320
- "\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\xFF",
321
- "\x00\x00\x00\x00\x00\x00\xFF\x00", "\x00\x00\x00\x00\x00\x00\xFF\xFF",
322
- "\x00\x00\x00\x00\x00\xFF\x00\x00", "\x00\x00\x00\x00\x00\xFF\x00\xFF",
323
- "\x00\x00\x00\x00\x00\xFF\xFF\x00", "\x00\x00\x00\x00\x00\xFF\xFF\xFF",
324
- "\x00\x00\x00\x00\xFF\x00\x00\x00", "\x00\x00\x00\x00\xFF\x00\x00\xFF",
325
- "\x00\x00\x00\x00\xFF\x00\xFF\x00", "\x00\x00\x00\x00\xFF\x00\xFF\xFF",
326
- "\x00\x00\x00\x00\xFF\xFF\x00\x00", "\x00\x00\x00\x00\xFF\xFF\x00\xFF",
327
- "\x00\x00\x00\x00\xFF\xFF\xFF\x00", "\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
328
- "\x00\x00\x00\xFF\x00\x00\x00\x00", "\x00\x00\x00\xFF\x00\x00\x00\xFF",
329
- "\x00\x00\x00\xFF\x00\x00\xFF\x00", "\x00\x00\x00\xFF\x00\x00\xFF\xFF",
330
- "\x00\x00\x00\xFF\x00\xFF\x00\x00", "\x00\x00\x00\xFF\x00\xFF\x00\xFF",
331
- "\x00\x00\x00\xFF\x00\xFF\xFF\x00", "\x00\x00\x00\xFF\x00\xFF\xFF\xFF",
332
- "\x00\x00\x00\xFF\xFF\x00\x00\x00", "\x00\x00\x00\xFF\xFF\x00\x00\xFF",
333
- "\x00\x00\x00\xFF\xFF\x00\xFF\x00", "\x00\x00\x00\xFF\xFF\x00\xFF\xFF",
334
- "\x00\x00\x00\xFF\xFF\xFF\x00\x00", "\x00\x00\x00\xFF\xFF\xFF\x00\xFF",
335
- "\x00\x00\x00\xFF\xFF\xFF\xFF\x00", "\x00\x00\x00\xFF\xFF\xFF\xFF\xFF",
336
- "\x00\x00\xFF\x00\x00\x00\x00\x00", "\x00\x00\xFF\x00\x00\x00\x00\xFF",
337
- "\x00\x00\xFF\x00\x00\x00\xFF\x00", "\x00\x00\xFF\x00\x00\x00\xFF\xFF",
338
- "\x00\x00\xFF\x00\x00\xFF\x00\x00", "\x00\x00\xFF\x00\x00\xFF\x00\xFF",
339
- "\x00\x00\xFF\x00\x00\xFF\xFF\x00", "\x00\x00\xFF\x00\x00\xFF\xFF\xFF",
340
- "\x00\x00\xFF\x00\xFF\x00\x00\x00", "\x00\x00\xFF\x00\xFF\x00\x00\xFF",
341
- "\x00\x00\xFF\x00\xFF\x00\xFF\x00", "\x00\x00\xFF\x00\xFF\x00\xFF\xFF",
342
- "\x00\x00\xFF\x00\xFF\xFF\x00\x00", "\x00\x00\xFF\x00\xFF\xFF\x00\xFF",
343
- "\x00\x00\xFF\x00\xFF\xFF\xFF\x00", "\x00\x00\xFF\x00\xFF\xFF\xFF\xFF",
344
- "\x00\x00\xFF\xFF\x00\x00\x00\x00", "\x00\x00\xFF\xFF\x00\x00\x00\xFF",
345
- "\x00\x00\xFF\xFF\x00\x00\xFF\x00", "\x00\x00\xFF\xFF\x00\x00\xFF\xFF",
346
- "\x00\x00\xFF\xFF\x00\xFF\x00\x00", "\x00\x00\xFF\xFF\x00\xFF\x00\xFF",
347
- "\x00\x00\xFF\xFF\x00\xFF\xFF\x00", "\x00\x00\xFF\xFF\x00\xFF\xFF\xFF",
348
- "\x00\x00\xFF\xFF\xFF\x00\x00\x00", "\x00\x00\xFF\xFF\xFF\x00\x00\xFF",
349
- "\x00\x00\xFF\xFF\xFF\x00\xFF\x00", "\x00\x00\xFF\xFF\xFF\x00\xFF\xFF",
350
- "\x00\x00\xFF\xFF\xFF\xFF\x00\x00", "\x00\x00\xFF\xFF\xFF\xFF\x00\xFF",
351
- "\x00\x00\xFF\xFF\xFF\xFF\xFF\x00", "\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF",
352
- "\x00\xFF\x00\x00\x00\x00\x00\x00", "\x00\xFF\x00\x00\x00\x00\x00\xFF",
353
- "\x00\xFF\x00\x00\x00\x00\xFF\x00", "\x00\xFF\x00\x00\x00\x00\xFF\xFF",
354
- "\x00\xFF\x00\x00\x00\xFF\x00\x00", "\x00\xFF\x00\x00\x00\xFF\x00\xFF",
355
- "\x00\xFF\x00\x00\x00\xFF\xFF\x00", "\x00\xFF\x00\x00\x00\xFF\xFF\xFF",
356
- "\x00\xFF\x00\x00\xFF\x00\x00\x00", "\x00\xFF\x00\x00\xFF\x00\x00\xFF",
357
- "\x00\xFF\x00\x00\xFF\x00\xFF\x00", "\x00\xFF\x00\x00\xFF\x00\xFF\xFF",
358
- "\x00\xFF\x00\x00\xFF\xFF\x00\x00", "\x00\xFF\x00\x00\xFF\xFF\x00\xFF",
359
- "\x00\xFF\x00\x00\xFF\xFF\xFF\x00", "\x00\xFF\x00\x00\xFF\xFF\xFF\xFF",
360
- "\x00\xFF\x00\xFF\x00\x00\x00\x00", "\x00\xFF\x00\xFF\x00\x00\x00\xFF",
361
- "\x00\xFF\x00\xFF\x00\x00\xFF\x00", "\x00\xFF\x00\xFF\x00\x00\xFF\xFF",
362
- "\x00\xFF\x00\xFF\x00\xFF\x00\x00", "\x00\xFF\x00\xFF\x00\xFF\x00\xFF",
363
- "\x00\xFF\x00\xFF\x00\xFF\xFF\x00", "\x00\xFF\x00\xFF\x00\xFF\xFF\xFF",
364
- "\x00\xFF\x00\xFF\xFF\x00\x00\x00", "\x00\xFF\x00\xFF\xFF\x00\x00\xFF",
365
- "\x00\xFF\x00\xFF\xFF\x00\xFF\x00", "\x00\xFF\x00\xFF\xFF\x00\xFF\xFF",
366
- "\x00\xFF\x00\xFF\xFF\xFF\x00\x00", "\x00\xFF\x00\xFF\xFF\xFF\x00\xFF",
367
- "\x00\xFF\x00\xFF\xFF\xFF\xFF\x00", "\x00\xFF\x00\xFF\xFF\xFF\xFF\xFF",
368
- "\x00\xFF\xFF\x00\x00\x00\x00\x00", "\x00\xFF\xFF\x00\x00\x00\x00\xFF",
369
- "\x00\xFF\xFF\x00\x00\x00\xFF\x00", "\x00\xFF\xFF\x00\x00\x00\xFF\xFF",
370
- "\x00\xFF\xFF\x00\x00\xFF\x00\x00", "\x00\xFF\xFF\x00\x00\xFF\x00\xFF",
371
- "\x00\xFF\xFF\x00\x00\xFF\xFF\x00", "\x00\xFF\xFF\x00\x00\xFF\xFF\xFF",
372
- "\x00\xFF\xFF\x00\xFF\x00\x00\x00", "\x00\xFF\xFF\x00\xFF\x00\x00\xFF",
373
- "\x00\xFF\xFF\x00\xFF\x00\xFF\x00", "\x00\xFF\xFF\x00\xFF\x00\xFF\xFF",
374
- "\x00\xFF\xFF\x00\xFF\xFF\x00\x00", "\x00\xFF\xFF\x00\xFF\xFF\x00\xFF",
375
- "\x00\xFF\xFF\x00\xFF\xFF\xFF\x00", "\x00\xFF\xFF\x00\xFF\xFF\xFF\xFF",
376
- "\x00\xFF\xFF\xFF\x00\x00\x00\x00", "\x00\xFF\xFF\xFF\x00\x00\x00\xFF",
377
- "\x00\xFF\xFF\xFF\x00\x00\xFF\x00", "\x00\xFF\xFF\xFF\x00\x00\xFF\xFF",
378
- "\x00\xFF\xFF\xFF\x00\xFF\x00\x00", "\x00\xFF\xFF\xFF\x00\xFF\x00\xFF",
379
- "\x00\xFF\xFF\xFF\x00\xFF\xFF\x00", "\x00\xFF\xFF\xFF\x00\xFF\xFF\xFF",
380
- "\x00\xFF\xFF\xFF\xFF\x00\x00\x00", "\x00\xFF\xFF\xFF\xFF\x00\x00\xFF",
381
- "\x00\xFF\xFF\xFF\xFF\x00\xFF\x00", "\x00\xFF\xFF\xFF\xFF\x00\xFF\xFF",
382
- "\x00\xFF\xFF\xFF\xFF\xFF\x00\x00", "\x00\xFF\xFF\xFF\xFF\xFF\x00\xFF",
383
- "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
384
- "\xFF\x00\x00\x00\x00\x00\x00\x00", "\xFF\x00\x00\x00\x00\x00\x00\xFF",
385
- "\xFF\x00\x00\x00\x00\x00\xFF\x00", "\xFF\x00\x00\x00\x00\x00\xFF\xFF",
386
- "\xFF\x00\x00\x00\x00\xFF\x00\x00", "\xFF\x00\x00\x00\x00\xFF\x00\xFF",
387
- "\xFF\x00\x00\x00\x00\xFF\xFF\x00", "\xFF\x00\x00\x00\x00\xFF\xFF\xFF",
388
- "\xFF\x00\x00\x00\xFF\x00\x00\x00", "\xFF\x00\x00\x00\xFF\x00\x00\xFF",
389
- "\xFF\x00\x00\x00\xFF\x00\xFF\x00", "\xFF\x00\x00\x00\xFF\x00\xFF\xFF",
390
- "\xFF\x00\x00\x00\xFF\xFF\x00\x00", "\xFF\x00\x00\x00\xFF\xFF\x00\xFF",
391
- "\xFF\x00\x00\x00\xFF\xFF\xFF\x00", "\xFF\x00\x00\x00\xFF\xFF\xFF\xFF",
392
- "\xFF\x00\x00\xFF\x00\x00\x00\x00", "\xFF\x00\x00\xFF\x00\x00\x00\xFF",
393
- "\xFF\x00\x00\xFF\x00\x00\xFF\x00", "\xFF\x00\x00\xFF\x00\x00\xFF\xFF",
394
- "\xFF\x00\x00\xFF\x00\xFF\x00\x00", "\xFF\x00\x00\xFF\x00\xFF\x00\xFF",
395
- "\xFF\x00\x00\xFF\x00\xFF\xFF\x00", "\xFF\x00\x00\xFF\x00\xFF\xFF\xFF",
396
- "\xFF\x00\x00\xFF\xFF\x00\x00\x00", "\xFF\x00\x00\xFF\xFF\x00\x00\xFF",
397
- "\xFF\x00\x00\xFF\xFF\x00\xFF\x00", "\xFF\x00\x00\xFF\xFF\x00\xFF\xFF",
398
- "\xFF\x00\x00\xFF\xFF\xFF\x00\x00", "\xFF\x00\x00\xFF\xFF\xFF\x00\xFF",
399
- "\xFF\x00\x00\xFF\xFF\xFF\xFF\x00", "\xFF\x00\x00\xFF\xFF\xFF\xFF\xFF",
400
- "\xFF\x00\xFF\x00\x00\x00\x00\x00", "\xFF\x00\xFF\x00\x00\x00\x00\xFF",
401
- "\xFF\x00\xFF\x00\x00\x00\xFF\x00", "\xFF\x00\xFF\x00\x00\x00\xFF\xFF",
402
- "\xFF\x00\xFF\x00\x00\xFF\x00\x00", "\xFF\x00\xFF\x00\x00\xFF\x00\xFF",
403
- "\xFF\x00\xFF\x00\x00\xFF\xFF\x00", "\xFF\x00\xFF\x00\x00\xFF\xFF\xFF",
404
- "\xFF\x00\xFF\x00\xFF\x00\x00\x00", "\xFF\x00\xFF\x00\xFF\x00\x00\xFF",
405
- "\xFF\x00\xFF\x00\xFF\x00\xFF\x00", "\xFF\x00\xFF\x00\xFF\x00\xFF\xFF",
406
- "\xFF\x00\xFF\x00\xFF\xFF\x00\x00", "\xFF\x00\xFF\x00\xFF\xFF\x00\xFF",
407
- "\xFF\x00\xFF\x00\xFF\xFF\xFF\x00", "\xFF\x00\xFF\x00\xFF\xFF\xFF\xFF",
408
- "\xFF\x00\xFF\xFF\x00\x00\x00\x00", "\xFF\x00\xFF\xFF\x00\x00\x00\xFF",
409
- "\xFF\x00\xFF\xFF\x00\x00\xFF\x00", "\xFF\x00\xFF\xFF\x00\x00\xFF\xFF",
410
- "\xFF\x00\xFF\xFF\x00\xFF\x00\x00", "\xFF\x00\xFF\xFF\x00\xFF\x00\xFF",
411
- "\xFF\x00\xFF\xFF\x00\xFF\xFF\x00", "\xFF\x00\xFF\xFF\x00\xFF\xFF\xFF",
412
- "\xFF\x00\xFF\xFF\xFF\x00\x00\x00", "\xFF\x00\xFF\xFF\xFF\x00\x00\xFF",
413
- "\xFF\x00\xFF\xFF\xFF\x00\xFF\x00", "\xFF\x00\xFF\xFF\xFF\x00\xFF\xFF",
414
- "\xFF\x00\xFF\xFF\xFF\xFF\x00\x00", "\xFF\x00\xFF\xFF\xFF\xFF\x00\xFF",
415
- "\xFF\x00\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\x00\xFF\xFF\xFF\xFF\xFF\xFF",
416
- "\xFF\xFF\x00\x00\x00\x00\x00\x00", "\xFF\xFF\x00\x00\x00\x00\x00\xFF",
417
- "\xFF\xFF\x00\x00\x00\x00\xFF\x00", "\xFF\xFF\x00\x00\x00\x00\xFF\xFF",
418
- "\xFF\xFF\x00\x00\x00\xFF\x00\x00", "\xFF\xFF\x00\x00\x00\xFF\x00\xFF",
419
- "\xFF\xFF\x00\x00\x00\xFF\xFF\x00", "\xFF\xFF\x00\x00\x00\xFF\xFF\xFF",
420
- "\xFF\xFF\x00\x00\xFF\x00\x00\x00", "\xFF\xFF\x00\x00\xFF\x00\x00\xFF",
421
- "\xFF\xFF\x00\x00\xFF\x00\xFF\x00", "\xFF\xFF\x00\x00\xFF\x00\xFF\xFF",
422
- "\xFF\xFF\x00\x00\xFF\xFF\x00\x00", "\xFF\xFF\x00\x00\xFF\xFF\x00\xFF",
423
- "\xFF\xFF\x00\x00\xFF\xFF\xFF\x00", "\xFF\xFF\x00\x00\xFF\xFF\xFF\xFF",
424
- "\xFF\xFF\x00\xFF\x00\x00\x00\x00", "\xFF\xFF\x00\xFF\x00\x00\x00\xFF",
425
- "\xFF\xFF\x00\xFF\x00\x00\xFF\x00", "\xFF\xFF\x00\xFF\x00\x00\xFF\xFF",
426
- "\xFF\xFF\x00\xFF\x00\xFF\x00\x00", "\xFF\xFF\x00\xFF\x00\xFF\x00\xFF",
427
- "\xFF\xFF\x00\xFF\x00\xFF\xFF\x00", "\xFF\xFF\x00\xFF\x00\xFF\xFF\xFF",
428
- "\xFF\xFF\x00\xFF\xFF\x00\x00\x00", "\xFF\xFF\x00\xFF\xFF\x00\x00\xFF",
429
- "\xFF\xFF\x00\xFF\xFF\x00\xFF\x00", "\xFF\xFF\x00\xFF\xFF\x00\xFF\xFF",
430
- "\xFF\xFF\x00\xFF\xFF\xFF\x00\x00", "\xFF\xFF\x00\xFF\xFF\xFF\x00\xFF",
431
- "\xFF\xFF\x00\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\x00\xFF\xFF\xFF\xFF\xFF",
432
- "\xFF\xFF\xFF\x00\x00\x00\x00\x00", "\xFF\xFF\xFF\x00\x00\x00\x00\xFF",
433
- "\xFF\xFF\xFF\x00\x00\x00\xFF\x00", "\xFF\xFF\xFF\x00\x00\x00\xFF\xFF",
434
- "\xFF\xFF\xFF\x00\x00\xFF\x00\x00", "\xFF\xFF\xFF\x00\x00\xFF\x00\xFF",
435
- "\xFF\xFF\xFF\x00\x00\xFF\xFF\x00", "\xFF\xFF\xFF\x00\x00\xFF\xFF\xFF",
436
- "\xFF\xFF\xFF\x00\xFF\x00\x00\x00", "\xFF\xFF\xFF\x00\xFF\x00\x00\xFF",
437
- "\xFF\xFF\xFF\x00\xFF\x00\xFF\x00", "\xFF\xFF\xFF\x00\xFF\x00\xFF\xFF",
438
- "\xFF\xFF\xFF\x00\xFF\xFF\x00\x00", "\xFF\xFF\xFF\x00\xFF\xFF\x00\xFF",
439
- "\xFF\xFF\xFF\x00\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\x00\xFF\xFF\xFF\xFF",
440
- "\xFF\xFF\xFF\xFF\x00\x00\x00\x00", "\xFF\xFF\xFF\xFF\x00\x00\x00\xFF",
441
- "\xFF\xFF\xFF\xFF\x00\x00\xFF\x00", "\xFF\xFF\xFF\xFF\x00\x00\xFF\xFF",
442
- "\xFF\xFF\xFF\xFF\x00\xFF\x00\x00", "\xFF\xFF\xFF\xFF\x00\xFF\x00\xFF",
443
- "\xFF\xFF\xFF\xFF\x00\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\x00\xFF\xFF\xFF",
444
- "\xFF\xFF\xFF\xFF\xFF\x00\x00\x00", "\xFF\xFF\xFF\xFF\xFF\x00\x00\xFF",
445
- "\xFF\xFF\xFF\xFF\xFF\x00\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\x00\xFF\xFF",
446
- "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\x00\xFF",
447
- "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
448
- );
449
-
450
- /**
451
- * IP mapping helper table.
452
- *
453
- * Indexing this table with each source byte performs the initial bit permutation.
454
- *
455
- * @var Array
456
- * @access private
457
- */
458
- var $ipmap = array(
459
- 0x00, 0x10, 0x01, 0x11, 0x20, 0x30, 0x21, 0x31,
460
- 0x02, 0x12, 0x03, 0x13, 0x22, 0x32, 0x23, 0x33,
461
- 0x40, 0x50, 0x41, 0x51, 0x60, 0x70, 0x61, 0x71,
462
- 0x42, 0x52, 0x43, 0x53, 0x62, 0x72, 0x63, 0x73,
463
- 0x04, 0x14, 0x05, 0x15, 0x24, 0x34, 0x25, 0x35,
464
- 0x06, 0x16, 0x07, 0x17, 0x26, 0x36, 0x27, 0x37,
465
- 0x44, 0x54, 0x45, 0x55, 0x64, 0x74, 0x65, 0x75,
466
- 0x46, 0x56, 0x47, 0x57, 0x66, 0x76, 0x67, 0x77,
467
- 0x80, 0x90, 0x81, 0x91, 0xA0, 0xB0, 0xA1, 0xB1,
468
- 0x82, 0x92, 0x83, 0x93, 0xA2, 0xB2, 0xA3, 0xB3,
469
- 0xC0, 0xD0, 0xC1, 0xD1, 0xE0, 0xF0, 0xE1, 0xF1,
470
- 0xC2, 0xD2, 0xC3, 0xD3, 0xE2, 0xF2, 0xE3, 0xF3,
471
- 0x84, 0x94, 0x85, 0x95, 0xA4, 0xB4, 0xA5, 0xB5,
472
- 0x86, 0x96, 0x87, 0x97, 0xA6, 0xB6, 0xA7, 0xB7,
473
- 0xC4, 0xD4, 0xC5, 0xD5, 0xE4, 0xF4, 0xE5, 0xF5,
474
- 0xC6, 0xD6, 0xC7, 0xD7, 0xE6, 0xF6, 0xE7, 0xF7,
475
- 0x08, 0x18, 0x09, 0x19, 0x28, 0x38, 0x29, 0x39,
476
- 0x0A, 0x1A, 0x0B, 0x1B, 0x2A, 0x3A, 0x2B, 0x3B,
477
- 0x48, 0x58, 0x49, 0x59, 0x68, 0x78, 0x69, 0x79,
478
- 0x4A, 0x5A, 0x4B, 0x5B, 0x6A, 0x7A, 0x6B, 0x7B,
479
- 0x0C, 0x1C, 0x0D, 0x1D, 0x2C, 0x3C, 0x2D, 0x3D,
480
- 0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F,
481
- 0x4C, 0x5C, 0x4D, 0x5D, 0x6C, 0x7C, 0x6D, 0x7D,
482
- 0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F,
483
- 0x88, 0x98, 0x89, 0x99, 0xA8, 0xB8, 0xA9, 0xB9,
484
- 0x8A, 0x9A, 0x8B, 0x9B, 0xAA, 0xBA, 0xAB, 0xBB,
485
- 0xC8, 0xD8, 0xC9, 0xD9, 0xE8, 0xF8, 0xE9, 0xF9,
486
- 0xCA, 0xDA, 0xCB, 0xDB, 0xEA, 0xFA, 0xEB, 0xFB,
487
- 0x8C, 0x9C, 0x8D, 0x9D, 0xAC, 0xBC, 0xAD, 0xBD,
488
- 0x8E, 0x9E, 0x8F, 0x9F, 0xAE, 0xBE, 0xAF, 0xBF,
489
- 0xCC, 0xDC, 0xCD, 0xDD, 0xEC, 0xFC, 0xED, 0xFD,
490
- 0xCE, 0xDE, 0xCF, 0xDF, 0xEE, 0xFE, 0xEF, 0xFF
491
- );
492
-
493
- /**
494
- * Inverse IP mapping helper table.
495
- * Indexing this table with a byte value reverses the bit order.
496
- *
497
- * @var Array
498
- * @access private
499
- */
500
- var $invipmap = array(
501
- 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
502
- 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
503
- 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
504
- 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
505
- 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
506
- 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
507
- 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
508
- 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
509
- 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
510
- 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
511
- 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
512
- 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
513
- 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
514
- 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
515
- 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
516
- 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
517
- 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
518
- 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
519
- 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
520
- 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
521
- 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
522
- 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
523
- 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
524
- 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
525
- 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
526
- 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
527
- 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
528
- 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
529
- 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
530
- 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
531
- 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
532
- 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
533
- );
534
-
535
- /**
536
- * Pre-permuted S-box1
537
- *
538
- * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the
539
- * P table: concatenation can then be replaced by exclusive ORs.
540
- *
541
- * @var Array
542
- * @access private
543
- */
544
- var $sbox1 = array(
545
- 0x00808200, 0x00000000, 0x00008000, 0x00808202,
546
- 0x00808002, 0x00008202, 0x00000002, 0x00008000,
547
- 0x00000200, 0x00808200, 0x00808202, 0x00000200,
548
- 0x00800202, 0x00808002, 0x00800000, 0x00000002,
549
- 0x00000202, 0x00800200, 0x00800200, 0x00008200,
550
- 0x00008200, 0x00808000, 0x00808000, 0x00800202,
551
- 0x00008002, 0x00800002, 0x00800002, 0x00008002,
552
- 0x00000000, 0x00000202, 0x00008202, 0x00800000,
553
- 0x00008000, 0x00808202, 0x00000002, 0x00808000,
554
- 0x00808200, 0x00800000, 0x00800000, 0x00000200,
555
- 0x00808002, 0x00008000, 0x00008200, 0x00800002,
556
- 0x00000200, 0x00000002, 0x00800202, 0x00008202,
557
- 0x00808202, 0x00008002, 0x00808000, 0x00800202,
558
- 0x00800002, 0x00000202, 0x00008202, 0x00808200,
559
- 0x00000202, 0x00800200, 0x00800200, 0x00000000,
560
- 0x00008002, 0x00008200, 0x00000000, 0x00808002
561
- );
562
-
563
- /**
564
- * Pre-permuted S-box2
565
- *
566
- * @var Array
567
- * @access private
568
- */
569
- var $sbox2 = array(
570
- 0x40084010, 0x40004000, 0x00004000, 0x00084010,
571
- 0x00080000, 0x00000010, 0x40080010, 0x40004010,
572
- 0x40000010, 0x40084010, 0x40084000, 0x40000000,
573
- 0x40004000, 0x00080000, 0x00000010, 0x40080010,
574
- 0x00084000, 0x00080010, 0x40004010, 0x00000000,
575
- 0x40000000, 0x00004000, 0x00084010, 0x40080000,
576
- 0x00080010, 0x40000010, 0x00000000, 0x00084000,
577
- 0x00004010, 0x40084000, 0x40080000, 0x00004010,
578
- 0x00000000, 0x00084010, 0x40080010, 0x00080000,
579
- 0x40004010, 0x40080000, 0x40084000, 0x00004000,
580
- 0x40080000, 0x40004000, 0x00000010, 0x40084010,
581
- 0x00084010, 0x00000010, 0x00004000, 0x40000000,
582
- 0x00004010, 0x40084000, 0x00080000, 0x40000010,
583
- 0x00080010, 0x40004010, 0x40000010, 0x00080010,
584
- 0x00084000, 0x00000000, 0x40004000, 0x00004010,
585
- 0x40000000, 0x40080010, 0x40084010, 0x00084000
586
- );
587
-
588
- /**
589
- * Pre-permuted S-box3
590
- *
591
- * @var Array
592
- * @access private
593
- */
594
- var $sbox3 = array(
595
- 0x00000104, 0x04010100, 0x00000000, 0x04010004,
596
- 0x04000100, 0x00000000, 0x00010104, 0x04000100,
597
- 0x00010004, 0x04000004, 0x04000004, 0x00010000,
598
- 0x04010104, 0x00010004, 0x04010000, 0x00000104,
599
- 0x04000000, 0x00000004, 0x04010100, 0x00000100,
600
- 0x00010100, 0x04010000, 0x04010004, 0x00010104,
601
- 0x04000104, 0x00010100, 0x00010000, 0x04000104,
602
- 0x00000004, 0x04010104, 0x00000100, 0x04000000,
603
- 0x04010100, 0x04000000, 0x00010004, 0x00000104,
604
- 0x00010000, 0x04010100, 0x04000100, 0x00000000,
605
- 0x00000100, 0x00010004, 0x04010104, 0x04000100,
606
- 0x04000004, 0x00000100, 0x00000000, 0x04010004,
607
- 0x04000104, 0x00010000, 0x04000000, 0x04010104,
608
- 0x00000004, 0x00010104, 0x00010100, 0x04000004,
609
- 0x04010000, 0x04000104, 0x00000104, 0x04010000,
610
- 0x00010104, 0x00000004, 0x04010004, 0x00010100
611
- );
612
-
613
- /**
614
- * Pre-permuted S-box4
615
- *
616
- * @var Array
617
- * @access private
618
- */
619
- var $sbox4 = array(
620
- 0x80401000, 0x80001040, 0x80001040, 0x00000040,
621
- 0x00401040, 0x80400040, 0x80400000, 0x80001000,
622
- 0x00000000, 0x00401000, 0x00401000, 0x80401040,
623
- 0x80000040, 0x00000000, 0x00400040, 0x80400000,
624
- 0x80000000, 0x00001000, 0x00400000, 0x80401000,
625
- 0x00000040, 0x00400000, 0x80001000, 0x00001040,
626
- 0x80400040, 0x80000000, 0x00001040, 0x00400040,
627
- 0x00001000, 0x00401040, 0x80401040, 0x80000040,
628
- 0x00400040, 0x80400000, 0x00401000, 0x80401040,
629
- 0x80000040, 0x00000000, 0x00000000, 0x00401000,
630
- 0x00001040, 0x00400040, 0x80400040, 0x80000000,
631
- 0x80401000, 0x80001040, 0x80001040, 0x00000040,
632
- 0x80401040, 0x80000040, 0x80000000, 0x00001000,
633
- 0x80400000, 0x80001000, 0x00401040, 0x80400040,
634
- 0x80001000, 0x00001040, 0x00400000, 0x80401000,
635
- 0x00000040, 0x00400000, 0x00001000, 0x00401040
636
- );
637
-
638
- /**
639
- * Pre-permuted S-box5
640
- *
641
- * @var Array
642
- * @access private
643
- */
644
- var $sbox5 = array(
645
- 0x00000080, 0x01040080, 0x01040000, 0x21000080,
646
- 0x00040000, 0x00000080, 0x20000000, 0x01040000,
647
- 0x20040080, 0x00040000, 0x01000080, 0x20040080,
648
- 0x21000080, 0x21040000, 0x00040080, 0x20000000,
649
- 0x01000000, 0x20040000, 0x20040000, 0x00000000,
650
- 0x20000080, 0x21040080, 0x21040080, 0x01000080,
651
- 0x21040000, 0x20000080, 0x00000000, 0x21000000,
652
- 0x01040080, 0x01000000, 0x21000000, 0x00040080,
653
- 0x00040000, 0x21000080, 0x00000080, 0x01000000,
654
- 0x20000000, 0x01040000, 0x21000080, 0x20040080,
655
- 0x01000080, 0x20000000, 0x21040000, 0x01040080,
656
- 0x20040080, 0x00000080, 0x01000000, 0x21040000,
657
- 0x21040080, 0x00040080, 0x21000000, 0x21040080,
658
- 0x01040000, 0x00000000, 0x20040000, 0x21000000,
659
- 0x00040080, 0x01000080, 0x20000080, 0x00040000,
660
- 0x00000000, 0x20040000, 0x01040080, 0x20000080
661
- );
662
-
663
- /**
664
- * Pre-permuted S-box6
665
- *
666
- * @var Array
667
- * @access private
668
- */
669
- var $sbox6 = array(
670
- 0x10000008, 0x10200000, 0x00002000, 0x10202008,
671
- 0x10200000, 0x00000008, 0x10202008, 0x00200000,
672
- 0x10002000, 0x00202008, 0x00200000, 0x10000008,
673
- 0x00200008, 0x10002000, 0x10000000, 0x00002008,
674
- 0x00000000, 0x00200008, 0x10002008, 0x00002000,
675
- 0x00202000, 0x10002008, 0x00000008, 0x10200008,
676
- 0x10200008, 0x00000000, 0x00202008, 0x10202000,
677
- 0x00002008, 0x00202000, 0x10202000, 0x10000000,
678
- 0x10002000, 0x00000008, 0x10200008, 0x00202000,
679
- 0x10202008, 0x00200000, 0x00002008, 0x10000008,
680
- 0x00200000, 0x10002000, 0x10000000, 0x00002008,
681
- 0x10000008, 0x10202008, 0x00202000, 0x10200000,
682
- 0x00202008, 0x10202000, 0x00000000, 0x10200008,
683
- 0x00000008, 0x00002000, 0x10200000, 0x00202008,
684
- 0x00002000, 0x00200008, 0x10002008, 0x00000000,
685
- 0x10202000, 0x10000000, 0x00200008, 0x10002008
686
- );
687
-
688
- /**
689
- * Pre-permuted S-box7
690
- *
691
- * @var Array
692
- * @access private
693
- */
694
- var $sbox7 = array(
695
- 0x00100000, 0x02100001, 0x02000401, 0x00000000,
696
- 0x00000400, 0x02000401, 0x00100401, 0x02100400,
697
- 0x02100401, 0x00100000, 0x00000000, 0x02000001,
698
- 0x00000001, 0x02000000, 0x02100001, 0x00000401,
699
- 0x02000400, 0x00100401, 0x00100001, 0x02000400,
700
- 0x02000001, 0x02100000, 0x02100400, 0x00100001,
701
- 0x02100000, 0x00000400, 0x00000401, 0x02100401,
702
- 0x00100400, 0x00000001, 0x02000000, 0x00100400,
703
- 0x02000000, 0x00100400, 0x00100000, 0x02000401,
704
- 0x02000401, 0x02100001, 0x02100001, 0x00000001,
705
- 0x00100001, 0x02000000, 0x02000400, 0x00100000,
706
- 0x02100400, 0x00000401, 0x00100401, 0x02100400,
707
- 0x00000401, 0x02000001, 0x02100401, 0x02100000,
708
- 0x00100400, 0x00000000, 0x00000001, 0x02100401,
709
- 0x00000000, 0x00100401, 0x02100000, 0x00000400,
710
- 0x02000001, 0x02000400, 0x00000400, 0x00100001
711
- );
712
-
713
- /**
714
- * Pre-permuted S-box8
715
- *
716
- * @var Array
717
- * @access private
718
- */
719
- var $sbox8 = array(
720
- 0x08000820, 0x00000800, 0x00020000, 0x08020820,
721
- 0x08000000, 0x08000820, 0x00000020, 0x08000000,
722
- 0x00020020, 0x08020000, 0x08020820, 0x00020800,
723
- 0x08020800, 0x00020820, 0x00000800, 0x00000020,
724
- 0x08020000, 0x08000020, 0x08000800, 0x00000820,
725
- 0x00020800, 0x00020020, 0x08020020, 0x08020800,
726
- 0x00000820, 0x00000000, 0x00000000, 0x08020020,
727
- 0x08000020, 0x08000800, 0x00020820, 0x00020000,
728
- 0x00020820, 0x00020000, 0x08020800, 0x00000800,
729
- 0x00000020, 0x08020020, 0x00000800, 0x00020820,
730
- 0x08000800, 0x00000020, 0x08000020, 0x08020000,
731
- 0x08020020, 0x08000000, 0x00020000, 0x08000820,
732
- 0x00000000, 0x08020820, 0x00020020, 0x08000020,
733
- 0x08020000, 0x08000800, 0x08000820, 0x00000000,
734
- 0x08020820, 0x00020800, 0x00020800, 0x00000820,
735
- 0x00000820, 0x00020020, 0x08000000, 0x08020800
736
- );
737
-
738
- /**
739
- * Default Constructor.
740
- *
741
- * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
742
- * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used.
743
- *
744
- * @param optional Integer $mode
745
- * @return Crypt_DES
746
- * @access public
747
- */
748
- function Crypt_DES($mode = CRYPT_DES_MODE_CBC)
749
- {
750
- if ( !defined('CRYPT_DES_MODE') ) {
751
- switch (true) {
752
- case extension_loaded('mcrypt') && in_array('des', mcrypt_list_algorithms()):
753
- define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
754
- break;
755
- default:
756
- define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
757
- }
758
- }
759
-
760
- switch ( CRYPT_DES_MODE ) {
761
- case CRYPT_DES_MODE_MCRYPT:
762
- switch ($mode) {
763
- case CRYPT_DES_MODE_ECB:
764
- $this->paddable = true;
765
- $this->mode = MCRYPT_MODE_ECB;
766
- break;
767
- case CRYPT_DES_MODE_CTR:
768
- $this->mode = 'ctr';
769
- //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_DES_MODE_CTR;
770
- break;
771
- case CRYPT_DES_MODE_CFB:
772
- $this->mode = 'ncfb';
773
- $this->ecb = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_ECB, '');
774
- break;
775
- case CRYPT_DES_MODE_OFB:
776
- $this->mode = MCRYPT_MODE_NOFB;
777
- break;
778
- case CRYPT_DES_MODE_CBC:
779
- default:
780
- $this->paddable = true;
781
- $this->mode = MCRYPT_MODE_CBC;
782
- }
783
- $this->enmcrypt = mcrypt_module_open(MCRYPT_DES, '', $this->mode, '');
784
- $this->demcrypt = mcrypt_module_open(MCRYPT_DES, '', $this->mode, '');
785
-
786
- break;
787
- default:
788
- switch ($mode) {
789
- case CRYPT_DES_MODE_ECB:
790
- case CRYPT_DES_MODE_CBC:
791
- $this->paddable = true;
792
- $this->mode = $mode;
793
- break;
794
- case CRYPT_DES_MODE_CTR:
795
- case CRYPT_DES_MODE_CFB:
796
- case CRYPT_DES_MODE_OFB:
797
- $this->mode = $mode;
798
- break;
799
- default:
800
- $this->paddable = true;
801
- $this->mode = CRYPT_DES_MODE_CBC;
802
- }
803
- if (function_exists('create_function') && is_callable('create_function')) {
804
- $this->inline_crypt_setup();
805
- $this->use_inline_crypt = true;
806
- }
807
- }
808
- }
809
-
810
- /**
811
- * Sets the key.
812
- *
813
- * Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we
814
- * only use the first eight, if $key has more then eight characters in it, and pad $key with the
815
- * null byte if it is less then eight characters long.
816
- *
817
- * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
818
- *
819
- * If the key is not explicitly set, it'll be assumed to be all zero's.
820
- *
821
- * @access public
822
- * @param String $key
823
- */
824
- function setKey($key)
825
- {
826
- $this->keys = ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) ? str_pad(substr($key, 0, 8), 8, chr(0)) : $this->_prepareKey($key);
827
- $this->enchanged = true;
828
- $this->dechanged = true;
829
- }
830
-
831
- /**
832
- * Sets the password.
833
- *
834
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
835
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
836
- * $hash, $salt, $count
837
- *
838
- * @param String $password
839
- * @param optional String $method
840
- * @access public
841
- */
842
- function setPassword($password, $method = 'pbkdf2')
843
- {
844
- $key = '';
845
-
846
- switch ($method) {
847
- default: // 'pbkdf2'
848
- list(, , $hash, $salt, $count) = func_get_args();
849
- if (!isset($hash)) {
850
- $hash = 'sha1';
851
- }
852
- // WPA and WPA2 use the SSID as the salt
853
- if (!isset($salt)) {
854
- $salt = 'phpseclib/salt';
855
- }
856
- // RFC2898#section-4.2 uses 1,000 iterations by default
857
- // WPA and WPA2 use 4,096.
858
- if (!isset($count)) {
859
- $count = 1000;
860
- }
861
-
862
- if (!class_exists('Crypt_Hash')) {
863
- require_once('Crypt/Hash.php');
864
- }
865
-
866
- $i = 1;
867
- while (strlen($key) < 8) { // $dkLen == 8
868
- //$dk.= $this->_pbkdf($password, $salt, $count, $i++);
869
- $hmac = new Crypt_Hash();
870
- $hmac->setHash($hash);
871
- $hmac->setKey($password);
872
- $f = $u = $hmac->hash($salt . pack('N', $i++));
873
- for ($j = 2; $j <= $count; $j++) {
874
- $u = $hmac->hash($u);
875
- $f^= $u;
876
- }
877
- $key.= $f;
878
- }
879
- }
880
-
881
- $this->setKey($key);
882
- }
883
-
884
- /**
885
- * Sets the initialization vector. (optional)
886
- *
887
- * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
888
- * to be all zero's.
889
- *
890
- * @access public
891
- * @param String $iv
892
- */
893
- function setIV($iv)
894
- {
895
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
896
- $this->enchanged = true;
897
- $this->dechanged = true;
898
- }
899
-
900
- /**
901
- * Generate CTR XOR encryption key
902
- *
903
- * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
904
- * plaintext / ciphertext in CTR mode.
905
- *
906
- * @see Crypt_DES::decrypt()
907
- * @see Crypt_DES::encrypt()
908
- * @access public
909
- * @param String $iv
910
- */
911
- function _generate_xor(&$iv)
912
- {
913
- $xor = $iv;
914
- for ($j = 4; $j <= 8; $j+=4) {
915
- $temp = substr($iv, -$j, 4);
916
- switch ($temp) {
917
- case "\xFF\xFF\xFF\xFF":
918
- $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
919
- break;
920
- case "\x7F\xFF\xFF\xFF":
921
- $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
922
- break 2;
923
- default:
924
- extract(unpack('Ncount', $temp));
925
- $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
926
- break 2;
927
- }
928
- }
929
-
930
- return $xor;
931
- }
932
-
933
- /**
934
- * Encrypts a message.
935
- *
936
- * $plaintext will be padded with up to 8 additional bytes. Other DES implementations may or may not pad in the
937
- * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
938
- * URL:
939
- *
940
- * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
941
- *
942
- * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
943
- * strlen($plaintext) will still need to be a multiple of 8, however, arbitrary values can be added to make it that
944
- * length.
945
- *
946
- * @see Crypt_DES::decrypt()
947
- * @access public
948
- * @param String $plaintext
949
- */
950
- function encrypt($plaintext)
951
- {
952
- if ($this->paddable) {
953
- $plaintext = $this->_pad($plaintext);
954
- }
955
-
956
- if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
957
- if ($this->enchanged) {
958
- mcrypt_generic_init($this->enmcrypt, $this->keys, $this->encryptIV);
959
- if ($this->mode == 'ncfb') {
960
- mcrypt_generic_init($this->ecb, $this->keys, "\0\0\0\0\0\0\0\0");
961
- }
962
- $this->enchanged = false;
963
- }
964
-
965
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
966
- $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
967
- } else {
968
- $iv = &$this->encryptIV;
969
- $pos = &$this->enbuffer['pos'];
970
- $len = strlen($plaintext);
971
- $ciphertext = '';
972
- $i = 0;
973
- if ($pos) {
974
- $orig_pos = $pos;
975
- $max = 8 - $pos;
976
- if ($len >= $max) {
977
- $i = $max;
978
- $len-= $max;
979
- $pos = 0;
980
- } else {
981
- $i = $len;
982
- $pos+= $len;
983
- $len = 0;
984
- }
985
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
986
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
987
- $this->enbuffer['enmcrypt_init'] = true;
988
- }
989
- if ($len >= 8) {
990
- if ($this->enbuffer['enmcrypt_init'] === false || $len > 600) {
991
- if ($this->enbuffer['enmcrypt_init'] === true) {
992
- mcrypt_generic_init($this->enmcrypt, $this->keys, $iv);
993
- $this->enbuffer['enmcrypt_init'] = false;
994
- }
995
- $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 8));
996
- $iv = substr($ciphertext, -8);
997
- $len%= 8;
998
- } else {
999
- while ($len >= 8) {
1000
- $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 8);
1001
- $ciphertext.= $iv;
1002
- $len-= 8;
1003
- $i+= 8;
1004
- }
1005
- }
1006
- }
1007
- if ($len) {
1008
- $iv = mcrypt_generic($this->ecb, $iv);
1009
- $block = $iv ^ substr($plaintext, -$len);
1010
- $iv = substr_replace($iv, $block, 0, $len);
1011
- $ciphertext.= $block;
1012
- $pos = $len;
1013
- }
1014
- return $ciphertext;
1015
- }
1016
-
1017
- if (!$this->continuousBuffer) {
1018
- mcrypt_generic_init($this->enmcrypt, $this->keys, $this->encryptIV);
1019
- }
1020
-
1021
- return $ciphertext;
1022
- }
1023
-
1024
- if (!is_array($this->keys)) {
1025
- $this->keys = $this->_prepareKey("\0\0\0\0\0\0\0\0");
1026
- }
1027
-
1028
- if ($this->use_inline_crypt) {
1029
- $inline = $this->inline_crypt;
1030
- return $inline('encrypt', $this, $plaintext);
1031
- }
1032
-
1033
- $buffer = &$this->enbuffer;
1034
- $continuousBuffer = $this->continuousBuffer;
1035
- $ciphertext = '';
1036
- switch ($this->mode) {
1037
- case CRYPT_DES_MODE_ECB:
1038
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1039
- $ciphertext.= $this->_processBlock(substr($plaintext, $i, 8), CRYPT_DES_ENCRYPT);
1040
- }
1041
- break;
1042
- case CRYPT_DES_MODE_CBC:
1043
- $xor = $this->encryptIV;
1044
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1045
- $block = substr($plaintext, $i, 8);
1046
- $block = $this->_processBlock($block ^ $xor, CRYPT_DES_ENCRYPT);
1047
- $xor = $block;
1048
- $ciphertext.= $block;
1049
- }
1050
- if ($this->continuousBuffer) {
1051
- $this->encryptIV = $xor;
1052
- }
1053
- break;
1054
- case CRYPT_DES_MODE_CTR:
1055
- $xor = $this->encryptIV;
1056
- if (strlen($buffer['encrypted'])) {
1057
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1058
- $block = substr($plaintext, $i, 8);
1059
- if (strlen($block) > strlen($buffer['encrypted'])) {
1060
- $buffer['encrypted'].= $this->_processBlock($this->_generate_xor($xor), CRYPT_DES_ENCRYPT);
1061
- }
1062
- $key = $this->_string_shift($buffer['encrypted']);
1063
- $ciphertext.= $block ^ $key;
1064
- }
1065
- } else {
1066
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1067
- $block = substr($plaintext, $i, 8);
1068
- $key = $this->_processBlock($this->_generate_xor($xor), CRYPT_DES_ENCRYPT);
1069
- $ciphertext.= $block ^ $key;
1070
- }
1071
- }
1072
- if ($this->continuousBuffer) {
1073
- $this->encryptIV = $xor;
1074
- if ($start = strlen($plaintext) & 7) {
1075
- $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
1076
- }
1077
- }
1078
- break;
1079
- case CRYPT_DES_MODE_CFB:
1080
- if ($this->continuousBuffer) {
1081
- $iv = &$this->encryptIV;
1082
- $pos = &$buffer['pos'];
1083
- } else {
1084
- $iv = $this->encryptIV;
1085
- $pos = 0;
1086
- }
1087
- $len = strlen($plaintext);
1088
- $i = 0;
1089
- if ($pos) {
1090
- $orig_pos = $pos;
1091
- $max = 8 - $pos;
1092
- if ($len >= $max) {
1093
- $i = $max;
1094
- $len-= $max;
1095
- $pos = 0;
1096
- } else {
1097
- $i = $len;
1098
- $pos+= $len;
1099
- $len = 0;
1100
- }
1101
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
1102
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
1103
- }
1104
- while ($len >= 8) {
1105
- $iv = $this->_processBlock($iv, CRYPT_DES_ENCRYPT) ^ substr($plaintext, $i, 8);
1106
- $ciphertext.= $iv;
1107
- $len-= 8;
1108
- $i+= 8;
1109
- }
1110
- if ($len) {
1111
- $iv = $this->_processBlock($iv, CRYPT_DES_ENCRYPT);
1112
- $block = $iv ^ substr($plaintext, $i);
1113
- $iv = substr_replace($iv, $block, 0, $len);
1114
- $ciphertext.= $block;
1115
- $pos = $len;
1116
- }
1117
- return $ciphertext;
1118
- case CRYPT_DES_MODE_OFB:
1119
- $xor = $this->encryptIV;
1120
- if (strlen($buffer['xor'])) {
1121
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1122
- $block = substr($plaintext, $i, 8);
1123
- if (strlen($block) > strlen($buffer['xor'])) {
1124
- $xor = $this->_processBlock($xor, CRYPT_DES_ENCRYPT);
1125
- $buffer['xor'].= $xor;
1126
- }
1127
- $key = $this->_string_shift($buffer['xor']);
1128
- $ciphertext.= $block ^ $key;
1129
- }
1130
- } else {
1131
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
1132
- $xor = $this->_processBlock($xor, CRYPT_DES_ENCRYPT);
1133
- $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
1134
- }
1135
- $key = $xor;
1136
- }
1137
- if ($this->continuousBuffer) {
1138
- $this->encryptIV = $xor;
1139
- if ($start = strlen($plaintext) & 7) {
1140
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1141
- }
1142
- }
1143
- }
1144
-
1145
- return $ciphertext;
1146
- }
1147
-
1148
- /**
1149
- * Decrypts a message.
1150
- *
1151
- * If strlen($ciphertext) is not a multiple of 8, null bytes will be added to the end of the string until it is.
1152
- *
1153
- * @see Crypt_DES::encrypt()
1154
- * @access public
1155
- * @param String $ciphertext
1156
- */
1157
- function decrypt($ciphertext)
1158
- {
1159
- if ($this->paddable) {
1160
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
1161
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
1162
- $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
1163
- }
1164
-
1165
- if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
1166
- if ($this->dechanged) {
1167
- mcrypt_generic_init($this->demcrypt, $this->keys, $this->decryptIV);
1168
- if ($this->mode == 'ncfb') {
1169
- mcrypt_generic_init($this->ecb, $this->keys, "\0\0\0\0\0\0\0\0");
1170
- }
1171
- $this->dechanged = false;
1172
- }
1173
-
1174
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
1175
- $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
1176
- } else {
1177
- $iv = &$this->decryptIV;
1178
- $pos = &$this->debuffer['pos'];
1179
- $len = strlen($ciphertext);
1180
- $plaintext = '';
1181
- $i = 0;
1182
- if ($pos) {
1183
- $orig_pos = $pos;
1184
- $max = 8 - $pos;
1185
- if ($len >= $max) {
1186
- $i = $max;
1187
- $len-= $max;
1188
- $pos = 0;
1189
- } else {
1190
- $i = $len;
1191
- $pos+= $len;
1192
- $len = 0;
1193
- }
1194
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1195
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1196
- }
1197
- if ($len >= 8) {
1198
- $cb = substr($ciphertext, $i, $len - $len % 8);
1199
- $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
1200
- $iv = substr($cb, -8);
1201
- $len%= 8;
1202
- }
1203
- if ($len) {
1204
- $iv = mcrypt_generic($this->ecb, $iv);
1205
- $plaintext.= $iv ^ substr($ciphertext, -$len);
1206
- $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
1207
- $pos = $len;
1208
- }
1209
- return $plaintext;
1210
- }
1211
-
1212
- if (!$this->continuousBuffer) {
1213
- mcrypt_generic_init($this->demcrypt, $this->keys, $this->decryptIV);
1214
- }
1215
-
1216
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1217
- }
1218
-
1219
- if (!is_array($this->keys)) {
1220
- $this->keys = $this->_prepareKey("\0\0\0\0\0\0\0\0");
1221
- }
1222
-
1223
- if ($this->use_inline_crypt) {
1224
- $inline = $this->inline_crypt;
1225
- return $inline('decrypt', $this, $ciphertext);
1226
- }
1227
-
1228
- $buffer = &$this->debuffer;
1229
- $continuousBuffer = $this->continuousBuffer;
1230
- $plaintext = '';
1231
- switch ($this->mode) {
1232
- case CRYPT_DES_MODE_ECB:
1233
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1234
- $plaintext.= $this->_processBlock(substr($ciphertext, $i, 8), CRYPT_DES_DECRYPT);
1235
- }
1236
- break;
1237
- case CRYPT_DES_MODE_CBC:
1238
- $xor = $this->decryptIV;
1239
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1240
- $block = substr($ciphertext, $i, 8);
1241
- $plaintext.= $this->_processBlock($block, CRYPT_DES_DECRYPT) ^ $xor;
1242
- $xor = $block;
1243
- }
1244
- if ($this->continuousBuffer) {
1245
- $this->decryptIV = $xor;
1246
- }
1247
- break;
1248
- case CRYPT_DES_MODE_CTR:
1249
- $xor = $this->decryptIV;
1250
- if (strlen($buffer['ciphertext'])) {
1251
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1252
- $block = substr($ciphertext, $i, 8);
1253
- if (strlen($block) > strlen($buffer['ciphertext'])) {
1254
- $buffer['ciphertext'].= $this->_processBlock($this->_generate_xor($xor), CRYPT_DES_ENCRYPT);
1255
- }
1256
- $key = $this->_string_shift($buffer['ciphertext']);
1257
- $plaintext.= $block ^ $key;
1258
- }
1259
- } else {
1260
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1261
- $block = substr($ciphertext, $i, 8);
1262
- $key = $this->_processBlock($this->_generate_xor($xor), CRYPT_DES_ENCRYPT);
1263
- $plaintext.= $block ^ $key;
1264
- }
1265
- }
1266
- if ($this->continuousBuffer) {
1267
- $this->decryptIV = $xor;
1268
- if ($start = strlen($ciphertext) % 8) {
1269
- $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
1270
- }
1271
- }
1272
- break;
1273
- case CRYPT_DES_MODE_CFB:
1274
- if ($this->continuousBuffer) {
1275
- $iv = &$this->decryptIV;
1276
- $pos = &$buffer['pos'];
1277
- } else {
1278
- $iv = $this->decryptIV;
1279
- $pos = 0;
1280
- }
1281
- $len = strlen($ciphertext);
1282
- $i = 0;
1283
- if ($pos) {
1284
- $orig_pos = $pos;
1285
- $max = 8 - $pos;
1286
- if ($len >= $max) {
1287
- $i = $max;
1288
- $len-= $max;
1289
- $pos = 0;
1290
- } else {
1291
- $i = $len;
1292
- $pos+= $len;
1293
- $len = 0;
1294
- }
1295
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1296
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1297
- }
1298
- while ($len >= 8) {
1299
- $iv = $this->_processBlock($iv, CRYPT_DES_ENCRYPT);
1300
- $cb = substr($ciphertext, $i, 8);
1301
- $plaintext.= $iv ^ $cb;
1302
- $iv = $cb;
1303
- $len-= 8;
1304
- $i+= 8;
1305
- }
1306
- if ($len) {
1307
- $iv = $this->_processBlock($iv, CRYPT_DES_ENCRYPT);
1308
- $plaintext.= $iv ^ substr($ciphertext, $i);
1309
- $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1310
- $pos = $len;
1311
- }
1312
- return $plaintext;
1313
- case CRYPT_DES_MODE_OFB:
1314
- $xor = $this->decryptIV;
1315
- if (strlen($buffer['xor'])) {
1316
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1317
- $block = substr($ciphertext, $i, 8);
1318
- if (strlen($block) > strlen($buffer['xor'])) {
1319
- $xor = $this->_processBlock($xor, CRYPT_DES_ENCRYPT);
1320
- $buffer['xor'].= $xor;
1321
- }
1322
- $key = $this->_string_shift($buffer['xor']);
1323
- $plaintext.= $block ^ $key;
1324
- }
1325
- } else {
1326
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
1327
- $xor = $this->_processBlock($xor, CRYPT_DES_ENCRYPT);
1328
- $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
1329
- }
1330
- $key = $xor;
1331
- }
1332
- if ($this->continuousBuffer) {
1333
- $this->decryptIV = $xor;
1334
- if ($start = strlen($ciphertext) % 8) {
1335
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1336
- }
1337
- }
1338
- }
1339
-
1340
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1341
- }
1342
-
1343
- /**
1344
- * Treat consecutive "packets" as if they are a continuous buffer.
1345
- *
1346
- * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1347
- * will yield different outputs:
1348
- *
1349
- * <code>
1350
- * echo $des->encrypt(substr($plaintext, 0, 8));
1351
- * echo $des->encrypt(substr($plaintext, 8, 8));
1352
- * </code>
1353
- * <code>
1354
- * echo $des->encrypt($plaintext);
1355
- * </code>
1356
- *
1357
- * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1358
- * another, as demonstrated with the following:
1359
- *
1360
- * <code>
1361
- * $des->encrypt(substr($plaintext, 0, 8));
1362
- * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
1363
- * </code>
1364
- * <code>
1365
- * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
1366
- * </code>
1367
- *
1368
- * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1369
- * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1370
- * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1371
- *
1372
- * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
1373
- * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1374
- * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1375
- * however, they are also less intuitive and more likely to cause you problems.
1376
- *
1377
- * @see Crypt_DES::disableContinuousBuffer()
1378
- * @access public
1379
- */
1380
- function enableContinuousBuffer()
1381
- {
1382
- $this->continuousBuffer = true;
1383
- }
1384
-
1385
- /**
1386
- * Treat consecutive packets as if they are a discontinuous buffer.
1387
- *
1388
- * The default behavior.
1389
- *
1390
- * @see Crypt_DES::enableContinuousBuffer()
1391
- * @access public
1392
- */
1393
- function disableContinuousBuffer()
1394
- {
1395
- $this->continuousBuffer = false;
1396
- $this->encryptIV = $this->iv;
1397
- $this->decryptIV = $this->iv;
1398
- $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1399
- $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1400
-
1401
- if (CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT) {
1402
- mcrypt_generic_init($this->enmcrypt, $this->keys, $this->iv);
1403
- mcrypt_generic_init($this->demcrypt, $this->keys, $this->iv);
1404
- }
1405
- }
1406
-
1407
- /**
1408
- * Pad "packets".
1409
- *
1410
- * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not
1411
- * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight.
1412
- *
1413
- * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
1414
- * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1415
- * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1416
- * transmitted separately)
1417
- *
1418
- * @see Crypt_DES::disablePadding()
1419
- * @access public
1420
- */
1421
- function enablePadding()
1422
- {
1423
- $this->padding = true;
1424
- }
1425
-
1426
- /**
1427
- * Do not pad packets.
1428
- *
1429
- * @see Crypt_DES::enablePadding()
1430
- * @access public
1431
- */
1432
- function disablePadding()
1433
- {
1434
- $this->padding = false;
1435
- }
1436
-
1437
- /**
1438
- * Pads a string
1439
- *
1440
- * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
1441
- * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7)
1442
- *
1443
- * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1444
- * and padding will, hence forth, be enabled.
1445
- *
1446
- * @see Crypt_DES::_unpad()
1447
- * @access private
1448
- */
1449
- function _pad($text)
1450
- {
1451
- $length = strlen($text);
1452
-
1453
- if (!$this->padding) {
1454
- if (($length & 7) == 0) {
1455
- return $text;
1456
- } else {
1457
- user_error("The plaintext's length ($length) is not a multiple of the block size (8)");
1458
- $this->padding = true;
1459
- }
1460
- }
1461
-
1462
- $pad = 8 - ($length & 7);
1463
- return str_pad($text, $length + $pad, chr($pad));
1464
- }
1465
-
1466
- /**
1467
- * Unpads a string
1468
- *
1469
- * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1470
- * and false will be returned.
1471
- *
1472
- * @see Crypt_DES::_pad()
1473
- * @access private
1474
- */
1475
- function _unpad($text)
1476
- {
1477
- if (!$this->padding) {
1478
- return $text;
1479
- }
1480
-
1481
- $length = ord($text[strlen($text) - 1]);
1482
-
1483
- if (!$length || $length > 8) {
1484
- return false;
1485
- }
1486
-
1487
- return substr($text, 0, -$length);
1488
- }
1489
-
1490
- /**
1491
- * Encrypts or decrypts a 64-bit block
1492
- *
1493
- * $mode should be either CRYPT_DES_ENCRYPT or CRYPT_DES_DECRYPT. See
1494
- * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general
1495
- * idea of what this function does.
1496
- *
1497
- * @access private
1498
- * @param String $block
1499
- * @param Integer $mode
1500
- * @return String
1501
- */
1502
- function _processBlock($block, $mode)
1503
- {
1504
- $shuffle = $this->shuffle;
1505
- $invipmap = $this->invipmap;
1506
- $ipmap = $this->ipmap;
1507
- $sbox1 = $this->sbox1;
1508
- $sbox2 = $this->sbox2;
1509
- $sbox3 = $this->sbox3;
1510
- $sbox4 = $this->sbox4;
1511
- $sbox5 = $this->sbox5;
1512
- $sbox6 = $this->sbox6;
1513
- $sbox7 = $this->sbox7;
1514
- $sbox8 = $this->sbox8;
1515
- $keys = $this->keys[$mode];
1516
-
1517
- // Do the initial IP permutation.
1518
- $t = unpack('Nl/Nr', $block);
1519
- list($l, $r) = array($t['l'], $t['r']);
1520
- $block = ($shuffle[$ipmap[$r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
1521
- ($shuffle[$ipmap[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
1522
- ($shuffle[$ipmap[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
1523
- ($shuffle[$ipmap[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
1524
- ($shuffle[$ipmap[$l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
1525
- ($shuffle[$ipmap[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
1526
- ($shuffle[$ipmap[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
1527
- ($shuffle[$ipmap[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x01");
1528
-
1529
- // Extract L0 and R0.
1530
- $t = unpack('Nl/Nr', $block);
1531
- list($l, $r) = array($t['l'], $t['r']);
1532
-
1533
- // Perform the 16 steps.
1534
- for ($i = 0; $i < 16; $i++) {
1535
- // start of "the Feistel (F) function" - see the following URL:
1536
- // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png
1537
- // Merge key schedule.
1538
- $b1 = (($r >> 3) & 0x1FFFFFFF) ^ ($r << 29) ^ $keys[$i][0];
1539
- $b2 = (($r >> 31) & 0x00000001) ^ ($r << 1) ^ $keys[$i][1];
1540
-
1541
- // S-box indexing.
1542
- $t = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^
1543
- $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^
1544
- $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^
1545
- $sbox7[$b1 & 0x3F] ^ $sbox8[$b2 & 0x3F] ^ $l;
1546
- // end of "the Feistel (F) function"
1547
-
1548
- $l = $r;
1549
- $r = $t;
1550
- }
1551
-
1552
- // Perform the inverse IP permutation.
1553
- return ($shuffle[$invipmap[($l >> 24) & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
1554
- ($shuffle[$invipmap[($r >> 24) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
1555
- ($shuffle[$invipmap[($l >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
1556
- ($shuffle[$invipmap[($r >> 16) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
1557
- ($shuffle[$invipmap[($l >> 8) & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
1558
- ($shuffle[$invipmap[($r >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
1559
- ($shuffle[$invipmap[$l & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
1560
- ($shuffle[$invipmap[$r & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x01");
1561
- }
1562
-
1563
- /**
1564
- * Creates the key schedule.
1565
- *
1566
- * @access private
1567
- * @param String $key
1568
- * @return Array
1569
- */
1570
- function _prepareKey($key)
1571
- {
1572
- static $shifts = array( // number of key bits shifted per round
1573
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
1574
- );
1575
-
1576
- static $pc1map = array(
1577
- 0x00, 0x00, 0x08, 0x08, 0x04, 0x04, 0x0C, 0x0C,
1578
- 0x02, 0x02, 0x0A, 0x0A, 0x06, 0x06, 0x0E, 0x0E,
1579
- 0x10, 0x10, 0x18, 0x18, 0x14, 0x14, 0x1C, 0x1C,
1580
- 0x12, 0x12, 0x1A, 0x1A, 0x16, 0x16, 0x1E, 0x1E,
1581
- 0x20, 0x20, 0x28, 0x28, 0x24, 0x24, 0x2C, 0x2C,
1582
- 0x22, 0x22, 0x2A, 0x2A, 0x26, 0x26, 0x2E, 0x2E,
1583
- 0x30, 0x30, 0x38, 0x38, 0x34, 0x34, 0x3C, 0x3C,
1584
- 0x32, 0x32, 0x3A, 0x3A, 0x36, 0x36, 0x3E, 0x3E,
1585
- 0x40, 0x40, 0x48, 0x48, 0x44, 0x44, 0x4C, 0x4C,
1586
- 0x42, 0x42, 0x4A, 0x4A, 0x46, 0x46, 0x4E, 0x4E,
1587
- 0x50, 0x50, 0x58, 0x58, 0x54, 0x54, 0x5C, 0x5C,
1588
- 0x52, 0x52, 0x5A, 0x5A, 0x56, 0x56, 0x5E, 0x5E,
1589
- 0x60, 0x60, 0x68, 0x68, 0x64, 0x64, 0x6C, 0x6C,
1590
- 0x62, 0x62, 0x6A, 0x6A, 0x66, 0x66, 0x6E, 0x6E,
1591
- 0x70, 0x70, 0x78, 0x78, 0x74, 0x74, 0x7C, 0x7C,
1592
- 0x72, 0x72, 0x7A, 0x7A, 0x76, 0x76, 0x7E, 0x7E,
1593
- 0x80, 0x80, 0x88, 0x88, 0x84, 0x84, 0x8C, 0x8C,
1594
- 0x82, 0x82, 0x8A, 0x8A, 0x86, 0x86, 0x8E, 0x8E,
1595
- 0x90, 0x90, 0x98, 0x98, 0x94, 0x94, 0x9C, 0x9C,
1596
- 0x92, 0x92, 0x9A, 0x9A, 0x96, 0x96, 0x9E, 0x9E,
1597
- 0xA0, 0xA0, 0xA8, 0xA8, 0xA4, 0xA4, 0xAC, 0xAC,
1598
- 0xA2, 0xA2, 0xAA, 0xAA, 0xA6, 0xA6, 0xAE, 0xAE,
1599
- 0xB0, 0xB0, 0xB8, 0xB8, 0xB4, 0xB4, 0xBC, 0xBC,
1600
- 0xB2, 0xB2, 0xBA, 0xBA, 0xB6, 0xB6, 0xBE, 0xBE,
1601
- 0xC0, 0xC0, 0xC8, 0xC8, 0xC4, 0xC4, 0xCC, 0xCC,
1602
- 0xC2, 0xC2, 0xCA, 0xCA, 0xC6, 0xC6, 0xCE, 0xCE,
1603
- 0xD0, 0xD0, 0xD8, 0xD8, 0xD4, 0xD4, 0xDC, 0xDC,
1604
- 0xD2, 0xD2, 0xDA, 0xDA, 0xD6, 0xD6, 0xDE, 0xDE,
1605
- 0xE0, 0xE0, 0xE8, 0xE8, 0xE4, 0xE4, 0xEC, 0xEC,
1606
- 0xE2, 0xE2, 0xEA, 0xEA, 0xE6, 0xE6, 0xEE, 0xEE,
1607
- 0xF0, 0xF0, 0xF8, 0xF8, 0xF4, 0xF4, 0xFC, 0xFC,
1608
- 0xF2, 0xF2, 0xFA, 0xFA, 0xF6, 0xF6, 0xFE, 0xFE
1609
- );
1610
-
1611
- // Mapping tables for the PC-2 transformation.
1612
- static $pc2mapc1 = array(
1613
- 0x00000000, 0x00000400, 0x00200000, 0x00200400,
1614
- 0x00000001, 0x00000401, 0x00200001, 0x00200401,
1615
- 0x02000000, 0x02000400, 0x02200000, 0x02200400,
1616
- 0x02000001, 0x02000401, 0x02200001, 0x02200401
1617
- );
1618
- static $pc2mapc2 = array(
1619
- 0x00000000, 0x00000800, 0x08000000, 0x08000800,
1620
- 0x00010000, 0x00010800, 0x08010000, 0x08010800,
1621
- 0x00000000, 0x00000800, 0x08000000, 0x08000800,
1622
- 0x00010000, 0x00010800, 0x08010000, 0x08010800,
1623
- 0x00000100, 0x00000900, 0x08000100, 0x08000900,
1624
- 0x00010100, 0x00010900, 0x08010100, 0x08010900,
1625
- 0x00000100, 0x00000900, 0x08000100, 0x08000900,
1626
- 0x00010100, 0x00010900, 0x08010100, 0x08010900,
1627
- 0x00000010, 0x00000810, 0x08000010, 0x08000810,
1628
- 0x00010010, 0x00010810, 0x08010010, 0x08010810,
1629
- 0x00000010, 0x00000810, 0x08000010, 0x08000810,
1630
- 0x00010010, 0x00010810, 0x08010010, 0x08010810,
1631
- 0x00000110, 0x00000910, 0x08000110, 0x08000910,
1632
- 0x00010110, 0x00010910, 0x08010110, 0x08010910,
1633
- 0x00000110, 0x00000910, 0x08000110, 0x08000910,
1634
- 0x00010110, 0x00010910, 0x08010110, 0x08010910,
1635
- 0x00040000, 0x00040800, 0x08040000, 0x08040800,
1636
- 0x00050000, 0x00050800, 0x08050000, 0x08050800,
1637
- 0x00040000, 0x00040800, 0x08040000, 0x08040800,
1638
- 0x00050000, 0x00050800, 0x08050000, 0x08050800,
1639
- 0x00040100, 0x00040900, 0x08040100, 0x08040900,
1640
- 0x00050100, 0x00050900, 0x08050100, 0x08050900,
1641
- 0x00040100, 0x00040900, 0x08040100, 0x08040900,
1642
- 0x00050100, 0x00050900, 0x08050100, 0x08050900,
1643
- 0x00040010, 0x00040810, 0x08040010, 0x08040810,
1644
- 0x00050010, 0x00050810, 0x08050010, 0x08050810,
1645
- 0x00040010, 0x00040810, 0x08040010, 0x08040810,
1646
- 0x00050010, 0x00050810, 0x08050010, 0x08050810,
1647
- 0x00040110, 0x00040910, 0x08040110, 0x08040910,
1648
- 0x00050110, 0x00050910, 0x08050110, 0x08050910,
1649
- 0x00040110, 0x00040910, 0x08040110, 0x08040910,
1650
- 0x00050110, 0x00050910, 0x08050110, 0x08050910,
1651
- 0x01000000, 0x01000800, 0x09000000, 0x09000800,
1652
- 0x01010000, 0x01010800, 0x09010000, 0x09010800,
1653
- 0x01000000, 0x01000800, 0x09000000, 0x09000800,
1654
- 0x01010000, 0x01010800, 0x09010000, 0x09010800,
1655
- 0x01000100, 0x01000900, 0x09000100, 0x09000900,
1656
- 0x01010100, 0x01010900, 0x09010100, 0x09010900,
1657
- 0x01000100, 0x01000900, 0x09000100, 0x09000900,
1658
- 0x01010100, 0x01010900, 0x09010100, 0x09010900,
1659
- 0x01000010, 0x01000810, 0x09000010, 0x09000810,
1660
- 0x01010010, 0x01010810, 0x09010010, 0x09010810,
1661
- 0x01000010, 0x01000810, 0x09000010, 0x09000810,
1662
- 0x01010010, 0x01010810, 0x09010010, 0x09010810,
1663
- 0x01000110, 0x01000910, 0x09000110, 0x09000910,
1664
- 0x01010110, 0x01010910, 0x09010110, 0x09010910,
1665
- 0x01000110, 0x01000910, 0x09000110, 0x09000910,
1666
- 0x01010110, 0x01010910, 0x09010110, 0x09010910,
1667
- 0x01040000, 0x01040800, 0x09040000, 0x09040800,
1668
- 0x01050000, 0x01050800, 0x09050000, 0x09050800,
1669
- 0x01040000, 0x01040800, 0x09040000, 0x09040800,
1670
- 0x01050000, 0x01050800, 0x09050000, 0x09050800,
1671
- 0x01040100, 0x01040900, 0x09040100, 0x09040900,
1672
- 0x01050100, 0x01050900, 0x09050100, 0x09050900,
1673
- 0x01040100, 0x01040900, 0x09040100, 0x09040900,
1674
- 0x01050100, 0x01050900, 0x09050100, 0x09050900,
1675
- 0x01040010, 0x01040810, 0x09040010, 0x09040810,
1676
- 0x01050010, 0x01050810, 0x09050010, 0x09050810,
1677
- 0x01040010, 0x01040810, 0x09040010, 0x09040810,
1678
- 0x01050010, 0x01050810, 0x09050010, 0x09050810,
1679
- 0x01040110, 0x01040910, 0x09040110, 0x09040910,
1680
- 0x01050110, 0x01050910, 0x09050110, 0x09050910,
1681
- 0x01040110, 0x01040910, 0x09040110, 0x09040910,
1682
- 0x01050110, 0x01050910, 0x09050110, 0x09050910
1683
- );
1684
- static $pc2mapc3 = array(
1685
- 0x00000000, 0x00000004, 0x00001000, 0x00001004,
1686
- 0x00000000, 0x00000004, 0x00001000, 0x00001004,
1687
- 0x10000000, 0x10000004, 0x10001000, 0x10001004,
1688
- 0x10000000, 0x10000004, 0x10001000, 0x10001004,
1689
- 0x00000020, 0x00000024, 0x00001020, 0x00001024,
1690
- 0x00000020, 0x00000024, 0x00001020, 0x00001024,
1691
- 0x10000020, 0x10000024, 0x10001020, 0x10001024,
1692
- 0x10000020, 0x10000024, 0x10001020, 0x10001024,
1693
- 0x00080000, 0x00080004, 0x00081000, 0x00081004,
1694
- 0x00080000, 0x00080004, 0x00081000, 0x00081004,
1695
- 0x10080000, 0x10080004, 0x10081000, 0x10081004,
1696
- 0x10080000, 0x10080004, 0x10081000, 0x10081004,
1697
- 0x00080020, 0x00080024, 0x00081020, 0x00081024,
1698
- 0x00080020, 0x00080024, 0x00081020, 0x00081024,
1699
- 0x10080020, 0x10080024, 0x10081020, 0x10081024,
1700
- 0x10080020, 0x10080024, 0x10081020, 0x10081024,
1701
- 0x20000000, 0x20000004, 0x20001000, 0x20001004,
1702
- 0x20000000, 0x20000004, 0x20001000, 0x20001004,
1703
- 0x30000000, 0x30000004, 0x30001000, 0x30001004,
1704
- 0x30000000, 0x30000004, 0x30001000, 0x30001004,
1705
- 0x20000020, 0x20000024, 0x20001020, 0x20001024,
1706
- 0x20000020, 0x20000024, 0x20001020, 0x20001024,
1707
- 0x30000020, 0x30000024, 0x30001020, 0x30001024,
1708
- 0x30000020, 0x30000024, 0x30001020, 0x30001024,
1709
- 0x20080000, 0x20080004, 0x20081000, 0x20081004,
1710
- 0x20080000, 0x20080004, 0x20081000, 0x20081004,
1711
- 0x30080000, 0x30080004, 0x30081000, 0x30081004,
1712
- 0x30080000, 0x30080004, 0x30081000, 0x30081004,
1713
- 0x20080020, 0x20080024, 0x20081020, 0x20081024,
1714
- 0x20080020, 0x20080024, 0x20081020, 0x20081024,
1715
- 0x30080020, 0x30080024, 0x30081020, 0x30081024,
1716
- 0x30080020, 0x30080024, 0x30081020, 0x30081024,
1717
- 0x00000002, 0x00000006, 0x00001002, 0x00001006,
1718
- 0x00000002, 0x00000006, 0x00001002, 0x00001006,
1719
- 0x10000002, 0x10000006, 0x10001002, 0x10001006,
1720
- 0x10000002, 0x10000006, 0x10001002, 0x10001006,
1721
- 0x00000022, 0x00000026, 0x00001022, 0x00001026,
1722
- 0x00000022, 0x00000026, 0x00001022, 0x00001026,
1723
- 0x10000022, 0x10000026, 0x10001022, 0x10001026,
1724
- 0x10000022, 0x10000026, 0x10001022, 0x10001026,
1725
- 0x00080002, 0x00080006, 0x00081002, 0x00081006,
1726
- 0x00080002, 0x00080006, 0x00081002, 0x00081006,
1727
- 0x10080002, 0x10080006, 0x10081002, 0x10081006,
1728
- 0x10080002, 0x10080006, 0x10081002, 0x10081006,
1729
- 0x00080022, 0x00080026, 0x00081022, 0x00081026,
1730
- 0x00080022, 0x00080026, 0x00081022, 0x00081026,
1731
- 0x10080022, 0x10080026, 0x10081022, 0x10081026,
1732
- 0x10080022, 0x10080026, 0x10081022, 0x10081026,
1733
- 0x20000002, 0x20000006, 0x20001002, 0x20001006,
1734
- 0x20000002, 0x20000006, 0x20001002, 0x20001006,
1735
- 0x30000002, 0x30000006, 0x30001002, 0x30001006,
1736
- 0x30000002, 0x30000006, 0x30001002, 0x30001006,
1737
- 0x20000022, 0x20000026, 0x20001022, 0x20001026,
1738
- 0x20000022, 0x20000026, 0x20001022, 0x20001026,
1739
- 0x30000022, 0x30000026, 0x30001022, 0x30001026,
1740
- 0x30000022, 0x30000026, 0x30001022, 0x30001026,
1741
- 0x20080002, 0x20080006, 0x20081002, 0x20081006,
1742
- 0x20080002, 0x20080006, 0x20081002, 0x20081006,
1743
- 0x30080002, 0x30080006, 0x30081002, 0x30081006,
1744
- 0x30080002, 0x30080006, 0x30081002, 0x30081006,
1745
- 0x20080022, 0x20080026, 0x20081022, 0x20081026,
1746
- 0x20080022, 0x20080026, 0x20081022, 0x20081026,
1747
- 0x30080022, 0x30080026, 0x30081022, 0x30081026,
1748
- 0x30080022, 0x30080026, 0x30081022, 0x30081026
1749
- );
1750
- static $pc2mapc4 = array(
1751
- 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1752
- 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1753
- 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1754
- 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1755
- 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1756
- 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1757
- 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1758
- 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1759
- 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1760
- 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1761
- 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1762
- 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1763
- 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1764
- 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1765
- 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1766
- 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1767
- 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1768
- 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1769
- 0x00000000, 0x00100000, 0x00000008, 0x00100008,
1770
- 0x00000200, 0x00100200, 0x00000208, 0x00100208,
1771
- 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1772
- 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1773
- 0x04000000, 0x04100000, 0x04000008, 0x04100008,
1774
- 0x04000200, 0x04100200, 0x04000208, 0x04100208,
1775
- 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1776
- 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1777
- 0x00002000, 0x00102000, 0x00002008, 0x00102008,
1778
- 0x00002200, 0x00102200, 0x00002208, 0x00102208,
1779
- 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1780
- 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1781
- 0x04002000, 0x04102000, 0x04002008, 0x04102008,
1782
- 0x04002200, 0x04102200, 0x04002208, 0x04102208,
1783
- 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1784
- 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1785
- 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1786
- 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1787
- 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1788
- 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1789
- 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1790
- 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1791
- 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1792
- 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1793
- 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1794
- 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1795
- 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1796
- 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1797
- 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1798
- 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1799
- 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1800
- 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1801
- 0x00020000, 0x00120000, 0x00020008, 0x00120008,
1802
- 0x00020200, 0x00120200, 0x00020208, 0x00120208,
1803
- 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1804
- 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1805
- 0x04020000, 0x04120000, 0x04020008, 0x04120008,
1806
- 0x04020200, 0x04120200, 0x04020208, 0x04120208,
1807
- 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1808
- 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1809
- 0x00022000, 0x00122000, 0x00022008, 0x00122008,
1810
- 0x00022200, 0x00122200, 0x00022208, 0x00122208,
1811
- 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1812
- 0x04022200, 0x04122200, 0x04022208, 0x04122208,
1813
- 0x04022000, 0x04122000, 0x04022008, 0x04122008,
1814
- 0x04022200, 0x04122200, 0x04022208, 0x04122208
1815
- );
1816
- static $pc2mapd1 = array(
1817
- 0x00000000, 0x00000001, 0x08000000, 0x08000001,
1818
- 0x00200000, 0x00200001, 0x08200000, 0x08200001,
1819
- 0x00000002, 0x00000003, 0x08000002, 0x08000003,
1820
- 0x00200002, 0x00200003, 0x08200002, 0x08200003
1821
- );
1822
- static $pc2mapd2 = array(
1823
- 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1824
- 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1825
- 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1826
- 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1827
- 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1828
- 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1829
- 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1830
- 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1831
- 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1832
- 0x00000000, 0x00100000, 0x00000800, 0x00100800,
1833
- 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1834
- 0x04000000, 0x04100000, 0x04000800, 0x04100800,
1835
- 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1836
- 0x00000004, 0x00100004, 0x00000804, 0x00100804,
1837
- 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1838
- 0x04000004, 0x04100004, 0x04000804, 0x04100804,
1839
- 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1840
- 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1841
- 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1842
- 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1843
- 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1844
- 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1845
- 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1846
- 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1847
- 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1848
- 0x00000200, 0x00100200, 0x00000A00, 0x00100A00,
1849
- 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1850
- 0x04000200, 0x04100200, 0x04000A00, 0x04100A00,
1851
- 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1852
- 0x00000204, 0x00100204, 0x00000A04, 0x00100A04,
1853
- 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1854
- 0x04000204, 0x04100204, 0x04000A04, 0x04100A04,
1855
- 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1856
- 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1857
- 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1858
- 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1859
- 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1860
- 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1861
- 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1862
- 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1863
- 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1864
- 0x00020000, 0x00120000, 0x00020800, 0x00120800,
1865
- 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1866
- 0x04020000, 0x04120000, 0x04020800, 0x04120800,
1867
- 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1868
- 0x00020004, 0x00120004, 0x00020804, 0x00120804,
1869
- 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1870
- 0x04020004, 0x04120004, 0x04020804, 0x04120804,
1871
- 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1872
- 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1873
- 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1874
- 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1875
- 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1876
- 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1877
- 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1878
- 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1879
- 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1880
- 0x00020200, 0x00120200, 0x00020A00, 0x00120A00,
1881
- 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1882
- 0x04020200, 0x04120200, 0x04020A00, 0x04120A00,
1883
- 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1884
- 0x00020204, 0x00120204, 0x00020A04, 0x00120A04,
1885
- 0x04020204, 0x04120204, 0x04020A04, 0x04120A04,
1886
- 0x04020204, 0x04120204, 0x04020A04, 0x04120A04
1887
- );
1888
- static $pc2mapd3 = array(
1889
- 0x00000000, 0x00010000, 0x02000000, 0x02010000,
1890
- 0x00000020, 0x00010020, 0x02000020, 0x02010020,
1891
- 0x00040000, 0x00050000, 0x02040000, 0x02050000,
1892
- 0x00040020, 0x00050020, 0x02040020, 0x02050020,
1893
- 0x00002000, 0x00012000, 0x02002000, 0x02012000,
1894
- 0x00002020, 0x00012020, 0x02002020, 0x02012020,
1895
- 0x00042000, 0x00052000, 0x02042000, 0x02052000,
1896
- 0x00042020, 0x00052020, 0x02042020, 0x02052020,
1897
- 0x00000000, 0x00010000, 0x02000000, 0x02010000,
1898
- 0x00000020, 0x00010020, 0x02000020, 0x02010020,
1899
- 0x00040000, 0x00050000, 0x02040000, 0x02050000,
1900
- 0x00040020, 0x00050020, 0x02040020, 0x02050020,
1901
- 0x00002000, 0x00012000, 0x02002000, 0x02012000,
1902
- 0x00002020, 0x00012020, 0x02002020, 0x02012020,
1903
- 0x00042000, 0x00052000, 0x02042000, 0x02052000,
1904
- 0x00042020, 0x00052020, 0x02042020, 0x02052020,
1905
- 0x00000010, 0x00010010, 0x02000010, 0x02010010,
1906
- 0x00000030, 0x00010030, 0x02000030, 0x02010030,
1907
- 0x00040010, 0x00050010, 0x02040010, 0x02050010,
1908
- 0x00040030, 0x00050030, 0x02040030, 0x02050030,
1909
- 0x00002010, 0x00012010, 0x02002010, 0x02012010,
1910
- 0x00002030, 0x00012030, 0x02002030, 0x02012030,
1911
- 0x00042010, 0x00052010, 0x02042010, 0x02052010,
1912
- 0x00042030, 0x00052030, 0x02042030, 0x02052030,
1913
- 0x00000010, 0x00010010, 0x02000010, 0x02010010,
1914
- 0x00000030, 0x00010030, 0x02000030, 0x02010030,
1915
- 0x00040010, 0x00050010, 0x02040010, 0x02050010,
1916
- 0x00040030, 0x00050030, 0x02040030, 0x02050030,
1917
- 0x00002010, 0x00012010, 0x02002010, 0x02012010,
1918
- 0x00002030, 0x00012030, 0x02002030, 0x02012030,
1919
- 0x00042010, 0x00052010, 0x02042010, 0x02052010,
1920
- 0x00042030, 0x00052030, 0x02042030, 0x02052030,
1921
- 0x20000000, 0x20010000, 0x22000000, 0x22010000,
1922
- 0x20000020, 0x20010020, 0x22000020, 0x22010020,
1923
- 0x20040000, 0x20050000, 0x22040000, 0x22050000,
1924
- 0x20040020, 0x20050020, 0x22040020, 0x22050020,
1925
- 0x20002000, 0x20012000, 0x22002000, 0x22012000,
1926
- 0x20002020, 0x20012020, 0x22002020, 0x22012020,
1927
- 0x20042000, 0x20052000, 0x22042000, 0x22052000,
1928
- 0x20042020, 0x20052020, 0x22042020, 0x22052020,
1929
- 0x20000000, 0x20010000, 0x22000000, 0x22010000,
1930
- 0x20000020, 0x20010020, 0x22000020, 0x22010020,
1931
- 0x20040000, 0x20050000, 0x22040000, 0x22050000,
1932
- 0x20040020, 0x20050020, 0x22040020, 0x22050020,
1933
- 0x20002000, 0x20012000, 0x22002000, 0x22012000,
1934
- 0x20002020, 0x20012020, 0x22002020, 0x22012020,
1935
- 0x20042000, 0x20052000, 0x22042000, 0x22052000,
1936
- 0x20042020, 0x20052020, 0x22042020, 0x22052020,
1937
- 0x20000010, 0x20010010, 0x22000010, 0x22010010,
1938
- 0x20000030, 0x20010030, 0x22000030, 0x22010030,
1939
- 0x20040010, 0x20050010, 0x22040010, 0x22050010,
1940
- 0x20040030, 0x20050030, 0x22040030, 0x22050030,
1941
- 0x20002010, 0x20012010, 0x22002010, 0x22012010,
1942
- 0x20002030, 0x20012030, 0x22002030, 0x22012030,
1943
- 0x20042010, 0x20052010, 0x22042010, 0x22052010,
1944
- 0x20042030, 0x20052030, 0x22042030, 0x22052030,
1945
- 0x20000010, 0x20010010, 0x22000010, 0x22010010,
1946
- 0x20000030, 0x20010030, 0x22000030, 0x22010030,
1947
- 0x20040010, 0x20050010, 0x22040010, 0x22050010,
1948
- 0x20040030, 0x20050030, 0x22040030, 0x22050030,
1949
- 0x20002010, 0x20012010, 0x22002010, 0x22012010,
1950
- 0x20002030, 0x20012030, 0x22002030, 0x22012030,
1951
- 0x20042010, 0x20052010, 0x22042010, 0x22052010,
1952
- 0x20042030, 0x20052030, 0x22042030, 0x22052030
1953
- );
1954
- static $pc2mapd4 = array(
1955
- 0x00000000, 0x00000400, 0x01000000, 0x01000400,
1956
- 0x00000000, 0x00000400, 0x01000000, 0x01000400,
1957
- 0x00000100, 0x00000500, 0x01000100, 0x01000500,
1958
- 0x00000100, 0x00000500, 0x01000100, 0x01000500,
1959
- 0x10000000, 0x10000400, 0x11000000, 0x11000400,
1960
- 0x10000000, 0x10000400, 0x11000000, 0x11000400,
1961
- 0x10000100, 0x10000500, 0x11000100, 0x11000500,
1962
- 0x10000100, 0x10000500, 0x11000100, 0x11000500,
1963
- 0x00080000, 0x00080400, 0x01080000, 0x01080400,
1964
- 0x00080000, 0x00080400, 0x01080000, 0x01080400,
1965
- 0x00080100, 0x00080500, 0x01080100, 0x01080500,
1966
- 0x00080100, 0x00080500, 0x01080100, 0x01080500,
1967
- 0x10080000, 0x10080400, 0x11080000, 0x11080400,
1968
- 0x10080000, 0x10080400, 0x11080000, 0x11080400,
1969
- 0x10080100, 0x10080500, 0x11080100, 0x11080500,
1970
- 0x10080100, 0x10080500, 0x11080100, 0x11080500,
1971
- 0x00000008, 0x00000408, 0x01000008, 0x01000408,
1972
- 0x00000008, 0x00000408, 0x01000008, 0x01000408,
1973
- 0x00000108, 0x00000508, 0x01000108, 0x01000508,
1974
- 0x00000108, 0x00000508, 0x01000108, 0x01000508,
1975
- 0x10000008, 0x10000408, 0x11000008, 0x11000408,
1976
- 0x10000008, 0x10000408, 0x11000008, 0x11000408,
1977
- 0x10000108, 0x10000508, 0x11000108, 0x11000508,
1978
- 0x10000108, 0x10000508, 0x11000108, 0x11000508,
1979
- 0x00080008, 0x00080408, 0x01080008, 0x01080408,
1980
- 0x00080008, 0x00080408, 0x01080008, 0x01080408,
1981
- 0x00080108, 0x00080508, 0x01080108, 0x01080508,
1982
- 0x00080108, 0x00080508, 0x01080108, 0x01080508,
1983
- 0x10080008, 0x10080408, 0x11080008, 0x11080408,
1984
- 0x10080008, 0x10080408, 0x11080008, 0x11080408,
1985
- 0x10080108, 0x10080508, 0x11080108, 0x11080508,
1986
- 0x10080108, 0x10080508, 0x11080108, 0x11080508,
1987
- 0x00001000, 0x00001400, 0x01001000, 0x01001400,
1988
- 0x00001000, 0x00001400, 0x01001000, 0x01001400,
1989
- 0x00001100, 0x00001500, 0x01001100, 0x01001500,
1990
- 0x00001100, 0x00001500, 0x01001100, 0x01001500,
1991
- 0x10001000, 0x10001400, 0x11001000, 0x11001400,
1992
- 0x10001000, 0x10001400, 0x11001000, 0x11001400,
1993
- 0x10001100, 0x10001500, 0x11001100, 0x11001500,
1994
- 0x10001100, 0x10001500, 0x11001100, 0x11001500,
1995
- 0x00081000, 0x00081400, 0x01081000, 0x01081400,
1996
- 0x00081000, 0x00081400, 0x01081000, 0x01081400,
1997
- 0x00081100, 0x00081500, 0x01081100, 0x01081500,
1998
- 0x00081100, 0x00081500, 0x01081100, 0x01081500,
1999
- 0x10081000, 0x10081400, 0x11081000, 0x11081400,
2000
- 0x10081000, 0x10081400, 0x11081000, 0x11081400,
2001
- 0x10081100, 0x10081500, 0x11081100, 0x11081500,
2002
- 0x10081100, 0x10081500, 0x11081100, 0x11081500,
2003
- 0x00001008, 0x00001408, 0x01001008, 0x01001408,
2004
- 0x00001008, 0x00001408, 0x01001008, 0x01001408,
2005
- 0x00001108, 0x00001508, 0x01001108, 0x01001508,
2006
- 0x00001108, 0x00001508, 0x01001108, 0x01001508,
2007
- 0x10001008, 0x10001408, 0x11001008, 0x11001408,
2008
- 0x10001008, 0x10001408, 0x11001008, 0x11001408,
2009
- 0x10001108, 0x10001508, 0x11001108, 0x11001508,
2010
- 0x10001108, 0x10001508, 0x11001108, 0x11001508,
2011
- 0x00081008, 0x00081408, 0x01081008, 0x01081408,
2012
- 0x00081008, 0x00081408, 0x01081008, 0x01081408,
2013
- 0x00081108, 0x00081508, 0x01081108, 0x01081508,
2014
- 0x00081108, 0x00081508, 0x01081108, 0x01081508,
2015
- 0x10081008, 0x10081408, 0x11081008, 0x11081408,
2016
- 0x10081008, 0x10081408, 0x11081008, 0x11081408,
2017
- 0x10081108, 0x10081508, 0x11081108, 0x11081508,
2018
- 0x10081108, 0x10081508, 0x11081108, 0x11081508
2019
- );
2020
-
2021
- // pad the key and remove extra characters as appropriate.
2022
- $key = str_pad(substr($key, 0, 8), 8, chr(0));
2023
-
2024
- // Perform the PC/1 transformation and compute C and D.
2025
- $t = unpack('Nl/Nr', $key);
2026
- list($l, $r) = array($t['l'], $t['r']);
2027
- $key = ($this->shuffle[$pc1map[$r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x00") |
2028
- ($this->shuffle[$pc1map[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x00") |
2029
- ($this->shuffle[$pc1map[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x00") |
2030
- ($this->shuffle[$pc1map[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x00") |
2031
- ($this->shuffle[$pc1map[$l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x00") |
2032
- ($this->shuffle[$pc1map[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x00") |
2033
- ($this->shuffle[$pc1map[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x00") |
2034
- ($this->shuffle[$pc1map[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x00");
2035
- $key = unpack('Nc/Nd', $key);
2036
- $c = ($key['c'] >> 4) & 0x0FFFFFFF;
2037
- $d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F);
2038
-
2039
- $keys = array();
2040
- for ($i = 0; $i < 16; $i++) {
2041
- $c <<= $shifts[$i];
2042
- $c = ($c | ($c >> 28)) & 0x0FFFFFFF;
2043
- $d <<= $shifts[$i];
2044
- $d = ($d | ($d >> 28)) & 0x0FFFFFFF;
2045
-
2046
- // Perform the PC-2 transformation.
2047
- $cp = $pc2mapc1[$c >> 24] | $pc2mapc2[($c >> 16) & 0xFF] |
2048
- $pc2mapc3[($c >> 8) & 0xFF] | $pc2mapc4[$c & 0xFF];
2049
- $dp = $pc2mapd1[$d >> 24] | $pc2mapd2[($d >> 16) & 0xFF] |
2050
- $pc2mapd3[($d >> 8) & 0xFF] | $pc2mapd4[$d & 0xFF];
2051
-
2052
- // Reorder: odd bytes/even bytes. Push the result in key schedule.
2053
- $keys[] = array(
2054
- ($cp & 0xFF000000) | (($cp << 8) & 0x00FF0000) |
2055
- (($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF),
2056
- (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) |
2057
- (($dp >> 8) & 0x0000FF00) | ($dp & 0x000000FF)
2058
- );
2059
- }
2060
-
2061
- $keys = array(
2062
- CRYPT_DES_ENCRYPT => $keys,
2063
- CRYPT_DES_DECRYPT => array_reverse($keys),
2064
- CRYPT_DES_ENCRYPT_1DIM => array(),
2065
- CRYPT_DES_DECRYPT_1DIM => array()
2066
- );
2067
-
2068
- // Generate 1-dim arrays for inline en/decrypting
2069
- for ($i = 0; $i < 16; ++$i) {
2070
- $keys[CRYPT_DES_ENCRYPT_1DIM][] = $keys[CRYPT_DES_ENCRYPT][$i][0];
2071
- $keys[CRYPT_DES_ENCRYPT_1DIM][] = $keys[CRYPT_DES_ENCRYPT][$i][1];
2072
- $keys[CRYPT_DES_DECRYPT_1DIM][] = $keys[CRYPT_DES_DECRYPT][$i][0];
2073
- $keys[CRYPT_DES_DECRYPT_1DIM][] = $keys[CRYPT_DES_DECRYPT][$i][1];
2074
- }
2075
-
2076
- return $keys;
2077
- }
2078
-
2079
- /**
2080
- * String Shift
2081
- *
2082
- * Inspired by array_shift
2083
- *
2084
- * @param String $string
2085
- * @return String
2086
- * @access private
2087
- */
2088
- function _string_shift(&$string)
2089
- {
2090
- $substr = substr($string, 0, 8);
2091
- $string = substr($string, 8);
2092
- return $substr;
2093
- }
2094
-
2095
- /**
2096
- * Creates performance-optimized function for de/encrypt(), storing it in $this->inline_crypt
2097
- *
2098
- * @param optional Integer $des_rounds (1 = DES[default], 3 = TribleDES)
2099
- * @access private
2100
- */
2101
- function inline_crypt_setup($des_rounds = 1)
2102
- {
2103
- $lambda_functions =& Crypt_DES::get_lambda_functions();
2104
- $block_size = 8;
2105
- $mode = $this->mode;
2106
-
2107
- $code_hash = "$mode,$des_rounds";
2108
-
2109
- if (!isset($lambda_functions[$code_hash])) {
2110
- // Generating encrypt code:
2111
- $ki = -1;
2112
- $init_cryptBlock = '
2113
- $shuffle = $self->shuffle;
2114
- $invipmap = $self->invipmap;
2115
- $ipmap = $self->ipmap;
2116
- $sbox1 = $self->sbox1;
2117
- $sbox2 = $self->sbox2;
2118
- $sbox3 = $self->sbox3;
2119
- $sbox4 = $self->sbox4;
2120
- $sbox5 = $self->sbox5;
2121
- $sbox6 = $self->sbox6;
2122
- $sbox7 = $self->sbox7;
2123
- $sbox8 = $self->sbox8;
2124
- ';
2125
-
2126
- $_cryptBlock = '$in = unpack("N*", $in);'."\n";
2127
- // Do the initial IP permutation.
2128
- $_cryptBlock .= '
2129
- $l = $in[1];
2130
- $r = $in[2];
2131
- $in = unpack("N*",
2132
- ($shuffle[$ipmap[ $r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
2133
- ($shuffle[$ipmap[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
2134
- ($shuffle[$ipmap[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
2135
- ($shuffle[$ipmap[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
2136
- ($shuffle[$ipmap[ $l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
2137
- ($shuffle[$ipmap[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
2138
- ($shuffle[$ipmap[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
2139
- ($shuffle[$ipmap[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x01")
2140
- );
2141
-
2142
- '.'' /* Extract L0 and R0 */ .'
2143
- $l = $in[1];
2144
- $r = $in[2];
2145
- ';
2146
-
2147
- $l = 'l';
2148
- $r = 'r';
2149
- for ($des_round = 0; $des_round < $des_rounds; ++$des_round) {
2150
- // Perform the 16 steps.
2151
- // start of "the Feistel (F) function" - see the following URL:
2152
- // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png
2153
- // Merge key schedule.
2154
- for ($i = 0; $i < 8; ++$i) {
2155
- $_cryptBlock .= '
2156
- $b1 = (($' . $r . ' >> 3) & 0x1FFFFFFF) ^ ($' . $r . ' << 29) ^ $k_'.(++$ki).';
2157
- $b2 = (($' . $r . ' >> 31) & 0x00000001) ^ ($' . $r . ' << 1) ^ $k_'.(++$ki).';
2158
- $' . $l . ' = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^
2159
- $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^
2160
- $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^
2161
- $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ $' . $l . ';
2162
-
2163
- $b1 = (($' . $l . ' >> 3) & 0x1FFFFFFF) ^ ($' . $l . ' << 29) ^ $k_'.(++$ki).';
2164
- $b2 = (($' . $l . ' >> 31) & 0x00000001) ^ ($' . $l . ' << 1) ^ $k_'.(++$ki).';
2165
- $' . $r . ' = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^
2166
- $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^
2167
- $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^
2168
- $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ $' . $r . ';
2169
- ';
2170
- }
2171
-
2172
- // Last step should not permute L & R.
2173
- $t = $l;
2174
- $l = $r;
2175
- $r = $t;
2176
- }
2177
-
2178
- // Perform the inverse IP permutation.
2179
- $_cryptBlock .= '$in = (
2180
- ($shuffle[$invipmap[($' . $r . ' >> 24) & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
2181
- ($shuffle[$invipmap[($' . $l . ' >> 24) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
2182
- ($shuffle[$invipmap[($' . $r . ' >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x20") |
2183
- ($shuffle[$invipmap[($' . $l . ' >> 16) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x10") |
2184
- ($shuffle[$invipmap[($' . $r . ' >> 8) & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x08") |
2185
- ($shuffle[$invipmap[($' . $l . ' >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x04") |
2186
- ($shuffle[$invipmap[ $' . $r . ' & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x02") |
2187
- ($shuffle[$invipmap[ $' . $l . ' & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x01")
2188
- );
2189
- ';
2190
-
2191
- // Generating mode of operation code:
2192
- switch ($mode) {
2193
- case CRYPT_DES_MODE_ECB:
2194
- $encrypt = $init_cryptBlock . '
2195
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2196
- $ciphertext = "";
2197
- $plaintext_len = strlen($text);
2198
-
2199
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2200
- $in = substr($text, $i, '.$block_size.');
2201
- '.$_cryptBlock.'
2202
- $ciphertext.= $in;
2203
- }
2204
-
2205
- return $ciphertext;
2206
- ';
2207
-
2208
- $decrypt = $init_cryptBlock . '
2209
- extract($self->keys[CRYPT_DES_DECRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2210
- $plaintext = "";
2211
- $ciphertext_len = strlen($text);
2212
-
2213
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2214
- $in = substr($text, $i, '.$block_size.');
2215
- '.$_cryptBlock.'
2216
- $plaintext.= $in;
2217
- }
2218
-
2219
- return $self->_unpad($plaintext);
2220
- ';
2221
- break;
2222
- case CRYPT_DES_MODE_CBC:
2223
- $encrypt = $init_cryptBlock . '
2224
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2225
- $ciphertext = "";
2226
- $plaintext_len = strlen($text);
2227
-
2228
- $in = $self->encryptIV;
2229
-
2230
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2231
- $in = substr($text, $i, '.$block_size.') ^ $in;
2232
- '.$_cryptBlock.'
2233
- $ciphertext.= $in;
2234
- }
2235
-
2236
- if ($self->continuousBuffer) {
2237
- $self->encryptIV = $in;
2238
- }
2239
-
2240
- return $ciphertext;
2241
- ';
2242
-
2243
- $decrypt = $init_cryptBlock . '
2244
- extract($self->keys[CRYPT_DES_DECRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2245
- $plaintext = "";
2246
- $ciphertext_len = strlen($text);
2247
-
2248
- $iv = $self->decryptIV;
2249
-
2250
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2251
- $in = $block = substr($text, $i, '.$block_size.');
2252
- '.$_cryptBlock.'
2253
- $plaintext.= $in ^ $iv;
2254
- $iv = $block;
2255
- }
2256
-
2257
- if ($self->continuousBuffer) {
2258
- $self->decryptIV = $iv;
2259
- }
2260
-
2261
- return $self->_unpad($plaintext);
2262
- ';
2263
- break;
2264
- case CRYPT_DES_MODE_CTR:
2265
- $encrypt = $init_cryptBlock . '
2266
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2267
- $ciphertext = "";
2268
- $plaintext_len = strlen($text);
2269
- $xor = $self->encryptIV;
2270
- $buffer = &$self->enbuffer;
2271
-
2272
- if (strlen($buffer["encrypted"])) {
2273
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2274
- $block = substr($text, $i, '.$block_size.');
2275
- if (strlen($block) > strlen($buffer["encrypted"])) {
2276
- $in = $self->_generate_xor($xor);
2277
- '.$_cryptBlock.'
2278
- $buffer["encrypted"].= $in;
2279
- }
2280
- $key = $self->_string_shift($buffer["encrypted"]);
2281
- $ciphertext.= $block ^ $key;
2282
- }
2283
- } else {
2284
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2285
- $block = substr($text, $i, '.$block_size.');
2286
- $in = $self->_generate_xor($xor);
2287
- '.$_cryptBlock.'
2288
- $key = $in;
2289
- $ciphertext.= $block ^ $key;
2290
- }
2291
- }
2292
- if ($self->continuousBuffer) {
2293
- $self->encryptIV = $xor;
2294
- if ($start = $plaintext_len % '.$block_size.') {
2295
- $buffer["encrypted"] = substr($key, $start) . $buffer["encrypted"];
2296
- }
2297
- }
2298
-
2299
- return $ciphertext;
2300
- ';
2301
-
2302
- $decrypt = $init_cryptBlock . '
2303
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2304
- $plaintext = "";
2305
- $ciphertext_len = strlen($text);
2306
- $xor = $self->decryptIV;
2307
- $buffer = &$self->debuffer;
2308
-
2309
- if (strlen($buffer["ciphertext"])) {
2310
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2311
- $block = substr($text, $i, '.$block_size.');
2312
- if (strlen($block) > strlen($buffer["ciphertext"])) {
2313
- $in = $self->_generate_xor($xor);
2314
- '.$_cryptBlock.'
2315
- $buffer["ciphertext"].= $in;
2316
- }
2317
- $key = $self->_string_shift($buffer["ciphertext"]);
2318
- $plaintext.= $block ^ $key;
2319
- }
2320
- } else {
2321
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2322
- $block = substr($text, $i, '.$block_size.');
2323
- $in = $self->_generate_xor($xor);
2324
- '.$_cryptBlock.'
2325
- $key = $in;
2326
- $plaintext.= $block ^ $key;
2327
- }
2328
- }
2329
- if ($self->continuousBuffer) {
2330
- $self->decryptIV = $xor;
2331
- if ($start = $ciphertext_len % '.$block_size.') {
2332
- $buffer["ciphertext"] = substr($key, $start) . $buffer["ciphertext"];
2333
- }
2334
- }
2335
-
2336
- return $plaintext;
2337
- ';
2338
- break;
2339
- case CRYPT_DES_MODE_CFB:
2340
- $encrypt = $init_cryptBlock . '
2341
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2342
- $ciphertext = "";
2343
- $buffer = &$self->enbuffer;
2344
-
2345
- if ($self->continuousBuffer) {
2346
- $iv = &$self->encryptIV;
2347
- $pos = &$buffer["pos"];
2348
- } else {
2349
- $iv = $self->encryptIV;
2350
- $pos = 0;
2351
- }
2352
- $len = strlen($text);
2353
- $i = 0;
2354
- if ($pos) {
2355
- $orig_pos = $pos;
2356
- $max = '.$block_size.' - $pos;
2357
- if ($len >= $max) {
2358
- $i = $max;
2359
- $len-= $max;
2360
- $pos = 0;
2361
- } else {
2362
- $i = $len;
2363
- $pos+= $len;
2364
- $len = 0;
2365
- }
2366
- $ciphertext = substr($iv, $orig_pos) ^ $text;
2367
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
2368
- }
2369
- while ($len >= '.$block_size.') {
2370
- $in = $iv;
2371
- '.$_cryptBlock.';
2372
- $iv = $in ^ substr($text, $i, '.$block_size.');
2373
- $ciphertext.= $iv;
2374
- $len-= '.$block_size.';
2375
- $i+= '.$block_size.';
2376
- }
2377
- if ($len) {
2378
- $in = $iv;
2379
- '.$_cryptBlock.'
2380
- $iv = $in;
2381
- $block = $iv ^ substr($text, $i);
2382
- $iv = substr_replace($iv, $block, 0, $len);
2383
- $ciphertext.= $block;
2384
- $pos = $len;
2385
- }
2386
- return $ciphertext;
2387
- ';
2388
-
2389
- $decrypt = $init_cryptBlock . '
2390
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2391
- $plaintext = "";
2392
- $buffer = &$self->debuffer;
2393
-
2394
- if ($self->continuousBuffer) {
2395
- $iv = &$self->decryptIV;
2396
- $pos = &$buffer["pos"];
2397
- } else {
2398
- $iv = $self->decryptIV;
2399
- $pos = 0;
2400
- }
2401
- $len = strlen($text);
2402
- $i = 0;
2403
- if ($pos) {
2404
- $orig_pos = $pos;
2405
- $max = '.$block_size.' - $pos;
2406
- if ($len >= $max) {
2407
- $i = $max;
2408
- $len-= $max;
2409
- $pos = 0;
2410
- } else {
2411
- $i = $len;
2412
- $pos+= $len;
2413
- $len = 0;
2414
- }
2415
- $plaintext = substr($iv, $orig_pos) ^ $text;
2416
- $iv = substr_replace($iv, substr($text, 0, $i), $orig_pos, $i);
2417
- }
2418
- while ($len >= '.$block_size.') {
2419
- $in = $iv;
2420
- '.$_cryptBlock.'
2421
- $iv = $in;
2422
- $cb = substr($text, $i, '.$block_size.');
2423
- $plaintext.= $iv ^ $cb;
2424
- $iv = $cb;
2425
- $len-= '.$block_size.';
2426
- $i+= '.$block_size.';
2427
- }
2428
- if ($len) {
2429
- $in = $iv;
2430
- '.$_cryptBlock.'
2431
- $iv = $in;
2432
- $plaintext.= $iv ^ substr($text, $i);
2433
- $iv = substr_replace($iv, substr($text, $i), 0, $len);
2434
- $pos = $len;
2435
- }
2436
-
2437
- return $plaintext;
2438
- ';
2439
- break;
2440
- case CRYPT_DES_MODE_OFB:
2441
- $encrypt = $init_cryptBlock . '
2442
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2443
- $ciphertext = "";
2444
- $plaintext_len = strlen($text);
2445
- $xor = $self->encryptIV;
2446
- $buffer = &$self->enbuffer;
2447
-
2448
- if (strlen($buffer["xor"])) {
2449
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2450
- $block = substr($text, $i, '.$block_size.');
2451
- if (strlen($block) > strlen($buffer["xor"])) {
2452
- $in = $xor;
2453
- '.$_cryptBlock.'
2454
- $xor = $in;
2455
- $buffer["xor"].= $xor;
2456
- }
2457
- $key = $self->_string_shift($buffer["xor"]);
2458
- $ciphertext.= $block ^ $key;
2459
- }
2460
- } else {
2461
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
2462
- $in = $xor;
2463
- '.$_cryptBlock.'
2464
- $xor = $in;
2465
- $ciphertext.= substr($text, $i, '.$block_size.') ^ $xor;
2466
- }
2467
- $key = $xor;
2468
- }
2469
- if ($self->continuousBuffer) {
2470
- $self->encryptIV = $xor;
2471
- if ($start = $plaintext_len % '.$block_size.') {
2472
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
2473
- }
2474
- }
2475
- return $ciphertext;
2476
- ';
2477
-
2478
- $decrypt = $init_cryptBlock . '
2479
- extract($self->keys[CRYPT_DES_ENCRYPT_1DIM], EXTR_PREFIX_ALL, "k");
2480
- $plaintext = "";
2481
- $ciphertext_len = strlen($text);
2482
- $xor = $self->decryptIV;
2483
- $buffer = &$self->debuffer;
2484
-
2485
- if (strlen($buffer["xor"])) {
2486
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2487
- $block = substr($text, $i, '.$block_size.');
2488
- if (strlen($block) > strlen($buffer["xor"])) {
2489
- $in = $xor;
2490
- '.$_cryptBlock.'
2491
- $xor = $in;
2492
- $buffer["xor"].= $xor;
2493
- }
2494
- $key = $self->_string_shift($buffer["xor"]);
2495
- $plaintext.= $block ^ $key;
2496
- }
2497
- } else {
2498
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2499
- $in = $xor;
2500
- '.$_cryptBlock.'
2501
- $xor = $in;
2502
- $plaintext.= substr($text, $i, '.$block_size.') ^ $xor;
2503
- }
2504
- $key = $xor;
2505
- }
2506
- if ($self->continuousBuffer) {
2507
- $self->decryptIV = $xor;
2508
- if ($start = $ciphertext_len % '.$block_size.') {
2509
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
2510
- }
2511
- }
2512
- return $plaintext;
2513
- ';
2514
- break;
2515
- }
2516
- $lambda_functions[$code_hash] = create_function('$action, &$self, $text', 'if ($action == "encrypt") { '.$encrypt.' } else { '.$decrypt.' }');
2517
- }
2518
- $this->inline_crypt = $lambda_functions[$code_hash];
2519
- }
2520
-
2521
- /**
2522
- * Holds the lambda_functions table (classwide)
2523
- *
2524
- * @see inline_crypt_setup()
2525
- * @return Array
2526
- * @access private
2527
- */
2528
- function &get_lambda_functions()
2529
- {
2530
- static $functions = array();
2531
- return $functions;
2532
- }
2533
- }
2534
-
2535
- // vim: ts=4:sw=4:et:
2536
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/RC4.php DELETED
@@ -1,492 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of RC4.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * Useful resources are as follows:
12
- *
13
- * - {@link http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt ARCFOUR Algorithm}
14
- * - {@link http://en.wikipedia.org/wiki/RC4 - Wikipedia: RC4}
15
- *
16
- * RC4 is also known as ARCFOUR or ARC4. The reason is elaborated upon at Wikipedia. This class is named RC4 and not
17
- * ARCFOUR or ARC4 because RC4 is how it is referred to in the SSH1 specification.
18
- *
19
- * Here's a short example of how to use this library:
20
- * <code>
21
- * <?php
22
- * include('Crypt/RC4.php');
23
- *
24
- * $rc4 = new Crypt_RC4();
25
- *
26
- * $rc4->setKey('abcdefgh');
27
- *
28
- * $size = 10 * 1024;
29
- * $plaintext = '';
30
- * for ($i = 0; $i < $size; $i++) {
31
- * $plaintext.= 'a';
32
- * }
33
- *
34
- * echo $rc4->decrypt($rc4->encrypt($plaintext));
35
- * ?>
36
- * </code>
37
- *
38
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
39
- * of this software and associated documentation files (the "Software"), to deal
40
- * in the Software without restriction, including without limitation the rights
41
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
42
- * copies of the Software, and to permit persons to whom the Software is
43
- * furnished to do so, subject to the following conditions:
44
- *
45
- * The above copyright notice and this permission notice shall be included in
46
- * all copies or substantial portions of the Software.
47
- *
48
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
54
- * THE SOFTWARE.
55
- *
56
- * @category Crypt
57
- * @package Crypt_RC4
58
- * @author Jim Wigginton <terrafrost@php.net>
59
- * @copyright MMVII Jim Wigginton
60
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
61
- * @link http://phpseclib.sourceforge.net
62
- */
63
-
64
- /**#@+
65
- * @access private
66
- * @see Crypt_RC4::Crypt_RC4()
67
- */
68
- /**
69
- * Toggles the internal implementation
70
- */
71
- define('CRYPT_RC4_MODE_INTERNAL', 1);
72
- /**
73
- * Toggles the mcrypt implementation
74
- */
75
- define('CRYPT_RC4_MODE_MCRYPT', 2);
76
- /**#@-*/
77
-
78
- /**#@+
79
- * @access private
80
- * @see Crypt_RC4::_crypt()
81
- */
82
- define('CRYPT_RC4_ENCRYPT', 0);
83
- define('CRYPT_RC4_DECRYPT', 1);
84
- /**#@-*/
85
-
86
- /**
87
- * Pure-PHP implementation of RC4.
88
- *
89
- * @author Jim Wigginton <terrafrost@php.net>
90
- * @version 0.1.0
91
- * @access public
92
- * @package Crypt_RC4
93
- */
94
- class Crypt_RC4 {
95
- /**
96
- * The Key
97
- *
98
- * @see Crypt_RC4::setKey()
99
- * @var String
100
- * @access private
101
- */
102
- var $key = "\0";
103
-
104
- /**
105
- * The Key Stream for encryption
106
- *
107
- * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
108
- *
109
- * @see Crypt_RC4::setKey()
110
- * @var Array
111
- * @access private
112
- */
113
- var $encryptStream = false;
114
-
115
- /**
116
- * The Key Stream for decryption
117
- *
118
- * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
119
- *
120
- * @see Crypt_RC4::setKey()
121
- * @var Array
122
- * @access private
123
- */
124
- var $decryptStream = false;
125
-
126
- /**
127
- * The $i and $j indexes for encryption
128
- *
129
- * @see Crypt_RC4::_crypt()
130
- * @var Integer
131
- * @access private
132
- */
133
- var $encryptIndex = 0;
134
-
135
- /**
136
- * The $i and $j indexes for decryption
137
- *
138
- * @see Crypt_RC4::_crypt()
139
- * @var Integer
140
- * @access private
141
- */
142
- var $decryptIndex = 0;
143
-
144
- /**
145
- * The Encryption Algorithm
146
- *
147
- * Only used if CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT. Only possible values are MCRYPT_RC4 or MCRYPT_ARCFOUR.
148
- *
149
- * @see Crypt_RC4::Crypt_RC4()
150
- * @var Integer
151
- * @access private
152
- */
153
- var $mode;
154
-
155
- /**
156
- * Continuous Buffer status
157
- *
158
- * @see Crypt_RC4::enableContinuousBuffer()
159
- * @var Boolean
160
- * @access private
161
- */
162
- var $continuousBuffer = false;
163
-
164
- /**
165
- * Default Constructor.
166
- *
167
- * Determines whether or not the mcrypt extension should be used.
168
- *
169
- * @return Crypt_RC4
170
- * @access public
171
- */
172
- function Crypt_RC4()
173
- {
174
- if ( !defined('CRYPT_RC4_MODE') ) {
175
- switch (true) {
176
- case extension_loaded('mcrypt') && (defined('MCRYPT_ARCFOUR') || defined('MCRYPT_RC4')) && in_array('arcfour', mcrypt_list_algorithms()):
177
- define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_MCRYPT);
178
- break;
179
- default:
180
- define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_INTERNAL);
181
- }
182
- }
183
-
184
- switch ( CRYPT_RC4_MODE ) {
185
- case CRYPT_RC4_MODE_MCRYPT:
186
- switch (true) {
187
- case defined('MCRYPT_ARCFOUR'):
188
- $this->mode = MCRYPT_ARCFOUR;
189
- break;
190
- case defined('MCRYPT_RC4');
191
- $this->mode = MCRYPT_RC4;
192
- }
193
- $this->encryptStream = mcrypt_module_open($this->mode, '', MCRYPT_MODE_STREAM, '');
194
- $this->decryptStream = mcrypt_module_open($this->mode, '', MCRYPT_MODE_STREAM, '');
195
-
196
- }
197
- }
198
-
199
- /**
200
- * Sets the key.
201
- *
202
- * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will
203
- * be used. If no key is explicitly set, it'll be assumed to be a single null byte.
204
- *
205
- * @access public
206
- * @param String $key
207
- */
208
- function setKey($key)
209
- {
210
- $this->key = $key;
211
-
212
- if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
213
- mcrypt_generic_init($this->encryptStream, $this->key, '');
214
- mcrypt_generic_init($this->decryptStream, $this->key, '');
215
- return;
216
- }
217
-
218
- $keyLength = strlen($key);
219
- $keyStream = array();
220
- for ($i = 0; $i < 256; $i++) {
221
- $keyStream[$i] = $i;
222
- }
223
- $j = 0;
224
- for ($i = 0; $i < 256; $i++) {
225
- $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
226
- $temp = $keyStream[$i];
227
- $keyStream[$i] = $keyStream[$j];
228
- $keyStream[$j] = $temp;
229
- }
230
-
231
- $this->encryptIndex = $this->decryptIndex = array(0, 0);
232
- $this->encryptStream = $this->decryptStream = $keyStream;
233
- }
234
-
235
- /**
236
- * Sets the password.
237
- *
238
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
239
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
240
- * $hash, $salt, $count, $dkLen
241
- *
242
- * @param String $password
243
- * @param optional String $method
244
- * @access public
245
- */
246
- function setPassword($password, $method = 'pbkdf2')
247
- {
248
- $key = '';
249
-
250
- switch ($method) {
251
- default: // 'pbkdf2'
252
- list(, , $hash, $salt, $count) = func_get_args();
253
- if (!isset($hash)) {
254
- $hash = 'sha1';
255
- }
256
- // WPA and WPA2 use the SSID as the salt
257
- if (!isset($salt)) {
258
- $salt = 'phpseclib/salt';
259
- }
260
- // RFC2898#section-4.2 uses 1,000 iterations by default
261
- // WPA and WPA2 use 4,096.
262
- if (!isset($count)) {
263
- $count = 1000;
264
- }
265
- if (!isset($dkLen)) {
266
- $dkLen = 128;
267
- }
268
-
269
- if (!class_exists('Crypt_Hash')) {
270
- require_once('Crypt/Hash.php');
271
- }
272
-
273
- $i = 1;
274
- while (strlen($key) < $dkLen) {
275
- //$dk.= $this->_pbkdf($password, $salt, $count, $i++);
276
- $hmac = new Crypt_Hash();
277
- $hmac->setHash($hash);
278
- $hmac->setKey($password);
279
- $f = $u = $hmac->hash($salt . pack('N', $i++));
280
- for ($j = 2; $j <= $count; $j++) {
281
- $u = $hmac->hash($u);
282
- $f^= $u;
283
- }
284
- $key.= $f;
285
- }
286
- }
287
-
288
- $this->setKey(substr($key, 0, $dkLen));
289
- }
290
-
291
- /**
292
- * Dummy function.
293
- *
294
- * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1].
295
- * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before
296
- * calling setKey().
297
- *
298
- * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol,
299
- * the IV's are relatively easy to predict, an attack described by
300
- * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir}
301
- * can be used to quickly guess at the rest of the key. The following links elaborate:
302
- *
303
- * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009}
304
- * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack}
305
- *
306
- * @param String $iv
307
- * @see Crypt_RC4::setKey()
308
- * @access public
309
- */
310
- function setIV($iv)
311
- {
312
- }
313
-
314
- /**
315
- * Encrypts a message.
316
- *
317
- * @see Crypt_RC4::_crypt()
318
- * @access public
319
- * @param String $plaintext
320
- */
321
- function encrypt($plaintext)
322
- {
323
- return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT);
324
- }
325
-
326
- /**
327
- * Decrypts a message.
328
- *
329
- * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
330
- * Atleast if the continuous buffer is disabled.
331
- *
332
- * @see Crypt_RC4::_crypt()
333
- * @access public
334
- * @param String $ciphertext
335
- */
336
- function decrypt($ciphertext)
337
- {
338
- return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT);
339
- }
340
-
341
- /**
342
- * Encrypts or decrypts a message.
343
- *
344
- * @see Crypt_RC4::encrypt()
345
- * @see Crypt_RC4::decrypt()
346
- * @access private
347
- * @param String $text
348
- * @param Integer $mode
349
- */
350
- function _crypt($text, $mode)
351
- {
352
- if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
353
- $keyStream = $mode == CRYPT_RC4_ENCRYPT ? 'encryptStream' : 'decryptStream';
354
-
355
- if (!$this->continuousBuffer) {
356
- mcrypt_generic_init($this->$keyStream, $this->key, '');
357
- }
358
-
359
- return mcrypt_generic($this->$keyStream, $text);
360
- }
361
-
362
- if ($this->encryptStream === false) {
363
- $this->setKey($this->key);
364
- }
365
-
366
- switch ($mode) {
367
- case CRYPT_RC4_ENCRYPT:
368
- $keyStream = $this->encryptStream;
369
- list($i, $j) = $this->encryptIndex;
370
- break;
371
- case CRYPT_RC4_DECRYPT:
372
- $keyStream = $this->decryptStream;
373
- list($i, $j) = $this->decryptIndex;
374
- }
375
-
376
- $newText = '';
377
- for ($k = 0; $k < strlen($text); $k++) {
378
- $i = ($i + 1) & 255;
379
- $j = ($j + $keyStream[$i]) & 255;
380
- $temp = $keyStream[$i];
381
- $keyStream[$i] = $keyStream[$j];
382
- $keyStream[$j] = $temp;
383
- $temp = $keyStream[($keyStream[$i] + $keyStream[$j]) & 255];
384
- $newText.= chr(ord($text[$k]) ^ $temp);
385
- }
386
-
387
- if ($this->continuousBuffer) {
388
- switch ($mode) {
389
- case CRYPT_RC4_ENCRYPT:
390
- $this->encryptStream = $keyStream;
391
- $this->encryptIndex = array($i, $j);
392
- break;
393
- case CRYPT_RC4_DECRYPT:
394
- $this->decryptStream = $keyStream;
395
- $this->decryptIndex = array($i, $j);
396
- }
397
- }
398
-
399
- return $newText;
400
- }
401
-
402
- /**
403
- * Treat consecutive "packets" as if they are a continuous buffer.
404
- *
405
- * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
406
- * will yield different outputs:
407
- *
408
- * <code>
409
- * echo $rc4->encrypt(substr($plaintext, 0, 8));
410
- * echo $rc4->encrypt(substr($plaintext, 8, 8));
411
- * </code>
412
- * <code>
413
- * echo $rc4->encrypt($plaintext);
414
- * </code>
415
- *
416
- * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
417
- * another, as demonstrated with the following:
418
- *
419
- * <code>
420
- * $rc4->encrypt(substr($plaintext, 0, 8));
421
- * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
422
- * </code>
423
- * <code>
424
- * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
425
- * </code>
426
- *
427
- * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
428
- * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
429
- * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
430
- *
431
- * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
432
- * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
433
- * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
434
- * however, they are also less intuitive and more likely to cause you problems.
435
- *
436
- * @see Crypt_RC4::disableContinuousBuffer()
437
- * @access public
438
- */
439
- function enableContinuousBuffer()
440
- {
441
- if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
442
- mcrypt_generic_init($this->encryptStream, $this->key, '');
443
- mcrypt_generic_init($this->decryptStream, $this->key, '');
444
- }
445
-
446
- $this->continuousBuffer = true;
447
- }
448
-
449
- /**
450
- * Treat consecutive packets as if they are a discontinuous buffer.
451
- *
452
- * The default behavior.
453
- *
454
- * @see Crypt_RC4::enableContinuousBuffer()
455
- * @access public
456
- */
457
- function disableContinuousBuffer()
458
- {
459
- if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_INTERNAL ) {
460
- $this->encryptIndex = $this->decryptIndex = array(0, 0);
461
- $this->encryptStream = $this->decryptStream = false;
462
- }
463
-
464
- $this->continuousBuffer = false;
465
- }
466
-
467
- /**
468
- * Dummy function.
469
- *
470
- * Since RC4 is a stream cipher and not a block cipher, no padding is necessary. The only reason this function is
471
- * included is so that you can switch between a block cipher and a stream cipher transparently.
472
- *
473
- * @see Crypt_RC4::disablePadding()
474
- * @access public
475
- */
476
- function enablePadding()
477
- {
478
- }
479
-
480
- /**
481
- * Dummy function.
482
- *
483
- * @see Crypt_RC4::enablePadding()
484
- * @access public
485
- */
486
- function disablePadding()
487
- {
488
- }
489
- }
490
-
491
- // vim: ts=4:sw=4:et:
492
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/Random.php DELETED
@@ -1,249 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Random Number Generator
6
- *
7
- * PHP versions 4 and 5
8
- *
9
- * Here's a short example of how to use this library:
10
- * <code>
11
- * <?php
12
- * include('Crypt/Random.php');
13
- *
14
- * echo bin2hex(crypt_random_string(8));
15
- * ?>
16
- * </code>
17
- *
18
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
19
- * of this software and associated documentation files (the "Software"), to deal
20
- * in the Software without restriction, including without limitation the rights
21
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
- * copies of the Software, and to permit persons to whom the Software is
23
- * furnished to do so, subject to the following conditions:
24
- *
25
- * The above copyright notice and this permission notice shall be included in
26
- * all copies or substantial portions of the Software.
27
- *
28
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34
- * THE SOFTWARE.
35
- *
36
- * @category Crypt
37
- * @package Crypt_Random
38
- * @author Jim Wigginton <terrafrost@php.net>
39
- * @copyright MMVII Jim Wigginton
40
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
41
- * @link http://phpseclib.sourceforge.net
42
- */
43
-
44
- /**
45
- * "Is Windows" test
46
- *
47
- * @access private
48
- */
49
- define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
50
-
51
- /**
52
- * Generate a random string.
53
- *
54
- * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
55
- * microoptimizations because this function has the potential of being called a huge number of times.
56
- * eg. for RSA key generation.
57
- *
58
- * @param Integer $length
59
- * @return String
60
- * @access public
61
- */
62
- function crypt_random_string($length)
63
- {
64
- if (CRYPT_RANDOM_IS_WINDOWS) {
65
- // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
66
- // ie. class_alias is a function that was introduced in PHP 5.3
67
- if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
68
- return mcrypt_create_iv($length);
69
- }
70
- // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
71
- // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
72
- // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
73
- // call php_win32_get_random_bytes():
74
- //
75
- // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
76
- // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
77
- //
78
- // php_win32_get_random_bytes() is defined thusly:
79
- //
80
- // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
81
- //
82
- // we're calling it, all the same, in the off chance that the mcrypt extension is not available
83
- if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
84
- return openssl_random_pseudo_bytes($length);
85
- }
86
- } else {
87
- // method 1. the fastest
88
- if (function_exists('openssl_random_pseudo_bytes')) {
89
- return openssl_random_pseudo_bytes($length);
90
- }
91
- // method 2
92
- static $fp = true;
93
- if ($fp === true) {
94
- // warning's will be output unles the error suppression operator is used. errors such as
95
- // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
96
- $fp = @fopen('/dev/urandom', 'rb');
97
- }
98
- if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
99
- return fread($fp, $length);
100
- }
101
- // method 3. pretty much does the same thing as method 2 per the following url:
102
- // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
103
- // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
104
- // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
105
- // restrictions or some such
106
- if (function_exists('mcrypt_create_iv')) {
107
- return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
108
- }
109
- }
110
- // at this point we have no choice but to use a pure-PHP CSPRNG
111
-
112
- // cascade entropy across multiple PHP instances by fixing the session and collecting all
113
- // environmental variables, including the previous session data and the current session
114
- // data.
115
- //
116
- // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
117
- // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
118
- // PHP isn't low level to be able to use those as sources and on a web server there's not likely
119
- // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
120
- // however. a ton of people visiting the website. obviously you don't want to base your seeding
121
- // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
122
- // by the user and (2) this isn't just looking at the data sent by the current user - it's based
123
- // on the data sent by all users. one user requests the page and a hash of their info is saved.
124
- // another user visits the page and the serialization of their data is utilized along with the
125
- // server envirnment stuff and a hash of the previous http request data (which itself utilizes
126
- // a hash of the session data before that). certainly an attacker should be assumed to have
127
- // full control over his own http requests. he, however, is not going to have control over
128
- // everyone's http requests.
129
- static $crypto = false, $v;
130
- if ($crypto === false) {
131
- // save old session data
132
- $old_session_id = session_id();
133
- $old_use_cookies = ini_get('session.use_cookies');
134
- $old_session_cache_limiter = session_cache_limiter();
135
- if (isset($_SESSION)) {
136
- $_OLD_SESSION = $_SESSION;
137
- }
138
- if ($old_session_id != '') {
139
- session_write_close();
140
- }
141
-
142
- session_id(1);
143
- ini_set('session.use_cookies', 0);
144
- session_cache_limiter('');
145
- session_start();
146
-
147
- $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
148
- serialize($_SERVER) .
149
- serialize($_POST) .
150
- serialize($_GET) .
151
- serialize($_COOKIE) .
152
- serialize($GLOBALS) .
153
- serialize($_SESSION) .
154
- serialize($_OLD_SESSION)
155
- ));
156
- if (!isset($_SESSION['count'])) {
157
- $_SESSION['count'] = 0;
158
- }
159
- $_SESSION['count']++;
160
-
161
- session_write_close();
162
-
163
- // restore old session data
164
- if ($old_session_id != '') {
165
- session_id($old_session_id);
166
- session_start();
167
- ini_set('session.use_cookies', $old_use_cookies);
168
- session_cache_limiter($old_session_cache_limiter);
169
- } else {
170
- if (isset($_OLD_SESSION)) {
171
- $_SESSION = $_OLD_SESSION;
172
- unset($_OLD_SESSION);
173
- } else {
174
- unset($_SESSION);
175
- }
176
- }
177
-
178
- // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
179
- // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
180
- // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
181
- // original hash and the current hash. we'll be emulating that. for more info see the following URL:
182
- //
183
- // http://tools.ietf.org/html/rfc4253#section-7.2
184
- //
185
- // see the is_string($crypto) part for an example of how to expand the keys
186
- $key = pack('H*', sha1($seed . 'A'));
187
- $iv = pack('H*', sha1($seed . 'C'));
188
-
189
- // ciphers are used as per the nist.gov link below. also, see this link:
190
- //
191
- // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
192
- switch (true) {
193
- case class_exists('Crypt_AES'):
194
- $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
195
- break;
196
- case class_exists('Crypt_TripleDES'):
197
- $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
198
- break;
199
- case class_exists('Crypt_DES'):
200
- $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
201
- break;
202
- case class_exists('Crypt_RC4'):
203
- $crypto = new Crypt_RC4();
204
- break;
205
- default:
206
- $crypto = $seed;
207
- return crypt_random_string($length);
208
- }
209
-
210
- $crypto->setKey($key);
211
- $crypto->setIV($iv);
212
- $crypto->enableContinuousBuffer();
213
- }
214
-
215
- if (is_string($crypto)) {
216
- // the following is based off of ANSI X9.31:
217
- //
218
- // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
219
- //
220
- // OpenSSL uses that same standard for it's random numbers:
221
- //
222
- // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
223
- // (do a search for "ANS X9.31 A.2.4")
224
- //
225
- // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see
226
- // later on in the code) but if they're not we'll use sha1
227
- $result = '';
228
- while (strlen($result) < $length) { // each loop adds 20 bytes
229
- // microtime() isn't packed as "densely" as it could be but then neither is that the idea.
230
- // the idea is simply to ensure that each "block" has a unique element to it.
231
- $i = pack('H*', sha1(microtime()));
232
- $r = pack('H*', sha1($i ^ $v));
233
- $v = pack('H*', sha1($r ^ $i));
234
- $result.= $r;
235
- }
236
- return substr($result, 0, $length);
237
- }
238
-
239
- //return $crypto->encrypt(str_repeat("\0", $length));
240
-
241
- $result = '';
242
- while (strlen($result) < $length) {
243
- $i = $crypto->encrypt(microtime());
244
- $r = $crypto->encrypt($i ^ $v);
245
- $v = $crypto->encrypt($r ^ $i);
246
- $result.= $r;
247
- }
248
- return substr($result, 0, $length);
249
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/Rijndael.php DELETED
@@ -1,2062 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of Rijndael.
6
- *
7
- * Does not use mcrypt, even when available, for reasons that are explained below.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * If {@link Crypt_Rijndael::setBlockLength() setBlockLength()} isn't called, it'll be assumed to be 128 bits. If
12
- * {@link Crypt_Rijndael::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
13
- * {@link Crypt_Rijndael::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's
14
- * 136-bits it'll be null-padded to 160-bits and 160 bits will be the key length until
15
- * {@link Crypt_Rijndael::setKey() setKey()} is called, again, at which point, it'll be recalculated.
16
- *
17
- * Not all Rijndael implementations may support 160-bits or 224-bits as the block length / key length. mcrypt, for example,
18
- * does not. AES, itself, only supports block lengths of 128 and key lengths of 128, 192, and 256.
19
- * {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=10 Rijndael-ammended.pdf#page=10} defines the
20
- * algorithm for block lengths of 192 and 256 but not for block lengths / key lengths of 160 and 224. Indeed, 160 and 224
21
- * are first defined as valid key / block lengths in
22
- * {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=44 Rijndael-ammended.pdf#page=44}:
23
- * Extensions: Other block and Cipher Key lengths.
24
- *
25
- * {@internal The variable names are the same as those in
26
- * {@link http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf#page=10 fips-197.pdf#page=10}.}}
27
- *
28
- * Here's a short example of how to use this library:
29
- * <code>
30
- * <?php
31
- * include('Crypt/Rijndael.php');
32
- *
33
- * $rijndael = new Crypt_Rijndael();
34
- *
35
- * $rijndael->setKey('abcdefghijklmnop');
36
- *
37
- * $size = 10 * 1024;
38
- * $plaintext = '';
39
- * for ($i = 0; $i < $size; $i++) {
40
- * $plaintext.= 'a';
41
- * }
42
- *
43
- * echo $rijndael->decrypt($rijndael->encrypt($plaintext));
44
- * ?>
45
- * </code>
46
- *
47
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
48
- * of this software and associated documentation files (the "Software"), to deal
49
- * in the Software without restriction, including without limitation the rights
50
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
- * copies of the Software, and to permit persons to whom the Software is
52
- * furnished to do so, subject to the following conditions:
53
- *
54
- * The above copyright notice and this permission notice shall be included in
55
- * all copies or substantial portions of the Software.
56
- *
57
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
63
- * THE SOFTWARE.
64
- *
65
- * @category Crypt
66
- * @package Crypt_Rijndael
67
- * @author Jim Wigginton <terrafrost@php.net>
68
- * @copyright MMVIII Jim Wigginton
69
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
70
- * @link http://phpseclib.sourceforge.net
71
- */
72
-
73
- /**#@+
74
- * @access public
75
- * @see Crypt_Rijndael::encrypt()
76
- * @see Crypt_Rijndael::decrypt()
77
- */
78
- /**
79
- * Encrypt / decrypt using the Counter mode.
80
- *
81
- * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
82
- *
83
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
84
- */
85
- define('CRYPT_RIJNDAEL_MODE_CTR', -1);
86
- /**
87
- * Encrypt / decrypt using the Electronic Code Book mode.
88
- *
89
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
90
- */
91
- define('CRYPT_RIJNDAEL_MODE_ECB', 1);
92
- /**
93
- * Encrypt / decrypt using the Code Book Chaining mode.
94
- *
95
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
96
- */
97
- define('CRYPT_RIJNDAEL_MODE_CBC', 2);
98
- /**
99
- * Encrypt / decrypt using the Cipher Feedback mode.
100
- *
101
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
102
- */
103
- define('CRYPT_RIJNDAEL_MODE_CFB', 3);
104
- /**
105
- * Encrypt / decrypt using the Cipher Feedback mode.
106
- *
107
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
108
- */
109
- define('CRYPT_RIJNDAEL_MODE_OFB', 4);
110
- /**#@-*/
111
-
112
- /**#@+
113
- * @access private
114
- * @see Crypt_Rijndael::Crypt_Rijndael()
115
- */
116
- /**
117
- * Toggles the internal implementation
118
- */
119
- define('CRYPT_RIJNDAEL_MODE_INTERNAL', 1);
120
- /**
121
- * Toggles the mcrypt implementation
122
- */
123
- define('CRYPT_RIJNDAEL_MODE_MCRYPT', 2);
124
- /**#@-*/
125
-
126
- /**
127
- * Pure-PHP implementation of Rijndael.
128
- *
129
- * @author Jim Wigginton <terrafrost@php.net>
130
- * @version 0.1.0
131
- * @access public
132
- * @package Crypt_Rijndael
133
- */
134
- class Crypt_Rijndael {
135
- /**
136
- * The Encryption Mode
137
- *
138
- * @see Crypt_Rijndael::Crypt_Rijndael()
139
- * @var Integer
140
- * @access private
141
- */
142
- var $mode;
143
-
144
- /**
145
- * The Key
146
- *
147
- * @see Crypt_Rijndael::setKey()
148
- * @var String
149
- * @access private
150
- */
151
- var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
152
-
153
- /**
154
- * The Initialization Vector
155
- *
156
- * @see Crypt_Rijndael::setIV()
157
- * @var String
158
- * @access private
159
- */
160
- var $iv = '';
161
-
162
- /**
163
- * A "sliding" Initialization Vector
164
- *
165
- * @see Crypt_Rijndael::enableContinuousBuffer()
166
- * @var String
167
- * @access private
168
- */
169
- var $encryptIV = '';
170
-
171
- /**
172
- * A "sliding" Initialization Vector
173
- *
174
- * @see Crypt_Rijndael::enableContinuousBuffer()
175
- * @var String
176
- * @access private
177
- */
178
- var $decryptIV = '';
179
-
180
- /**
181
- * Continuous Buffer status
182
- *
183
- * @see Crypt_Rijndael::enableContinuousBuffer()
184
- * @var Boolean
185
- * @access private
186
- */
187
- var $continuousBuffer = false;
188
-
189
- /**
190
- * Padding status
191
- *
192
- * @see Crypt_Rijndael::enablePadding()
193
- * @var Boolean
194
- * @access private
195
- */
196
- var $padding = true;
197
-
198
- /**
199
- * Does the key schedule need to be (re)calculated?
200
- *
201
- * @see setKey()
202
- * @see setBlockLength()
203
- * @see setKeyLength()
204
- * @var Boolean
205
- * @access private
206
- */
207
- var $changed = true;
208
-
209
- /**
210
- * Has the key length explicitly been set or should it be derived from the key, itself?
211
- *
212
- * @see setKeyLength()
213
- * @var Boolean
214
- * @access private
215
- */
216
- var $explicit_key_length = false;
217
-
218
- /**
219
- * The Key Schedule
220
- *
221
- * @see _setup()
222
- * @var Array
223
- * @access private
224
- */
225
- var $w;
226
-
227
- /**
228
- * The Inverse Key Schedule
229
- *
230
- * @see _setup()
231
- * @var Array
232
- * @access private
233
- */
234
- var $dw;
235
-
236
- /**
237
- * The Block Length
238
- *
239
- * @see setBlockLength()
240
- * @var Integer
241
- * @access private
242
- * @internal The max value is 32, the min value is 16. All valid values are multiples of 4. Exists in conjunction with
243
- * $Nb because we need this value and not $Nb to pad strings appropriately.
244
- */
245
- var $block_size = 16;
246
-
247
- /**
248
- * The Block Length divided by 32
249
- *
250
- * @see setBlockLength()
251
- * @var Integer
252
- * @access private
253
- * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size
254
- * because the encryption / decryption / key schedule creation requires this number and not $block_size. We could
255
- * derive this from $block_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
256
- * of that, we'll just precompute it once.
257
- *
258
- */
259
- var $Nb = 4;
260
-
261
- /**
262
- * The Key Length
263
- *
264
- * @see setKeyLength()
265
- * @var Integer
266
- * @access private
267
- * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $key_size
268
- * because the encryption / decryption / key schedule creation requires this number and not $key_size. We could
269
- * derive this from $key_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
270
- * of that, we'll just precompute it once.
271
- */
272
- var $key_size = 16;
273
-
274
- /**
275
- * The Key Length divided by 32
276
- *
277
- * @see setKeyLength()
278
- * @var Integer
279
- * @access private
280
- * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4
281
- */
282
- var $Nk = 4;
283
-
284
- /**
285
- * The Number of Rounds
286
- *
287
- * @var Integer
288
- * @access private
289
- * @internal The max value is 14, the min value is 10.
290
- */
291
- var $Nr;
292
-
293
- /**
294
- * Shift offsets
295
- *
296
- * @var Array
297
- * @access private
298
- */
299
- var $c;
300
-
301
- /**
302
- * Precomputed mixColumns table
303
- *
304
- * @see Crypt_Rijndael()
305
- * @var Array
306
- * @access private
307
- */
308
- var $t0;
309
-
310
- /**
311
- * Precomputed mixColumns table
312
- *
313
- * @see Crypt_Rijndael()
314
- * @var Array
315
- * @access private
316
- */
317
- var $t1;
318
-
319
- /**
320
- * Precomputed mixColumns table
321
- *
322
- * @see Crypt_Rijndael()
323
- * @var Array
324
- * @access private
325
- */
326
- var $t2;
327
-
328
- /**
329
- * Precomputed mixColumns table
330
- *
331
- * @see Crypt_Rijndael()
332
- * @var Array
333
- * @access private
334
- */
335
- var $t3;
336
-
337
- /**
338
- * Precomputed invMixColumns table
339
- *
340
- * @see Crypt_Rijndael()
341
- * @var Array
342
- * @access private
343
- */
344
- var $dt0;
345
-
346
- /**
347
- * Precomputed invMixColumns table
348
- *
349
- * @see Crypt_Rijndael()
350
- * @var Array
351
- * @access private
352
- */
353
- var $dt1;
354
-
355
- /**
356
- * Precomputed invMixColumns table
357
- *
358
- * @see Crypt_Rijndael()
359
- * @var Array
360
- * @access private
361
- */
362
- var $dt2;
363
-
364
- /**
365
- * Precomputed invMixColumns table
366
- *
367
- * @see Crypt_Rijndael()
368
- * @var Array
369
- * @access private
370
- */
371
- var $dt3;
372
-
373
- /**
374
- * The SubByte S-Box
375
- *
376
- * @see Crypt_Rijndael::_encryptBlock()
377
- * @var Array
378
- * @access private
379
- */
380
- var $sbox;
381
-
382
- /**
383
- * The inverse SubByte S-Box
384
- *
385
- * @see Crypt_Rijndael::_decryptBlock()
386
- * @var Array
387
- * @access private
388
- */
389
- var $isbox;
390
-
391
- /**
392
- * Performance-optimized callback function for en/decrypt()
393
- *
394
- * @see Crypt_Rijndael::encrypt()
395
- * @see Crypt_Rijndael::decrypt()
396
- * @see Crypt_Rijndael::inline_crypt_setup()
397
- * @see Crypt_Rijndael::$use_inline_crypt
398
- * @var Callback
399
- * @access private
400
- */
401
- var $inline_crypt;
402
-
403
- /**
404
- * Holds whether performance-optimized $inline_crypt should be used or not.
405
- *
406
- * @see Crypt_Rijndael::Crypt_Rijndael()
407
- * @see Crypt_Rijndael::inline_crypt_setup()
408
- * @see Crypt_Rijndael::$inline_crypt
409
- * @var Boolean
410
- * @access private
411
- */
412
- var $use_inline_crypt = true;
413
-
414
- /**
415
- * Is the mode one that is paddable?
416
- *
417
- * @see Crypt_Rijndael::Crypt_Rijndael()
418
- * @var Boolean
419
- * @access private
420
- */
421
- var $paddable = false;
422
-
423
- /**
424
- * Encryption buffer for CTR, OFB and CFB modes
425
- *
426
- * @see Crypt_Rijndael::encrypt()
427
- * @var String
428
- * @access private
429
- */
430
- var $enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0);
431
-
432
- /**
433
- * Decryption buffer for CTR, OFB and CFB modes
434
- *
435
- * @see Crypt_Rijndael::decrypt()
436
- * @var String
437
- * @access private
438
- */
439
- var $debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0);
440
-
441
- /**
442
- * Default Constructor.
443
- *
444
- * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
445
- * CRYPT_RIJNDAEL_MODE_ECB or CRYPT_RIJNDAEL_MODE_CBC. If not explictly set, CRYPT_RIJNDAEL_MODE_CBC will be used.
446
- *
447
- * @param optional Integer $mode
448
- * @return Crypt_Rijndael
449
- * @access public
450
- */
451
- function Crypt_Rijndael($mode = CRYPT_RIJNDAEL_MODE_CBC)
452
- {
453
- switch ($mode) {
454
- case CRYPT_RIJNDAEL_MODE_ECB:
455
- case CRYPT_RIJNDAEL_MODE_CBC:
456
- $this->paddable = true;
457
- $this->mode = $mode;
458
- break;
459
- case CRYPT_RIJNDAEL_MODE_CTR:
460
- case CRYPT_RIJNDAEL_MODE_CFB:
461
- case CRYPT_RIJNDAEL_MODE_OFB:
462
- $this->mode = $mode;
463
- break;
464
- default:
465
- $this->paddable = true;
466
- $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
467
- }
468
-
469
- $t3 = &$this->t3;
470
- $t2 = &$this->t2;
471
- $t1 = &$this->t1;
472
- $t0 = &$this->t0;
473
-
474
- $dt3 = &$this->dt3;
475
- $dt2 = &$this->dt2;
476
- $dt1 = &$this->dt1;
477
- $dt0 = &$this->dt0;
478
-
479
- // according to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=19> (section 5.2.1),
480
- // precomputed tables can be used in the mixColumns phase. in that example, they're assigned t0...t3, so
481
- // those are the names we'll use.
482
- $t3 = array(
483
- 0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491,
484
- 0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC,
485
- 0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB,
486
- 0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B,
487
- 0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83,
488
- 0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A,
489
- 0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F,
490
- 0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA,
491
- 0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B,
492
- 0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713,
493
- 0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6,
494
- 0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85,
495
- 0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411,
496
- 0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B,
497
- 0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1,
498
- 0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF,
499
- 0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E,
500
- 0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6,
501
- 0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B,
502
- 0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD,
503
- 0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8,
504
- 0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2,
505
- 0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049,
506
- 0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810,
507
- 0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197,
508
- 0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F,
509
- 0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C,
510
- 0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927,
511
- 0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733,
512
- 0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5,
513
- 0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0,
514
- 0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C
515
- );
516
-
517
- $dt3 = array(
518
- 0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B,
519
- 0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5,
520
- 0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B,
521
- 0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E,
522
- 0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D,
523
- 0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9,
524
- 0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66,
525
- 0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED,
526
- 0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4,
527
- 0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD,
528
- 0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60,
529
- 0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79,
530
- 0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C,
531
- 0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24,
532
- 0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C,
533
- 0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814,
534
- 0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B,
535
- 0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084,
536
- 0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077,
537
- 0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22,
538
- 0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F,
539
- 0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582,
540
- 0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB,
541
- 0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF,
542
- 0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035,
543
- 0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17,
544
- 0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46,
545
- 0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D,
546
- 0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A,
547
- 0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678,
548
- 0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF,
549
- 0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0
550
- );
551
-
552
- for ($i = 0; $i < 256; $i++) {
553
- $t2[] = (($t3[$i] << 8) & 0xFFFFFF00) | (($t3[$i] >> 24) & 0x000000FF);
554
- $t1[] = (($t3[$i] << 16) & 0xFFFF0000) | (($t3[$i] >> 16) & 0x0000FFFF);
555
- $t0[] = (($t3[$i] << 24) & 0xFF000000) | (($t3[$i] >> 8) & 0x00FFFFFF);
556
-
557
- $dt2[] = (($dt3[$i] << 8) & 0xFFFFFF00) | (($dt3[$i] >> 24) & 0x000000FF);
558
- $dt1[] = (($dt3[$i] << 16) & 0xFFFF0000) | (($dt3[$i] >> 16) & 0x0000FFFF);
559
- $dt0[] = (($dt3[$i] << 24) & 0xFF000000) | (($dt3[$i] >> 8) & 0x00FFFFFF);
560
- }
561
-
562
- // sbox for the S-Box substitution
563
- $this->sbox = array(
564
- 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
565
- 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
566
- 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
567
- 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
568
- 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
569
- 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
570
- 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
571
- 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
572
- 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
573
- 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
574
- 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
575
- 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
576
- 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
577
- 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
578
- 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
579
- 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
580
- );
581
-
582
- // sbox for the inverse S-Box substitution
583
- $this->isbox = array(
584
- 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
585
- 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
586
- 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
587
- 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
588
- 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
589
- 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
590
- 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
591
- 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
592
- 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
593
- 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
594
- 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
595
- 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
596
- 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
597
- 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
598
- 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
599
- 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
600
- );
601
-
602
- if (!function_exists('create_function') || !is_callable('create_function')) {
603
- $this->use_inline_crypt = false;
604
- }
605
- }
606
-
607
- /**
608
- * Sets the key.
609
- *
610
- * Keys can be of any length. Rijndael, itself, requires the use of a key that's between 128-bits and 256-bits long and
611
- * whose length is a multiple of 32. If the key is less than 256-bits and the key length isn't set, we round the length
612
- * up to the closest valid key length, padding $key with null bytes. If the key is more than 256-bits, we trim the
613
- * excess bits.
614
- *
615
- * If the key is not explicitly set, it'll be assumed to be all null bytes.
616
- *
617
- * @access public
618
- * @param String $key
619
- */
620
- function setKey($key)
621
- {
622
- $this->key = $key;
623
- $this->changed = true;
624
- }
625
-
626
- /**
627
- * Sets the initialization vector. (optional)
628
- *
629
- * SetIV is not required when CRYPT_RIJNDAEL_MODE_ECB is being used. If not explictly set, it'll be assumed
630
- * to be all zero's.
631
- *
632
- * @access public
633
- * @param String $iv
634
- */
635
- function setIV($iv)
636
- {
637
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, $this->block_size), $this->block_size, chr(0));
638
- }
639
-
640
- /**
641
- * Sets the key length
642
- *
643
- * Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
644
- * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
645
- *
646
- * @access public
647
- * @param Integer $length
648
- */
649
- function setKeyLength($length)
650
- {
651
- $length >>= 5;
652
- if ($length > 8) {
653
- $length = 8;
654
- } else if ($length < 4) {
655
- $length = 4;
656
- }
657
- $this->Nk = $length;
658
- $this->key_size = $length << 2;
659
-
660
- $this->explicit_key_length = true;
661
- $this->changed = true;
662
- }
663
-
664
- /**
665
- * Sets the password.
666
- *
667
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
668
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
669
- * $hash, $salt, $method
670
- * Set $dkLen by calling setKeyLength()
671
- *
672
- * @param String $password
673
- * @param optional String $method
674
- * @access public
675
- */
676
- function setPassword($password, $method = 'pbkdf2')
677
- {
678
- $key = '';
679
-
680
- switch ($method) {
681
- default: // 'pbkdf2'
682
- list(, , $hash, $salt, $count) = func_get_args();
683
- if (!isset($hash)) {
684
- $hash = 'sha1';
685
- }
686
- // WPA and WPA2 use the SSID as the salt
687
- if (!isset($salt)) {
688
- $salt = 'phpseclib';
689
- }
690
- // RFC2898#section-4.2 uses 1,000 iterations by default
691
- // WPA and WPA2 use 4,096.
692
- if (!isset($count)) {
693
- $count = 1000;
694
- }
695
-
696
- if (!class_exists('Crypt_Hash')) {
697
- require_once('Crypt/Hash.php');
698
- }
699
-
700
- $i = 1;
701
- while (strlen($key) < $this->key_size) { // $dkLen == $this->key_size
702
- //$dk.= $this->_pbkdf($password, $salt, $count, $i++);
703
- $hmac = new Crypt_Hash();
704
- $hmac->setHash($hash);
705
- $hmac->setKey($password);
706
- $f = $u = $hmac->hash($salt . pack('N', $i++));
707
- for ($j = 2; $j <= $count; $j++) {
708
- $u = $hmac->hash($u);
709
- $f^= $u;
710
- }
711
- $key.= $f;
712
- }
713
- }
714
-
715
- $this->setKey(substr($key, 0, $this->key_size));
716
- }
717
-
718
- /**
719
- * Sets the block length
720
- *
721
- * Valid block lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
722
- * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
723
- *
724
- * @access public
725
- * @param Integer $length
726
- */
727
- function setBlockLength($length)
728
- {
729
- $length >>= 5;
730
- if ($length > 8) {
731
- $length = 8;
732
- } else if ($length < 4) {
733
- $length = 4;
734
- }
735
- $this->Nb = $length;
736
- $this->block_size = $length << 2;
737
- $this->changed = true;
738
- }
739
-
740
- /**
741
- * Generate CTR XOR encryption key
742
- *
743
- * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
744
- * plaintext / ciphertext in CTR mode.
745
- *
746
- * @see Crypt_Rijndael::decrypt()
747
- * @see Crypt_Rijndael::encrypt()
748
- * @access public
749
- * @param Integer $length
750
- * @param String $iv
751
- */
752
- function _generate_xor($length, &$iv)
753
- {
754
- $xor = '';
755
- $block_size = $this->block_size;
756
- $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
757
- for ($i = 0; $i < $num_blocks; $i++) {
758
- $xor.= $iv;
759
- for ($j = 4; $j <= $block_size; $j+=4) {
760
- $temp = substr($iv, -$j, 4);
761
- switch ($temp) {
762
- case "\xFF\xFF\xFF\xFF":
763
- $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
764
- break;
765
- case "\x7F\xFF\xFF\xFF":
766
- $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
767
- break 2;
768
- default:
769
- extract(unpack('Ncount', $temp));
770
- $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
771
- break 2;
772
- }
773
- }
774
- }
775
-
776
- return $xor;
777
- }
778
-
779
- /**
780
- * Encrypts a message.
781
- *
782
- * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other Rjindael
783
- * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
784
- * necessary are discussed in the following
785
- * URL:
786
- *
787
- * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
788
- *
789
- * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
790
- * strlen($plaintext) will still need to be a multiple of 8, however, arbitrary values can be added to make it that
791
- * length.
792
- *
793
- * @see Crypt_Rijndael::decrypt()
794
- * @access public
795
- * @param String $plaintext
796
- */
797
- function encrypt($plaintext)
798
- {
799
- if ($this->changed) {
800
- $this->_setup();
801
- }
802
- if ($this->use_inline_crypt) {
803
- $inline = $this->inline_crypt;
804
- return $inline('encrypt', $this, $plaintext);
805
- }
806
- if ($this->paddable) {
807
- $plaintext = $this->_pad($plaintext);
808
- }
809
-
810
- $block_size = $this->block_size;
811
- $buffer = &$this->enbuffer;
812
- $ciphertext = '';
813
- switch ($this->mode) {
814
- case CRYPT_RIJNDAEL_MODE_ECB:
815
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
816
- $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
817
- }
818
- break;
819
- case CRYPT_RIJNDAEL_MODE_CBC:
820
- $xor = $this->encryptIV;
821
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
822
- $block = substr($plaintext, $i, $block_size);
823
- $block = $this->_encryptBlock($block ^ $xor);
824
- $xor = $block;
825
- $ciphertext.= $block;
826
- }
827
- if ($this->continuousBuffer) {
828
- $this->encryptIV = $xor;
829
- }
830
- break;
831
- case CRYPT_RIJNDAEL_MODE_CTR:
832
- $xor = $this->encryptIV;
833
- if (strlen($buffer['encrypted'])) {
834
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
835
- $block = substr($plaintext, $i, $block_size);
836
- if (strlen($block) > strlen($buffer['encrypted'])) {
837
- $buffer['encrypted'].= $this->_encryptBlock($this->_generate_xor($block_size, $xor));
838
- }
839
- $key = $this->_string_shift($buffer['encrypted'], $block_size);
840
- $ciphertext.= $block ^ $key;
841
- }
842
- } else {
843
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
844
- $block = substr($plaintext, $i, $block_size);
845
- $key = $this->_encryptBlock($this->_generate_xor($block_size, $xor));
846
- $ciphertext.= $block ^ $key;
847
- }
848
- }
849
- if ($this->continuousBuffer) {
850
- $this->encryptIV = $xor;
851
- if ($start = strlen($plaintext) % $block_size) {
852
- $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
853
- }
854
- }
855
- break;
856
- case CRYPT_RIJNDAEL_MODE_CFB:
857
- // cfb loosely routines inspired by openssl's:
858
- // http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1
859
- if ($this->continuousBuffer) {
860
- $iv = &$this->encryptIV;
861
- $pos = &$buffer['pos'];
862
- } else {
863
- $iv = $this->encryptIV;
864
- $pos = 0;
865
- }
866
- $len = strlen($plaintext);
867
- $i = 0;
868
- if ($pos) {
869
- $orig_pos = $pos;
870
- $max = $block_size - $pos;
871
- if ($len >= $max) {
872
- $i = $max;
873
- $len-= $max;
874
- $pos = 0;
875
- } else {
876
- $i = $len;
877
- $pos+= $len;
878
- $len = 0;
879
- }
880
- // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
881
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
882
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
883
- }
884
- while ($len >= $block_size) {
885
- $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
886
- $ciphertext.= $iv;
887
- $len-= $block_size;
888
- $i+= $block_size;
889
- }
890
- if ($len) {
891
- $iv = $this->_encryptBlock($iv);
892
- $block = $iv ^ substr($plaintext, $i);
893
- $iv = substr_replace($iv, $block, 0, $len);
894
- $ciphertext.= $block;
895
- $pos = $len;
896
- }
897
- break;
898
- case CRYPT_RIJNDAEL_MODE_OFB:
899
- $xor = $this->encryptIV;
900
- if (strlen($buffer['xor'])) {
901
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
902
- $block = substr($plaintext, $i, $block_size);
903
- if (strlen($block) > strlen($buffer['xor'])) {
904
- $xor = $this->_encryptBlock($xor);
905
- $buffer['xor'].= $xor;
906
- }
907
- $key = $this->_string_shift($buffer['xor'], $block_size);
908
- $ciphertext.= $block ^ $key;
909
- }
910
- } else {
911
- for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
912
- $xor = $this->_encryptBlock($xor);
913
- $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
914
- }
915
- $key = $xor;
916
- }
917
- if ($this->continuousBuffer) {
918
- $this->encryptIV = $xor;
919
- if ($start = strlen($plaintext) % $block_size) {
920
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
921
- }
922
- }
923
- }
924
-
925
- return $ciphertext;
926
- }
927
-
928
- /**
929
- * Decrypts a message.
930
- *
931
- * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
932
- * it is.
933
- *
934
- * @see Crypt_Rijndael::encrypt()
935
- * @access public
936
- * @param String $ciphertext
937
- */
938
- function decrypt($ciphertext)
939
- {
940
- if ($this->changed) {
941
- $this->_setup();
942
- }
943
- if ($this->use_inline_crypt) {
944
- $inline = $this->inline_crypt;
945
- return $inline('decrypt', $this, $ciphertext);
946
- }
947
- if ($this->paddable) {
948
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
949
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
950
- $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($this->block_size - strlen($ciphertext) % $this->block_size) % $this->block_size, chr(0));
951
- }
952
-
953
- $block_size = $this->block_size;
954
- $buffer = &$this->debuffer;
955
- $plaintext = '';
956
- switch ($this->mode) {
957
- case CRYPT_RIJNDAEL_MODE_ECB:
958
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
959
- $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
960
- }
961
- break;
962
- case CRYPT_RIJNDAEL_MODE_CBC:
963
- $xor = $this->decryptIV;
964
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
965
- $block = substr($ciphertext, $i, $block_size);
966
- $plaintext.= $this->_decryptBlock($block) ^ $xor;
967
- $xor = $block;
968
- }
969
- if ($this->continuousBuffer) {
970
- $this->decryptIV = $xor;
971
- }
972
- break;
973
- case CRYPT_RIJNDAEL_MODE_CTR:
974
- $xor = $this->decryptIV;
975
- if (strlen($buffer['ciphertext'])) {
976
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
977
- $block = substr($ciphertext, $i, $block_size);
978
- if (strlen($block) > strlen($buffer['ciphertext'])) {
979
- $buffer['ciphertext'].= $this->_encryptBlock($this->_generate_xor($block_size, $xor));
980
- }
981
- $key = $this->_string_shift($buffer['ciphertext'], $block_size);
982
- $plaintext.= $block ^ $key;
983
- }
984
- } else {
985
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
986
- $block = substr($ciphertext, $i, $block_size);
987
- $key = $this->_encryptBlock($this->_generate_xor($block_size, $xor));
988
- $plaintext.= $block ^ $key;
989
- }
990
- }
991
- if ($this->continuousBuffer) {
992
- $this->decryptIV = $xor;
993
- if ($start = strlen($ciphertext) % $block_size) {
994
- $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
995
- }
996
- }
997
- break;
998
- case CRYPT_RIJNDAEL_MODE_CFB:
999
- if ($this->continuousBuffer) {
1000
- $iv = &$this->decryptIV;
1001
- $pos = &$buffer['pos'];
1002
- } else {
1003
- $iv = $this->decryptIV;
1004
- $pos = 0;
1005
- }
1006
- $len = strlen($ciphertext);
1007
- $i = 0;
1008
- if ($pos) {
1009
- $orig_pos = $pos;
1010
- $max = $block_size - $pos;
1011
- if ($len >= $max) {
1012
- $i = $max;
1013
- $len-= $max;
1014
- $pos = 0;
1015
- } else {
1016
- $i = $len;
1017
- $pos+= $len;
1018
- $len = 0;
1019
- }
1020
- // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
1021
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1022
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1023
- }
1024
- while ($len >= $block_size) {
1025
- $iv = $this->_encryptBlock($iv);
1026
- $cb = substr($ciphertext, $i, $block_size);
1027
- $plaintext.= $iv ^ $cb;
1028
- $iv = $cb;
1029
- $len-= $block_size;
1030
- $i+= $block_size;
1031
- }
1032
- if ($len) {
1033
- $iv = $this->_encryptBlock($iv);
1034
- $plaintext.= $iv ^ substr($ciphertext, $i);
1035
- $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1036
- $pos = $len;
1037
- }
1038
- break;
1039
- case CRYPT_RIJNDAEL_MODE_OFB:
1040
- $xor = $this->decryptIV;
1041
- if (strlen($buffer['xor'])) {
1042
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1043
- $block = substr($ciphertext, $i, $block_size);
1044
- if (strlen($block) > strlen($buffer['xor'])) {
1045
- $xor = $this->_encryptBlock($xor);
1046
- $buffer['xor'].= $xor;
1047
- }
1048
- $key = $this->_string_shift($buffer['xor'], $block_size);
1049
- $plaintext.= $block ^ $key;
1050
- }
1051
- } else {
1052
- for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1053
- $xor = $this->_encryptBlock($xor);
1054
- $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
1055
- }
1056
- $key = $xor;
1057
- }
1058
- if ($this->continuousBuffer) {
1059
- $this->decryptIV = $xor;
1060
- if ($start = strlen($ciphertext) % $block_size) {
1061
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1062
- }
1063
- }
1064
- }
1065
-
1066
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1067
- }
1068
-
1069
- /**
1070
- * Encrypts a block
1071
- *
1072
- * @access private
1073
- * @param String $in
1074
- * @return String
1075
- */
1076
- function _encryptBlock($in)
1077
- {
1078
- $state = array();
1079
- $words = unpack('N*word', $in);
1080
-
1081
- $w = $this->w;
1082
- $t0 = $this->t0;
1083
- $t1 = $this->t1;
1084
- $t2 = $this->t2;
1085
- $t3 = $this->t3;
1086
- $Nb = $this->Nb;
1087
- $Nr = $this->Nr;
1088
- $c = $this->c;
1089
-
1090
- // addRoundKey
1091
- $i = -1;
1092
- foreach ($words as $word) {
1093
- $state[] = $word ^ $w[0][++$i];
1094
- }
1095
-
1096
- // fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components -
1097
- // subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding
1098
- // Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf.
1099
- // Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization.
1100
- // Unfortunately, the description given there is not quite correct. Per aes.spec.v316.pdf#page=19 [1],
1101
- // equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well.
1102
-
1103
- // [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf
1104
- $temp = array();
1105
- for ($round = 1; $round < $Nr; ++$round) {
1106
- $i = 0; // $c[0] == 0
1107
- $j = $c[1];
1108
- $k = $c[2];
1109
- $l = $c[3];
1110
-
1111
- while ($i < $Nb) {
1112
- $temp[$i] = $t0[$state[$i] >> 24 & 0x000000FF] ^
1113
- $t1[$state[$j] >> 16 & 0x000000FF] ^
1114
- $t2[$state[$k] >> 8 & 0x000000FF] ^
1115
- $t3[$state[$l] & 0x000000FF] ^
1116
- $w[$round][$i];
1117
- ++$i;
1118
- $j = ($j + 1) % $Nb;
1119
- $k = ($k + 1) % $Nb;
1120
- $l = ($l + 1) % $Nb;
1121
- }
1122
- $state = $temp;
1123
- }
1124
-
1125
- // subWord
1126
- for ($i = 0; $i < $Nb; ++$i) {
1127
- $state[$i] = $this->_subWord($state[$i]);
1128
- }
1129
-
1130
- // shiftRows + addRoundKey
1131
- $i = 0; // $c[0] == 0
1132
- $j = $c[1];
1133
- $k = $c[2];
1134
- $l = $c[3];
1135
- while ($i < $Nb) {
1136
- $temp[$i] = ($state[$i] & 0xFF000000) ^
1137
- ($state[$j] & 0x00FF0000) ^
1138
- ($state[$k] & 0x0000FF00) ^
1139
- ($state[$l] & 0x000000FF) ^
1140
- $w[$Nr][$i];
1141
- ++$i;
1142
- $j = ($j + 1) % $Nb;
1143
- $k = ($k + 1) % $Nb;
1144
- $l = ($l + 1) % $Nb;
1145
- }
1146
-
1147
- // 100% ugly switch/case code... but ~5% faster ("smart code" below commented out)
1148
- switch ($Nb) {
1149
- case 8:
1150
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
1151
- case 7:
1152
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
1153
- case 6:
1154
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
1155
- case 5:
1156
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
1157
- default:
1158
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
1159
- }
1160
- /*
1161
- $state = $temp;
1162
-
1163
- array_unshift($state, 'N*');
1164
-
1165
- return call_user_func_array('pack', $state);
1166
- */
1167
- }
1168
-
1169
- /**
1170
- * Decrypts a block
1171
- *
1172
- * @access private
1173
- * @param String $in
1174
- * @return String
1175
- */
1176
- function _decryptBlock($in)
1177
- {
1178
- $state = array();
1179
- $words = unpack('N*word', $in);
1180
-
1181
- $dw = $this->dw;
1182
- $dt0 = $this->dt0;
1183
- $dt1 = $this->dt1;
1184
- $dt2 = $this->dt2;
1185
- $dt3 = $this->dt3;
1186
- $Nb = $this->Nb;
1187
- $Nr = $this->Nr;
1188
- $c = $this->c;
1189
-
1190
- // addRoundKey
1191
- $i = -1;
1192
- foreach ($words as $word) {
1193
- $state[] = $word ^ $dw[$Nr][++$i];
1194
- }
1195
-
1196
- $temp = array();
1197
- for ($round = $Nr - 1; $round > 0; --$round) {
1198
- $i = 0; // $c[0] == 0
1199
- $j = $Nb - $c[1];
1200
- $k = $Nb - $c[2];
1201
- $l = $Nb - $c[3];
1202
-
1203
- while ($i < $Nb) {
1204
- $temp[$i] = $dt0[$state[$i] >> 24 & 0x000000FF] ^
1205
- $dt1[$state[$j] >> 16 & 0x000000FF] ^
1206
- $dt2[$state[$k] >> 8 & 0x000000FF] ^
1207
- $dt3[$state[$l] & 0x000000FF] ^
1208
- $dw[$round][$i];
1209
- ++$i;
1210
- $j = ($j + 1) % $Nb;
1211
- $k = ($k + 1) % $Nb;
1212
- $l = ($l + 1) % $Nb;
1213
- }
1214
- $state = $temp;
1215
- }
1216
-
1217
- // invShiftRows + invSubWord + addRoundKey
1218
- $i = 0; // $c[0] == 0
1219
- $j = $Nb - $c[1];
1220
- $k = $Nb - $c[2];
1221
- $l = $Nb - $c[3];
1222
-
1223
- while ($i < $Nb) {
1224
- $temp[$i] = $dw[0][$i] ^
1225
- $this->_invSubWord(($state[$i] & 0xFF000000) |
1226
- ($state[$j] & 0x00FF0000) |
1227
- ($state[$k] & 0x0000FF00) |
1228
- ($state[$l] & 0x000000FF));
1229
- ++$i;
1230
- $j = ($j + 1) % $Nb;
1231
- $k = ($k + 1) % $Nb;
1232
- $l = ($l + 1) % $Nb;
1233
- }
1234
-
1235
- switch ($Nb) {
1236
- case 8:
1237
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
1238
- case 7:
1239
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
1240
- case 6:
1241
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
1242
- case 5:
1243
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
1244
- default:
1245
- return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
1246
- }
1247
- /*
1248
- $state = $temp;
1249
-
1250
- array_unshift($state, 'N*');
1251
-
1252
- return call_user_func_array('pack', $state);
1253
- */
1254
- }
1255
-
1256
- /**
1257
- * Setup Rijndael
1258
- *
1259
- * Validates all the variables and calculates $Nr - the number of rounds that need to be performed - and $w - the key
1260
- * key schedule.
1261
- *
1262
- * @access private
1263
- */
1264
- function _setup()
1265
- {
1266
- // Each number in $rcon is equal to the previous number multiplied by two in Rijndael's finite field.
1267
- // See http://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplicative_inverse
1268
- static $rcon = array(0,
1269
- 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
1270
- 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000,
1271
- 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000,
1272
- 0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000,
1273
- 0x97000000, 0x35000000, 0x6A000000, 0xD4000000, 0xB3000000,
1274
- 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000
1275
- );
1276
-
1277
- if (!$this->explicit_key_length) {
1278
- // we do >> 2, here, and not >> 5, as we do above, since strlen($this->key) tells us the number of bytes - not bits
1279
- $length = strlen($this->key) >> 2;
1280
- if ($length > 8) {
1281
- $length = 8;
1282
- } else if ($length < 4) {
1283
- $length = 4;
1284
- }
1285
- $this->Nk = $length;
1286
- $this->key_size = $length << 2;
1287
- }
1288
-
1289
- $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, chr(0));
1290
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, chr(0));
1291
-
1292
- // see Rijndael-ammended.pdf#page=44
1293
- $this->Nr = max($this->Nk, $this->Nb) + 6;
1294
-
1295
- // shift offsets for Nb = 5, 7 are defined in Rijndael-ammended.pdf#page=44,
1296
- // "Table 8: Shift offsets in Shiftrow for the alternative block lengths"
1297
- // shift offsets for Nb = 4, 6, 8 are defined in Rijndael-ammended.pdf#page=14,
1298
- // "Table 2: Shift offsets for different block lengths"
1299
- switch ($this->Nb) {
1300
- case 4:
1301
- case 5:
1302
- case 6:
1303
- $this->c = array(0, 1, 2, 3);
1304
- break;
1305
- case 7:
1306
- $this->c = array(0, 1, 2, 4);
1307
- break;
1308
- case 8:
1309
- $this->c = array(0, 1, 3, 4);
1310
- }
1311
-
1312
- $key = $this->key;
1313
-
1314
- $w = array_values(unpack('N*words', $key));
1315
-
1316
- $length = $this->Nb * ($this->Nr + 1);
1317
- for ($i = $this->Nk; $i < $length; $i++) {
1318
- $temp = $w[$i - 1];
1319
- if ($i % $this->Nk == 0) {
1320
- // according to <http://php.net/language.types.integer>, "the size of an integer is platform-dependent".
1321
- // on a 32-bit machine, it's 32-bits, and on a 64-bit machine, it's 64-bits. on a 32-bit machine,
1322
- // 0xFFFFFFFF << 8 == 0xFFFFFF00, but on a 64-bit machine, it equals 0xFFFFFFFF00. as such, doing 'and'
1323
- // with 0xFFFFFFFF (or 0xFFFFFF00) on a 32-bit machine is unnecessary, but on a 64-bit machine, it is.
1324
- $temp = (($temp << 8) & 0xFFFFFF00) | (($temp >> 24) & 0x000000FF); // rotWord
1325
- $temp = $this->_subWord($temp) ^ $rcon[$i / $this->Nk];
1326
- } else if ($this->Nk > 6 && $i % $this->Nk == 4) {
1327
- $temp = $this->_subWord($temp);
1328
- }
1329
- $w[$i] = $w[$i - $this->Nk] ^ $temp;
1330
- }
1331
-
1332
- // convert the key schedule from a vector of $Nb * ($Nr + 1) length to a matrix with $Nr + 1 rows and $Nb columns
1333
- // and generate the inverse key schedule. more specifically,
1334
- // according to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=23> (section 5.3.3),
1335
- // "The key expansion for the Inverse Cipher is defined as follows:
1336
- // 1. Apply the Key Expansion.
1337
- // 2. Apply InvMixColumn to all Round Keys except the first and the last one."
1338
- // also, see fips-197.pdf#page=27, "5.3.5 Equivalent Inverse Cipher"
1339
- $temp = $this->w = $this->dw = array();
1340
- for ($i = $row = $col = 0; $i < $length; $i++, $col++) {
1341
- if ($col == $this->Nb) {
1342
- if ($row == 0) {
1343
- $this->dw[0] = $this->w[0];
1344
- } else {
1345
- // subWord + invMixColumn + invSubWord = invMixColumn
1346
- $j = 0;
1347
- while ($j < $this->Nb) {
1348
- $dw = $this->_subWord($this->w[$row][$j]);
1349
- $temp[$j] = $this->dt0[$dw >> 24 & 0x000000FF] ^
1350
- $this->dt1[$dw >> 16 & 0x000000FF] ^
1351
- $this->dt2[$dw >> 8 & 0x000000FF] ^
1352
- $this->dt3[$dw & 0x000000FF];
1353
- $j++;
1354
- }
1355
- $this->dw[$row] = $temp;
1356
- }
1357
-
1358
- $col = 0;
1359
- $row++;
1360
- }
1361
- $this->w[$row][$col] = $w[$i];
1362
- }
1363
-
1364
- $this->dw[$row] = $this->w[$row];
1365
-
1366
- // In case of $this->use_inline_crypt === true we have to use 1-dim key arrays (both ascending)
1367
- if ($this->use_inline_crypt) {
1368
- $this->dw = array_reverse($this->dw);
1369
- $w = array_pop($this->w);
1370
- $dw = array_pop($this->dw);
1371
- foreach ($this->w as $r => $wr) {
1372
- foreach ($wr as $c => $wc) {
1373
- $w[] = $wc;
1374
- $dw[] = $this->dw[$r][$c];
1375
- }
1376
- }
1377
- $this->w = $w;
1378
- $this->dw = $dw;
1379
-
1380
- $this->inline_crypt_setup();
1381
- }
1382
-
1383
- $this->changed = false;
1384
- }
1385
-
1386
- /**
1387
- * Performs S-Box substitutions
1388
- *
1389
- * @access private
1390
- */
1391
- function _subWord($word)
1392
- {
1393
- $sbox = $this->sbox;
1394
-
1395
- return $sbox[$word & 0x000000FF] |
1396
- ($sbox[$word >> 8 & 0x000000FF] << 8) |
1397
- ($sbox[$word >> 16 & 0x000000FF] << 16) |
1398
- ($sbox[$word >> 24 & 0x000000FF] << 24);
1399
- }
1400
-
1401
- /**
1402
- * Performs inverse S-Box substitutions
1403
- *
1404
- * @access private
1405
- */
1406
- function _invSubWord($word)
1407
- {
1408
- $isbox = $this->isbox;
1409
-
1410
- return $isbox[$word & 0x000000FF] |
1411
- ($isbox[$word >> 8 & 0x000000FF] << 8) |
1412
- ($isbox[$word >> 16 & 0x000000FF] << 16) |
1413
- ($isbox[$word >> 24 & 0x000000FF] << 24);
1414
- }
1415
-
1416
- /**
1417
- * Pad "packets".
1418
- *
1419
- * Rijndael works by encrypting between sixteen and thirty-two bytes at a time, provided that number is also a multiple
1420
- * of four. If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
1421
- * pad the input so that it is of the proper length.
1422
- *
1423
- * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
1424
- * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1425
- * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1426
- * transmitted separately)
1427
- *
1428
- * @see Crypt_Rijndael::disablePadding()
1429
- * @access public
1430
- */
1431
- function enablePadding()
1432
- {
1433
- $this->padding = true;
1434
- }
1435
-
1436
- /**
1437
- * Do not pad packets.
1438
- *
1439
- * @see Crypt_Rijndael::enablePadding()
1440
- * @access public
1441
- */
1442
- function disablePadding()
1443
- {
1444
- $this->padding = false;
1445
- }
1446
-
1447
- /**
1448
- * Pads a string
1449
- *
1450
- * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
1451
- * $block_size - (strlen($text) % $block_size) bytes are added, each of which is equal to
1452
- * chr($block_size - (strlen($text) % $block_size)
1453
- *
1454
- * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1455
- * and padding will, hence forth, be enabled.
1456
- *
1457
- * @see Crypt_Rijndael::_unpad()
1458
- * @access private
1459
- */
1460
- function _pad($text)
1461
- {
1462
- $length = strlen($text);
1463
-
1464
- if (!$this->padding) {
1465
- if ($length % $this->block_size == 0) {
1466
- return $text;
1467
- } else {
1468
- user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
1469
- $this->padding = true;
1470
- }
1471
- }
1472
-
1473
- $pad = $this->block_size - ($length % $this->block_size);
1474
-
1475
- return str_pad($text, $length + $pad, chr($pad));
1476
- }
1477
-
1478
- /**
1479
- * Unpads a string.
1480
- *
1481
- * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1482
- * and false will be returned.
1483
- *
1484
- * @see Crypt_Rijndael::_pad()
1485
- * @access private
1486
- */
1487
- function _unpad($text)
1488
- {
1489
- if (!$this->padding) {
1490
- return $text;
1491
- }
1492
-
1493
- $length = ord($text[strlen($text) - 1]);
1494
-
1495
- if (!$length || $length > $this->block_size) {
1496
- return false;
1497
- }
1498
-
1499
- return substr($text, 0, -$length);
1500
- }
1501
-
1502
- /**
1503
- * Treat consecutive "packets" as if they are a continuous buffer.
1504
- *
1505
- * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1506
- * will yield different outputs:
1507
- *
1508
- * <code>
1509
- * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1510
- * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1511
- * </code>
1512
- * <code>
1513
- * echo $rijndael->encrypt($plaintext);
1514
- * </code>
1515
- *
1516
- * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1517
- * another, as demonstrated with the following:
1518
- *
1519
- * <code>
1520
- * $rijndael->encrypt(substr($plaintext, 0, 16));
1521
- * echo $rijndael->decrypt($des->encrypt(substr($plaintext, 16, 16)));
1522
- * </code>
1523
- * <code>
1524
- * echo $rijndael->decrypt($des->encrypt(substr($plaintext, 16, 16)));
1525
- * </code>
1526
- *
1527
- * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1528
- * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1529
- * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1530
- *
1531
- * Put another way, when the continuous buffer is enabled, the state of the Crypt_Rijndael() object changes after each
1532
- * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1533
- * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1534
- * however, they are also less intuitive and more likely to cause you problems.
1535
- *
1536
- * @see Crypt_Rijndael::disableContinuousBuffer()
1537
- * @access public
1538
- */
1539
- function enableContinuousBuffer()
1540
- {
1541
- $this->continuousBuffer = true;
1542
- }
1543
-
1544
- /**
1545
- * Treat consecutive packets as if they are a discontinuous buffer.
1546
- *
1547
- * The default behavior.
1548
- *
1549
- * @see Crypt_Rijndael::enableContinuousBuffer()
1550
- * @access public
1551
- */
1552
- function disableContinuousBuffer()
1553
- {
1554
- $this->continuousBuffer = false;
1555
- $this->encryptIV = $this->iv;
1556
- $this->decryptIV = $this->iv;
1557
- $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0);
1558
- $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0);
1559
- }
1560
-
1561
- /**
1562
- * String Shift
1563
- *
1564
- * Inspired by array_shift
1565
- *
1566
- * @param String $string
1567
- * @param optional Integer $index
1568
- * @return String
1569
- * @access private
1570
- */
1571
- function _string_shift(&$string, $index = 1)
1572
- {
1573
- $substr = substr($string, 0, $index);
1574
- $string = substr($string, $index);
1575
- return $substr;
1576
- }
1577
-
1578
- /**
1579
- * Creates performance-optimized function for de/encrypt(), storing it in $this->inline_crypt
1580
- *
1581
- * @see Crypt_Rijndael::encrypt()
1582
- * @see Crypt_Rijndael::decrypt()
1583
- * @access private
1584
- */
1585
- function inline_crypt_setup()
1586
- {
1587
- // Note: inline_crypt_setup() will be called only if $this->changed === true
1588
- // So here we are'nt under the same heavy timing-stress as we are in _de/encryptBlock() or de/encrypt().
1589
- // However...the here generated function- $code, stored as php callback in $this->inline_crypt, must work as fast as even possible.
1590
-
1591
- $lambda_functions =& Crypt_Rijndael::get_lambda_functions();
1592
- $block_size = $this->block_size;
1593
- $mode = $this->mode;
1594
-
1595
- // The first 5 generated $lambda_functions will use the key-words hardcoded for better performance.
1596
- // For memory reason we limit those ultra-optimized function code to 5.
1597
- // After that, we use pure (extracted) integer vars for the key-words which is faster than accessing them via array.
1598
- if (count($lambda_functions) < 5) {
1599
- $w = $this->w;
1600
- $dw = $this->dw;
1601
- $init_encryptBlock = '';
1602
- $init_decryptBlock = '';
1603
- } else {
1604
- for ($i = 0, $cw = count($this->w); $i < $cw; ++$i) {
1605
- $w[] = '$w_'.$i;
1606
- $dw[] = '$dw_'.$i;
1607
- }
1608
- $init_encryptBlock = 'extract($self->w, EXTR_PREFIX_ALL, "w");';
1609
- $init_decryptBlock = 'extract($self->dw, EXTR_PREFIX_ALL, "dw");';
1610
- }
1611
-
1612
- $code_hash = md5("$mode, $block_size, " . implode(',', $w));
1613
-
1614
- if (!isset($lambda_functions[$code_hash])) {
1615
- $Nr = $this->Nr;
1616
- $Nb = $this->Nb;
1617
- $c = $this->c;
1618
-
1619
- // Generating encrypt code:
1620
- $init_encryptBlock.= '
1621
- $t0 = $self->t0;
1622
- $t1 = $self->t1;
1623
- $t2 = $self->t2;
1624
- $t3 = $self->t3;
1625
- $sbox = $self->sbox;';
1626
-
1627
- $s = 'e';
1628
- $e = 's';
1629
- $wc = $Nb - 1;
1630
-
1631
- // Preround: addRoundKey
1632
- $_encryptBlock = '$in = unpack("N*", $in);'."\n";
1633
- for ($i = 0; $i < $Nb; ++$i) {
1634
- $_encryptBlock .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n";
1635
- }
1636
-
1637
- // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
1638
- for ($round = 1; $round < $Nr; ++$round) {
1639
- list($s, $e) = array($e, $s);
1640
- for ($i = 0; $i < $Nb; ++$i) {
1641
- $_encryptBlock.=
1642
- '$'.$e.$i.' =
1643
- $t0[($'.$s.$i .' >> 24) & 0xff] ^
1644
- $t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^
1645
- $t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^
1646
- $t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^
1647
- '.$w[++$wc].";\n";
1648
- }
1649
- }
1650
-
1651
- // Finalround: subWord + shiftRows + addRoundKey
1652
- for ($i = 0; $i < $Nb; ++$i) {
1653
- $_encryptBlock.=
1654
- '$'.$e.$i.' =
1655
- $sbox[ $'.$e.$i.' & 0xff] |
1656
- ($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
1657
- ($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
1658
- ($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
1659
- }
1660
- $_encryptBlock .= '$in = pack("N*"'."\n";
1661
- for ($i = 0; $i < $Nb; ++$i) {
1662
- $_encryptBlock.= ',
1663
- ($'.$e.$i .' & 0xFF000000) ^
1664
- ($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000) ^
1665
- ($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00) ^
1666
- ($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF) ^
1667
- '.$w[$i]."\n";
1668
- }
1669
- $_encryptBlock .= ');';
1670
-
1671
- // Generating decrypt code:
1672
- $init_decryptBlock.= '
1673
- $dt0 = $self->dt0;
1674
- $dt1 = $self->dt1;
1675
- $dt2 = $self->dt2;
1676
- $dt3 = $self->dt3;
1677
- $isbox = $self->isbox;';
1678
-
1679
- $s = 'e';
1680
- $e = 's';
1681
- $wc = $Nb - 1;
1682
-
1683
- // Preround: addRoundKey
1684
- $_decryptBlock = '$in = unpack("N*", $in);'."\n";
1685
- for ($i = 0; $i < $Nb; ++$i) {
1686
- $_decryptBlock .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n";
1687
- }
1688
-
1689
- // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
1690
- for ($round = 1; $round < $Nr; ++$round) {
1691
- list($s, $e) = array($e, $s);
1692
- for ($i = 0; $i < $Nb; ++$i) {
1693
- $_decryptBlock.=
1694
- '$'.$e.$i.' =
1695
- $dt0[($'.$s.$i .' >> 24) & 0xff] ^
1696
- $dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^
1697
- $dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^
1698
- $dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^
1699
- '.$dw[++$wc].";\n";
1700
- }
1701
- }
1702
-
1703
- // Finalround: subWord + shiftRows + addRoundKey
1704
- for ($i = 0; $i < $Nb; ++$i) {
1705
- $_decryptBlock.=
1706
- '$'.$e.$i.' =
1707
- $isbox[ $'.$e.$i.' & 0xff] |
1708
- ($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
1709
- ($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
1710
- ($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
1711
- }
1712
- $_decryptBlock .= '$in = pack("N*"'."\n";
1713
- for ($i = 0; $i < $Nb; ++$i) {
1714
- $_decryptBlock.= ',
1715
- ($'.$e.$i. ' & 0xFF000000) ^
1716
- ($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000) ^
1717
- ($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00) ^
1718
- ($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF) ^
1719
- '.$dw[$i]."\n";
1720
- }
1721
- $_decryptBlock .= ');';
1722
-
1723
- // Generating mode of operation code:
1724
- switch ($mode) {
1725
- case CRYPT_RIJNDAEL_MODE_ECB:
1726
- $encrypt = $init_encryptBlock . '
1727
- $ciphertext = "";
1728
- $text = $self->_pad($text);
1729
- $plaintext_len = strlen($text);
1730
-
1731
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1732
- $in = substr($text, $i, '.$block_size.');
1733
- '.$_encryptBlock.'
1734
- $ciphertext.= $in;
1735
- }
1736
-
1737
- return $ciphertext;
1738
- ';
1739
-
1740
- $decrypt = $init_decryptBlock . '
1741
- $plaintext = "";
1742
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1743
- $ciphertext_len = strlen($text);
1744
-
1745
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1746
- $in = substr($text, $i, '.$block_size.');
1747
- '.$_decryptBlock.'
1748
- $plaintext.= $in;
1749
- }
1750
-
1751
- return $self->_unpad($plaintext);
1752
- ';
1753
- break;
1754
- case CRYPT_RIJNDAEL_MODE_CBC:
1755
- $encrypt = $init_encryptBlock . '
1756
- $ciphertext = "";
1757
- $text = $self->_pad($text);
1758
- $plaintext_len = strlen($text);
1759
-
1760
- $in = $self->encryptIV;
1761
-
1762
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1763
- $in = substr($text, $i, '.$block_size.') ^ $in;
1764
- '.$_encryptBlock.'
1765
- $ciphertext.= $in;
1766
- }
1767
-
1768
- if ($self->continuousBuffer) {
1769
- $self->encryptIV = $in;
1770
- }
1771
-
1772
- return $ciphertext;
1773
- ';
1774
-
1775
- $decrypt = $init_decryptBlock . '
1776
- $plaintext = "";
1777
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1778
- $ciphertext_len = strlen($text);
1779
-
1780
- $iv = $self->decryptIV;
1781
-
1782
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1783
- $in = $block = substr($text, $i, '.$block_size.');
1784
- '.$_decryptBlock.'
1785
- $plaintext.= $in ^ $iv;
1786
- $iv = $block;
1787
- }
1788
-
1789
- if ($self->continuousBuffer) {
1790
- $self->decryptIV = $iv;
1791
- }
1792
-
1793
- return $self->_unpad($plaintext);
1794
- ';
1795
- break;
1796
- case CRYPT_RIJNDAEL_MODE_CTR:
1797
- $encrypt = $init_encryptBlock . '
1798
- $ciphertext = "";
1799
- $plaintext_len = strlen($text);
1800
- $xor = $self->encryptIV;
1801
- $buffer = &$self->enbuffer;
1802
-
1803
- if (strlen($buffer["encrypted"])) {
1804
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1805
- $block = substr($text, $i, '.$block_size.');
1806
- if (strlen($block) > strlen($buffer["encrypted"])) {
1807
- $in = $self->_generate_xor('.$block_size.', $xor);
1808
- '.$_encryptBlock.'
1809
- $buffer["encrypted"].= $in;
1810
- }
1811
- $key = $self->_string_shift($buffer["encrypted"], '.$block_size.');
1812
- $ciphertext.= $block ^ $key;
1813
- }
1814
- } else {
1815
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1816
- $block = substr($text, $i, '.$block_size.');
1817
- $in = $self->_generate_xor('.$block_size.', $xor);
1818
- '.$_encryptBlock.'
1819
- $key = $in;
1820
- $ciphertext.= $block ^ $key;
1821
- }
1822
- }
1823
- if ($self->continuousBuffer) {
1824
- $self->encryptIV = $xor;
1825
- if ($start = $plaintext_len % '.$block_size.') {
1826
- $buffer["encrypted"] = substr($key, $start) . $buffer["encrypted"];
1827
- }
1828
- }
1829
-
1830
- return $ciphertext;
1831
- ';
1832
-
1833
- $decrypt = $init_encryptBlock . '
1834
- $plaintext = "";
1835
- $ciphertext_len = strlen($text);
1836
- $xor = $self->decryptIV;
1837
- $buffer = &$self->debuffer;
1838
-
1839
- if (strlen($buffer["ciphertext"])) {
1840
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1841
- $block = substr($text, $i, '.$block_size.');
1842
- if (strlen($block) > strlen($buffer["ciphertext"])) {
1843
- $in = $self->_generate_xor('.$block_size.', $xor);
1844
- '.$_encryptBlock.'
1845
- $buffer["ciphertext"].= $in;
1846
- }
1847
- $key = $self->_string_shift($buffer["ciphertext"], '.$block_size.');
1848
- $plaintext.= $block ^ $key;
1849
- }
1850
- } else {
1851
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1852
- $block = substr($text, $i, '.$block_size.');
1853
- $in = $self->_generate_xor('.$block_size.', $xor);
1854
- '.$_encryptBlock.'
1855
- $key = $in;
1856
- $plaintext.= $block ^ $key;
1857
- }
1858
- }
1859
- if ($self->continuousBuffer) {
1860
- $self->decryptIV = $xor;
1861
- if ($start = $ciphertext_len % '.$block_size.') {
1862
- $buffer["ciphertext"] = substr($key, $start) . $buffer["ciphertext"];
1863
- }
1864
- }
1865
-
1866
- return $plaintext;
1867
- ';
1868
- break;
1869
- case CRYPT_RIJNDAEL_MODE_CFB:
1870
- $encrypt = $init_encryptBlock . '
1871
- $ciphertext = "";
1872
- $buffer = &$self->enbuffer;
1873
-
1874
- if ($self->continuousBuffer) {
1875
- $iv = &$self->encryptIV;
1876
- $pos = &$buffer["pos"];
1877
- } else {
1878
- $iv = $self->encryptIV;
1879
- $pos = 0;
1880
- }
1881
- $len = strlen($text);
1882
- $i = 0;
1883
- if ($pos) {
1884
- $orig_pos = $pos;
1885
- $max = '.$block_size.' - $pos;
1886
- if ($len >= $max) {
1887
- $i = $max;
1888
- $len-= $max;
1889
- $pos = 0;
1890
- } else {
1891
- $i = $len;
1892
- $pos+= $len;
1893
- $len = 0;
1894
- }
1895
- $ciphertext = substr($iv, $orig_pos) ^ $text;
1896
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
1897
- }
1898
- while ($len >= '.$block_size.') {
1899
- $in = $iv;
1900
- '.$_encryptBlock.';
1901
- $iv = $in ^ substr($text, $i, '.$block_size.');
1902
- $ciphertext.= $iv;
1903
- $len-= '.$block_size.';
1904
- $i+= '.$block_size.';
1905
- }
1906
- if ($len) {
1907
- $in = $iv;
1908
- '.$_encryptBlock.'
1909
- $iv = $in;
1910
- $block = $iv ^ substr($text, $i);
1911
- $iv = substr_replace($iv, $block, 0, $len);
1912
- $ciphertext.= $block;
1913
- $pos = $len;
1914
- }
1915
- return $ciphertext;
1916
- ';
1917
-
1918
- $decrypt = $init_encryptBlock . '
1919
- $plaintext = "";
1920
- $buffer = &$self->debuffer;
1921
-
1922
- if ($self->continuousBuffer) {
1923
- $iv = &$self->decryptIV;
1924
- $pos = &$buffer["pos"];
1925
- } else {
1926
- $iv = $self->decryptIV;
1927
- $pos = 0;
1928
- }
1929
- $len = strlen($text);
1930
- $i = 0;
1931
- if ($pos) {
1932
- $orig_pos = $pos;
1933
- $max = '.$block_size.' - $pos;
1934
- if ($len >= $max) {
1935
- $i = $max;
1936
- $len-= $max;
1937
- $pos = 0;
1938
- } else {
1939
- $i = $len;
1940
- $pos+= $len;
1941
- $len = 0;
1942
- }
1943
- $plaintext = substr($iv, $orig_pos) ^ $text;
1944
- $iv = substr_replace($iv, substr($text, 0, $i), $orig_pos, $i);
1945
- }
1946
- while ($len >= '.$block_size.') {
1947
- $in = $iv;
1948
- '.$_encryptBlock.'
1949
- $iv = $in;
1950
- $cb = substr($text, $i, '.$block_size.');
1951
- $plaintext.= $iv ^ $cb;
1952
- $iv = $cb;
1953
- $len-= '.$block_size.';
1954
- $i+= '.$block_size.';
1955
- }
1956
- if ($len) {
1957
- $in = $iv;
1958
- '.$_encryptBlock.'
1959
- $iv = $in;
1960
- $plaintext.= $iv ^ substr($text, $i);
1961
- $iv = substr_replace($iv, substr($text, $i), 0, $len);
1962
- $pos = $len;
1963
- }
1964
-
1965
- return $plaintext;
1966
- ';
1967
- break;
1968
- case CRYPT_RIJNDAEL_MODE_OFB:
1969
- $encrypt = $init_encryptBlock . '
1970
- $ciphertext = "";
1971
- $plaintext_len = strlen($text);
1972
- $xor = $self->encryptIV;
1973
- $buffer = &$self->enbuffer;
1974
-
1975
- if (strlen($buffer["xor"])) {
1976
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1977
- $block = substr($text, $i, '.$block_size.');
1978
- if (strlen($block) > strlen($buffer["xor"])) {
1979
- $in = $xor;
1980
- '.$_encryptBlock.'
1981
- $xor = $in;
1982
- $buffer["xor"].= $xor;
1983
- }
1984
- $key = $self->_string_shift($buffer["xor"], '.$block_size.');
1985
- $ciphertext.= $block ^ $key;
1986
- }
1987
- } else {
1988
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1989
- $in = $xor;
1990
- '.$_encryptBlock.'
1991
- $xor = $in;
1992
- $ciphertext.= substr($text, $i, '.$block_size.') ^ $xor;
1993
- }
1994
- $key = $xor;
1995
- }
1996
- if ($self->continuousBuffer) {
1997
- $self->encryptIV = $xor;
1998
- if ($start = $plaintext_len % '.$block_size.') {
1999
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
2000
- }
2001
- }
2002
- return $ciphertext;
2003
- ';
2004
-
2005
- $decrypt = $init_encryptBlock . '
2006
- $plaintext = "";
2007
- $ciphertext_len = strlen($text);
2008
- $xor = $self->decryptIV;
2009
- $buffer = &$self->debuffer;
2010
-
2011
- if (strlen($buffer["xor"])) {
2012
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2013
- $block = substr($text, $i, '.$block_size.');
2014
- if (strlen($block) > strlen($buffer["xor"])) {
2015
- $in = $xor;
2016
- '.$_encryptBlock.'
2017
- $xor = $in;
2018
- $buffer["xor"].= $xor;
2019
- }
2020
- $key = $self->_string_shift($buffer["xor"], '.$block_size.');
2021
- $plaintext.= $block ^ $key;
2022
- }
2023
- } else {
2024
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
2025
- $in = $xor;
2026
- '.$_encryptBlock.'
2027
- $xor = $in;
2028
- $plaintext.= substr($text, $i, '.$block_size.') ^ $xor;
2029
- }
2030
- $key = $xor;
2031
- }
2032
- if ($self->continuousBuffer) {
2033
- $self->decryptIV = $xor;
2034
- if ($start = $ciphertext_len % '.$block_size.') {
2035
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
2036
- }
2037
- }
2038
- return $plaintext;
2039
- ';
2040
- break;
2041
- }
2042
- $lambda_functions[$code_hash] = create_function('$action, &$self, $text', 'if ($action == "encrypt") { '.$encrypt.' } else { '.$decrypt.' }');
2043
- }
2044
- $this->inline_crypt = $lambda_functions[$code_hash];
2045
- }
2046
-
2047
- /**
2048
- * Holds the lambda_functions table (classwide)
2049
- *
2050
- * @see Crypt_Rijndael::inline_crypt_setup()
2051
- * @return Array
2052
- * @access private
2053
- */
2054
- function &get_lambda_functions()
2055
- {
2056
- static $functions = array();
2057
- return $functions;
2058
- }
2059
- }
2060
-
2061
- // vim: ts=4:sw=4:et:
2062
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/TripleDES.php DELETED
@@ -1,842 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of Triple DES.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * Here's a short example of how to use this library:
12
- * <code>
13
- * <?php
14
- * include('Crypt/TripleDES.php');
15
- *
16
- * $des = new Crypt_TripleDES();
17
- *
18
- * $des->setKey('abcdefghijklmnopqrstuvwx');
19
- *
20
- * $size = 10 * 1024;
21
- * $plaintext = '';
22
- * for ($i = 0; $i < $size; $i++) {
23
- * $plaintext.= 'a';
24
- * }
25
- *
26
- * echo $des->decrypt($des->encrypt($plaintext));
27
- * ?>
28
- * </code>
29
- *
30
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
31
- * of this software and associated documentation files (the "Software"), to deal
32
- * in the Software without restriction, including without limitation the rights
33
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34
- * copies of the Software, and to permit persons to whom the Software is
35
- * furnished to do so, subject to the following conditions:
36
- *
37
- * The above copyright notice and this permission notice shall be included in
38
- * all copies or substantial portions of the Software.
39
- *
40
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
46
- * THE SOFTWARE.
47
- *
48
- * @category Crypt
49
- * @package Crypt_TripleDES
50
- * @author Jim Wigginton <terrafrost@php.net>
51
- * @copyright MMVII Jim Wigginton
52
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
53
- * @link http://phpseclib.sourceforge.net
54
- */
55
-
56
- /**
57
- * Include Crypt_DES
58
- */
59
- if (!class_exists('Crypt_DES')) {
60
- require_once('DES.php');
61
- }
62
-
63
- /**
64
- * Encrypt / decrypt using inner chaining
65
- *
66
- * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
67
- */
68
- define('CRYPT_DES_MODE_3CBC', -2);
69
-
70
- /**
71
- * Encrypt / decrypt using outer chaining
72
- *
73
- * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
74
- */
75
- define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
76
-
77
- /**
78
- * Pure-PHP implementation of Triple DES.
79
- *
80
- * @author Jim Wigginton <terrafrost@php.net>
81
- * @version 0.1.0
82
- * @access public
83
- * @package Crypt_TerraDES
84
- */
85
- class Crypt_TripleDES extends Crypt_DES {
86
- /**
87
- * The Crypt_DES objects
88
- *
89
- * @var Array
90
- * @access private
91
- */
92
- var $des;
93
-
94
- /**
95
- * Default Constructor.
96
- *
97
- * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
98
- * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used.
99
- *
100
- * @param optional Integer $mode
101
- * @return Crypt_TripleDES
102
- * @access public
103
- */
104
- function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
105
- {
106
- if ( !defined('CRYPT_DES_MODE') ) {
107
- switch (true) {
108
- case extension_loaded('mcrypt') && in_array('tripledes', mcrypt_list_algorithms()):
109
- define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
110
- break;
111
- default:
112
- define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
113
- }
114
- }
115
-
116
- if ( $mode == CRYPT_DES_MODE_3CBC ) {
117
- $this->mode = CRYPT_DES_MODE_3CBC;
118
- $this->des = array(
119
- new Crypt_DES(CRYPT_DES_MODE_CBC),
120
- new Crypt_DES(CRYPT_DES_MODE_CBC),
121
- new Crypt_DES(CRYPT_DES_MODE_CBC)
122
- );
123
- $this->paddable = true;
124
-
125
- // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
126
- $this->des[0]->disablePadding();
127
- $this->des[1]->disablePadding();
128
- $this->des[2]->disablePadding();
129
-
130
- return;
131
- }
132
-
133
- switch ( CRYPT_DES_MODE ) {
134
- case CRYPT_DES_MODE_MCRYPT:
135
- switch ($mode) {
136
- case CRYPT_DES_MODE_ECB:
137
- $this->paddable = true;
138
- $this->mode = MCRYPT_MODE_ECB;
139
- break;
140
- case CRYPT_DES_MODE_CTR:
141
- $this->mode = 'ctr';
142
- break;
143
- case CRYPT_DES_MODE_CFB:
144
- $this->mode = 'ncfb';
145
- $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
146
- break;
147
- case CRYPT_DES_MODE_OFB:
148
- $this->mode = MCRYPT_MODE_NOFB;
149
- break;
150
- case CRYPT_DES_MODE_CBC:
151
- default:
152
- $this->paddable = true;
153
- $this->mode = MCRYPT_MODE_CBC;
154
- }
155
- $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
156
- $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
157
-
158
- break;
159
- default:
160
- $this->des = array(
161
- new Crypt_DES(CRYPT_DES_MODE_ECB),
162
- new Crypt_DES(CRYPT_DES_MODE_ECB),
163
- new Crypt_DES(CRYPT_DES_MODE_ECB)
164
- );
165
-
166
- // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
167
- $this->des[0]->disablePadding();
168
- $this->des[1]->disablePadding();
169
- $this->des[2]->disablePadding();
170
-
171
- switch ($mode) {
172
- case CRYPT_DES_MODE_ECB:
173
- case CRYPT_DES_MODE_CBC:
174
- $this->paddable = true;
175
- $this->mode = $mode;
176
- break;
177
- case CRYPT_DES_MODE_CTR:
178
- case CRYPT_DES_MODE_CFB:
179
- case CRYPT_DES_MODE_OFB:
180
- $this->mode = $mode;
181
- break;
182
- default:
183
- $this->paddable = true;
184
- $this->mode = CRYPT_DES_MODE_CBC;
185
- }
186
- if (function_exists('create_function') && is_callable('create_function')) {
187
- $this->inline_crypt_setup(3);
188
- $this->use_inline_crypt = true;
189
- }
190
- }
191
- }
192
-
193
- /**
194
- * Sets the key.
195
- *
196
- * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
197
- * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
198
- *
199
- * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
200
- *
201
- * If the key is not explicitly set, it'll be assumed to be all zero's.
202
- *
203
- * @access public
204
- * @param String $key
205
- */
206
- function setKey($key)
207
- {
208
- $length = strlen($key);
209
- if ($length > 8) {
210
- $key = str_pad($key, 24, chr(0));
211
- // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
212
- // http://php.net/function.mcrypt-encrypt#47973
213
- //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
214
- } else {
215
- $key = str_pad($key, 8, chr(0));
216
- }
217
- $this->key = $key;
218
- switch (true) {
219
- case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
220
- case $this->mode == CRYPT_DES_MODE_3CBC:
221
- $this->des[0]->setKey(substr($key, 0, 8));
222
- $this->des[1]->setKey(substr($key, 8, 8));
223
- $this->des[2]->setKey(substr($key, 16, 8));
224
-
225
- // Merge the three DES-1-dim-key-arrays for 3DES-inline-en/decrypting
226
- if ($this->use_inline_crypt && $this->mode != CRYPT_DES_MODE_3CBC) {
227
- $this->keys = array(
228
- CRYPT_DES_ENCRYPT_1DIM => array_merge(
229
- $this->des[0]->keys[CRYPT_DES_ENCRYPT_1DIM],
230
- $this->des[1]->keys[CRYPT_DES_DECRYPT_1DIM],
231
- $this->des[2]->keys[CRYPT_DES_ENCRYPT_1DIM]
232
- ),
233
- CRYPT_DES_DECRYPT_1DIM => array_merge(
234
- $this->des[2]->keys[CRYPT_DES_DECRYPT_1DIM],
235
- $this->des[1]->keys[CRYPT_DES_ENCRYPT_1DIM],
236
- $this->des[0]->keys[CRYPT_DES_DECRYPT_1DIM]
237
- ),
238
- );
239
- }
240
- }
241
- $this->enchanged = $this->dechanged = true;
242
- }
243
-
244
- /**
245
- * Sets the password.
246
- *
247
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
248
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
249
- * $hash, $salt, $method
250
- *
251
- * @param String $password
252
- * @param optional String $method
253
- * @access public
254
- */
255
- function setPassword($password, $method = 'pbkdf2')
256
- {
257
- $key = '';
258
-
259
- switch ($method) {
260
- default: // 'pbkdf2'
261
- list(, , $hash, $salt, $count) = func_get_args();
262
- if (!isset($hash)) {
263
- $hash = 'sha1';
264
- }
265
- // WPA and WPA2 use the SSID as the salt
266
- if (!isset($salt)) {
267
- $salt = 'phpseclib';
268
- }
269
- // RFC2898#section-4.2 uses 1,000 iterations by default
270
- // WPA and WPA2 use 4,096.
271
- if (!isset($count)) {
272
- $count = 1000;
273
- }
274
-
275
- if (!class_exists('Crypt_Hash')) {
276
- require_once('Crypt/Hash.php');
277
- }
278
-
279
- $i = 1;
280
- while (strlen($key) < 24) { // $dkLen == 24
281
- $hmac = new Crypt_Hash();
282
- $hmac->setHash($hash);
283
- $hmac->setKey($password);
284
- $f = $u = $hmac->hash($salt . pack('N', $i++));
285
- for ($j = 2; $j <= $count; $j++) {
286
- $u = $hmac->hash($u);
287
- $f^= $u;
288
- }
289
- $key.= $f;
290
- }
291
- }
292
-
293
- $this->setKey($key);
294
- }
295
-
296
- /**
297
- * Sets the initialization vector. (optional)
298
- *
299
- * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
300
- * to be all zero's.
301
- *
302
- * @access public
303
- * @param String $iv
304
- */
305
- function setIV($iv)
306
- {
307
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
308
- if ($this->mode == CRYPT_DES_MODE_3CBC) {
309
- $this->des[0]->setIV($iv);
310
- $this->des[1]->setIV($iv);
311
- $this->des[2]->setIV($iv);
312
- }
313
- $this->enchanged = $this->dechanged = true;
314
- }
315
-
316
- /**
317
- * Encrypts a message.
318
- *
319
- * @access public
320
- * @param String $plaintext
321
- */
322
- function encrypt($plaintext)
323
- {
324
- if ($this->paddable) {
325
- $plaintext = $this->_pad($plaintext);
326
- }
327
-
328
- // if the key is smaller then 8, do what we'd normally do
329
- if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
330
- $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
331
-
332
- return $ciphertext;
333
- }
334
-
335
- if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
336
- if ($this->enchanged) {
337
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
338
- if ($this->mode == 'ncfb') {
339
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
340
- }
341
- $this->enchanged = false;
342
- }
343
-
344
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
345
- $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
346
- } else {
347
- $iv = &$this->encryptIV;
348
- $pos = &$this->enbuffer['pos'];
349
- $len = strlen($plaintext);
350
- $ciphertext = '';
351
- $i = 0;
352
- if ($pos) {
353
- $orig_pos = $pos;
354
- $max = 8 - $pos;
355
- if ($len >= $max) {
356
- $i = $max;
357
- $len-= $max;
358
- $pos = 0;
359
- } else {
360
- $i = $len;
361
- $pos+= $len;
362
- $len = 0;
363
- }
364
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
365
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
366
- $this->enbuffer['enmcrypt_init'] = true;
367
- }
368
- if ($len >= 8) {
369
- if ($this->enbuffer['enmcrypt_init'] === false || $len > 950) {
370
- if ($this->enbuffer['enmcrypt_init'] === true) {
371
- mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
372
- $this->enbuffer['enmcrypt_init'] = false;
373
- }
374
- $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 8));
375
- $iv = substr($ciphertext, -8);
376
- $i = strlen($ciphertext);
377
- $len%= 8;
378
- } else {
379
- while ($len >= 8) {
380
- $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 8);
381
- $ciphertext.= $iv;
382
- $len-= 8;
383
- $i+= 8;
384
- }
385
- }
386
- }
387
- if ($len) {
388
- $iv = mcrypt_generic($this->ecb, $iv);
389
- $block = $iv ^ substr($plaintext, $i);
390
- $iv = substr_replace($iv, $block, 0, $len);
391
- $ciphertext.= $block;
392
- $pos = $len;
393
- }
394
- return $ciphertext;
395
- }
396
-
397
- if (!$this->continuousBuffer) {
398
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
399
- }
400
-
401
- return $ciphertext;
402
- }
403
-
404
- if (strlen($this->key) <= 8) {
405
- $this->des[0]->mode = $this->mode;
406
-
407
- return $this->des[0]->encrypt($plaintext);
408
- }
409
-
410
- if ($this->use_inline_crypt) {
411
- $inline = $this->inline_crypt;
412
- return $inline('encrypt', $this, $plaintext);
413
- }
414
-
415
- $des = $this->des;
416
-
417
- $buffer = &$this->enbuffer;
418
- $continuousBuffer = $this->continuousBuffer;
419
- $ciphertext = '';
420
- switch ($this->mode) {
421
- case CRYPT_DES_MODE_ECB:
422
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
423
- $block = substr($plaintext, $i, 8);
424
- // all of these _processBlock calls could, in theory, be put in a function - say Crypt_TripleDES::_ede_encrypt() or something.
425
- // only problem with that: it would slow encryption and decryption down. $this->des would have to be called every time that
426
- // function is called, instead of once for the whole string of text that's being encrypted, which would, in turn, make
427
- // encryption and decryption take more time, per this:
428
- //
429
- // http://blog.libssh2.org/index.php?/archives/21-Compiled-Variables.html
430
- $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
431
- $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
432
- $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
433
- $ciphertext.= $block;
434
- }
435
- break;
436
- case CRYPT_DES_MODE_CBC:
437
- $xor = $this->encryptIV;
438
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
439
- $block = substr($plaintext, $i, 8) ^ $xor;
440
- $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
441
- $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
442
- $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
443
- $xor = $block;
444
- $ciphertext.= $block;
445
- }
446
- if ($this->continuousBuffer) {
447
- $this->encryptIV = $xor;
448
- }
449
- break;
450
- case CRYPT_DES_MODE_CTR:
451
- $xor = $this->encryptIV;
452
- if (strlen($buffer['encrypted'])) {
453
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
454
- $block = substr($plaintext, $i, 8);
455
- if (strlen($block) > strlen($buffer['encrypted'])) {
456
- $key = $this->_generate_xor($xor);
457
- $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
458
- $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
459
- $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
460
- $buffer['encrypted'].= $key;
461
- }
462
- $key = $this->_string_shift($buffer['encrypted']);
463
- $ciphertext.= $block ^ $key;
464
- }
465
- } else {
466
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
467
- $block = substr($plaintext, $i, 8);
468
- $key = $this->_generate_xor($xor);
469
- $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
470
- $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
471
- $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
472
- $ciphertext.= $block ^ $key;
473
- }
474
- }
475
- if ($this->continuousBuffer) {
476
- $this->encryptIV = $xor;
477
- if ($start = strlen($plaintext) & 7) {
478
- $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
479
- }
480
- }
481
- break;
482
- case CRYPT_DES_MODE_CFB:
483
- if (strlen($buffer['xor'])) {
484
- $ciphertext = $plaintext ^ $buffer['xor'];
485
- $iv = $buffer['encrypted'] . $ciphertext;
486
- $start = strlen($ciphertext);
487
- $buffer['encrypted'].= $ciphertext;
488
- $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
489
- } else {
490
- $ciphertext = '';
491
- $iv = $this->encryptIV;
492
- $start = 0;
493
- }
494
-
495
- for ($i = $start; $i < strlen($plaintext); $i+=8) {
496
- $block = substr($plaintext, $i, 8);
497
- $iv = $des[0]->_processBlock($iv, CRYPT_DES_ENCRYPT);
498
- $iv = $des[1]->_processBlock($iv, CRYPT_DES_DECRYPT);
499
- $xor= $des[2]->_processBlock($iv, CRYPT_DES_ENCRYPT);
500
-
501
- $iv = $block ^ $xor;
502
- if ($continuousBuffer && strlen($iv) != 8) {
503
- $buffer = array(
504
- 'encrypted' => $iv,
505
- 'xor' => substr($xor, strlen($iv))
506
- );
507
- }
508
- $ciphertext.= $iv;
509
- }
510
-
511
- if ($this->continuousBuffer) {
512
- $this->encryptIV = $iv;
513
- }
514
- break;
515
- case CRYPT_DES_MODE_OFB:
516
- $xor = $this->encryptIV;
517
- if (strlen($buffer['xor'])) {
518
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
519
- $block = substr($plaintext, $i, 8);
520
- if (strlen($block) > strlen($buffer['xor'])) {
521
- $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
522
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
523
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
524
- $buffer['xor'].= $xor;
525
- }
526
- $key = $this->_string_shift($buffer['xor']);
527
- $ciphertext.= $block ^ $key;
528
- }
529
- } else {
530
- for ($i = 0; $i < strlen($plaintext); $i+=8) {
531
- $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
532
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
533
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
534
- $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
535
- }
536
- $key = $xor;
537
- }
538
- if ($this->continuousBuffer) {
539
- $this->encryptIV = $xor;
540
- if ($start = strlen($plaintext) & 7) {
541
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
542
- }
543
- }
544
- }
545
-
546
- return $ciphertext;
547
- }
548
-
549
- /**
550
- * Decrypts a message.
551
- *
552
- * @access public
553
- * @param String $ciphertext
554
- */
555
- function decrypt($ciphertext)
556
- {
557
- if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
558
- $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
559
-
560
- return $this->_unpad($plaintext);
561
- }
562
-
563
- if ($this->paddable) {
564
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
565
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
566
- $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
567
- }
568
-
569
- if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
570
- if ($this->dechanged) {
571
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
572
- if ($this->mode == 'ncfb') {
573
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
574
- }
575
- $this->dechanged = false;
576
- }
577
-
578
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
579
- $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
580
- } else {
581
- $iv = &$this->decryptIV;
582
- $pos = &$this->debuffer['pos'];
583
- $len = strlen($ciphertext);
584
- $plaintext = '';
585
- $i = 0;
586
- if ($pos) {
587
- $orig_pos = $pos;
588
- $max = 8 - $pos;
589
- if ($len >= $max) {
590
- $i = $max;
591
- $len-= $max;
592
- $pos = 0;
593
- } else {
594
- $i = $len;
595
- $pos+= $len;
596
- $len = 0;
597
- }
598
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
599
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
600
- }
601
- if ($len >= 8) {
602
- $cb = substr($ciphertext, $i, $len - $len % 8);
603
- $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
604
- $iv = substr($cb, -8);
605
- $len%= 8;
606
- }
607
- if ($len) {
608
- $iv = mcrypt_generic($this->ecb, $iv);
609
- $cb = substr($ciphertext, -$len);
610
- $plaintext.= $iv ^ $cb;
611
- $iv = substr_replace($iv, $cb, 0, $len);
612
- $pos = $len;
613
- }
614
- return $plaintext;
615
- }
616
-
617
- if (!$this->continuousBuffer) {
618
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
619
- }
620
-
621
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
622
- }
623
-
624
- if (strlen($this->key) <= 8) {
625
- $this->des[0]->mode = $this->mode;
626
- $plaintext = $this->des[0]->decrypt($ciphertext);
627
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
628
- }
629
-
630
- if ($this->use_inline_crypt) {
631
- $inline = $this->inline_crypt;
632
- return $inline('decrypt', $this, $ciphertext);
633
- }
634
-
635
- $des = $this->des;
636
-
637
- $buffer = &$this->debuffer;
638
- $continuousBuffer = $this->continuousBuffer;
639
- $plaintext = '';
640
- switch ($this->mode) {
641
- case CRYPT_DES_MODE_ECB:
642
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
643
- $block = substr($ciphertext, $i, 8);
644
- $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
645
- $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
646
- $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
647
- $plaintext.= $block;
648
- }
649
- break;
650
- case CRYPT_DES_MODE_CBC:
651
- $xor = $this->decryptIV;
652
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
653
- $orig = $block = substr($ciphertext, $i, 8);
654
- $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
655
- $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
656
- $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
657
- $plaintext.= $block ^ $xor;
658
- $xor = $orig;
659
- }
660
- if ($this->continuousBuffer) {
661
- $this->decryptIV = $xor;
662
- }
663
- break;
664
- case CRYPT_DES_MODE_CTR:
665
- $xor = $this->decryptIV;
666
- if (strlen($buffer['ciphertext'])) {
667
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
668
- $block = substr($ciphertext, $i, 8);
669
- if (strlen($block) > strlen($buffer['ciphertext'])) {
670
- $key = $this->_generate_xor($xor);
671
- $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
672
- $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
673
- $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
674
- $buffer['ciphertext'].= $key;
675
- }
676
- $key = $this->_string_shift($buffer['ciphertext']);
677
- $plaintext.= $block ^ $key;
678
- }
679
- } else {
680
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
681
- $block = substr($ciphertext, $i, 8);
682
- $key = $this->_generate_xor($xor);
683
- $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
684
- $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
685
- $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
686
- $plaintext.= $block ^ $key;
687
- }
688
- }
689
- if ($this->continuousBuffer) {
690
- $this->decryptIV = $xor;
691
- if ($start = strlen($plaintext) & 7) {
692
- $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
693
- }
694
- }
695
- break;
696
- case CRYPT_DES_MODE_CFB:
697
- if (strlen($buffer['ciphertext'])) {
698
- $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($buffer['ciphertext']));
699
- $buffer['ciphertext'].= substr($ciphertext, 0, strlen($plaintext));
700
- if (strlen($buffer['ciphertext']) != 8) {
701
- $block = $this->decryptIV;
702
- } else {
703
- $block = $buffer['ciphertext'];
704
- $xor = $des[0]->_processBlock($buffer['ciphertext'], CRYPT_DES_ENCRYPT);
705
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
706
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
707
- $buffer['ciphertext'] = '';
708
- }
709
- $start = strlen($plaintext);
710
- } else {
711
- $plaintext = '';
712
- $xor = $des[0]->_processBlock($this->decryptIV, CRYPT_DES_ENCRYPT);
713
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
714
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
715
- $start = 0;
716
- }
717
-
718
- for ($i = $start; $i < strlen($ciphertext); $i+=8) {
719
- $block = substr($ciphertext, $i, 8);
720
- $plaintext.= $block ^ $xor;
721
- if ($continuousBuffer && strlen($block) != 8) {
722
- $buffer['ciphertext'].= $block;
723
- $block = $xor;
724
- } else if (strlen($block) == 8) {
725
- $xor = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
726
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
727
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
728
- }
729
- }
730
- if ($this->continuousBuffer) {
731
- $this->decryptIV = $block;
732
- }
733
- break;
734
- case CRYPT_DES_MODE_OFB:
735
- $xor = $this->decryptIV;
736
- if (strlen($buffer['xor'])) {
737
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
738
- $block = substr($ciphertext, $i, 8);
739
- if (strlen($block) > strlen($buffer['xor'])) {
740
- $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
741
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
742
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
743
- $buffer['xor'].= $xor;
744
- }
745
- $key = $this->_string_shift($buffer['xor']);
746
- $plaintext.= $block ^ $key;
747
- }
748
- } else {
749
- for ($i = 0; $i < strlen($ciphertext); $i+=8) {
750
- $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
751
- $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
752
- $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
753
- $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
754
- }
755
- $key = $xor;
756
- }
757
- if ($this->continuousBuffer) {
758
- $this->decryptIV = $xor;
759
- if ($start = strlen($ciphertext) & 7) {
760
- $buffer['xor'] = substr($key, $start) . $buffer['xor'];
761
- }
762
- }
763
- }
764
-
765
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
766
- }
767
-
768
- /**
769
- * Treat consecutive "packets" as if they are a continuous buffer.
770
- *
771
- * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
772
- * will yield different outputs:
773
- *
774
- * <code>
775
- * echo $des->encrypt(substr($plaintext, 0, 8));
776
- * echo $des->encrypt(substr($plaintext, 8, 8));
777
- * </code>
778
- * <code>
779
- * echo $des->encrypt($plaintext);
780
- * </code>
781
- *
782
- * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
783
- * another, as demonstrated with the following:
784
- *
785
- * <code>
786
- * $des->encrypt(substr($plaintext, 0, 8));
787
- * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
788
- * </code>
789
- * <code>
790
- * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
791
- * </code>
792
- *
793
- * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
794
- * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
795
- * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
796
- *
797
- * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
798
- * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
799
- * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
800
- * however, they are also less intuitive and more likely to cause you problems.
801
- *
802
- * @see Crypt_TripleDES::disableContinuousBuffer()
803
- * @access public
804
- */
805
- function enableContinuousBuffer()
806
- {
807
- $this->continuousBuffer = true;
808
- if ($this->mode == CRYPT_DES_MODE_3CBC) {
809
- $this->des[0]->enableContinuousBuffer();
810
- $this->des[1]->enableContinuousBuffer();
811
- $this->des[2]->enableContinuousBuffer();
812
- }
813
- }
814
-
815
- /**
816
- * Treat consecutive packets as if they are a discontinuous buffer.
817
- *
818
- * The default behavior.
819
- *
820
- * @see Crypt_TripleDES::enableContinuousBuffer()
821
- * @access public
822
- */
823
- function disableContinuousBuffer()
824
- {
825
- $this->continuousBuffer = false;
826
- $this->encryptIV = $this->iv;
827
- $this->decryptIV = $this->iv;
828
- $this->enchanged = true;
829
- $this->dechanged = true;
830
- $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
831
- $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
832
-
833
- if ($this->mode == CRYPT_DES_MODE_3CBC) {
834
- $this->des[0]->disableContinuousBuffer();
835
- $this->des[1]->disableContinuousBuffer();
836
- $this->des[2]->disableContinuousBuffer();
837
- }
838
- }
839
- }
840
-
841
- // vim: ts=4:sw=4:et:
842
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/PHPSecLib/Crypt/Twofish.php DELETED
@@ -1,1664 +0,0 @@
1
- <?php
2
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
-
4
- /**
5
- * Pure-PHP implementation of Twofish.
6
- *
7
- * Uses mcrypt, if available, and an internal implementation, otherwise.
8
- *
9
- * PHP versions 4 and 5
10
- *
11
- * Useful resources are as follows:
12
- *
13
- * - {@link http://en.wikipedia.org/wiki/Twofish Wikipedia description of Twofish}
14
- *
15
- * Here's a short example of how to use this library:
16
- * <code>
17
- * <?php
18
- * include('Crypt/Twofish.php');
19
- *
20
- * $Twofish = new Crypt_Twofish();
21
- *
22
- * $Twofish->setKey('12345678901234567890123456789012');
23
- *
24
- * $plaintext = str_repeat('a', 1024);
25
- *
26
- * echo $Twofish->decrypt($Twofish->encrypt($plaintext));
27
- * ?>
28
- * </code>
29
- *
30
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
31
- * of this software and associated documentation files (the "Software"), to deal
32
- * in the Software without restriction, including without limitation the rights
33
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34
- * copies of the Software, and to permit persons to whom the Software is
35
- * furnished to do so, subject to the following conditions:
36
- *
37
- * The above copyright notice and this permission notice shall be included in
38
- * all copies or substantial portions of the Software.
39
- *
40
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
46
- * THE SOFTWARE.
47
- *
48
- * @category Crypt
49
- * @package Crypt_Twofish
50
- * @author Jim Wigginton <terrafrost@php.net>
51
- * @author Hans-Juergen Petrich <petrich@tronic-media.com>
52
- * @copyright MMVII Jim Wigginton
53
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
54
- * @version 1.0
55
- * @link http://phpseclib.sourceforge.net
56
- */
57
-
58
- /**#@+
59
- * @access public
60
- * @see Crypt_Twofish::encrypt()
61
- * @see Crypt_Twofish::decrypt()
62
- */
63
- /**
64
- * Encrypt / decrypt using the Counter mode.
65
- *
66
- * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
67
- *
68
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
69
- */
70
- define('CRYPT_TWOFISH_MODE_CTR', -1);
71
- /**
72
- * Encrypt / decrypt using the Electronic Code Book mode.
73
- *
74
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
75
- */
76
- define('CRYPT_TWOFISH_MODE_ECB', 1);
77
- /**
78
- * Encrypt / decrypt using the Code Book Chaining mode.
79
- *
80
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
81
- */
82
- define('CRYPT_TWOFISH_MODE_CBC', 2);
83
- /**
84
- * Encrypt / decrypt using the Cipher Feedback mode.
85
- *
86
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
87
- */
88
- define('CRYPT_TWOFISH_MODE_CFB', 3);
89
- /**
90
- * Encrypt / decrypt using the Cipher Feedback mode.
91
- *
92
- * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
93
- */
94
- define('CRYPT_TWOFISH_MODE_OFB', 4);
95
- /**#@-*/
96
-
97
- /**#@+
98
- * @access private
99
- * @see Crypt_Twofish::Crypt_Twofish()
100
- */
101
- /**
102
- * Toggles the internal implementation
103
- */
104
- define('CRYPT_TWOFISH_MODE_INTERNAL', 1);
105
- /**
106
- * Toggles the mcrypt implementation
107
- */
108
- define('CRYPT_TWOFISH_MODE_MCRYPT', 2);
109
- /**#@-*/
110
-
111
- /**
112
- * Pure-PHP implementation of Twofish.
113
- *
114
- * @author Jim Wigginton <terrafrost@php.net>
115
- * @author Hans-Juergen Petrich <petrich@tronic-media.com>
116
- * @version 1.0
117
- * @access public
118
- * @package Crypt_Twofish
119
- */
120
- class Crypt_Twofish {
121
- /**
122
- * The Key as String
123
- *
124
- * @see Crypt_Twofish::setKey()
125
- * @var Array
126
- * @access private
127
- */
128
- var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
129
-
130
- /**
131
- * The Encryption Mode
132
- *
133
- * @see Crypt_Twofish::Crypt_Twofish()
134
- * @var Integer
135
- * @access private
136
- */
137
- var $mode;
138
-
139
- /**
140
- * Continuous Buffer status
141
- *
142
- * @see Crypt_Twofish::enableContinuousBuffer()
143
- * @var Boolean
144
- * @access private
145
- */
146
- var $continuousBuffer = false;
147
-
148
- /**
149
- * Padding status
150
- *
151
- * @see Crypt_Twofish::enablePadding()
152
- * @var Boolean
153
- * @access private
154
- */
155
- var $padding = true;
156
-
157
- /**
158
- * The Initialization Vector
159
- *
160
- * @see Crypt_Twofish::setIV()
161
- * @var String
162
- * @access private
163
- */
164
- var $iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
165
-
166
- /**
167
- * A "sliding" Initialization Vector
168
- *
169
- * @see Crypt_Twofish::enableContinuousBuffer()
170
- * @var String
171
- * @access private
172
- */
173
- var $encryptIV = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
174
-
175
- /**
176
- * A "sliding" Initialization Vector
177
- *
178
- * @see Crypt_Twofish::enableContinuousBuffer()
179
- * @var String
180
- * @access private
181
- */
182
- var $decryptIV = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
183
-
184
- /**
185
- * mcrypt resource for encryption
186
- *
187
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
188
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
189
- *
190
- * @see Crypt_Twofish::encrypt()
191
- * @var String
192
- * @access private
193
- */
194
- var $enmcrypt;
195
-
196
- /**
197
- * mcrypt resource for decryption
198
- *
199
- * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
200
- * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
201
- *
202
- * @see Crypt_Twofish::decrypt()
203
- * @var String
204
- * @access private
205
- */
206
- var $demcrypt;
207
-
208
- /**
209
- * Does the enmcrypt resource need to be (re)initialized?
210
- *
211
- * @see Crypt_Twofish::setKey()
212
- * @see Crypt_Twofish::setIV()
213
- * @var Boolean
214
- * @access private
215
- */
216
- var $enchanged = true;
217
-
218
- /**
219
- * Does the demcrypt resource need to be (re)initialized?
220
- *
221
- * @see Crypt_Twofish::setKey()
222
- * @see Crypt_Twofish::setIV()
223
- * @var Boolean
224
- * @access private
225
- */
226
- var $dechanged = true;
227
-
228
- /**
229
- * Is the mode one that is paddable?
230
- *
231
- * @see Crypt_Twofish::Crypt_Twofish()
232
- * @var Boolean
233
- * @access private
234
- */
235
- var $paddable = false;
236
-
237
- /**
238
- * Encryption buffer for CTR, OFB and CFB modes
239
- *
240
- * @see Crypt_Twofish::encrypt()
241
- * @var Array
242
- * @access private
243
- */
244
- var $enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
245
-
246
- /**
247
- * Decryption buffer for CTR, OFB and CFB modes
248
- *
249
- * @see Crypt_Twofish::decrypt()
250
- * @var Array
251
- * @access private
252
- */
253
- var $debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
254
-
255
- /**
256
- * mcrypt resource for CFB mode
257
- *
258
- * @see Crypt_Twofish::encrypt()
259
- * @see Crypt_Twofish::decrypt()
260
- * @var String
261
- * @access private
262
- */
263
- var $ecb;
264
-
265
- /**
266
- * Performance-optimized callback function for en/decrypt()
267
- *
268
- * @var Callback
269
- * @access private
270
- */
271
- var $inline_crypt;
272
-
273
- /**
274
- * Q-Table
275
- *
276
- * @var Array
277
- * @access private
278
- */
279
- var $q0 = array (
280
- 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76,
281
- 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38,
282
- 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C,
283
- 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48,
284
- 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23,
285
- 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82,
286
- 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C,
287
- 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61,
288
- 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B,
289
- 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1,
290
- 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66,
291
- 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7,
292
- 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA,
293
- 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71,
294
- 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8,
295
- 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7,
296
- 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2,
297
- 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90,
298
- 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB,
299
- 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF,
300
- 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B,
301
- 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64,
302
- 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A,
303
- 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A,
304
- 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02,
305
- 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D,
306
- 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72,
307
- 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34,
308
- 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8,
309
- 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4,
310
- 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00,
311
- 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0
312
- );
313
-
314
- /**
315
- * Q-Table
316
- *
317
- * @var Array
318
- * @access private
319
- */
320
- var $q1 = array (
321
- 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8,
322
- 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B,
323
- 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1,
324
- 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F,
325
- 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D,
326
- 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5,
327
- 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3,
328
- 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51,
329
- 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96,
330
- 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C,
331
- 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70,
332
- 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8,
333
- 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC,
334
- 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2,
335
- 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9,
336
- 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17,
337
- 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3,
338
- 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E,
339
- 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49,
340
- 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9,
341
- 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01,
342
- 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48,
343
- 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19,
344
- 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64,
345
- 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5,
346
- 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69,
347
- 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E,
348
- 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC,
349
- 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB,
350
- 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9,
351
- 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2,
352
- 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91
353
- );
354
-
355
- /**
356
- * M-Table
357
- *
358
- * @var Array
359
- * @access private
360
- */
361
- var $m0 = array (
362
- 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8,
363
- 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B,
364
- 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1,
365
- 0x24243C30, 0x5151E20F, 0xBABAC6F8, 0x4A4AF31B, 0xBFBF4887, 0x0D0D70FA, 0xB0B0B306, 0x7575DE3F,
366
- 0xD2D2FD5E, 0x7D7D20BA, 0x666631AE, 0x3A3AA35B, 0x59591C8A, 0x00000000, 0xCDCD93BC, 0x1A1AE09D,
367
- 0xAEAE2C6D, 0x7F7FABC1, 0x2B2BC7B1, 0xBEBEB90E, 0xE0E0A080, 0x8A8A105D, 0x3B3B52D2, 0x6464BAD5,
368
- 0xD8D888A0, 0xE7E7A584, 0x5F5FE807, 0x1B1B1114, 0x2C2CC2B5, 0xFCFCB490, 0x3131272C, 0x808065A3,
369
- 0x73732AB2, 0x0C0C8173, 0x79795F4C, 0x6B6B4154, 0x4B4B0292, 0x53536974, 0x94948F36, 0x83831F51,
370
- 0x2A2A3638, 0xC4C49CB0, 0x2222C8BD, 0xD5D5F85A, 0xBDBDC3FC, 0x48487860, 0xFFFFCE62, 0x4C4C0796,
371
- 0x4141776C, 0xC7C7E642, 0xEBEB24F7, 0x1C1C1410, 0x5D5D637C, 0x36362228, 0x6767C027, 0xE9E9AF8C,
372
- 0x4444F913, 0x1414EA95, 0xF5F5BB9C, 0xCFCF18C7, 0x3F3F2D24, 0xC0C0E346, 0x7272DB3B, 0x54546C70,
373
- 0x29294CCA, 0xF0F035E3, 0x0808FE85, 0xC6C617CB, 0xF3F34F11, 0x8C8CE4D0, 0xA4A45993, 0xCACA96B8,
374
- 0x68683BA6, 0xB8B84D83, 0x38382820, 0xE5E52EFF, 0xADAD569F, 0x0B0B8477, 0xC8C81DC3, 0x9999FFCC,
375
- 0x5858ED03, 0x19199A6F, 0x0E0E0A08, 0x95957EBF, 0x70705040, 0xF7F730E7, 0x6E6ECF2B, 0x1F1F6EE2,
376
- 0xB5B53D79, 0x09090F0C, 0x616134AA, 0x57571682, 0x9F9F0B41, 0x9D9D803A, 0x111164EA, 0x2525CDB9,
377
- 0xAFAFDDE4, 0x4545089A, 0xDFDF8DA4, 0xA3A35C97, 0xEAEAD57E, 0x353558DA, 0xEDEDD07A, 0x4343FC17,
378
- 0xF8F8CB66, 0xFBFBB194, 0x3737D3A1, 0xFAFA401D, 0xC2C2683D, 0xB4B4CCF0, 0x32325DDE, 0x9C9C71B3,
379
- 0x5656E70B, 0xE3E3DA72, 0x878760A7, 0x15151B1C, 0xF9F93AEF, 0x6363BFD1, 0x3434A953, 0x9A9A853E,
380
- 0xB1B1428F, 0x7C7CD133, 0x88889B26, 0x3D3DA65F, 0xA1A1D7EC, 0xE4E4DF76, 0x8181942A, 0x91910149,
381
- 0x0F0FFB81, 0xEEEEAA88, 0x161661EE, 0xD7D77321, 0x9797F5C4, 0xA5A5A81A, 0xFEFE3FEB, 0x6D6DB5D9,
382
- 0x7878AEC5, 0xC5C56D39, 0x1D1DE599, 0x7676A4CD, 0x3E3EDCAD, 0xCBCB6731, 0xB6B6478B, 0xEFEF5B01,
383
- 0x12121E18, 0x6060C523, 0x6A6AB0DD, 0x4D4DF61F, 0xCECEE94E, 0xDEDE7C2D, 0x55559DF9, 0x7E7E5A48,
384
- 0x2121B24F, 0x03037AF2, 0xA0A02665, 0x5E5E198E, 0x5A5A6678, 0x65654B5C, 0x62624E58, 0xFDFD4519,
385
- 0x0606F48D, 0x404086E5, 0xF2F2BE98, 0x3333AC57, 0x17179067, 0x05058E7F, 0xE8E85E05, 0x4F4F7D64,
386
- 0x89896AAF, 0x10109563, 0x74742FB6, 0x0A0A75FE, 0x5C5C92F5, 0x9B9B74B7, 0x2D2D333C, 0x3030D6A5,
387
- 0x2E2E49CE, 0x494989E9, 0x46467268, 0x77775544, 0xA8A8D8E0, 0x9696044D, 0x2828BD43, 0xA9A92969,
388
- 0xD9D97929, 0x8686912E, 0xD1D187AC, 0xF4F44A15, 0x8D8D1559, 0xD6D682A8, 0xB9B9BC0A, 0x42420D9E,
389
- 0xF6F6C16E, 0x2F2FB847, 0xDDDD06DF, 0x23233934, 0xCCCC6235, 0xF1F1C46A, 0xC1C112CF, 0x8585EBDC,
390
- 0x8F8F9E22, 0x7171A1C9, 0x9090F0C0, 0xAAAA539B, 0x0101F189, 0x8B8BE1D4, 0x4E4E8CED, 0x8E8E6FAB,
391
- 0xABABA212, 0x6F6F3EA2, 0xE6E6540D, 0xDBDBF252, 0x92927BBB, 0xB7B7B602, 0x6969CA2F, 0x3939D9A9,
392
- 0xD3D30CD7, 0xA7A72361, 0xA2A2AD1E, 0xC3C399B4, 0x6C6C4450, 0x07070504, 0x04047FF6, 0x272746C2,
393
- 0xACACA716, 0xD0D07625, 0x50501386, 0xDCDCF756, 0x84841A55, 0xE1E15109, 0x7A7A25BE, 0x1313EF91
394
- );
395
-
396
- /**
397
- * M-Table
398
- *
399
- * @var Array
400
- * @access private
401
- */
402
- var $m1 = array (
403
- 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4,
404
- 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A,
405
- 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141,
406
- 0x43BD2828, 0x7532BCBC, 0x37D47B7B, 0x269B8888, 0xFA700D0D, 0x13F94444, 0x94B1FBFB, 0x485A7E7E,
407
- 0xF27A0303, 0xD0E48C8C, 0x8B47B6B6, 0x303C2424, 0x84A5E7E7, 0x54416B6B, 0xDF06DDDD, 0x23C56060,
408
- 0x1945FDFD, 0x5BA33A3A, 0x3D68C2C2, 0x59158D8D, 0xF321ECEC, 0xAE316666, 0xA23E6F6F, 0x82165757,
409
- 0x63951010, 0x015BEFEF, 0x834DB8B8, 0x2E918686, 0xD9B56D6D, 0x511F8383, 0x9B53AAAA, 0x7C635D5D,
410
- 0xA63B6868, 0xEB3FFEFE, 0xA5D63030, 0xBE257A7A, 0x16A7ACAC, 0x0C0F0909, 0xE335F0F0, 0x6123A7A7,
411
- 0xC0F09090, 0x8CAFE9E9, 0x3A809D9D, 0xF5925C5C, 0x73810C0C, 0x2C273131, 0x2576D0D0, 0x0BE75656,
412
- 0xBB7B9292, 0x4EE9CECE, 0x89F10101, 0x6B9F1E1E, 0x53A93434, 0x6AC4F1F1, 0xB499C3C3, 0xF1975B5B,
413
- 0xE1834747, 0xE66B1818, 0xBDC82222, 0x450E9898, 0xE26E1F1F, 0xF4C9B3B3, 0xB62F7474, 0x66CBF8F8,
414
- 0xCCFF9999, 0x95EA1414, 0x03ED5858, 0x56F7DCDC, 0xD4E18B8B, 0x1C1B1515, 0x1EADA2A2, 0xD70CD3D3,
415
- 0xFB2BE2E2, 0xC31DC8C8, 0x8E195E5E, 0xB5C22C2C, 0xE9894949, 0xCF12C1C1, 0xBF7E9595, 0xBA207D7D,
416
- 0xEA641111, 0x77840B0B, 0x396DC5C5, 0xAF6A8989, 0x33D17C7C, 0xC9A17171, 0x62CEFFFF, 0x7137BBBB,
417
- 0x81FB0F0F, 0x793DB5B5, 0x0951E1E1, 0xADDC3E3E, 0x242D3F3F, 0xCDA47676, 0xF99D5555, 0xD8EE8282,
418
- 0xE5864040, 0xC5AE7878, 0xB9CD2525, 0x4D049696, 0x44557777, 0x080A0E0E, 0x86135050, 0xE730F7F7,
419
- 0xA1D33737, 0x1D40FAFA, 0xAA346161, 0xED8C4E4E, 0x06B3B0B0, 0x706C5454, 0xB22A7373, 0xD2523B3B,
420
- 0x410B9F9F, 0x7B8B0202, 0xA088D8D8, 0x114FF3F3, 0x3167CBCB, 0xC2462727, 0x27C06767, 0x90B4FCFC,
421
- 0x20283838, 0xF67F0404, 0x60784848, 0xFF2EE5E5, 0x96074C4C, 0x5C4B6565, 0xB1C72B2B, 0xAB6F8E8E,
422
- 0x9E0D4242, 0x9CBBF5F5, 0x52F2DBDB, 0x1BF34A4A, 0x5FA63D3D, 0x9359A4A4, 0x0ABCB9B9, 0xEF3AF9F9,
423
- 0x91EF1313, 0x85FE0808, 0x49019191, 0xEE611616, 0x2D7CDEDE, 0x4FB22121, 0x8F42B1B1, 0x3BDB7272,
424
- 0x47B82F2F, 0x8748BFBF, 0x6D2CAEAE, 0x46E3C0C0, 0xD6573C3C, 0x3E859A9A, 0x6929A9A9, 0x647D4F4F,
425
- 0x2A948181, 0xCE492E2E, 0xCB17C6C6, 0x2FCA6969, 0xFCC3BDBD, 0x975CA3A3, 0x055EE8E8, 0x7AD0EDED,
426
- 0xAC87D1D1, 0x7F8E0505, 0xD5BA6464, 0x1AA8A5A5, 0x4BB72626, 0x0EB9BEBE, 0xA7608787, 0x5AF8D5D5,
427
- 0x28223636, 0x14111B1B, 0x3FDE7575, 0x2979D9D9, 0x88AAEEEE, 0x3C332D2D, 0x4C5F7979, 0x02B6B7B7,
428
- 0xB896CACA, 0xDA583535, 0xB09CC4C4, 0x17FC4343, 0x551A8484, 0x1FF64D4D, 0x8A1C5959, 0x7D38B2B2,
429
- 0x57AC3333, 0xC718CFCF, 0x8DF40606, 0x74695353, 0xB7749B9B, 0xC4F59797, 0x9F56ADAD, 0x72DAE3E3,
430
- 0x7ED5EAEA, 0x154AF4F4, 0x229E8F8F, 0x12A2ABAB, 0x584E6262, 0x07E85F5F, 0x99E51D1D, 0x34392323,
431
- 0x6EC1F6F6, 0x50446C6C, 0xDE5D3232, 0x68724646, 0x6526A0A0, 0xBC93CDCD, 0xDB03DADA, 0xF8C6BABA,
432
- 0xC8FA9E9E, 0xA882D6D6, 0x2BCF6E6E, 0x40507070, 0xDCEB8585, 0xFE750A0A, 0x328A9393, 0xA48DDFDF,
433
- 0xCA4C2929, 0x10141C1C, 0x2173D7D7, 0xF0CCB4B4, 0xD309D4D4, 0x5D108A8A, 0x0FE25151, 0x00000000,
434
- 0x6F9A1919, 0x9DE01A1A, 0x368F9494, 0x42E6C7C7, 0x4AECC9C9, 0x5EFDD2D2, 0xC1AB7F7F, 0xE0D8A8A8
435
- );
436
-
437
- /**
438
- * M-Table
439
- *
440
- * @var Array
441
- * @access private
442
- */
443
- var $m2 = array (
444
- 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA,
445
- 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7,
446
- 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783,
447
- 0x2430243C, 0x510F51E2, 0xBAF8BAC6, 0x4A1B4AF3, 0xBF87BF48, 0x0DFA0D70, 0xB006B0B3, 0x753F75DE,
448
- 0xD25ED2FD, 0x7DBA7D20, 0x66AE6631, 0x3A5B3AA3, 0x598A591C, 0x00000000, 0xCDBCCD93, 0x1A9D1AE0,
449
- 0xAE6DAE2C, 0x7FC17FAB, 0x2BB12BC7, 0xBE0EBEB9, 0xE080E0A0, 0x8A5D8A10, 0x3BD23B52, 0x64D564BA,
450
- 0xD8A0D888, 0xE784E7A5, 0x5F075FE8, 0x1B141B11, 0x2CB52CC2, 0xFC90FCB4, 0x312C3127, 0x80A38065,
451
- 0x73B2732A, 0x0C730C81, 0x794C795F, 0x6B546B41, 0x4B924B02, 0x53745369, 0x9436948F, 0x8351831F,
452
- 0x2A382A36, 0xC4B0C49C, 0x22BD22C8, 0xD55AD5F8, 0xBDFCBDC3, 0x48604878, 0xFF62FFCE, 0x4C964C07,
453
- 0x416C4177, 0xC742C7E6, 0xEBF7EB24, 0x1C101C14, 0x5D7C5D63, 0x36283622, 0x672767C0, 0xE98CE9AF,
454
- 0x441344F9, 0x149514EA, 0xF59CF5BB, 0xCFC7CF18, 0x3F243F2D, 0xC046C0E3, 0x723B72DB, 0x5470546C,
455
- 0x29CA294C, 0xF0E3F035, 0x088508FE, 0xC6CBC617, 0xF311F34F, 0x8CD08CE4, 0xA493A459, 0xCAB8CA96,
456
- 0x68A6683B, 0xB883B84D, 0x38203828, 0xE5FFE52E, 0xAD9FAD56, 0x0B770B84, 0xC8C3C81D, 0x99CC99FF,
457
- 0x580358ED, 0x196F199A, 0x0E080E0A, 0x95BF957E, 0x70407050, 0xF7E7F730, 0x6E2B6ECF, 0x1FE21F6E,
458
- 0xB579B53D, 0x090C090F, 0x61AA6134, 0x57825716, 0x9F419F0B, 0x9D3A9D80, 0x11EA1164, 0x25B925CD,
459
- 0xAFE4AFDD, 0x459A4508, 0xDFA4DF8D, 0xA397A35C, 0xEA7EEAD5, 0x35DA3558, 0xED7AEDD0, 0x431743FC,
460
- 0xF866F8CB, 0xFB94FBB1, 0x37A137D3, 0xFA1DFA40, 0xC23DC268, 0xB4F0B4CC, 0x32DE325D, 0x9CB39C71,
461
- 0x560B56E7, 0xE372E3DA, 0x87A78760, 0x151C151B, 0xF9EFF93A, 0x63D163BF, 0x345334A9, 0x9A3E9A85,
462
- 0xB18FB142, 0x7C337CD1, 0x8826889B, 0x3D5F3DA6, 0xA1ECA1D7, 0xE476E4DF, 0x812A8194, 0x91499101,
463
- 0x0F810FFB, 0xEE88EEAA, 0x16EE1661, 0xD721D773, 0x97C497F5, 0xA51AA5A8, 0xFEEBFE3F, 0x6DD96DB5,
464
- 0x78C578AE, 0xC539C56D, 0x1D991DE5, 0x76CD76A4, 0x3EAD3EDC, 0xCB31CB67, 0xB68BB647, 0xEF01EF5B,
465
- 0x1218121E, 0x602360C5, 0x6ADD6AB0, 0x4D1F4DF6, 0xCE4ECEE9, 0xDE2DDE7C, 0x55F9559D, 0x7E487E5A,
466
- 0x214F21B2, 0x03F2037A, 0xA065A026, 0x5E8E5E19, 0x5A785A66, 0x655C654B, 0x6258624E, 0xFD19FD45,
467
- 0x068D06F4, 0x40E54086, 0xF298F2BE, 0x335733AC, 0x17671790, 0x057F058E, 0xE805E85E, 0x4F644F7D,
468
- 0x89AF896A, 0x10631095, 0x74B6742F, 0x0AFE0A75, 0x5CF55C92, 0x9BB79B74, 0x2D3C2D33, 0x30A530D6,
469
- 0x2ECE2E49, 0x49E94989, 0x46684672, 0x77447755, 0xA8E0A8D8, 0x964D9604, 0x284328BD, 0xA969A929,
470
- 0xD929D979, 0x862E8691, 0xD1ACD187, 0xF415F44A, 0x8D598D15, 0xD6A8D682, 0xB90AB9BC, 0x429E420D,
471
- 0xF66EF6C1, 0x2F472FB8, 0xDDDFDD06, 0x23342339, 0xCC35CC62, 0xF16AF1C4, 0xC1CFC112, 0x85DC85EB,
472
- 0x8F228F9E, 0x71C971A1, 0x90C090F0, 0xAA9BAA53, 0x018901F1, 0x8BD48BE1, 0x4EED4E8C, 0x8EAB8E6F,
473
- 0xAB12ABA2, 0x6FA26F3E, 0xE60DE654, 0xDB52DBF2, 0x92BB927B, 0xB702B7B6, 0x692F69CA, 0x39A939D9,
474
- 0xD3D7D30C, 0xA761A723, 0xA21EA2AD, 0xC3B4C399, 0x6C506C44, 0x07040705, 0x04F6047F, 0x27C22746,
475
- 0xAC16ACA7, 0xD025D076, 0x50865013, 0xDC56DCF7, 0x8455841A, 0xE109E151, 0x7ABE7A25, 0x139113EF
476
- );
477
-
478
- /**
479
- * M-Table
480
- *
481
- * @var Array
482
- * @access private
483
- */
484
- var $m3 = array (
485
- 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF,
486
- 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836,
487
- 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77,
488
- 0xBD2843BD, 0x32BC7532, 0xD47B37D4, 0x9B88269B, 0x700DFA70, 0xF94413F9, 0xB1FB94B1, 0x5A7E485A,
489
- 0x7A03F27A, 0xE48CD0E4, 0x47B68B47, 0x3C24303C, 0xA5E784A5, 0x416B5441, 0x06DDDF06, 0xC56023C5,
490
- 0x45FD1945, 0xA33A5BA3, 0x68C23D68, 0x158D5915, 0x21ECF321, 0x3166AE31, 0x3E6FA23E, 0x16578216,
491
- 0x95106395, 0x5BEF015B, 0x4DB8834D, 0x91862E91, 0xB56DD9B5, 0x1F83511F, 0x53AA9B53, 0x635D7C63,
492
- 0x3B68A63B, 0x3FFEEB3F, 0xD630A5D6, 0x257ABE25, 0xA7AC16A7, 0x0F090C0F, 0x35F0E335, 0x23A76123,
493
- 0xF090C0F0, 0xAFE98CAF, 0x809D3A80, 0x925CF592, 0x810C7381, 0x27312C27, 0x76D02576, 0xE7560BE7,
494
- 0x7B92BB7B, 0xE9CE4EE9, 0xF10189F1, 0x9F1E6B9F, 0xA93453A9, 0xC4F16AC4, 0x99C3B499, 0x975BF197,
495
- 0x8347E183, 0x6B18E66B, 0xC822BDC8, 0x0E98450E, 0x6E1FE26E, 0xC9B3F4C9, 0x2F74B62F, 0xCBF866CB,
496
- 0xFF99CCFF, 0xEA1495EA, 0xED5803ED, 0xF7DC56F7, 0xE18BD4E1, 0x1B151C1B, 0xADA21EAD, 0x0CD3D70C,
497
- 0x2BE2FB2B, 0x1DC8C31D, 0x195E8E19, 0xC22CB5C2, 0x8949E989, 0x12C1CF12, 0x7E95BF7E, 0x207DBA20,
498
- 0x6411EA64, 0x840B7784, 0x6DC5396D, 0x6A89AF6A, 0xD17C33D1, 0xA171C9A1, 0xCEFF62CE, 0x37BB7137,
499
- 0xFB0F81FB, 0x3DB5793D, 0x51E10951, 0xDC3EADDC, 0x2D3F242D, 0xA476CDA4, 0x9D55F99D, 0xEE82D8EE,
500
- 0x8640E586, 0xAE78C5AE, 0xCD25B9CD, 0x04964D04, 0x55774455, 0x0A0E080A, 0x13508613, 0x30F7E730,
501
- 0xD337A1D3, 0x40FA1D40, 0x3461AA34, 0x8C4EED8C, 0xB3B006B3, 0x6C54706C, 0x2A73B22A, 0x523BD252,
502
- 0x0B9F410B, 0x8B027B8B, 0x88D8A088, 0x4FF3114F, 0x67CB3167, 0x4627C246, 0xC06727C0, 0xB4FC90B4,
503
- 0x28382028, 0x7F04F67F, 0x78486078, 0x2EE5FF2E, 0x074C9607, 0x4B655C4B, 0xC72BB1C7, 0x6F8EAB6F,
504
- 0x0D429E0D, 0xBBF59CBB, 0xF2DB52F2, 0xF34A1BF3, 0xA63D5FA6, 0x59A49359, 0xBCB90ABC, 0x3AF9EF3A,
505
- 0xEF1391EF, 0xFE0885FE, 0x01914901, 0x6116EE61, 0x7CDE2D7C, 0xB2214FB2, 0x42B18F42, 0xDB723BDB,
506
- 0xB82F47B8, 0x48BF8748, 0x2CAE6D2C, 0xE3C046E3, 0x573CD657, 0x859A3E85, 0x29A96929, 0x7D4F647D,
507
- 0x94812A94, 0x492ECE49, 0x17C6CB17, 0xCA692FCA, 0xC3BDFCC3, 0x5CA3975C, 0x5EE8055E, 0xD0ED7AD0,
508
- 0x87D1AC87, 0x8E057F8E, 0xBA64D5BA, 0xA8A51AA8, 0xB7264BB7, 0xB9BE0EB9, 0x6087A760, 0xF8D55AF8,
509
- 0x22362822, 0x111B1411, 0xDE753FDE, 0x79D92979, 0xAAEE88AA, 0x332D3C33, 0x5F794C5F, 0xB6B702B6,
510
- 0x96CAB896, 0x5835DA58, 0x9CC4B09C, 0xFC4317FC, 0x1A84551A, 0xF64D1FF6, 0x1C598A1C, 0x38B27D38,
511
- 0xAC3357AC, 0x18CFC718, 0xF4068DF4, 0x69537469, 0x749BB774, 0xF597C4F5, 0x56AD9F56, 0xDAE372DA,
512
- 0xD5EA7ED5, 0x4AF4154A, 0x9E8F229E, 0xA2AB12A2, 0x4E62584E, 0xE85F07E8, 0xE51D99E5, 0x39233439,
513
- 0xC1F66EC1, 0x446C5044, 0x5D32DE5D, 0x72466872, 0x26A06526, 0x93CDBC93, 0x03DADB03, 0xC6BAF8C6,
514
- 0xFA9EC8FA, 0x82D6A882, 0xCF6E2BCF, 0x50704050, 0xEB85DCEB, 0x750AFE75, 0x8A93328A, 0x8DDFA48D,
515
- 0x4C29CA4C, 0x141C1014, 0x73D72173, 0xCCB4F0CC, 0x09D4D309, 0x108A5D10, 0xE2510FE2, 0x00000000,
516
- 0x9A196F9A, 0xE01A9DE0, 0x8F94368F, 0xE6C742E6, 0xECC94AEC, 0xFDD25EFD, 0xAB7FC1AB, 0xD8A8E0D8
517
- );
518
-
519
- /**
520
- * The Key Schedule Array
521
- *
522
- * @var Array
523
- * @access private
524
- */
525
- var $K = array();
526
-
527
- /**
528
- * The Key depended S-Table 0
529
- *
530
- * @var Array
531
- * @access private
532
- */
533
- var $S0 = array();
534
-
535
- /**
536
- * The Key depended S-Table 1
537
- *
538
- * @var Array
539
- * @access private
540
- */
541
- var $S1 = array();
542
-
543
- /**
544
- * The Key depended S-Table 2
545
- *
546
- * @var Array
547
- * @access private
548
- */
549
- var $S2 = array();
550
-
551
- /**
552
- * The Key depended S-Table 3
553
- *
554
- * @var Array
555
- * @access private
556
- */
557
- var $S3 = array();
558
-
559
- /**
560
- * Default Constructor.
561
- *
562
- * Determines whether or not the mcrypt extension should be used.
563
- * If not explictly set, CRYPT_TWOFISH_MODE_CBC will be used.
564
- *
565
- * @param optional Integer $mode
566
- * @access public
567
- */
568
- function Crypt_Twofish($mode = CRYPT_TWOFISH_MODE_CBC)
569
- {
570
- if ( !defined('CRYPT_TWOFISH_MODE') ) {
571
- switch (true) {
572
- case extension_loaded('mcrypt') && in_array('twofish', mcrypt_list_algorithms()):
573
- define('CRYPT_TWOFISH_MODE', CRYPT_TWOFISH_MODE_MCRYPT);
574
- break;
575
- default:
576
- define('CRYPT_TWOFISH_MODE', CRYPT_TWOFISH_MODE_INTERNAL);
577
- }
578
- }
579
-
580
- switch ( CRYPT_TWOFISH_MODE ) {
581
- case CRYPT_TWOFISH_MODE_MCRYPT:
582
- switch ($mode) {
583
- case CRYPT_TWOFISH_MODE_ECB:
584
- $this->paddable = true;
585
- $this->mode = MCRYPT_MODE_ECB;
586
- break;
587
- case CRYPT_TWOFISH_MODE_CTR:
588
- $this->mode = 'ctr';
589
- break;
590
- case CRYPT_TWOFISH_MODE_CFB:
591
- $this->mode = 'ncfb';
592
- $this->ecb = mcrypt_module_open(MCRYPT_TWOFISH, '', MCRYPT_MODE_ECB, '');
593
- break;
594
- case CRYPT_TWOFISH_MODE_OFB:
595
- $this->mode = MCRYPT_MODE_NOFB;
596
- break;
597
- case CRYPT_TWOFISH_MODE_CBC:
598
- default:
599
- $this->paddable = true;
600
- $this->mode = MCRYPT_MODE_CBC;
601
- }
602
- $this->enmcrypt = mcrypt_module_open(MCRYPT_TWOFISH, '', $this->mode, '');
603
- $this->demcrypt = mcrypt_module_open(MCRYPT_TWOFISH, '', $this->mode, '');
604
-
605
- break;
606
- default:
607
- switch ($mode) {
608
- case CRYPT_TWOFISH_MODE_ECB:
609
- case CRYPT_TWOFISH_MODE_CBC:
610
- $this->paddable = true;
611
- $this->mode = $mode;
612
- break;
613
- case CRYPT_TWOFISH_MODE_CTR:
614
- case CRYPT_TWOFISH_MODE_CFB:
615
- case CRYPT_TWOFISH_MODE_OFB:
616
- $this->mode = $mode;
617
- break;
618
- default:
619
- $this->paddable = true;
620
- $this->mode = CRYPT_TWOFISH_MODE_CBC;
621
- }
622
- $this->inline_crypt_setup();
623
- }
624
- }
625
-
626
- /**
627
- * Sets the key.
628
- *
629
- * Keys can be of any length. Twofish, itself, requires the use of a key that's 128, 192 or 256-bits long.
630
- * If the key is less than 256-bits we round the length up to the closest valid key length,
631
- * padding $key with null bytes. If the key is more than 256-bits, we trim the excess bits.
632
- *
633
- * If the key is not explicitly set, it'll be assumed a 128 bits key to be all null bytes.
634
- *
635
- * @access public
636
- * @param String $key
637
- */
638
- function setKey($key)
639
- {
640
- $keylength = strlen($key);
641
- switch (true) {
642
- case $keylength <= 16:
643
- $key.= str_repeat("\0", 16 - $keylength);
644
- break;
645
- case $keylength <= 24:
646
- $key.= str_repeat("\0", 24 - $keylength);
647
- break;
648
- case $keylength <= 32:
649
- $key.= str_repeat("\0", 32 - $keylength);
650
- break;
651
- default:
652
- $key = substr($key, 0, 32);
653
- }
654
- $this->key = $key;
655
-
656
- $this->enchanged = true;
657
- $this->dechanged = true;
658
-
659
- if (CRYPT_TWOFISH_MODE == CRYPT_TWOFISH_MODE_MCRYPT) {
660
- return;
661
- }
662
-
663
- /* Key expanding and generating the key-depended s-boxes */
664
- $le_longs = unpack('V*', $key);
665
- $key = unpack('C*', $key);
666
- $m0 = $this->m0;
667
- $m1 = $this->m1;
668
- $m2 = $this->m2;
669
- $m3 = $this->m3;
670
- $q0 = $this->q0;
671
- $q1 = $this->q1;
672
-
673
- $K = $S0 = $S1 = $S2 = $S3 = array();
674
-
675
- switch (strlen($this->key)) {
676
- case 16:
677
- list ($s7, $s6, $s5, $s4) = $this->mds_rem($le_longs[1], $le_longs[2]);
678
- list ($s3, $s2, $s1, $s0) = $this->mds_rem($le_longs[3], $le_longs[4]);
679
- for ($i = 0, $j = 1; $i < 40; $i+= 2,$j+= 2) {
680
- $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^
681
- $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^
682
- $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^
683
- $m3[$q1[$q1[$i] ^ $key[12]] ^ $key[4]];
684
- $B = $m0[$q0[$q0[$j] ^ $key[13]] ^ $key[5]] ^
685
- $m1[$q0[$q1[$j] ^ $key[14]] ^ $key[6]] ^
686
- $m2[$q1[$q0[$j] ^ $key[15]] ^ $key[7]] ^
687
- $m3[$q1[$q1[$j] ^ $key[16]] ^ $key[8]];
688
- $B = ($B << 8) | ($B >> 24 & 0xff);
689
- $K[] = $A+= $B;
690
- $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
691
- }
692
- for ($i = 0; $i < 256; ++$i) {
693
- $S0[$i] = $m0[$q0[$q0[$i] ^ $s4] ^ $s0];
694
- $S1[$i] = $m1[$q0[$q1[$i] ^ $s5] ^ $s1];
695
- $S2[$i] = $m2[$q1[$q0[$i] ^ $s6] ^ $s2];
696
- $S3[$i] = $m3[$q1[$q1[$i] ^ $s7] ^ $s3];
697
- }
698
- break;
699
- case 24:
700
- list ($sb, $sa, $s9, $s8) = $this->mds_rem($le_longs[1], $le_longs[2]);
701
- list ($s7, $s6, $s5, $s4) = $this->mds_rem($le_longs[3], $le_longs[4]);
702
- list ($s3, $s2, $s1, $s0) = $this->mds_rem($le_longs[5], $le_longs[6]);
703
- for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
704
- $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
705
- $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
706
- $m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
707
- $m3[$q1[$q1[$q0[$i] ^ $key[20]] ^ $key[12]] ^ $key[4]];
708
- $B = $m0[$q0[$q0[$q1[$j] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^
709
- $m1[$q0[$q1[$q1[$j] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^
710
- $m2[$q1[$q0[$q0[$j] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^
711
- $m3[$q1[$q1[$q0[$j] ^ $key[24]] ^ $key[16]] ^ $key[8]];
712
- $B = ($B << 8) | ($B >> 24 & 0xff);
713
- $K[] = $A+= $B;
714
- $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
715
- }
716
- for ($i = 0; $i < 256; ++$i) {
717
- $S0[$i] = $m0[$q0[$q0[$q1[$i] ^ $s8] ^ $s4] ^ $s0];
718
- $S1[$i] = $m1[$q0[$q1[$q1[$i] ^ $s9] ^ $s5] ^ $s1];
719
- $S2[$i] = $m2[$q1[$q0[$q0[$i] ^ $sa] ^ $s6] ^ $s2];
720
- $S3[$i] = $m3[$q1[$q1[$q0[$i] ^ $sb] ^ $s7] ^ $s3];
721
- }
722
- break;
723
- default: // 32
724
- list ($sf, $se, $sd, $sc) = $this->mds_rem($le_longs[1], $le_longs[2]);
725
- list ($sb, $sa, $s9, $s8) = $this->mds_rem($le_longs[3], $le_longs[4]);
726
- list ($s7, $s6, $s5, $s4) = $this->mds_rem($le_longs[5], $le_longs[6]);
727
- list ($s3, $s2, $s1, $s0) = $this->mds_rem($le_longs[7], $le_longs[8]);
728
- for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
729
- $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
730
- $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
731
- $m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
732
- $m3[$q1[$q1[$q0[$q1[$i] ^ $key[28]] ^ $key[20]] ^ $key[12]] ^ $key[4]];
733
- $B = $m0[$q0[$q0[$q1[$q1[$j] ^ $key[29]] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^
734
- $m1[$q0[$q1[$q1[$q0[$j] ^ $key[30]] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^
735
- $m2[$q1[$q0[$q0[$q0[$j] ^ $key[31]] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^
736
- $m3[$q1[$q1[$q0[$q1[$j] ^ $key[32]] ^ $key[24]] ^ $key[16]] ^ $key[8]];
737
- $B = ($B << 8) | ($B >> 24 & 0xff);
738
- $K[] = $A+= $B;
739
- $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff);
740
- }
741
- for ($i = 0; $i < 256; ++$i) {
742
- $S0[$i] = $m0[$q0[$q0[$q1[$q1[$i] ^ $sc] ^ $s8] ^ $s4] ^ $s0];
743
- $S1[$i] = $m1[$q0[$q1[$q1[$q0[$i] ^ $sd] ^ $s9] ^ $s5] ^ $s1];
744
- $S2[$i] = $m2[$q1[$q0[$q0[$q0[$i] ^ $se] ^ $sa] ^ $s6] ^ $s2];
745
- $S3[$i] = $m3[$q1[$q1[$q0[$q1[$i] ^ $sf] ^ $sb] ^ $s7] ^ $s3];
746
- }
747
- }
748
-
749
- $this->K = $K;
750
- $this->S0 = $S0;
751
- $this->S1 = $S1;
752
- $this->S2 = $S2;
753
- $this->S3 = $S3;
754
- }
755
-
756
- /**
757
- * Sets the password.
758
- *
759
- * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
760
- * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
761
- * $hash, $salt, $count
762
- *
763
- * @param String $password
764
- * @param optional String $method
765
- * @access public
766
- */
767
- function setPassword($password, $method = 'pbkdf2')
768
- {
769
- $key = '';
770
-
771
- switch ($method) {
772
- default: // 'pbkdf2'
773
- list(, , $hash, $salt, $count) = func_get_args();
774
- if (!isset($hash)) {
775
- $hash = 'sha1';
776
- }
777
- // WPA and WPA2 use the SSID as the salt
778
- if (!isset($salt)) {
779
- $salt = 'phpseclib/salt';
780
- }
781
- // RFC2898#section-4.2 uses 1,000 iterations by default
782
- // WPA and WPA2 use 4,096.
783
- if (!isset($count)) {
784
- $count = 1000;
785
- }
786
-
787
- if (!class_exists('Crypt_Hash')) {
788
- require_once('Crypt/Hash.php');
789
- }
790
-
791
- $i = 1;
792
- while (strlen($key) < 32) {
793
- $hmac = new Crypt_Hash();
794
- $hmac->setHash($hash);
795
- $hmac->setKey($password);
796
- $f = $u = $hmac->hash($salt . pack('N', $i++));
797
- for ($j = 2; $j <= $count; ++$j) {
798
- $u = $hmac->hash($u);
799
- $f^= $u;
800
- }
801
- $key.= $f;
802
- }
803
- }
804
-
805
- $this->setKey($key);
806
- }
807
-
808
- /**
809
- * Sets the initialization vector. (optional)
810
- *
811
- * SetIV is not required when CRYPT_TWOFISH_MODE_ECB is being used. If not explictly set, it'll be assumed
812
- * to be all null bytes.
813
- *
814
- * @access public
815
- * @param String $iv
816
- */
817
- function setIV($iv)
818
- {
819
- $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 16), 16, chr(0));
820
- $this->enchanged = true;
821
- $this->dechanged = true;
822
- }
823
-
824
- /**
825
- * Encrypts a message.
826
- *
827
- * $plaintext will be padded with up to 16 additional bytes. Other Twofish implementations may or may not pad in the
828
- * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
829
- * URL:
830
- *
831
- * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
832
- *
833
- * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
834
- * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
835
- * length.
836
- *
837
- * @see Crypt_Twofish::decrypt()
838
- * @access public
839
- * @param String $plaintext
840
- */
841
- function encrypt($plaintext)
842
- {
843
- if ( CRYPT_TWOFISH_MODE == CRYPT_TWOFISH_MODE_MCRYPT ) {
844
- if ($this->paddable) {
845
- $plaintext = $this->_pad($plaintext);
846
- }
847
-
848
- if ($this->enchanged) {
849
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
850
- if ($this->mode == 'ncfb') {
851
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
852
- }
853
- $this->enchanged = false;
854
- }
855
-
856
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
857
- $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
858
- } else {
859
- $iv = &$this->encryptIV;
860
- $pos = &$this->enbuffer['pos'];
861
- $len = strlen($plaintext);
862
- $ciphertext = '';
863
- $i = 0;
864
- if ($pos) {
865
- $orig_pos = $pos;
866
- $max = 16 - $pos;
867
- if ($len >= $max) {
868
- $i = $max;
869
- $len-= $max;
870
- $pos = 0;
871
- } else {
872
- $i = $len;
873
- $pos+= $len;
874
- $len = 0;
875
- }
876
- $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
877
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
878
- $this->enbuffer['enmcrypt_init'] = true;
879
- }
880
- if ($len >= 16) {
881
- if ($this->enbuffer['enmcrypt_init'] === false || $len > 600) {
882
- if ($this->enbuffer['enmcrypt_init'] === true) {
883
- mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
884
- $this->enbuffer['enmcrypt_init'] = false;
885
- }
886
- $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 16));
887
- $iv = substr($ciphertext, -16);
888
- $len%= 16;
889
- } else {
890
- while ($len >= 16) {
891
- $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 16);
892
- $ciphertext.= $iv;
893
- $len-= 16;
894
- $i+= 16;
895
- }
896
- }
897
- }
898
- if ($len) {
899
- $iv = mcrypt_generic($this->ecb, $iv);
900
- $block = $iv ^ substr($plaintext, -$len);
901
- $iv = substr_replace($iv, $block, 0, $len);
902
- $ciphertext.= $block;
903
- $pos = $len;
904
- }
905
- return $ciphertext;
906
- }
907
-
908
- if (!$this->continuousBuffer) {
909
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
910
- }
911
-
912
- return $ciphertext;
913
- }
914
-
915
- if (empty($this->K)) {
916
- $this->setKey($this->key);
917
- }
918
-
919
- $inline = $this->inline_crypt;
920
- return $inline('encrypt', $this, $plaintext);
921
- }
922
-
923
- /**
924
- * Decrypts a message.
925
- *
926
- * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
927
- *
928
- * @see Crypt_Twofish::encrypt()
929
- * @access public
930
- * @param String $ciphertext
931
- */
932
- function decrypt($ciphertext)
933
- {
934
- if ( CRYPT_TWOFISH_MODE == CRYPT_TWOFISH_MODE_MCRYPT ) {
935
- if ($this->paddable) {
936
- // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
937
- // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
938
- $ciphertext = str_pad($ciphertext, strlen($ciphertext) + (16 - strlen($ciphertext) % 16) % 16, chr(0));
939
- }
940
-
941
- if ($this->dechanged) {
942
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
943
- if ($this->mode == 'ncfb') {
944
- mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
945
- }
946
- $this->dechanged = false;
947
- }
948
-
949
- if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
950
- $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
951
- } else {
952
- $iv = &$this->decryptIV;
953
- $pos = &$this->debuffer['pos'];
954
- $len = strlen($ciphertext);
955
- $plaintext = '';
956
- $i = 0;
957
- if ($pos) {
958
- $orig_pos = $pos;
959
- $max = 16 - $pos;
960
- if ($len >= $max) {
961
- $i = $max;
962
- $len-= $max;
963
- $pos = 0;
964
- } else {
965
- $i = $len;
966
- $pos+= $len;
967
- $len = 0;
968
- }
969
- $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
970
- $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
971
- }
972
- if ($len >= 16) {
973
- $cb = substr($ciphertext, $i, $len - $len % 16);
974
- $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
975
- $iv = substr($cb, -16);
976
- $len%= 16;
977
- }
978
- if ($len) {
979
- $iv = mcrypt_generic($this->ecb, $iv);
980
- $plaintext.= $iv ^ substr($ciphertext, -$len);
981
- $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
982
- $pos = $len;
983
- }
984
- return $plaintext;
985
- }
986
-
987
- if (!$this->continuousBuffer) {
988
- mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
989
- }
990
-
991
- return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
992
- }
993
-
994
- if (empty($this->K)) {
995
- $this->setKey($this->key);
996
- }
997
-
998
- $inline = $this->inline_crypt;
999
- return $inline('decrypt', $this, $ciphertext);
1000
- }
1001
-
1002
- /**
1003
- * Treat consecutive "packets" as if they are a continuous buffer.
1004
- *
1005
- * @see Crypt_Twofish::disableContinuousBuffer()
1006
- * @access public
1007
- */
1008
- function enableContinuousBuffer()
1009
- {
1010
- $this->continuousBuffer = true;
1011
- }
1012
-
1013
- /**
1014
- * Treat consecutive packets as if they are a discontinuous buffer.
1015
- *
1016
- * The default behavior.
1017
- *
1018
- * @see Crypt_Twofish::enableContinuousBuffer()
1019
- * @access public
1020
- */
1021
- function disableContinuousBuffer()
1022
- {
1023
- $this->continuousBuffer = false;
1024
- $this->encryptIV = $this->iv;
1025
- $this->decryptIV = $this->iv;
1026
- $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1027
- $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1028
-
1029
- if (CRYPT_TWOFISH_MODE == CRYPT_TWOFISH_MODE_MCRYPT) {
1030
- mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
1031
- mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
1032
- }
1033
- }
1034
-
1035
- /**
1036
- * Pad "packets".
1037
- *
1038
- * Twofish works by encrypting 16 bytes at a time. If you ever need to encrypt or decrypt something that's not
1039
- * a multiple of 16, it becomes necessary to pad the input so that it's length is a multiple of eight.
1040
- *
1041
- * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
1042
- * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1043
- * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1044
- * transmitted separately)
1045
- *
1046
- * @see Crypt_Twofish::disablePadding()
1047
- * @access public
1048
- */
1049
- function enablePadding()
1050
- {
1051
- $this->padding = true;
1052
- }
1053
-
1054
- /**
1055
- * Do not pad packets.
1056
- *
1057
- * @see Crypt_Twofish::enablePadding()
1058
- * @access public
1059
- */
1060
- function disablePadding()
1061
- {
1062
- $this->padding = false;
1063
- }
1064
-
1065
- /**
1066
- * Pads a string
1067
- *
1068
- * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (16).
1069
- *
1070
- * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1071
- * and padding will, hence forth, be enabled.
1072
- *
1073
- * @see Crypt_Twofish::_unpad()
1074
- * @access private
1075
- */
1076
- function _pad($text)
1077
- {
1078
- $length = strlen($text);
1079
-
1080
- if (!$this->padding) {
1081
- if ($length % 16 == 0) {
1082
- return $text;
1083
- } else {
1084
- user_error("The plaintext's length ($length) is not a multiple of the block size (16)");
1085
- $this->padding = true;
1086
- }
1087
- }
1088
-
1089
- $pad = 16 - ($length % 16);
1090
-
1091
- return str_pad($text, $length + $pad, chr($pad));
1092
- }
1093
-
1094
- /**
1095
- * Unpads a string
1096
- *
1097
- * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1098
- * and false will be returned.
1099
- *
1100
- * @see Crypt_Twofish::_pad()
1101
- * @access private
1102
- */
1103
- function _unpad($text)
1104
- {
1105
- if (!$this->padding) {
1106
- return $text;
1107
- }
1108
-
1109
- $length = ord($text[strlen($text) - 1]);
1110
-
1111
- if (!$length || $length > 16) {
1112
- return false;
1113
- }
1114
-
1115
- return substr($text, 0, -$length);
1116
- }
1117
-
1118
- /**
1119
- * String Shift
1120
- *
1121
- * Inspired by array_shift
1122
- *
1123
- * @param String $string
1124
- * @return String
1125
- * @access private
1126
- */
1127
- function _string_shift(&$string)
1128
- {
1129
- $substr = substr($string, 0, 16);
1130
- $string = substr($string, 16);
1131
- return $substr;
1132
- }
1133
-
1134
- /**
1135
- * Generate CTR XOR encryption key
1136
- *
1137
- * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1138
- * plaintext / ciphertext in CTR mode.
1139
- *
1140
- * @see Crypt_Twofish::decrypt()
1141
- * @see Crypt_Twofish::encrypt()
1142
- * @access public
1143
- * @param String $iv
1144
- */
1145
- function _generate_xor(&$iv)
1146
- {
1147
- $xor = $iv;
1148
- for ($j = 4; $j <= 16; $j+=4) {
1149
- $temp = substr($iv, -$j, 4);
1150
- switch ($temp) {
1151
- case "\xFF\xFF\xFF\xFF":
1152
- $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1153
- break;
1154
- case "\x7F\xFF\xFF\xFF":
1155
- $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1156
- break 2;
1157
- default:
1158
- extract(unpack('Ncount', $temp));
1159
- $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1160
- break 2;
1161
- }
1162
- }
1163
-
1164
- return $xor;
1165
- }
1166
-
1167
- /**
1168
- * mds_rem function using by the twofish cipher algorithm
1169
- *
1170
- * @access private
1171
- * @param String $A
1172
- * @param String $B
1173
- * @return Array
1174
- */
1175
- function mds_rem($A, $B)
1176
- {
1177
- // No gain by unrolling this loop.
1178
- for ($i = 0; $i < 8; ++$i) {
1179
- // Get most significant coefficient.
1180
- $t = 0xff & ($B >> 24);
1181
-
1182
- // Shift the others up.
1183
- $B = ($B << 8) | (0xff & ($A >> 24));
1184
- $A<<= 8;
1185
-
1186
- $u = $t << 1;
1187
-
1188
- // Subtract the modular polynomial on overflow.
1189
- if ($t & 0x80) {
1190
- $u^= 0x14d;
1191
- }
1192
-
1193
- // Remove t * (a * x^2 + 1).
1194
- $B ^= $t ^ ($u << 16);
1195
-
1196
- // Form u = a*t + t/a = t*(a + 1/a).
1197
- $u^= 0x7fffffff & ($t >> 1);
1198
-
1199
- // Add the modular polynomial on underflow.
1200
- if ($t & 0x01) $u^= 0xa6 ;
1201
-
1202
- // Remove t * (a + 1/a) * (x^3 + x).
1203
- $B^= ($u << 24) | ($u << 8);
1204
- }
1205
-
1206
- return array(
1207
- 0xff & $B >> 24,
1208
- 0xff & $B >> 16,
1209
- 0xff & $B >> 8,
1210
- 0xff & $B);
1211
- }
1212
-
1213
- /**
1214
- * Creates performance-optimized function for de/encrypt(), storing it in $this->inline_crypt
1215
- *
1216
- * @access private
1217
- */
1218
- function inline_crypt_setup()
1219
- {
1220
- $lambda_functions =& Crypt_Twofish::get_lambda_functions();
1221
- $block_size = 16;
1222
- $mode = $this->mode;
1223
- $code_hash = "$mode";
1224
-
1225
- if (!isset($lambda_functions[$code_hash])) {
1226
- $init_cryptBlock = '
1227
- $S0 = $self->S0;
1228
- $S1 = $self->S1;
1229
- $S2 = $self->S2;
1230
- $S3 = $self->S3;
1231
- extract($self->K, EXTR_PREFIX_ALL, "K");
1232
- ';
1233
-
1234
- // Generating encrypt code:
1235
- $_encryptBlock = '
1236
- $in = unpack("V4", $in);
1237
- $R0 = $K_0 ^ $in[1];
1238
- $R1 = $K_1 ^ $in[2];
1239
- $R2 = $K_2 ^ $in[3];
1240
- $R3 = $K_3 ^ $in[4];
1241
- ';
1242
- for ($ki = 7, $i = 0; $i < 8; ++$i) {
1243
- $_encryptBlock.= '
1244
- $t0 = $S0[ $R0 & 0xff] ^
1245
- $S1[($R0 >> 8) & 0xff] ^
1246
- $S2[($R0 >> 16) & 0xff] ^
1247
- $S3[($R0 >> 24) & 0xff];
1248
- $t1 = $S0[($R1 >> 24) & 0xff] ^
1249
- $S1[ $R1 & 0xff] ^
1250
- $S2[($R1 >> 8) & 0xff] ^
1251
- $S3[($R1 >> 16) & 0xff];
1252
- $R2^= ($t0 + $t1 + $K_'.(++$ki).');
1253
- $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31);
1254
- $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + $K_'.(++$ki).');
1255
-
1256
- $t0 = $S0[ $R2 & 0xff] ^
1257
- $S1[($R2 >> 8) & 0xff] ^
1258
- $S2[($R2 >> 16) & 0xff] ^
1259
- $S3[($R2 >> 24) & 0xff];
1260
- $t1 = $S0[($R3 >> 24) & 0xff] ^
1261
- $S1[ $R3 & 0xff] ^
1262
- $S2[($R3 >> 8) & 0xff] ^
1263
- $S3[($R3 >> 16) & 0xff];
1264
- $R0^= ($t0 + $t1 + $K_'.(++$ki).');
1265
- $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31);
1266
- $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + $K_'.(++$ki).');
1267
- ';
1268
- }
1269
- $_encryptBlock.= '
1270
- $in = pack("V4", $K_4 ^ $R2,
1271
- $K_5 ^ $R3,
1272
- $K_6 ^ $R0,
1273
- $K_7 ^ $R1);
1274
- ';
1275
-
1276
- // Generating decrypt code:
1277
- $_decryptBlock = '
1278
- $in = unpack("V4", $in);
1279
- $R0 = $K_4 ^ $in[1];
1280
- $R1 = $K_5 ^ $in[2];
1281
- $R2 = $K_6 ^ $in[3];
1282
- $R3 = $K_7 ^ $in[4];
1283
- ';
1284
- for ($ki = 40, $i = 0; $i < 8; ++$i) {
1285
- $_decryptBlock.= '
1286
- $t0 = $S0[$R0 & 0xff] ^
1287
- $S1[$R0 >> 8 & 0xff] ^
1288
- $S2[$R0 >> 16 & 0xff] ^
1289
- $S3[$R0 >> 24 & 0xff];
1290
- $t1 = $S0[$R1 >> 24 & 0xff] ^
1291
- $S1[$R1 & 0xff] ^
1292
- $S2[$R1 >> 8 & 0xff] ^
1293
- $S3[$R1 >> 16 & 0xff];
1294
- $R3^= $t0 + ($t1 << 1) + $K_'.(--$ki).';
1295
- $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
1296
- $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + $K_'.(--$ki).');
1297
-
1298
- $t0 = $S0[$R2 & 0xff] ^
1299
- $S1[$R2 >> 8 & 0xff] ^
1300
- $S2[$R2 >> 16 & 0xff] ^
1301
- $S3[$R2 >> 24 & 0xff];
1302
- $t1 = $S0[$R3 >> 24 & 0xff] ^
1303
- $S1[$R3 & 0xff] ^
1304
- $S2[$R3 >> 8 & 0xff] ^
1305
- $S3[$R3 >> 16 & 0xff];
1306
- $R1^= $t0 + ($t1 << 1) + $K_'.(--$ki).';
1307
- $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
1308
- $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + $K_'.(--$ki).');
1309
- ';
1310
- }
1311
- $_decryptBlock.= '
1312
- $in = pack("V4", $K_0 ^ $R2,
1313
- $K_1 ^ $R3,
1314
- $K_2 ^ $R0,
1315
- $K_3 ^ $R1);
1316
- ';
1317
-
1318
- // Generating mode of operation code:
1319
- switch ($mode) {
1320
- case CRYPT_TWOFISH_MODE_ECB:
1321
- $encrypt = '
1322
- $ciphertext = "";
1323
- $text = $self->_pad($text);
1324
- $plaintext_len = strlen($text);
1325
-
1326
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1327
- $in = substr($text, $i, '.$block_size.');
1328
- '.$_encryptBlock.'
1329
- $ciphertext.= $in;
1330
- }
1331
-
1332
- return $ciphertext;
1333
- ';
1334
-
1335
- $decrypt = '
1336
- $plaintext = "";
1337
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1338
- $ciphertext_len = strlen($text);
1339
-
1340
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1341
- $in = substr($text, $i, '.$block_size.');
1342
- '.$_decryptBlock.'
1343
- $plaintext.= $in;
1344
- }
1345
-
1346
- return $self->_unpad($plaintext);
1347
- ';
1348
- break;
1349
- case CRYPT_TWOFISH_MODE_CBC:
1350
- $encrypt = '
1351
- $ciphertext = "";
1352
- $text = $self->_pad($text);
1353
- $plaintext_len = strlen($text);
1354
-
1355
- $in = $self->encryptIV;
1356
-
1357
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1358
- $in = substr($text, $i, '.$block_size.') ^ $in;
1359
- '.$_encryptBlock.'
1360
- $ciphertext.= $in;
1361
- }
1362
-
1363
- if ($self->continuousBuffer) {
1364
- $self->encryptIV = $in;
1365
- }
1366
-
1367
- return $ciphertext;
1368
- ';
1369
-
1370
- $decrypt = '
1371
- $plaintext = "";
1372
- $text = str_pad($text, strlen($text) + ('.$block_size.' - strlen($text) % '.$block_size.') % '.$block_size.', chr(0));
1373
- $ciphertext_len = strlen($text);
1374
-
1375
- $iv = $self->decryptIV;
1376
-
1377
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1378
- $in = $block = substr($text, $i, '.$block_size.');
1379
- '.$_decryptBlock.'
1380
- $plaintext.= $in ^ $iv;
1381
- $iv = $block;
1382
- }
1383
-
1384
- if ($self->continuousBuffer) {
1385
- $self->decryptIV = $iv;
1386
- }
1387
-
1388
- return $self->_unpad($plaintext);
1389
- ';
1390
- break;
1391
- case CRYPT_TWOFISH_MODE_CTR:
1392
- $encrypt = '
1393
- $ciphertext = "";
1394
- $plaintext_len = strlen($text);
1395
- $xor = $self->encryptIV;
1396
- $buffer = &$self->enbuffer;
1397
-
1398
- if (strlen($buffer["encrypted"])) {
1399
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1400
- $block = substr($text, $i, '.$block_size.');
1401
- if (strlen($block) > strlen($buffer["encrypted"])) {
1402
- $in = $self->_generate_xor($xor);
1403
- '.$_encryptBlock.'
1404
- $buffer["encrypted"].= $in;
1405
- }
1406
- $key = $self->_string_shift($buffer["encrypted"]);
1407
- $ciphertext.= $block ^ $key;
1408
- }
1409
- } else {
1410
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1411
- $block = substr($text, $i, '.$block_size.');
1412
- $in = $self->_generate_xor($xor);
1413
- '.$_encryptBlock.'
1414
- $key = $in;
1415
- $ciphertext.= $block ^ $key;
1416
- }
1417
- }
1418
- if ($self->continuousBuffer) {
1419
- $self->encryptIV = $xor;
1420
- if ($start = $plaintext_len % '.$block_size.') {
1421
- $buffer["encrypted"] = substr($key, $start) . $buffer["encrypted"];
1422
- }
1423
- }
1424
-
1425
- return $ciphertext;
1426
- ';
1427
-
1428
- $decrypt = '
1429
- $plaintext = "";
1430
- $ciphertext_len = strlen($text);
1431
- $xor = $self->decryptIV;
1432
- $buffer = &$self->debuffer;
1433
-
1434
- if (strlen($buffer["ciphertext"])) {
1435
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1436
- $block = substr($text, $i, '.$block_size.');
1437
- if (strlen($block) > strlen($buffer["ciphertext"])) {
1438
- $in = $self->_generate_xor($xor);
1439
- '.$_encryptBlock.'
1440
- $buffer["ciphertext"].= $in;
1441
- }
1442
- $key = $self->_string_shift($buffer["ciphertext"]);
1443
- $plaintext.= $block ^ $key;
1444
- }
1445
- } else {
1446
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1447
- $block = substr($text, $i, '.$block_size.');
1448
- $in = $self->_generate_xor($xor);
1449
- '.$_encryptBlock.'
1450
- $key = $in;
1451
- $plaintext.= $block ^ $key;
1452
- }
1453
- }
1454
- if ($self->continuousBuffer) {
1455
- $self->decryptIV = $xor;
1456
- if ($start = $ciphertext_len % '.$block_size.') {
1457
- $buffer["ciphertext"] = substr($key, $start) . $buffer["ciphertext"];
1458
- }
1459
- }
1460
-
1461
- return $plaintext;
1462
- ';
1463
- break;
1464
- case CRYPT_TWOFISH_MODE_CFB:
1465
- $encrypt = '
1466
- $ciphertext = "";
1467
- $buffer = &$self->enbuffer;
1468
-
1469
- if ($self->continuousBuffer) {
1470
- $iv = &$self->encryptIV;
1471
- $pos = &$buffer["pos"];
1472
- } else {
1473
- $iv = $self->encryptIV;
1474
- $pos = 0;
1475
- }
1476
- $len = strlen($text);
1477
- $i = 0;
1478
- if ($pos) {
1479
- $orig_pos = $pos;
1480
- $max = '.$block_size.' - $pos;
1481
- if ($len >= $max) {
1482
- $i = $max;
1483
- $len-= $max;
1484
- $pos = 0;
1485
- } else {
1486
- $i = $len;
1487
- $pos+= $len;
1488
- $len = 0;
1489
- }
1490
- $ciphertext = substr($iv, $orig_pos) ^ $text;
1491
- $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
1492
- }
1493
- while ($len >= '.$block_size.') {
1494
- $in = $iv;
1495
- '.$_encryptBlock.';
1496
- $iv = $in ^ substr($text, $i, '.$block_size.');
1497
- $ciphertext.= $iv;
1498
- $len-= '.$block_size.';
1499
- $i+= '.$block_size.';
1500
- }
1501
- if ($len) {
1502
- $in = $iv;
1503
- '.$_encryptBlock.'
1504
- $iv = $in;
1505
- $block = $iv ^ substr($text, $i);
1506
- $iv = substr_replace($iv, $block, 0, $len);
1507
- $ciphertext.= $block;
1508
- $pos = $len;
1509
- }
1510
- return $ciphertext;
1511
- ';
1512
-
1513
- $decrypt = '
1514
- $plaintext = "";
1515
- $buffer = &$self->debuffer;
1516
-
1517
- if ($self->continuousBuffer) {
1518
- $iv = &$self->decryptIV;
1519
- $pos = &$buffer["pos"];
1520
- } else {
1521
- $iv = $self->decryptIV;
1522
- $pos = 0;
1523
- }
1524
- $len = strlen($text);
1525
- $i = 0;
1526
- if ($pos) {
1527
- $orig_pos = $pos;
1528
- $max = '.$block_size.' - $pos;
1529
- if ($len >= $max) {
1530
- $i = $max;
1531
- $len-= $max;
1532
- $pos = 0;
1533
- } else {
1534
- $i = $len;
1535
- $pos+= $len;
1536
- $len = 0;
1537
- }
1538
- $plaintext = substr($iv, $orig_pos) ^ $text;
1539
- $iv = substr_replace($iv, substr($text, 0, $i), $orig_pos, $i);
1540
- }
1541
- while ($len >= '.$block_size.') {
1542
- $in = $iv;
1543
- '.$_encryptBlock.'
1544
- $iv = $in;
1545
- $cb = substr($text, $i, '.$block_size.');
1546
- $plaintext.= $iv ^ $cb;
1547
- $iv = $cb;
1548
- $len-= '.$block_size.';
1549
- $i+= '.$block_size.';
1550
- }
1551
- if ($len) {
1552
- $in = $iv;
1553
- '.$_encryptBlock.'
1554
- $iv = $in;
1555
- $plaintext.= $iv ^ substr($text, $i);
1556
- $iv = substr_replace($iv, substr($text, $i), 0, $len);
1557
- $pos = $len;
1558
- }
1559
-
1560
- return $plaintext;
1561
- ';
1562
- break;
1563
- case CRYPT_TWOFISH_MODE_OFB:
1564
- $encrypt = '
1565
- $ciphertext = "";
1566
- $plaintext_len = strlen($text);
1567
- $xor = $self->encryptIV;
1568
- $buffer = &$self->enbuffer;
1569
-
1570
- if (strlen($buffer["xor"])) {
1571
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1572
- $block = substr($text, $i, '.$block_size.');
1573
- if (strlen($block) > strlen($buffer["xor"])) {
1574
- $in = $xor;
1575
- '.$_encryptBlock.'
1576
- $xor = $in;
1577
- $buffer["xor"].= $xor;
1578
- }
1579
- $key = $self->_string_shift($buffer["xor"]);
1580
- $ciphertext.= $block ^ $key;
1581
- }
1582
- } else {
1583
- for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
1584
- $in = $xor;
1585
- '.$_encryptBlock.'
1586
- $xor = $in;
1587
- $ciphertext.= substr($text, $i, '.$block_size.') ^ $xor;
1588
- }
1589
- $key = $xor;
1590
- }
1591
- if ($self->continuousBuffer) {
1592
- $self->encryptIV = $xor;
1593
- if ($start = $plaintext_len % '.$block_size.') {
1594
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
1595
- }
1596
- }
1597
- return $ciphertext;
1598
- ';
1599
-
1600
- $decrypt = '
1601
- $plaintext = "";
1602
- $ciphertext_len = strlen($text);
1603
- $xor = $self->decryptIV;
1604
- $buffer = &$self->debuffer;
1605
-
1606
- if (strlen($buffer["xor"])) {
1607
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1608
- $block = substr($text, $i, '.$block_size.');
1609
- if (strlen($block) > strlen($buffer["xor"])) {
1610
- $in = $xor;
1611
- '.$_encryptBlock.'
1612
- $xor = $in;
1613
- $buffer["xor"].= $xor;
1614
- }
1615
- $key = $self->_string_shift($buffer["xor"]);
1616
- $plaintext.= $block ^ $key;
1617
- }
1618
- } else {
1619
- for ($i = 0; $i < $ciphertext_len; $i+= '.$block_size.') {
1620
- $in = $xor;
1621
- '.$_encryptBlock.'
1622
- $xor = $in;
1623
- $plaintext.= substr($text, $i, '.$block_size.') ^ $xor;
1624
- }
1625
- $key = $xor;
1626
- }
1627
- if ($self->continuousBuffer) {
1628
- $self->decryptIV = $xor;
1629
- if ($start = $ciphertext_len % '.$block_size.') {
1630
- $buffer["xor"] = substr($key, $start) . $buffer["xor"];
1631
- }
1632
- }
1633
- return $plaintext;
1634
- ';
1635
- break;
1636
- }
1637
- $fnc_head = '$action, &$self, $text';
1638
- $fnc_body = $init_cryptBlock . 'if ($action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }';
1639
-
1640
- if (function_exists('create_function') && is_callable('create_function')) {
1641
- $lambda_functions[$code_hash] = create_function($fnc_head, $fnc_body);
1642
- } else {
1643
- eval('function ' . ($lambda_functions[$code_hash] = 'f' . md5(microtime())) . '(' . $fnc_head . ') { ' . $fnc_body . ' }');
1644
- }
1645
- }
1646
- $this->inline_crypt = $lambda_functions[$code_hash];
1647
- }
1648
-
1649
- /**
1650
- * Holds the lambda_functions table (classwide)
1651
- *
1652
- * @see inline_crypt_setup()
1653
- * @return Array
1654
- * @access private
1655
- */
1656
- function &get_lambda_functions()
1657
- {
1658
- static $functions = array();
1659
- return $functions;
1660
- }
1661
- }
1662
-
1663
- // vim: ts=4:sw=4:et:
1664
- // vim6: fdl=1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/dropbox.php DELETED
@@ -1,283 +0,0 @@
1
- <?php
2
- class Dropbox {
3
- const API_URL = 'https://api.dropbox.com/';
4
- const API_CONTENT_URL = 'https://api-content.dropbox.com/';
5
- const API_WWW_URL = 'https://www.dropbox.com/';
6
- const API_VERSION_URL = '1/';
7
-
8
- private $root;
9
- private $ProgressFunction = false;
10
- private $oauth_app_key;
11
- private $oauth_app_secret;
12
- private $oauth_token;
13
- private $oauth_token_secret;
14
-
15
- public function __construct($oauth_app_key, $oauth_app_secret, $dropbox=false) {
16
- $this->oauth_app_key = $oauth_app_key;
17
- $this->oauth_app_secret = $oauth_app_secret;
18
-
19
- if ($dropbox)
20
- $this->root = 'dropbox';
21
- else
22
- $this->root = 'sandbox';
23
- }
24
-
25
- public function setOAuthTokens($token,$secret) {
26
- $this->oauth_token = $token;
27
- $this->oauth_token_secret = $secret;
28
- }
29
-
30
- public function setProgressFunction($function=null) {
31
- if (function_exists($function))
32
- $this->ProgressFunction = $function;
33
- else
34
- $this->ProgressFunction = false;
35
- }
36
-
37
- public function accountInfo(){
38
- $url = self::API_URL.self::API_VERSION_URL.'account/info';
39
- return $this->request($url);
40
- }
41
-
42
- public function upload($file, $path = '',$overwrite=true){
43
- $file = str_replace("\\", "/",$file);
44
- if (!is_readable($file) or !is_file($file))
45
- throw new DropboxException("Error: File \"$file\" is not readable or doesn't exist.");
46
- $filesize=filesize($file);
47
- if ($filesize<(1024*1024*50)) { //chunk transfer on bigger uploads <50MB
48
- $filehandle = fopen($file,'r');
49
- $url = self::API_CONTENT_URL.self::API_VERSION_URL.'files_put/'.$this->root.'/'.trim($path, '/');
50
- $output = $this->request($url, array('overwrite' => ($overwrite)? 'true' : 'false'), 'PUT', $filehandle, $filesize);
51
- fclose($filehandle);
52
- } else {
53
- $output = $this->chunked_upload($file, $path,$overwrite);
54
- }
55
- return $output;
56
- }
57
-
58
- public function chunked_upload($file, $path = '',$overwrite=true){
59
- $file = str_replace("\\", "/",$file);
60
- if (!is_readable($file) or !is_file($file))
61
- throw new DropboxException("Error: File \"$file\" is not readable or doesn't exist.");
62
- $file_handle=fopen($file,'r');
63
- $uploadid=null;
64
- $offset=0;
65
- $ProgressFunction=null;
66
- while ($data=fread($file_handle,(1024*1024*30))) { // 30MB chunk size
67
- $chunkHandle = fopen('php://memory', 'rw');
68
- fwrite($chunkHandle,$data);
69
- rewind($chunkHandle);
70
- //overwrite progress function
71
- if (!empty($this->ProgressFunction) and function_exists($this->ProgressFunction)) {
72
- $ProgressFunction=$this->ProgressFunction;
73
- $this->ProgressFunction=false;
74
- }
75
- $url = self::API_CONTENT_URL.self::API_VERSION_URL.'chunked_upload';
76
- $output = $this->request($url, array('upload_id' => $uploadid,'offset'=>$offset), 'PUT', $chunkHandle, strlen($data));
77
- fclose($chunkHandle);
78
- if ($ProgressFunction) {
79
- call_user_func($ProgressFunction,0,0,0,$offset);
80
- $this->ProgressFunction=$ProgressFunction;
81
- }
82
- //args for next chunk
83
- $offset=$output['offset'];
84
- $uploadid=$output['upload_id'];
85
- fseek($file_handle,$offset);
86
- }
87
- fclose($file_handle);
88
- $url = self::API_CONTENT_URL.self::API_VERSION_URL.'commit_chunked_upload/'.$this->root.'/'.trim($path, '/');
89
- return $this->request($url, array('overwrite' => ($overwrite)? 'true' : 'false','upload_id'=>$uploadid), 'POST');
90
- }
91
-
92
- public function download($path,$echo=false){
93
- $url = self::API_CONTENT_URL.self::API_VERSION_URL.'files/'.$this->root.'/'.trim($path,'/');
94
- if (!$echo)
95
- return $this->request($url);
96
- else
97
- $this->request($url,'','GET','','',true);
98
- }
99
-
100
- public function metadata($path = '', $listContents = true, $fileLimit = 10000){
101
- $url = self::API_URL.self::API_VERSION_URL.'metadata/'.$this->root.'/'.trim($path,'/');
102
- return $this->request($url, array('list' => ($listContents)? 'true' : 'false', 'file_limit' => $fileLimit));
103
- }
104
-
105
- public function search($path = '', $query , $fileLimit = 1000){
106
- if (strlen($query)>=3)
107
- throw new DropboxException("Error: Query \"$query\" must three characters long.");
108
- $url = self::API_URL.self::API_VERSION_URL.'search/'.$this->root.'/'.trim($path,'/');
109
- return $this->request($url, array('query' => $query, 'file_limit' => $fileLimit));
110
- }
111
-
112
- public function shares($path = ''){
113
- $url = self::API_URL.self::API_VERSION_URL.'shares/'.$this->root.'/'.trim($path,'/');
114
- return $this->request($url);
115
- }
116
-
117
- public function media($path = ''){
118
- $url = self::API_URL.self::API_VERSION_URL.'media/'.$this->root.'/'.trim($path,'/');
119
- return $this->request($url);
120
- }
121
-
122
- public function fileopsDelete($path){
123
- $url = self::API_URL.self::API_VERSION_URL.'fileops/delete';
124
- return $this->request($url, array('path' => '/'.trim($path,'/'), 'root' => $this->root));
125
- }
126
-
127
- public function fileopsCreate_folder($path){
128
- $url = self::API_URL.self::API_VERSION_URL.'fileops/create_folder';
129
- return $this->request($url, array('path' => '/'.trim($path,'/'), 'root' => $this->root));
130
- }
131
-
132
- public function oAuthAuthorize($callback_url) {
133
- $headers[] = 'Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.$this->oauth_app_key.'", oauth_signature="'.$this->oauth_app_secret.'&"';
134
- $ch = curl_init();
135
- curl_setopt($ch, CURLOPT_URL, self::API_URL . self::API_VERSION_URL . 'oauth/request_token' );
136
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
137
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
138
- curl_setopt($ch, CURLOPT_SSLVERSION,3);
139
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
140
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
141
- if (is_file(dirname(__FILE__).'/aws/lib/requestcore/cacert.pem'))
142
- curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/aws/lib/requestcore/cacert.pem');
143
- curl_setopt($ch, CURLOPT_AUTOREFERER , true);
144
- curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
145
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
146
- $content = curl_exec($ch);
147
- $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
148
- if ($status>=200 and $status<300 and 0==curl_errno($ch) ) {
149
- parse_str($content, $oauth_token);
150
- } else {
151
- $output = json_decode($content, true);
152
- if(isset($output['error']) && is_string($output['error'])) $message = $output['error'];
153
- elseif(isset($output['error']['hash']) && $output['error']['hash'] != '') $message = (string) $output['error']['hash'];
154
- elseif (0!=curl_errno($ch)) $message = '('.curl_errno($ch).') '.curl_error($ch);
155
- else $message = '('.$status.') Invalid response.';
156
- throw new DropboxException($message);
157
- }
158
- curl_close($ch);
159
- return array( 'authurl' => self::API_WWW_URL . self::API_VERSION_URL . 'oauth/authorize?oauth_token='.$oauth_token['oauth_token'].'&oauth_callback='.urlencode($callback_url),
160
- 'oauth_token' => $oauth_token['oauth_token'],
161
- 'oauth_token_secret'=> $oauth_token['oauth_token_secret'] );
162
- }
163
-
164
- public function oAuthAccessToken($oauth_token, $oauth_token_secret) {
165
- $headers[] = 'Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.$this->oauth_app_key.'", oauth_token="'.$oauth_token.'", oauth_signature="'.$this->oauth_app_secret.'&'.$oauth_token_secret.'"';
166
- $ch = curl_init();
167
- curl_setopt($ch, CURLOPT_URL, self::API_URL . self::API_VERSION_URL . 'oauth/access_token' );
168
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
169
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
170
- curl_setopt($ch, CURLOPT_SSLVERSION,3);
171
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
172
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
173
- if (is_file(dirname(__FILE__).'/aws/lib/requestcore/cacert.pem'))
174
- curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/aws/lib/requestcore/cacert.pem');
175
- curl_setopt($ch, CURLOPT_AUTOREFERER , true);
176
- curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
177
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
178
- $content = curl_exec($ch);
179
- $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
180
- if ($status>=200 and $status<300 and 0==curl_errno($ch)) {
181
- parse_str($content, $oauth_token);
182
- $this->setOAuthTokens($oauth_token['oauth_token'], $oauth_token['oauth_token_secret']);
183
- return $oauth_token;
184
- } else {
185
- $output = json_decode($content, true);
186
- if(isset($output['error']) && is_string($output['error'])) $message = $output['error'];
187
- elseif(isset($output['error']['hash']) && $output['error']['hash'] != '') $message = (string) $output['error']['hash'];
188
- elseif (0!=curl_errno($ch)) $message = '('.curl_errno($ch).') '.curl_error($ch);
189
- else $message = '('.$status.') Invalid response.';
190
- throw new DropboxException($message);
191
- }
192
- }
193
-
194
- private function request($url, $args = null, $method = 'GET', $filehandle = null, $filesize=0, $echo=false){
195
- $args = (is_array($args)) ? $args : array();
196
- $url = $this->url_encode($url);
197
-
198
- /* Header*/
199
- $headers[]='Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.$this->oauth_app_key.'", oauth_token="'.$this->oauth_token.'", oauth_signature="'.$this->oauth_app_secret.'&'.$this->oauth_token_secret.'"';
200
- $headers[]='Expect:';
201
-
202
- /* Build cURL Request */
203
- $ch = curl_init();
204
- if ($method == 'POST') {
205
- curl_setopt($ch, CURLOPT_POST, true);
206
- curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
207
- curl_setopt($ch, CURLOPT_URL, $url);
208
- } elseif ($method == 'PUT') {
209
- curl_setopt($ch,CURLOPT_PUT,true);
210
- curl_setopt($ch,CURLOPT_INFILE,$filehandle);
211
- curl_setopt($ch,CURLOPT_INFILESIZE,$filesize);
212
- $args = (is_array($args)) ? '?'.http_build_query($args, '', '&') : $args;
213
- curl_setopt($ch, CURLOPT_URL, $url.$args);
214
- } else {
215
- $args = (is_array($args)) ? '?'.http_build_query($args, '', '&') : $args;
216
- curl_setopt($ch, CURLOPT_URL, $url.$args);
217
- }
218
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
219
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
220
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
221
- curl_setopt($ch, CURLOPT_SSLVERSION,3);
222
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
223
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
224
- if (is_file(dirname(__FILE__).'/aws/lib/requestcore/cacert.pem'))
225
- curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/aws/lib/requestcore/cacert.pem');
226
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
227
- curl_setopt($ch, CURLINFO_HEADER_OUT, true);
228
- if (!empty($this->ProgressFunction) and function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION') and $method == 'PUT') {
229
- curl_setopt($ch, CURLOPT_NOPROGRESS, false);
230
- curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction);
231
- curl_setopt($ch, CURLOPT_BUFFERSIZE, 512);
232
- }
233
- if ($echo) {
234
- echo curl_exec($ch);
235
- $output='';
236
- } else {
237
- $content = curl_exec($ch);
238
- $output = json_decode($content, true);
239
- }
240
- $status = curl_getinfo($ch);
241
-
242
- if (isset($output['error']) or $status['http_code']>=300 or $status['http_code']<200 or curl_errno($ch)>0) {
243
- if(isset($output['error']) && is_string($output['error'])) $message = '('.$status['http_code'].') '.$output['error'];
244
- elseif(isset($output['error']['hash']) && $output['error']['hash'] != '') $message = (string) '('.$status['http_code'].') '.$output['error']['hash'];
245
- elseif (0!=curl_errno($ch)) $message = '('.curl_errno($ch).') '.curl_error($ch);
246
- elseif ($status['http_code']==304) $message = '(304) The folder contents have not changed (relies on hash parameter).';
247
- elseif ($status['http_code']==400) $message = '(400) Bad input parameter: '.strip_tags($content);
248
- elseif ($status['http_code']==401) $message = '(401) Bad or expired token. This can happen if the user or Dropbox revoked or expired an access token. To fix, you should re-authenticate the user.';
249
- elseif ($status['http_code']==403) $message = '(403) Bad OAuth request (wrong consumer key, bad nonce, expired timestamp, ...). Unfortunately, reauthenticating the user won\'t help here.';
250
- elseif ($status['http_code']==404) $message = '(404) The file was not found at the specified path, or was not found at the specified rev.';
251
- elseif ($status['http_code']==405) $message = '(405) Request method not expected (generally should be GET,PUT or POST).';
252
- elseif ($status['http_code']==406) $message = '(406) There are too many file entries to return.';
253
- elseif ($status['http_code']==411) $message = '(411) Chunked encoding was attempted for this upload, but is not supported by Dropbox.';
254
- elseif ($status['http_code']==415) $message = '(415) The image is invalid and cannot be thumbnailed.';
255
- elseif ($status['http_code']==503) $message = '(503) Your app is making too many requests and is being rate limited. 503s can trigger on a per-app or per-user basis.';
256
- elseif ($status['http_code']==507) $message = '(507) User is over Dropbox storage quota.';
257
- else $message = '('.$status['http_code'].') Invalid response.';
258
- throw new DropboxException($message);
259
- } else {
260
- curl_close($ch);
261
- if (!is_array($output))
262
- return $content;
263
- else
264
- return $output;
265
- }
266
- }
267
-
268
- private function url_encode($string) {
269
- $string = str_replace('?','%3F',$string);
270
- $string = str_replace('=','%3D',$string);
271
- $string = str_replace(' ','%20',$string);
272
- $string = str_replace('(','%28',$string);
273
- $string = str_replace(')','%29',$string);
274
- $string = str_replace('&','%26',$string);
275
- $string = str_replace('@','%40',$string);
276
- return $string;
277
- }
278
-
279
- }
280
-
281
- class DropboxException extends Exception {
282
- }
283
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/Google_Client.php DELETED
@@ -1,448 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- // Check for the required json and curl extensions, the Google APIs PHP Client
19
- // won't function without them.
20
- if (! function_exists('curl_init')) {
21
- throw new Exception('Google PHP API Client requires the CURL PHP extension');
22
- }
23
-
24
- if (! function_exists('json_decode')) {
25
- throw new Exception('Google PHP API Client requires the JSON PHP extension');
26
- }
27
-
28
- if (! function_exists('http_build_query')) {
29
- throw new Exception('Google PHP API Client requires http_build_query()');
30
- }
31
-
32
- if (! ini_get('date.timezone') && function_exists('date_default_timezone_set')) {
33
- date_default_timezone_set('UTC');
34
- }
35
-
36
- // hack around with the include paths a bit so the library 'just works'
37
- set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());
38
-
39
- require_once "config.php";
40
- // If a local configuration file is found, merge it's values with the default configuration
41
- if (file_exists(dirname(__FILE__) . '/local_config.php')) {
42
- $defaultConfig = $apiConfig;
43
- require_once (dirname(__FILE__) . '/local_config.php');
44
- $apiConfig = array_merge($defaultConfig, $apiConfig);
45
- }
46
-
47
- // Include the top level classes, they each include their own dependencies
48
- require_once 'service/Google_Model.php';
49
- require_once 'service/Google_Service.php';
50
- require_once 'service/Google_ServiceResource.php';
51
- require_once 'auth/Google_AssertionCredentials.php';
52
- require_once 'auth/Google_Signer.php';
53
- require_once 'auth/Google_P12Signer.php';
54
- require_once 'service/Google_BatchRequest.php';
55
- require_once 'external/URITemplateParser.php';
56
- require_once 'auth/Google_Auth.php';
57
- require_once 'cache/Google_Cache.php';
58
- require_once 'io/Google_IO.php';
59
- require_once('service/Google_MediaFileUpload.php');
60
-
61
- /**
62
- * The Google API Client
63
- * http://code.google.com/p/google-api-php-client/
64
- *
65
- * @author Chris Chabot <chabotc@google.com>
66
- * @author Chirag Shah <chirags@google.com>
67
- */
68
- class Google_Client {
69
- /**
70
- * @static
71
- * @var Google_Auth $auth
72
- */
73
- static $auth;
74
-
75
- /**
76
- * @static
77
- * @var Google_IO $io
78
- */
79
- static $io;
80
-
81
- /**
82
- * @static
83
- * @var Google_Cache $cache
84
- */
85
- static $cache;
86
-
87
- /**
88
- * @static
89
- * @var boolean $useBatch
90
- */
91
- static $useBatch = false;
92
-
93
- /** @var array $scopes */
94
- protected $scopes = array();
95
-
96
- /** @var bool $useObjects */
97
- protected $useObjects = false;
98
-
99
- // definitions of services that are discovered.
100
- protected $services = array();
101
-
102
- // Used to track authenticated state, can't discover services after doing authenticate()
103
- private $authenticated = false;
104
-
105
- public function __construct($config = array()) {
106
- global $apiConfig;
107
- $apiConfig = array_merge($apiConfig, $config);
108
- self::$cache = new $apiConfig['cacheClass']();
109
- self::$auth = new $apiConfig['authClass']();
110
- self::$io = new $apiConfig['ioClass']();
111
- }
112
-
113
- /**
114
- * Add a service
115
- */
116
- public function addService($service, $version = false) {
117
- global $apiConfig;
118
- if ($this->authenticated) {
119
- throw new Google_Exception('Cant add services after having authenticated');
120
- }
121
- $this->services[$service] = array();
122
- if (isset($apiConfig['services'][$service])) {
123
- // Merge the service descriptor with the default values
124
- $this->services[$service] = array_merge($this->services[$service], $apiConfig['services'][$service]);
125
- }
126
- }
127
-
128
- public function authenticate($code = null) {
129
- $service = $this->prepareService();
130
- $this->authenticated = true;
131
- return self::$auth->authenticate($service, $code);
132
- }
133
-
134
- /**
135
- * @return array
136
- * @visible For Testing
137
- */
138
- public function prepareService() {
139
- $service = array();
140
- $scopes = array();
141
- if ($this->scopes) {
142
- $scopes = $this->scopes;
143
- } else {
144
- foreach ($this->services as $key => $val) {
145
- if (isset($val['scope'])) {
146
- if (is_array($val['scope'])) {
147
- $scopes = array_merge($val['scope'], $scopes);
148
- } else {
149
- $scopes[] = $val['scope'];
150
- }
151
- } else {
152
- $scopes[] = 'https://www.googleapis.com/auth/' . $key;
153
- }
154
- unset($val['discoveryURI']);
155
- unset($val['scope']);
156
- $service = array_merge($service, $val);
157
- }
158
- }
159
- $service['scope'] = implode(' ', $scopes);
160
- return $service;
161
- }
162
-
163
- /**
164
- * Set the OAuth 2.0 access token using the string that resulted from calling authenticate()
165
- * or Google_Client#getAccessToken().
166
- * @param string $accessToken JSON encoded string containing in the following format:
167
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
168
- * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
169
- */
170
- public function setAccessToken($accessToken) {
171
- if ($accessToken == null || 'null' == $accessToken) {
172
- $accessToken = null;
173
- }
174
- self::$auth->setAccessToken($accessToken);
175
- }
176
-
177
- /**
178
- * Set the type of Auth class the client should use.
179
- * @param string $authClassName
180
- */
181
- public function setAuthClass($authClassName) {
182
- self::$auth = new $authClassName();
183
- }
184
-
185
- /**
186
- * Construct the OAuth 2.0 authorization request URI.
187
- * @return string
188
- */
189
- public function createAuthUrl() {
190
- $service = $this->prepareService();
191
- return self::$auth->createAuthUrl($service['scope']);
192
- }
193
-
194
- /**
195
- * Get the OAuth 2.0 access token.
196
- * @return string $accessToken JSON encoded string in the following format:
197
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
198
- * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
199
- */
200
- public function getAccessToken() {
201
- $token = self::$auth->getAccessToken();
202
- return (null == $token || 'null' == $token) ? null : $token;
203
- }
204
-
205
- /**
206
- * Returns if the access_token is expired.
207
- * @return bool Returns True if the access_token is expired.
208
- */
209
- public function isAccessTokenExpired() {
210
- return self::$auth->isAccessTokenExpired();
211
- }
212
-
213
- /**
214
- * Set the developer key to use, these are obtained through the API Console.
215
- * @see http://code.google.com/apis/console-help/#generatingdevkeys
216
- * @param string $developerKey
217
- */
218
- public function setDeveloperKey($developerKey) {
219
- self::$auth->setDeveloperKey($developerKey);
220
- }
221
-
222
- /**
223
- * Set OAuth 2.0 "state" parameter to achieve per-request customization.
224
- * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
225
- * @param string $state
226
- */
227
- public function setState($state) {
228
- self::$auth->setState($state);
229
- }
230
-
231
- /**
232
- * @param string $accessType Possible values for access_type include:
233
- * {@code "offline"} to request offline access from the user. (This is the default value)
234
- * {@code "online"} to request online access from the user.
235
- */
236
- public function setAccessType($accessType) {
237
- self::$auth->setAccessType($accessType);
238
- }
239
-
240
- /**
241
- * @param string $approvalPrompt Possible values for approval_prompt include:
242
- * {@code "force"} to force the approval UI to appear. (This is the default value)
243
- * {@code "auto"} to request auto-approval when possible.
244
- */
245
- public function setApprovalPrompt($approvalPrompt) {
246
- self::$auth->setApprovalPrompt($approvalPrompt);
247
- }
248
-
249
- /**
250
- * Set the application name, this is included in the User-Agent HTTP header.
251
- * @param string $applicationName
252
- */
253
- public function setApplicationName($applicationName) {
254
- global $apiConfig;
255
- $apiConfig['application_name'] = $applicationName;
256
- }
257
-
258
- /**
259
- * Set the OAuth 2.0 Client ID.
260
- * @param string $clientId
261
- */
262
- public function setClientId($clientId) {
263
- global $apiConfig;
264
- $apiConfig['oauth2_client_id'] = $clientId;
265
- self::$auth->clientId = $clientId;
266
- }
267
-
268
- /**
269
- * Get the OAuth 2.0 Client ID.
270
- */
271
- public function getClientId() {
272
- return self::$auth->clientId;
273
- }
274
-
275
- /**
276
- * Set the OAuth 2.0 Client Secret.
277
- * @param string $clientSecret
278
- */
279
- public function setClientSecret($clientSecret) {
280
- global $apiConfig;
281
- $apiConfig['oauth2_client_secret'] = $clientSecret;
282
- self::$auth->clientSecret = $clientSecret;
283
- }
284
-
285
- /**
286
- * Get the OAuth 2.0 Client Secret.
287
- */
288
- public function getClientSecret() {
289
- return self::$auth->clientSecret;
290
- }
291
-
292
- /**
293
- * Set the OAuth 2.0 Redirect URI.
294
- * @param string $redirectUri
295
- */
296
- public function setRedirectUri($redirectUri) {
297
- global $apiConfig;
298
- $apiConfig['oauth2_redirect_uri'] = $redirectUri;
299
- self::$auth->redirectUri = $redirectUri;
300
- }
301
-
302
- /**
303
- * Get the OAuth 2.0 Redirect URI.
304
- */
305
- public function getRedirectUri() {
306
- return self::$auth->redirectUri;
307
- }
308
-
309
- /**
310
- * Fetches a fresh OAuth 2.0 access token with the given refresh token.
311
- * @param string $refreshToken
312
- * @return void
313
- */
314
- public function refreshToken($refreshToken) {
315
- self::$auth->refreshToken($refreshToken);
316
- }
317
-
318
- /**
319
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
320
- * token, if a token isn't provided.
321
- * @throws Google_AuthException
322
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
323
- * @return boolean Returns True if the revocation was successful, otherwise False.
324
- */
325
- public function revokeToken($token = null) {
326
- return self::$auth->revokeToken($token);
327
- }
328
-
329
- /**
330
- * Verify an id_token. This method will verify the current id_token, if one
331
- * isn't provided.
332
- * @throws Google_AuthException
333
- * @param string|null $token The token (id_token) that should be verified.
334
- * @return Google_LoginTicket Returns an apiLoginTicket if the verification was
335
- * successful.
336
- */
337
- public function verifyIdToken($token = null) {
338
- return self::$auth->verifyIdToken($token);
339
- }
340
-
341
- /**
342
- * @param Google_AssertionCredentials $creds
343
- * @return void
344
- */
345
- public function setAssertionCredentials(Google_AssertionCredentials $creds) {
346
- self::$auth->setAssertionCredentials($creds);
347
- }
348
-
349
- /**
350
- * This function allows you to overrule the automatically generated scopes,
351
- * so that you can ask for more or less permission in the auth flow
352
- * Set this before you call authenticate() though!
353
- * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/moderator')
354
- */
355
- public function setScopes($scopes) {
356
- $this->scopes = is_string($scopes) ? explode(" ", $scopes) : $scopes;
357
- }
358
-
359
- /**
360
- * Declare if objects should be returned by the api service classes.
361
- *
362
- * @param boolean $useObjects True if objects should be returned by the service classes.
363
- * False if associative arrays should be returned (default behavior).
364
- * @experimental
365
- */
366
- public function setUseObjects($useObjects) {
367
- global $apiConfig;
368
- $apiConfig['use_objects'] = $useObjects;
369
- }
370
-
371
- /**
372
- * Declare if objects should be returned by the api service classes.
373
- *
374
- * @param boolean $useBatch True if the experimental batch support should
375
- * be enabled. Defaults to False.
376
- * @experimental
377
- */
378
- public function setUseBatch($useBatch) {
379
- self::$useBatch = $useBatch;
380
- }
381
-
382
- /**
383
- * @static
384
- * @return Google_Auth the implementation of apiAuth.
385
- */
386
- public static function getAuth() {
387
- return Google_Client::$auth;
388
- }
389
-
390
- /**
391
- * @static
392
- * @return Google_IO the implementation of apiIo.
393
- */
394
- public static function getIo() {
395
- return Google_Client::$io;
396
- }
397
-
398
- /**
399
- * @return Google_Cache the implementation of apiCache.
400
- */
401
- public function getCache() {
402
- return Google_Client::$cache;
403
- }
404
- }
405
-
406
- // Exceptions that the Google PHP API Library can throw
407
- class Google_Exception extends Exception {}
408
- class Google_AuthException extends Google_Exception {}
409
- class Google_CacheException extends Google_Exception {}
410
- class Google_IOException extends Google_Exception {}
411
- class Google_ServiceException extends Google_Exception {
412
- /**
413
- * Optional list of errors returned in a JSON body of an HTTP error response.
414
- */
415
- protected $errors = array();
416
-
417
- /**
418
- * Override default constructor to add ability to set $errors.
419
- *
420
- * @param string $message
421
- * @param int $code
422
- * @param Exception|null $previous
423
- * @param [{string, string}] errors List of errors returned in an HTTP
424
- * response. Defaults to [].
425
- */
426
- public function __construct($message, $code = 0, Exception $previous = null,
427
- $errors = array()) {
428
- parent::__construct($message, $code, $previous);
429
- $this->errors = $errors;
430
- }
431
-
432
- /**
433
- * An example of the possible errors returned.
434
- *
435
- * {
436
- * "domain": "global",
437
- * "reason": "authError",
438
- * "message": "Invalid Credentials",
439
- * "locationType": "header",
440
- * "location": "Authorization",
441
- * }
442
- *
443
- * @return [{string, string}] List of errors return in an HTTP response or [].
444
- */
445
- public function getErrors() {
446
- return $this->errors;
447
- }
448
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_AssertionCredentials.php DELETED
@@ -1,95 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
20
- *
21
- * @author Chirag Shah <chirags@google.com>
22
- */
23
- class Google_AssertionCredentials {
24
- const MAX_TOKEN_LIFETIME_SECS = 3600;
25
-
26
- public $serviceAccountName;
27
- public $scopes;
28
- public $privateKey;
29
- public $privateKeyPassword;
30
- public $assertionType;
31
- public $prn;
32
-
33
- /**
34
- * @param $serviceAccountName
35
- * @param $scopes array List of scopes
36
- * @param $privateKey
37
- * @param string $privateKeyPassword
38
- * @param string $assertionType
39
- * @param bool|string $prn The email address of the user for which the
40
- * application is requesting delegated access.
41
- */
42
- public function __construct(
43
- $serviceAccountName,
44
- $scopes,
45
- $privateKey,
46
- $privateKeyPassword = 'notasecret',
47
- $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
48
- $prn = false) {
49
- $this->serviceAccountName = $serviceAccountName;
50
- $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
51
- $this->privateKey = $privateKey;
52
- $this->privateKeyPassword = $privateKeyPassword;
53
- $this->assertionType = $assertionType;
54
- $this->prn = $prn;
55
- }
56
-
57
- public function generateAssertion() {
58
- $now = time();
59
-
60
- $jwtParams = array(
61
- 'aud' => Google_OAuth2::OAUTH2_TOKEN_URI,
62
- 'scope' => $this->scopes,
63
- 'iat' => $now,
64
- 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
65
- 'iss' => $this->serviceAccountName,
66
- );
67
-
68
- if ($this->prn !== false) {
69
- $jwtParams['prn'] = $this->prn;
70
- }
71
-
72
- return $this->makeSignedJwt($jwtParams);
73
- }
74
-
75
- /**
76
- * Creates a signed JWT.
77
- * @param array $payload
78
- * @return string The signed JWT.
79
- */
80
- private function makeSignedJwt($payload) {
81
- $header = array('typ' => 'JWT', 'alg' => 'RS256');
82
-
83
- $segments = array(
84
- Google_Utils::urlSafeB64Encode(json_encode($header)),
85
- Google_Utils::urlSafeB64Encode(json_encode($payload))
86
- );
87
-
88
- $signingInput = implode('.', $segments);
89
- $signer = new Google_P12Signer($this->privateKey, $this->privateKeyPassword);
90
- $signature = $signer->sign($signingInput);
91
- $segments[] = Google_Utils::urlSafeB64Encode($signature);
92
-
93
- return implode(".", $segments);
94
- }
95
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_AuthNone.php DELETED
@@ -1,48 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Do-nothing authentication implementation, use this if you want to make un-authenticated calls
20
- * @author Chris Chabot <chabotc@google.com>
21
- * @author Chirag Shah <chirags@google.com>
22
- */
23
- class Google_AuthNone extends Google_Auth {
24
- public $key = null;
25
-
26
- public function __construct() {
27
- global $apiConfig;
28
- if (!empty($apiConfig['developer_key'])) {
29
- $this->setDeveloperKey($apiConfig['developer_key']);
30
- }
31
- }
32
-
33
- public function setDeveloperKey($key) {$this->key = $key;}
34
- public function authenticate($service) {/*noop*/}
35
- public function setAccessToken($accessToken) {/* noop*/}
36
- public function getAccessToken() {return null;}
37
- public function createAuthUrl($scope) {return null;}
38
- public function refreshToken($refreshToken) {/* noop*/}
39
- public function revokeToken() {/* noop*/}
40
-
41
- public function sign(Google_HttpRequest $request) {
42
- if ($this->key) {
43
- $request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&')
44
- . 'key='.urlencode($this->key));
45
- }
46
- return $request;
47
- }
48
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_LoginTicket.php DELETED
@@ -1,63 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2011 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Class to hold information about an authenticated login.
20
- *
21
- * @author Brian Eaton <beaton@google.com>
22
- */
23
- class Google_LoginTicket {
24
- const USER_ATTR = "id";
25
-
26
- // Information from id token envelope.
27
- private $envelope;
28
-
29
- // Information from id token payload.
30
- private $payload;
31
-
32
- /**
33
- * Creates a user based on the supplied token.
34
- *
35
- * @param string $envelope Header from a verified authentication token.
36
- * @param string $payload Information from a verified authentication token.
37
- */
38
- public function __construct($envelope, $payload) {
39
- $this->envelope = $envelope;
40
- $this->payload = $payload;
41
- }
42
-
43
- /**
44
- * Returns the numeric identifier for the user.
45
- * @throws Google_AuthException
46
- * @return
47
- */
48
- public function getUserId() {
49
- if (array_key_exists(self::USER_ATTR, $this->payload)) {
50
- return $this->payload[self::USER_ATTR];
51
- }
52
- throw new Google_AuthException("No user_id in token");
53
- }
54
-
55
- /**
56
- * Returns attributes from the login ticket. This can contain
57
- * various information about the user session.
58
- * @return array
59
- */
60
- public function getAttributes() {
61
- return array("envelope" => $this->envelope, "payload" => $this->payload);
62
- }
63
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_OAuth2.php DELETED
@@ -1,444 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- require_once "Google_Verifier.php";
19
- require_once "Google_LoginTicket.php";
20
- require_once "service/Google_Utils.php";
21
-
22
- /**
23
- * Authentication class that deals with the OAuth 2 web-server authentication flow
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- * @author Chirag Shah <chirags@google.com>
27
- *
28
- */
29
- class Google_OAuth2 extends Google_Auth {
30
- public $clientId;
31
- public $clientSecret;
32
- public $developerKey;
33
- public $token;
34
- public $redirectUri;
35
- public $state;
36
- public $accessType = 'offline';
37
- public $approvalPrompt = 'force';
38
-
39
- /** @var Google_AssertionCredentials $assertionCredentials */
40
- public $assertionCredentials;
41
-
42
- const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
43
- const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
44
- const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
45
- const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
46
- const CLOCK_SKEW_SECS = 300; // five minutes in seconds
47
- const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
48
- const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
49
-
50
- /**
51
- * Instantiates the class, but does not initiate the login flow, leaving it
52
- * to the discretion of the caller (which is done by calling authenticate()).
53
- */
54
- public function __construct() {
55
- global $apiConfig;
56
-
57
- if (! empty($apiConfig['developer_key'])) {
58
- $this->developerKey = $apiConfig['developer_key'];
59
- }
60
-
61
- if (! empty($apiConfig['oauth2_client_id'])) {
62
- $this->clientId = $apiConfig['oauth2_client_id'];
63
- }
64
-
65
- if (! empty($apiConfig['oauth2_client_secret'])) {
66
- $this->clientSecret = $apiConfig['oauth2_client_secret'];
67
- }
68
-
69
- if (! empty($apiConfig['oauth2_redirect_uri'])) {
70
- $this->redirectUri = $apiConfig['oauth2_redirect_uri'];
71
- }
72
-
73
- if (! empty($apiConfig['oauth2_access_type'])) {
74
- $this->accessType = $apiConfig['oauth2_access_type'];
75
- }
76
-
77
- if (! empty($apiConfig['oauth2_approval_prompt'])) {
78
- $this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
79
- }
80
- }
81
-
82
- /**
83
- * @param $service
84
- * @param string|null $code
85
- * @throws Google_AuthException
86
- * @return string
87
- */
88
- public function authenticate($service, $code = null) {
89
- if (!$code && isset($_GET['code'])) {
90
- $code = $_GET['code'];
91
- }
92
-
93
- if ($code) {
94
- // We got here from the redirect from a successful authorization grant, fetch the access token
95
- $request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
96
- 'code' => $code,
97
- 'grant_type' => 'authorization_code',
98
- 'redirect_uri' => $this->redirectUri,
99
- 'client_id' => $this->clientId,
100
- 'client_secret' => $this->clientSecret
101
- )));
102
-
103
- if ($request->getResponseHttpCode() == 200) {
104
- $this->setAccessToken($request->getResponseBody());
105
- $this->token['created'] = time();
106
- return $this->getAccessToken();
107
- } else {
108
- $response = $request->getResponseBody();
109
- $decodedResponse = json_decode($response, true);
110
- if ($decodedResponse != null && $decodedResponse['error']) {
111
- $response = $decodedResponse['error'];
112
- }
113
- throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
114
- }
115
- }
116
-
117
- $authUrl = $this->createAuthUrl($service['scope']);
118
- header('Location: ' . $authUrl);
119
- return true;
120
- }
121
-
122
- /**
123
- * Create a URL to obtain user authorization.
124
- * The authorization endpoint allows the user to first
125
- * authenticate, and then grant/deny the access request.
126
- * @param string $scope The scope is expressed as a list of space-delimited strings.
127
- * @return string
128
- */
129
- public function createAuthUrl($scope) {
130
- $params = array(
131
- 'response_type=code',
132
- 'redirect_uri=' . urlencode($this->redirectUri),
133
- 'client_id=' . urlencode($this->clientId),
134
- 'scope=' . urlencode($scope),
135
- 'access_type=' . urlencode($this->accessType),
136
- 'approval_prompt=' . urlencode($this->approvalPrompt)
137
- );
138
-
139
- if (isset($this->state)) {
140
- $params[] = 'state=' . urlencode($this->state);
141
- }
142
- $params = implode('&', $params);
143
- return self::OAUTH2_AUTH_URL . "?$params";
144
- }
145
-
146
- /**
147
- * @param string $token
148
- * @throws Google_AuthException
149
- */
150
- public function setAccessToken($token) {
151
- $token = json_decode($token, true);
152
- if ($token == null) {
153
- throw new Google_AuthException('Could not json decode the token');
154
- }
155
- if (! isset($token['access_token'])) {
156
- throw new Google_AuthException("Invalid token format");
157
- }
158
- $this->token = $token;
159
- }
160
-
161
- public function getAccessToken() {
162
- return json_encode($this->token);
163
- }
164
-
165
- public function setDeveloperKey($developerKey) {
166
- $this->developerKey = $developerKey;
167
- }
168
-
169
- public function setState($state) {
170
- $this->state = $state;
171
- }
172
-
173
- public function setAccessType($accessType) {
174
- $this->accessType = $accessType;
175
- }
176
-
177
- public function setApprovalPrompt($approvalPrompt) {
178
- $this->approvalPrompt = $approvalPrompt;
179
- }
180
-
181
- public function setAssertionCredentials(Google_AssertionCredentials $creds) {
182
- $this->assertionCredentials = $creds;
183
- }
184
-
185
- /**
186
- * Include an accessToken in a given apiHttpRequest.
187
- * @param Google_HttpRequest $request
188
- * @return Google_HttpRequest
189
- * @throws Google_AuthException
190
- */
191
- public function sign(Google_HttpRequest $request) {
192
- // add the developer key to the request before signing it
193
- if ($this->developerKey) {
194
- $requestUrl = $request->getUrl();
195
- $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
196
- $requestUrl .= 'key=' . urlencode($this->developerKey);
197
- $request->setUrl($requestUrl);
198
- }
199
-
200
- // Cannot sign the request without an OAuth access token.
201
- if (null == $this->token && null == $this->assertionCredentials) {
202
- return $request;
203
- }
204
-
205
- // Check if the token is set to expire in the next 30 seconds
206
- // (or has already expired).
207
- if ($this->isAccessTokenExpired()) {
208
- if ($this->assertionCredentials) {
209
- $this->refreshTokenWithAssertion();
210
- } else {
211
- if (! array_key_exists('refresh_token', $this->token)) {
212
- throw new Google_AuthException("The OAuth 2.0 access token has expired, "
213
- . "and a refresh token is not available. Refresh tokens are not "
214
- . "returned for responses that were auto-approved.");
215
- }
216
- $this->refreshToken($this->token['refresh_token']);
217
- }
218
- }
219
-
220
- // Add the OAuth2 header to the request
221
- $request->setRequestHeaders(
222
- array('Authorization' => 'Bearer ' . $this->token['access_token'])
223
- );
224
-
225
- return $request;
226
- }
227
-
228
- /**
229
- * Fetches a fresh access token with the given refresh token.
230
- * @param string $refreshToken
231
- * @return void
232
- */
233
- public function refreshToken($refreshToken) {
234
- $this->refreshTokenRequest(array(
235
- 'client_id' => $this->clientId,
236
- 'client_secret' => $this->clientSecret,
237
- 'refresh_token' => $refreshToken,
238
- 'grant_type' => 'refresh_token'
239
- ));
240
- }
241
-
242
- /**
243
- * Fetches a fresh access token with a given assertion token.
244
- * @param Google_AssertionCredentials $assertionCredentials optional.
245
- * @return void
246
- */
247
- public function refreshTokenWithAssertion($assertionCredentials = null) {
248
- if (!$assertionCredentials) {
249
- $assertionCredentials = $this->assertionCredentials;
250
- }
251
-
252
- $this->refreshTokenRequest(array(
253
- 'grant_type' => 'assertion',
254
- 'assertion_type' => $assertionCredentials->assertionType,
255
- 'assertion' => $assertionCredentials->generateAssertion(),
256
- ));
257
- }
258
-
259
- private function refreshTokenRequest($params) {
260
- $http = new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
261
- $request = Google_Client::$io->makeRequest($http);
262
-
263
- $code = $request->getResponseHttpCode();
264
- $body = $request->getResponseBody();
265
- if (200 == $code) {
266
- $token = json_decode($body, true);
267
- if ($token == null) {
268
- throw new Google_AuthException("Could not json decode the access token");
269
- }
270
-
271
- if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
272
- throw new Google_AuthException("Invalid token format");
273
- }
274
-
275
- $this->token['access_token'] = $token['access_token'];
276
- $this->token['expires_in'] = $token['expires_in'];
277
- $this->token['created'] = time();
278
- } else {
279
- throw new Google_AuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
280
- }
281
- }
282
-
283
- /**
284
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
285
- * token, if a token isn't provided.
286
- * @throws Google_AuthException
287
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
288
- * @return boolean Returns True if the revocation was successful, otherwise False.
289
- */
290
- public function revokeToken($token = null) {
291
- if (!$token) {
292
- $token = $this->token['access_token'];
293
- }
294
- $request = new Google_HttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
295
- $response = Google_Client::$io->makeRequest($request);
296
- $code = $response->getResponseHttpCode();
297
- if ($code == 200) {
298
- $this->token = null;
299
- return true;
300
- }
301
-
302
- return false;
303
- }
304
-
305
- /**
306
- * Returns if the access_token is expired.
307
- * @return bool Returns True if the access_token is expired.
308
- */
309
- public function isAccessTokenExpired() {
310
- if (null == $this->token) {
311
- return true;
312
- }
313
-
314
- // If the token is set to expire in the next 30 seconds.
315
- $expired = ($this->token['created']
316
- + ($this->token['expires_in'] - 30)) < time();
317
-
318
- return $expired;
319
- }
320
-
321
- // Gets federated sign-on certificates to use for verifying identity tokens.
322
- // Returns certs as array structure, where keys are key ids, and values
323
- // are PEM encoded certificates.
324
- private function getFederatedSignOnCerts() {
325
- // This relies on makeRequest caching certificate responses.
326
- $request = Google_Client::$io->makeRequest(new Google_HttpRequest(
327
- self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
328
- if ($request->getResponseHttpCode() == 200) {
329
- $certs = json_decode($request->getResponseBody(), true);
330
- if ($certs) {
331
- return $certs;
332
- }
333
- }
334
- throw new Google_AuthException(
335
- "Failed to retrieve verification certificates: '" .
336
- $request->getResponseBody() . "'.",
337
- $request->getResponseHttpCode());
338
- }
339
-
340
- /**
341
- * Verifies an id token and returns the authenticated apiLoginTicket.
342
- * Throws an exception if the id token is not valid.
343
- * The audience parameter can be used to control which id tokens are
344
- * accepted. By default, the id token must have been issued to this OAuth2 client.
345
- *
346
- * @param $id_token
347
- * @param $audience
348
- * @return Google_LoginTicket
349
- */
350
- public function verifyIdToken($id_token = null, $audience = null) {
351
- if (!$id_token) {
352
- $id_token = $this->token['id_token'];
353
- }
354
-
355
- $certs = $this->getFederatedSignonCerts();
356
- if (!$audience) {
357
- $audience = $this->clientId;
358
- }
359
- return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
360
- }
361
-
362
- // Verifies the id token, returns the verified token contents.
363
- // Visible for testing.
364
- function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
365
- $segments = explode(".", $jwt);
366
- if (count($segments) != 3) {
367
- throw new Google_AuthException("Wrong number of segments in token: $jwt");
368
- }
369
- $signed = $segments[0] . "." . $segments[1];
370
- $signature = Google_Utils::urlSafeB64Decode($segments[2]);
371
-
372
- // Parse envelope.
373
- $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
374
- if (!$envelope) {
375
- throw new Google_AuthException("Can't parse token envelope: " . $segments[0]);
376
- }
377
-
378
- // Parse token
379
- $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
380
- $payload = json_decode($json_body, true);
381
- if (!$payload) {
382
- throw new Google_AuthException("Can't parse token payload: " . $segments[1]);
383
- }
384
-
385
- // Check signature
386
- $verified = false;
387
- foreach ($certs as $keyName => $pem) {
388
- $public_key = new Google_PemVerifier($pem);
389
- if ($public_key->verify($signed, $signature)) {
390
- $verified = true;
391
- break;
392
- }
393
- }
394
-
395
- if (!$verified) {
396
- throw new Google_AuthException("Invalid token signature: $jwt");
397
- }
398
-
399
- // Check issued-at timestamp
400
- $iat = 0;
401
- if (array_key_exists("iat", $payload)) {
402
- $iat = $payload["iat"];
403
- }
404
- if (!$iat) {
405
- throw new Google_AuthException("No issue time in token: $json_body");
406
- }
407
- $earliest = $iat - self::CLOCK_SKEW_SECS;
408
-
409
- // Check expiration timestamp
410
- $now = time();
411
- $exp = 0;
412
- if (array_key_exists("exp", $payload)) {
413
- $exp = $payload["exp"];
414
- }
415
- if (!$exp) {
416
- throw new Google_AuthException("No expiration time in token: $json_body");
417
- }
418
- if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
419
- throw new Google_AuthException(
420
- "Expiration time too far in future: $json_body");
421
- }
422
-
423
- $latest = $exp + self::CLOCK_SKEW_SECS;
424
- if ($now < $earliest) {
425
- throw new Google_AuthException(
426
- "Token used too early, $now < $earliest: $json_body");
427
- }
428
- if ($now > $latest) {
429
- throw new Google_AuthException(
430
- "Token used too late, $now > $latest: $json_body");
431
- }
432
-
433
- // TODO(beaton): check issuer field?
434
-
435
- // Check audience
436
- $aud = $payload["aud"];
437
- if ($aud != $required_audience) {
438
- throw new Google_AuthException("Wrong recipient, $aud != $required_audience: $json_body");
439
- }
440
-
441
- // All good.
442
- return new Google_LoginTicket($envelope, $payload);
443
- }
444
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_P12Signer.php DELETED
@@ -1,66 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2011 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Signs data.
20
- *
21
- * Only used for testing.
22
- *
23
- * @author Brian Eaton <beaton@google.com>
24
- */
25
- class Google_P12Signer extends Google_Signer {
26
- // OpenSSL private key resource
27
- private $privateKey;
28
-
29
- // Creates a new signer from a .p12 file.
30
- function __construct($p12, $password) {
31
- if (!function_exists('openssl_x509_read')) {
32
- throw new Exception(
33
- 'The Google PHP API library needs the openssl PHP extension');
34
- }
35
-
36
- // This throws on error
37
- $certs = array();
38
- if (!openssl_pkcs12_read($p12, $certs, $password)) {
39
- throw new Google_AuthException("Unable to parse the p12 file. " .
40
- "Is this a .p12 file? Is the password correct? OpenSSL error: " .
41
- openssl_error_string());
42
- }
43
- // TODO(beaton): is this part of the contract for the openssl_pkcs12_read
44
- // method? What happens if there are multiple private keys? Do we care?
45
- if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
46
- throw new Google_AuthException("No private key found in p12 file.");
47
- }
48
- $this->privateKey = openssl_pkey_get_private($certs["pkey"]);
49
- if (!$this->privateKey) {
50
- throw new Google_AuthException("Unable to load private key in ");
51
- }
52
- }
53
-
54
- function __destruct() {
55
- if ($this->privateKey) {
56
- openssl_pkey_free($this->privateKey);
57
- }
58
- }
59
-
60
- function sign($data) {
61
- if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) {
62
- throw new Google_AuthException("Unable to sign data");
63
- }
64
- return $signature;
65
- }
66
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/auth/Google_PemVerifier.php DELETED
@@ -1,66 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2011 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Verifies signatures using PEM encoded certificates.
20
- *
21
- * @author Brian Eaton <beaton@google.com>
22
- */
23
- class Google_PemVerifier extends Google_Verifier {
24
- private $publicKey;
25
-
26
- /**
27
- * Constructs a verifier from the supplied PEM-encoded certificate.
28
- *
29
- * $pem: a PEM encoded certificate (not a file).
30
- * @param $pem
31
- * @throws Google_AuthException
32
- * @throws Google_Exception
33
- */
34
- function __construct($pem) {
35
- if (!function_exists('openssl_x509_read')) {
36
- throw new Google_Exception('Google API PHP client needs the openssl PHP extension');
37
- }
38
- $this->publicKey = openssl_x509_read($pem);
39
- if (!$this->publicKey) {
40
- throw new Google_AuthException("Unable to parse PEM: $pem");
41
- }
42
- }
43
-
44
- function __destruct() {
45
- if ($this->publicKey) {
46
- openssl_x509_free($this->publicKey);
47
- }
48
- }
49
-
50
- /**
51
- * Verifies the signature on data.
52
- *
53
- * Returns true if the signature is valid, false otherwise.
54
- * @param $data
55
- * @param $signature
56
- * @throws Google_AuthException
57
- * @return bool
58
- */
59
- function verify($data, $signature) {
60
- $status = openssl_verify($data, $signature, $this->publicKey, "sha256");
61
- if ($status === -1) {
62
- throw new Google_AuthException('Signature verification error: ' . openssl_error_string());
63
- }
64
- return $status === 1;
65
- }
66
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/cache/Google_ApcCache.php DELETED
@@ -1,98 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * A persistent storage class based on the APC cache, which is not
20
- * really very persistent, as soon as you restart your web server
21
- * the storage will be wiped, however for debugging and/or speed
22
- * it can be useful, kinda, and cache is a lot cheaper then storage.
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- */
26
- class googleApcCache extends Google_Cache {
27
-
28
- public function __construct() {
29
- if (! function_exists('apc_add')) {
30
- throw new Google_CacheException("Apc functions not available");
31
- }
32
- }
33
-
34
- private function isLocked($key) {
35
- if ((@apc_fetch($key . '.lock')) === false) {
36
- return false;
37
- }
38
- return true;
39
- }
40
-
41
- private function createLock($key) {
42
- // the interesting thing is that this could fail if the lock was created in the meantime..
43
- // but we'll ignore that out of convenience
44
- @apc_add($key . '.lock', '', 5);
45
- }
46
-
47
- private function removeLock($key) {
48
- // suppress all warnings, if some other process removed it that's ok too
49
- @apc_delete($key . '.lock');
50
- }
51
-
52
- private function waitForLock($key) {
53
- // 20 x 250 = 5 seconds
54
- $tries = 20;
55
- $cnt = 0;
56
- do {
57
- // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
58
- usleep(250);
59
- $cnt ++;
60
- } while ($cnt <= $tries && $this->isLocked($key));
61
- if ($this->isLocked($key)) {
62
- // 5 seconds passed, assume the owning process died off and remove it
63
- $this->removeLock($key);
64
- }
65
- }
66
-
67
- /**
68
- * @inheritDoc
69
- */
70
- public function get($key, $expiration = false) {
71
-
72
- if (($ret = @apc_fetch($key)) === false) {
73
- return false;
74
- }
75
- if (!$expiration || (time() - $ret['time'] > $expiration)) {
76
- $this->delete($key);
77
- return false;
78
- }
79
- return unserialize($ret['data']);
80
- }
81
-
82
- /**
83
- * @inheritDoc
84
- */
85
- public function set($key, $value) {
86
- if (@apc_store($key, array('time' => time(), 'data' => serialize($value))) == false) {
87
- throw new Google_CacheException("Couldn't store data");
88
- }
89
- }
90
-
91
- /**
92
- * @inheritDoc
93
- * @param String $key
94
- */
95
- public function delete($key) {
96
- @apc_delete($key);
97
- }
98
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/cache/Google_Cache.php DELETED
@@ -1,55 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- require_once "Google_FileCache.php";
19
- require_once "Google_MemcacheCache.php";
20
-
21
- /**
22
- * Abstract storage class
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- */
26
- abstract class Google_Cache {
27
-
28
- /**
29
- * Retrieves the data for the given key, or false if they
30
- * key is unknown or expired
31
- *
32
- * @param String $key The key who's data to retrieve
33
- * @param boolean|int $expiration Expiration time in seconds
34
- *
35
- */
36
- abstract function get($key, $expiration = false);
37
-
38
- /**
39
- * Store the key => $value set. The $value is serialized
40
- * by this function so can be of any type
41
- *
42
- * @param string $key Key of the data
43
- * @param string $value data
44
- */
45
- abstract function set($key, $value);
46
-
47
- /**
48
- * Removes the key/data pair for the given $key
49
- *
50
- * @param String $key
51
- */
52
- abstract function delete($key);
53
- }
54
-
55
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/cache/Google_FileCache.php DELETED
@@ -1,137 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /*
19
- * This class implements a basic on disk storage. While that does
20
- * work quite well it's not the most elegant and scalable solution.
21
- * It will also get you into a heap of trouble when you try to run
22
- * this in a clustered environment. In those cases please use the
23
- * MySql back-end
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- */
27
- class Google_FileCache extends Google_Cache {
28
- private $path;
29
-
30
- public function __construct() {
31
- global $apiConfig;
32
- $this->path = $apiConfig['ioFileCache_directory'];
33
- }
34
-
35
- private function isLocked($storageFile) {
36
- // our lock file convention is simple: /the/file/path.lock
37
- return file_exists($storageFile . '.lock');
38
- }
39
-
40
- private function createLock($storageFile) {
41
- $storageDir = dirname($storageFile);
42
- if (! is_dir($storageDir)) {
43
- // @codeCoverageIgnoreStart
44
- if (! @mkdir($storageDir, 0755, true)) {
45
- // make sure the failure isn't because of a concurrency issue
46
- if (! is_dir($storageDir)) {
47
- throw new Google_CacheException("Could not create storage directory: $storageDir");
48
- }
49
- }
50
- // @codeCoverageIgnoreEnd
51
- }
52
- @touch($storageFile . '.lock');
53
- }
54
-
55
- private function removeLock($storageFile) {
56
- // suppress all warnings, if some other process removed it that's ok too
57
- @unlink($storageFile . '.lock');
58
- }
59
-
60
- private function waitForLock($storageFile) {
61
- // 20 x 250 = 5 seconds
62
- $tries = 20;
63
- $cnt = 0;
64
- do {
65
- // make sure PHP picks up on file changes. This is an expensive action but really can't be avoided
66
- clearstatcache();
67
- // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
68
- usleep(250);
69
- $cnt ++;
70
- } while ($cnt <= $tries && $this->isLocked($storageFile));
71
- if ($this->isLocked($storageFile)) {
72
- // 5 seconds passed, assume the owning process died off and remove it
73
- $this->removeLock($storageFile);
74
- }
75
- }
76
-
77
- private function getCacheDir($hash) {
78
- // use the first 2 characters of the hash as a directory prefix
79
- // this should prevent slowdowns due to huge directory listings
80
- // and thus give some basic amount of scalability
81
- return $this->path . '/' . substr($hash, 0, 2);
82
- }
83
-
84
- private function getCacheFile($hash) {
85
- return $this->getCacheDir($hash) . '/' . $hash;
86
- }
87
-
88
- public function get($key, $expiration = false) {
89
- $storageFile = $this->getCacheFile(md5($key));
90
- // See if this storage file is locked, if so we wait upto 5 seconds for the lock owning process to
91
- // complete it's work. If the lock is not released within that time frame, it's cleaned up.
92
- // This should give us a fair amount of 'Cache Stampeding' protection
93
- if ($this->isLocked($storageFile)) {
94
- $this->waitForLock($storageFile);
95
- }
96
- if (file_exists($storageFile) && is_readable($storageFile)) {
97
- $now = time();
98
- if (! $expiration || (($mtime = @filemtime($storageFile)) !== false && ($now - $mtime) < $expiration)) {
99
- if (($data = @file_get_contents($storageFile)) !== false) {
100
- $data = unserialize($data);
101
- return $data;
102
- }
103
- }
104
- }
105
- return false;
106
- }
107
-
108
- public function set($key, $value) {
109
- $storageDir = $this->getCacheDir(md5($key));
110
- $storageFile = $this->getCacheFile(md5($key));
111
- if ($this->isLocked($storageFile)) {
112
- // some other process is writing to this file too, wait until it's done to prevent hickups
113
- $this->waitForLock($storageFile);
114
- }
115
- if (! is_dir($storageDir)) {
116
- if (! @mkdir($storageDir, 0755, true)) {
117
- throw new Google_CacheException("Could not create storage directory: $storageDir");
118
- }
119
- }
120
- // we serialize the whole request object, since we don't only want the
121
- // responseContent but also the postBody used, headers, size, etc
122
- $data = serialize($value);
123
- $this->createLock($storageFile);
124
- if (! @file_put_contents($storageFile, $data)) {
125
- $this->removeLock($storageFile);
126
- throw new Google_CacheException("Could not store data in the file");
127
- }
128
- $this->removeLock($storageFile);
129
- }
130
-
131
- public function delete($key) {
132
- $file = $this->getCacheFile(md5($key));
133
- if (! @unlink($file)) {
134
- throw new Google_CacheException("Cache file could not be deleted");
135
- }
136
- }
137
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/cache/Google_MemcacheCache.php DELETED
@@ -1,130 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * A persistent storage class based on the memcache, which is not
20
- * really very persistent, as soon as you restart your memcache daemon
21
- * the storage will be wiped, however for debugging and/or speed
22
- * it can be useful, kinda, and cache is a lot cheaper then storage.
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- */
26
- class Google_MemcacheCache extends Google_Cache {
27
- private $connection = false;
28
-
29
- public function __construct() {
30
- global $apiConfig;
31
- if (! function_exists('memcache_connect')) {
32
- throw new Google_CacheException("Memcache functions not available");
33
- }
34
- $this->host = $apiConfig['ioMemCacheCache_host'];
35
- $this->port = $apiConfig['ioMemCacheCache_port'];
36
- if (empty($this->host) || empty($this->port)) {
37
- throw new Google_CacheException("You need to supply a valid memcache host and port");
38
- }
39
- }
40
-
41
- private function isLocked($key) {
42
- $this->check();
43
- if ((@memcache_get($this->connection, $key . '.lock')) === false) {
44
- return false;
45
- }
46
- return true;
47
- }
48
-
49
- private function createLock($key) {
50
- $this->check();
51
- // the interesting thing is that this could fail if the lock was created in the meantime..
52
- // but we'll ignore that out of convenience
53
- @memcache_add($this->connection, $key . '.lock', '', 0, 5);
54
- }
55
-
56
- private function removeLock($key) {
57
- $this->check();
58
- // suppress all warnings, if some other process removed it that's ok too
59
- @memcache_delete($this->connection, $key . '.lock');
60
- }
61
-
62
- private function waitForLock($key) {
63
- $this->check();
64
- // 20 x 250 = 5 seconds
65
- $tries = 20;
66
- $cnt = 0;
67
- do {
68
- // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
69
- usleep(250);
70
- $cnt ++;
71
- } while ($cnt <= $tries && $this->isLocked($key));
72
- if ($this->isLocked($key)) {
73
- // 5 seconds passed, assume the owning process died off and remove it
74
- $this->removeLock($key);
75
- }
76
- }
77
-
78
- // I prefer lazy initialization since the cache isn't used every request
79
- // so this potentially saves a lot of overhead
80
- private function connect() {
81
- if (! $this->connection = @memcache_pconnect($this->host, $this->port)) {
82
- throw new Google_CacheException("Couldn't connect to memcache server");
83
- }
84
- }
85
-
86
- private function check() {
87
- if (! $this->connection) {
88
- $this->connect();
89
- }
90
- }
91
-
92
- /**
93
- * @inheritDoc
94
- */
95
- public function get($key, $expiration = false) {
96
- $this->check();
97
- if (($ret = @memcache_get($this->connection, $key)) === false) {
98
- return false;
99
- }
100
- if (! $expiration || (time() - $ret['time'] > $expiration)) {
101
- $this->delete($key);
102
- return false;
103
- }
104
- return $ret['data'];
105
- }
106
-
107
- /**
108
- * @inheritDoc
109
- * @param string $key
110
- * @param string $value
111
- * @throws Google_CacheException
112
- */
113
- public function set($key, $value) {
114
- $this->check();
115
- // we store it with the cache_time default expiration so objects will at least get cleaned eventually.
116
- if (@memcache_set($this->connection, $key, array('time' => time(),
117
- 'data' => $value), false) == false) {
118
- throw new Google_CacheException("Couldn't store data in cache");
119
- }
120
- }
121
-
122
- /**
123
- * @inheritDoc
124
- * @param String $key
125
- */
126
- public function delete($key) {
127
- $this->check();
128
- @memcache_delete($this->connection, $key);
129
- }
130
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/config.php DELETED
@@ -1,83 +0,0 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- global $apiConfig;
19
- $apiConfig = array(
20
- // True if objects should be returned by the service classes.
21
- // False if associative arrays should be returned (default behavior).
22
- 'use_objects' => false,
23
-
24
- // The application_name is included in the User-Agent HTTP header.
25
-
26
- 'application_name' => '',
27
-
28
- // OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
29
- 'oauth2_client_id' => '',
30
- 'oauth2_client_secret' => '',
31
- 'oauth2_redirect_uri' => '',
32
-
33
- // The developer key, you get this at https://code.google.com/apis/console
34
- 'developer_key' => '',
35
-
36
- // Site name to show in the Google's OAuth 1 authentication screen.
37
- 'site_name' => 'www.example.org',
38
-
39
- // Which Authentication, Storage and HTTP IO classes to use.
40
- 'authClass' => 'Google_OAuth2',
41
- 'ioClass' => 'Google_CurlIO',
42
- 'cacheClass' => 'Google_FileCache',
43
-
44
- // Don't change these unless you're working against a special development or testing environment.
45
- 'basePath' => 'https://www.googleapis.com',
46
-
47
- // IO Class dependent configuration, you only have to configure the values
48
- // for the class that was configured as the ioClass above
49
- 'ioFileCache_directory' =>
50
- (function_exists('sys_get_temp_dir') ?
51
- sys_get_temp_dir() . '/Google_Client' :
52
- '/tmp/Google_Client'),
53
-
54
- // Definition of service specific values like scopes, oauth token URLs, etc
55
- 'services' => array(
56
- 'analytics' => array('scope' => 'https://www.googleapis.com/auth/analytics.readonly'),
57
- 'calendar' => array(
58
- 'scope' => array(
59
- "https://www.googleapis.com/auth/calendar",
60
- "https://www.googleapis.com/auth/calendar.readonly",
61
- )
62
- ),
63
- 'books' => array('scope' => 'https://www.googleapis.com/auth/books'),
64
- 'latitude' => array(
65
- 'scope' => array(
66
- 'https://www.googleapis.com/auth/latitude.all.best',
67
- 'https://www.googleapis.com/auth/latitude.all.city',
68
- )
69
- ),
70
- 'moderator' => array('scope' => 'https://www.googleapis.com/auth/moderator'),
71
- 'oauth2' => array(
72
- 'scope' => array(
73
- 'https://www.googleapis.com/auth/userinfo.profile',
74
- 'https://www.googleapis.com/auth/userinfo.email',
75
- )
76
- ),
77
- 'plus' => array('scope' => 'https://www.googleapis.com/auth/plus.me'),
78
- 'siteVerification' => array('scope' => 'https://www.googleapis.com/auth/siteverification'),
79
- 'tasks' => array('scope' => 'https://www.googleapis.com/auth/tasks'),
80
- 'urlshortener' => array('scope' => 'https://www.googleapis.com/auth/urlshortener')
81
- )
82
-
83
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/contrib/Google_AdexchangebuyerService.php DELETED
@@ -1,567 +0,0 @@
1
- <?php
2
- /*
3
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
- * use this file except in compliance with the License. You may obtain a copy of
5
- * the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
- * License for the specific language governing permissions and limitations under
13
- * the License.
14
- */
15
-
16
-
17
- /**
18
- * The "directDeals" collection of methods.
19
- * Typical usage is:
20
- * <code>
21
- * $adexchangebuyerService = new Google_AdexchangebuyerService(...);
22
- * $directDeals = $adexchangebuyerService->directDeals;
23
- * </code>
24
- */
25
- class Google_DirectDealsServiceResource extends Google_ServiceResource {
26
-
27
-
28
- /**
29
- * Retrieves the authenticated user's list of direct deals. (directDeals.list)
30
- *
31
- * @param array $optParams Optional parameters.
32
- * @return Google_DirectDealsList
33
- */
34
- public function listDirectDeals($optParams = array()) {
35
- $params = array();
36
- $params = array_merge($params, $optParams);
37
- $data = $this->__call('list', array($params));
38
- if ($this->useObjects()) {
39
- return new Google_DirectDealsList($data);
40
- } else {
41
- return $data;
42
- }
43
- }
44
- /**
45
- * Gets one direct deal by ID. (directDeals.get)
46
- *
47
- * @param string $id The direct deal id
48
- * @param array $optParams Optional parameters.
49
- * @return Google_DirectDeal
50
- */
51
- public function get($id, $optParams = array()) {
52
- $params = array('id' => $id);
53
- $params = array_merge($params, $optParams);
54
- $data = $this->__call('get', array($params));
55
- if ($this->useObjects()) {
56
- return new Google_DirectDeal($data);
57
- } else {
58
- return $data;
59
- }
60
- }
61
- }
62
-
63
- /**
64
- * The "accounts" collection of methods.
65
- * Typical usage is:
66
- * <code>
67
- * $adexchangebuyerService = new Google_AdexchangebuyerService(...);
68
- * $accounts = $adexchangebuyerService->accounts;
69
- * </code>
70
- */
71
- class Google_AccountsServiceResource extends Google_ServiceResource {
72
-
73
-
74
- /**
75
- * Updates an existing account. This method supports patch semantics. (accounts.patch)
76
- *
77
- * @param int $id The account id
78
- * @param Google_Account $postBody
79
- * @param array $optParams Optional parameters.
80
- * @return Google_Account
81
- */
82
- public function patch($id, Google_Account $postBody, $optParams = array()) {
83
- $params = array('id' => $id, 'postBody' => $postBody);
84
- $params = array_merge($params, $optParams);
85
- $data = $this->__call('patch', array($params));
86
- if ($this->useObjects()) {
87
- return new Google_Account($data);
88
- } else {
89
- return $data;
90
- }
91
- }
92
- /**
93
- * Retrieves the authenticated user's list of accounts. (accounts.list)
94
- *
95
- * @param array $optParams Optional parameters.
96
- * @return Google_AccountsList
97
- */
98
- public function listAccounts($optParams = array()) {
99
- $params = array();
100
- $params = array_merge($params, $optParams);
101
- $data = $this->__call('list', array($params));
102
- if ($this->useObjects()) {
103
- return new Google_AccountsList($data);
104
- } else {
105
- return $data;
106
- }
107
- }
108
- /**
109
- * Updates an existing account. (accounts.update)
110
- *
111
- * @param int $id The account id
112
- * @param Google_Account $postBody
113
- * @param array $optParams Optional parameters.
114
- * @return Google_Account
115
- */
116
- public function update($id, Google_Account $postBody, $optParams = array()) {
117
- $params = array('id' => $id, 'postBody' => $postBody);
118
- $params = array_merge($params, $optParams);
119
- $data = $this->__call('update', array($params));
120
- if ($this->useObjects()) {
121
- return new Google_Account($data);
122
- } else {
123
- return $data;
124
- }
125
- }
126
- /**
127
- * Gets one account by ID. (accounts.get)
128
- *
129
- * @param int $id The account id
130
- * @param array $optParams Optional parameters.
131
- * @return Google_Account
132
- */
133
- public function get($id, $optParams = array()) {
134
- $params = array('id' => $id);
135
- $params = array_merge($params, $optParams);
136
- $data = $this->__call('get', array($params));
137
- if ($this->useObjects()) {
138
- return new Google_Account($data);
139
- } else {
140
- return $data;
141
- }
142
- }
143
- }
144
-
145
- /**
146
- * The "creatives" collection of methods.
147
- * Typical usage is:
148
- * <code>
149
- * $adexchangebuyerService = new Google_AdexchangebuyerService(...);
150
- * $creatives = $adexchangebuyerService->creatives;
151
- * </code>
152
- */
153
- class Google_CreativesServiceResource extends Google_ServiceResource {
154
-
155
-
156
- /**
157
- * Submit a new creative. (creatives.insert)
158
- *
159
- * @param Google_Creative $postBody
160
- * @param array $optParams Optional parameters.
161
- * @return Google_Creative
162
- */
163
- public function insert(Google_Creative $postBody, $optParams = array()) {
164
- $params = array('postBody' => $postBody);
165
- $params = array_merge($params, $optParams);
166
- $data = $this->__call('insert', array($params));
167
- if ($this->useObjects()) {
168
- return new Google_Creative($data);
169
- } else {
170
- return $data;
171
- }
172
- }
173
- /**
174
- * Retrieves a list of the authenticated user's active creatives. (creatives.list)
175
- *
176
- * @param array $optParams Optional parameters.
177
- *
178
- * @opt_param string pageToken A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. Optional.
179
- * @opt_param string maxResults Maximum number of entries returned on one result page. If not set, the default is 100. Optional.
180
- * @return Google_CreativesList
181
- */
182
- public function listCreatives($optParams = array()) {
183
- $params = array();
184
- $params = array_merge($params, $optParams);
185
- $data = $this->__call('list', array($params));
186
- if ($this->useObjects()) {
187
- return new Google_CreativesList($data);
188
- } else {
189
- return $data;
190
- }
191
- }
192
- /**
193
- * Gets the status for a single creative. (creatives.get)
194
- *
195
- * @param int $accountId The id for the account that will serve this creative.
196
- * @param string $buyerCreativeId The buyer-specific id for this creative.
197
- * @param string $adgroupId The adgroup this creative belongs to.
198
- * @param array $optParams Optional parameters.
199
- * @return Google_Creative
200
- */
201
- public function get($accountId, $buyerCreativeId, $adgroupId, $optParams = array()) {
202
- $params = array('accountId' => $accountId, 'buyerCreativeId' => $buyerCreativeId, 'adgroupId' => $adgroupId);
203
- $params = array_merge($params, $optParams);
204
- $data = $this->__call('get', array($params));
205
- if ($this->useObjects()) {
206
- return new Google_Creative($data);
207
- } else {
208
- return $data;
209
- }
210
- }
211
- }
212
-
213
- /**
214
- * Service definition for Google_Adexchangebuyer (v1).
215
- *
216
- * <p>
217
- * Lets you manage your Ad Exchange Buyer account
218
- * </p>
219
- *
220
- * <p>
221
- * For more information about this service, see the
222
- * <a href="https://developers.google.com/ad-exchange/buyer-rest" target="_blank">API Documentation</a>
223
- * </p>
224
- *
225
- * @author Google, Inc.
226
- */
227
- class Google_AdexchangebuyerService extends Google_Service {
228
- public $directDeals;
229
- public $accounts;
230
- public $creatives;
231
- /**
232
- * Constructs the internal representation of the Adexchangebuyer service.
233
- *
234
- * @param Google_Client $client
235
- */
236
- public function __construct(Google_Client $client) {
237
- $this->servicePath = 'adexchangebuyer/v1/';
238
- $this->version = 'v1';
239
- $this->serviceName = 'adexchangebuyer';
240
-
241
- $client->addService($this->serviceName, $this->version);
242
- $this->directDeals = new Google_DirectDealsServiceResource($this, $this->serviceName, 'directDeals', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "path": "directdeals", "response": {"$ref": "DirectDealsList"}, "id": "adexchangebuyer.directDeals.list", "httpMethod": "GET"}, "get": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"id": {"required": true, "type": "string", "location": "path", "format": "int64"}}, "id": "adexchangebuyer.directDeals.get", "httpMethod": "GET", "path": "directdeals/{id}", "response": {"$ref": "DirectDeal"}}}}', true));
243
- $this->accounts = new Google_AccountsServiceResource($this, $this->serviceName, 'accounts', json_decode('{"methods": {"patch": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"id": {"required": true, "type": "integer", "location": "path", "format": "int32"}}, "request": {"$ref": "Account"}, "response": {"$ref": "Account"}, "httpMethod": "PATCH", "path": "accounts/{id}", "id": "adexchangebuyer.accounts.patch"}, "list": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "path": "accounts", "response": {"$ref": "AccountsList"}, "id": "adexchangebuyer.accounts.list", "httpMethod": "GET"}, "update": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"id": {"required": true, "type": "integer", "location": "path", "format": "int32"}}, "request": {"$ref": "Account"}, "response": {"$ref": "Account"}, "httpMethod": "PUT", "path": "accounts/{id}", "id": "adexchangebuyer.accounts.update"}, "get": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"id": {"required": true, "type": "integer", "location": "path", "format": "int32"}}, "id": "adexchangebuyer.accounts.get", "httpMethod": "GET", "path": "accounts/{id}", "response": {"$ref": "Account"}}}}', true));
244
- $this->creatives = new Google_CreativesServiceResource($this, $this->serviceName, 'creatives', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "request": {"$ref": "Creative"}, "response": {"$ref": "Creative"}, "httpMethod": "POST", "path": "creatives", "id": "adexchangebuyer.creatives.insert"}, "list": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "1", "type": "integer", "maximum": "1000", "format": "uint32"}}, "response": {"$ref": "CreativesList"}, "httpMethod": "GET", "path": "creatives", "id": "adexchangebuyer.creatives.list"}, "get": {"scopes": ["https://www.googleapis.com/auth/adexchange.buyer"], "parameters": {"adgroupId": {"required": true, "type": "string", "location": "query", "format": "int64"}, "buyerCreativeId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "integer", "location": "path", "format": "int32"}}, "id": "adexchangebuyer.creatives.get", "httpMethod": "GET", "path": "creatives/{accountId}/{buyerCreativeId}", "response": {"$ref": "Creative"}}}}', true));
245
-
246
- }
247
- }
248
-
249
- class Google_Account extends Google_Model {
250
- public $kind;
251
- public $maximumTotalQps;
252
- protected $__bidderLocationType = 'Google_AccountBidderLocation';
253
- protected $__bidderLocationDataType = 'array';
254
- public $bidderLocation;
255
- public $cookieMatchingNid;
256
- public $id;
257
- public $cookieMatchingUrl;
258
- public function setKind($kind) {
259
- $this->kind = $kind;
260
- }
261
- public function getKind() {
262
- return $this->kind;
263
- }
264
- public function setMaximumTotalQps($maximumTotalQps) {
265
- $this->maximumTotalQps = $maximumTotalQps;
266
- }
267
- public function getMaximumTotalQps() {
268
- return $this->maximumTotalQps;
269
- }
270
- public function setBidderLocation(/* array(Google_AccountBidderLocation) */ $bidderLocation) {
271
- $this->assertIsArray($bidderLocation, 'Google_AccountBidderLocation', __METHOD__);
272
- $this->bidderLocation = $bidderLocation;
273
- }
274
- public function getBidderLocation() {
275
- return $this->bidderLocation;
276
- }
277
- public function setCookieMatchingNid($cookieMatchingNid) {
278
- $this->cookieMatchingNid = $cookieMatchingNid;
279
- }
280
- public function getCookieMatchingNid() {
281
- return $this->cookieMatchingNid;
282
- }
283
- public function setId($id) {
284
- $this->id = $id;
285
- }
286
- public function getId() {
287
- return $this->id;
288
- }
289
- public function setCookieMatchingUrl($cookieMatchingUrl) {
290
- $this->cookieMatchingUrl = $cookieMatchingUrl;
291
- }
292
- public function getCookieMatchingUrl() {
293
- return $this->cookieMatchingUrl;
294
- }
295
- }
296
-
297
- class Google_AccountBidderLocation extends Google_Model {
298
- public $url;
299
- public $maximumQps;
300
- public function setUrl($url) {
301
- $this->url = $url;
302
- }
303
- public function getUrl() {
304
- return $this->url;
305
- }
306
- public function setMaximumQps($maximumQps) {
307
- $this->maximumQps = $maximumQps;
308
- }
309
- public function getMaximumQps() {
310
- return $this->maximumQps;
311
- }
312
- }
313
-
314
- class Google_AccountsList extends Google_Model {
315
- protected $__itemsType = 'Google_Account';
316
- protected $__itemsDataType = 'array';
317
- public $items;
318
- public $kind;
319
- public function setItems(/* array(Google_Account) */ $items) {
320
- $this->assertIsArray($items, 'Google_Account', __METHOD__);
321
- $this->items = $items;
322
- }
323
- public function getItems() {
324
- return $this->items;
325
- }
326
- public function setKind($kind) {
327
- $this->kind = $kind;
328
- }
329
- public function getKind() {
330
- return $this->kind;
331
- }
332
- }
333
-
334
- class Google_Creative extends Google_Model {
335
- public $productCategories;
336
- public $advertiserName;
337
- public $adgroupId;
338
- public $videoURL;
339
- public $width;
340
- public $attribute;
341
- public $kind;
342
- public $height;
343
- public $advertiserId;
344
- public $HTMLSnippet;
345
- public $status;
346
- public $buyerCreativeId;
347
- public $clickThroughUrl;
348
- public $vendorType;
349
- public $disapprovalReasons;
350
- public $sensitiveCategories;
351
- public $accountId;
352
- public function setProductCategories(/* array(Google_int) */ $productCategories) {
353
- $this->assertIsArray($productCategories, 'Google_int', __METHOD__);
354
- $this->productCategories = $productCategories;
355
- }
356
- public function getProductCategories() {
357
- return $this->productCategories;
358
- }
359
- public function setAdvertiserName($advertiserName) {
360
- $this->advertiserName = $advertiserName;
361
- }
362
- public function getAdvertiserName() {
363
- return $this->advertiserName;
364
- }
365
- public function setAdgroupId($adgroupId) {
366
- $this->adgroupId = $adgroupId;
367
- }
368
- public function getAdgroupId() {
369
- return $this->adgroupId;
370
- }
371
- public function setVideoURL($videoURL) {
372
- $this->videoURL = $videoURL;
373
- }
374
- public function getVideoURL() {
375
- return $this->videoURL;
376
- }
377
- public function setWidth($width) {
378
- $this->width = $width;
379
- }
380
- public function getWidth() {
381
- return $this->width;
382
- }
383
- public function setAttribute(/* array(Google_int) */ $attribute) {
384
- $this->assertIsArray($attribute, 'Google_int', __METHOD__);
385
- $this->attribute = $attribute;
386
- }
387
- public function getAttribute() {
388
- return $this->attribute;
389
- }
390
- public function setKind($kind) {
391
- $this->kind = $kind;
392
- }
393
- public function getKind() {
394
- return $this->kind;
395
- }
396
- public function setHeight($height) {
397
- $this->height = $height;
398
- }
399
- public function getHeight() {
400
- return $this->height;
401
- }
402
- public function setAdvertiserId(/* array(Google_string) */ $advertiserId) {
403
- $this->assertIsArray($advertiserId, 'Google_string', __METHOD__);
404
- $this->advertiserId = $advertiserId;
405
- }
406
- public function getAdvertiserId() {
407
- return $this->advertiserId;
408
- }
409
- public function setHTMLSnippet($HTMLSnippet) {
410
- $this->HTMLSnippet = $HTMLSnippet;
411
- }
412
- public function getHTMLSnippet() {
413
- return $this->HTMLSnippet;
414
- }
415
- public function setStatus($status) {
416
- $this->status = $status;
417
- }
418
- public function getStatus() {
419
- return $this->status;
420
- }
421
- public function setBuyerCreativeId($buyerCreativeId) {
422
- $this->buyerCreativeId = $buyerCreativeId;
423
- }
424
- public function getBuyerCreativeId() {
425
- return $this->buyerCreativeId;
426
- }
427
- public function setClickThroughUrl(/* array(Google_string) */ $clickThroughUrl) {
428
- $this->assertIsArray($clickThroughUrl, 'Google_string', __METHOD__);
429
- $this->clickThroughUrl = $clickThroughUrl;
430
- }
431
- public function getClickThroughUrl() {
432
- return $this->clickThroughUrl;
433
- }
434
- public function setVendorType(/* array(Google_int) */ $vendorType) {
435
- $this->assertIsArray($vendorType, 'Google_int', __METHOD__);
436
- $this->vendorType = $vendorType;
437
- }
438
- public function getVendorType() {
439
- return $this->vendorType;
440
- }
441
- public function setDisapprovalReasons(/* array(Google_string) */ $disapprovalReasons) {
442
- $this->assertIsArray($disapprovalReasons, 'Google_string', __METHOD__);
443
- $this->disapprovalReasons = $disapprovalReasons;
444
- }
445
- public function getDisapprovalReasons() {
446
- return $this->disapprovalReasons;
447
- }
448
- public function setSensitiveCategories(/* array(Google_int) */ $sensitiveCategories) {
449
- $this->assertIsArray($sensitiveCategories, 'Google_int', __METHOD__);
450
- $this->sensitiveCategories = $sensitiveCategories;
451
- }
452
- public function getSensitiveCategories() {
453
- return $this->sensitiveCategories;
454
- }
455
- public function setAccountId($accountId) {
456
- $this->accountId = $accountId;
457
- }
458
- public function getAccountId() {
459
- return $this->accountId;
460
- }
461
- }
462
-
463
- class Google_CreativesList extends Google_Model {
464
- protected $__itemsType = 'Google_Creative';
465
- protected $__itemsDataType = 'array';
466
- public $items;
467
- public $kind;
468
- public function setItems(/* array(Google_Creative) */ $items) {
469
- $this->assertIsArray($items, 'Google_Creative', __METHOD__);
470
- $this->items = $items;
471
- }
472
- public function getItems() {
473
- return $this->items;
474
- }
475
- public function setKind($kind) {
476
- $this->kind = $kind;
477
- }
478
- public function getKind() {
479
- return $this->kind;
480
- }
481
- }
482
-
483
- class Google_DirectDeal extends Google_Model {
484
- public $advertiser;
485
- public $kind;
486
- public $currencyCode;
487
- public $fixedCpm;
488
- public $startTime;
489
- public $endTime;
490
- public $sellerNetwork;
491
- public $id;
492
- public $accountId;
493
- public function setAdvertiser($advertiser) {
494
- $this->advertiser = $advertiser;
495
- }
496
- public function getAdvertiser() {
497
- return $this->advertiser;
498
- }
499
- public function setKind($kind) {
500
- $this->kind = $kind;
501
- }
502
- public function getKind() {
503
- return $this->kind;
504
- }
505
- public function setCurrencyCode($currencyCode) {
506
- $this->currencyCode = $currencyCode;
507
- }
508
- public function getCurrencyCode() {
509
- return $this->currencyCode;
510
- }
511
- public function setFixedCpm($fixedCpm) {
512
- $this->fixedCpm = $fixedCpm;
513
- }
514
- public function getFixedCpm() {
515
- return $this->fixedCpm;
516
- }
517
- public function setStartTime($startTime) {
518
- $this->startTime = $startTime;
519
- }
520
- public function getStartTime() {
521
- return $this->startTime;
522
- }
523
- public function setEndTime($endTime) {
524
- $this->endTime = $endTime;
525
- }
526
- public function getEndTime() {
527
- return $this->endTime;
528
- }
529
- public function setSellerNetwork($sellerNetwork) {
530
- $this->sellerNetwork = $sellerNetwork;
531
- }
532
- public function getSellerNetwork() {
533
- return $this->sellerNetwork;
534
- }
535
- public function setId($id) {
536
- $this->id = $id;
537
- }
538
- public function getId() {
539
- return $this->id;
540
- }
541
- public function setAccountId($accountId) {
542
- $this->accountId = $accountId;
543
- }
544
- public function getAccountId() {
545
- return $this->accountId;
546
- }
547
- }
548
-
549
- class Google_DirectDealsList extends Google_Model {
550
- public $kind;
551
- protected $__directDealsType = 'Google_DirectDeal';
552
- protected $__directDealsDataType = 'array';
553
- public $directDeals;
554
- public function setKind($kind) {
555
- $this->kind = $kind;
556
- }
557
- public function getKind() {
558
- return $this->kind;
559
- }
560
- public function setDirectDeals(/* array(Google_DirectDeal) */ $directDeals) {
561
- $this->assertIsArray($directDeals, 'Google_DirectDeal', __METHOD__);
562
- $this->directDeals = $directDeals;
563
- }
564
- public function getDirectDeals() {
565
- return $this->directDeals;
566
- }
567
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/contrib/Google_AdsenseService.php DELETED
@@ -1,1144 +0,0 @@
1
- <?php
2
- /*
3
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
- * use this file except in compliance with the License. You may obtain a copy of
5
- * the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
- * License for the specific language governing permissions and limitations under
13
- * the License.
14
- */
15
-
16
-
17
- /**
18
- * The "urlchannels" collection of methods.
19
- * Typical usage is:
20
- * <code>
21
- * $adsenseService = new Google_AdsenseService(...);
22
- * $urlchannels = $adsenseService->urlchannels;
23
- * </code>
24
- */
25
- class Google_UrlchannelsServiceResource extends Google_ServiceResource {
26
-
27
-
28
- /**
29
- * List all URL channels in the specified ad client for this AdSense account. (urlchannels.list)
30
- *
31
- * @param string $adClientId Ad client for which to list URL channels.
32
- * @param array $optParams Optional parameters.
33
- *
34
- * @opt_param string pageToken A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
35
- * @opt_param int maxResults The maximum number of URL channels to include in the response, used for paging.
36
- * @return Google_UrlChannels
37
- */
38
- public function listUrlchannels($adClientId, $optParams = array()) {
39
- $params = array('adClientId' => $adClientId);
40
- $params = array_merge($params, $optParams);
41
- $data = $this->__call('list', array($params));
42
- if ($this->useObjects()) {
43
- return new Google_UrlChannels($data);
44
- } else {
45
- return $data;
46
- }
47
- }
48
- }
49
-
50
- /**
51
- * The "adunits" collection of methods.
52
- * Typical usage is:
53
- * <code>
54
- * $adsenseService = new Google_AdsenseService(...);
55
- * $adunits = $adsenseService->adunits;
56
- * </code>
57
- */
58
- class Google_AdunitsServiceResource extends Google_ServiceResource {
59
-
60
-
61
- /**
62
- * List all ad units in the specified ad client for this AdSense account. (adunits.list)
63
- *
64
- * @param string $adClientId Ad client for which to list ad units.
65
- * @param array $optParams Optional parameters.
66
- *
67
- * @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
68
- * @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
69
- * @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
70
- * @return Google_AdUnits
71
- */
72
- public function listAdunits($adClientId, $optParams = array()) {
73
- $params = array('adClientId' => $adClientId);
74
- $params = array_merge($params, $optParams);
75
- $data = $this->__call('list', array($params));
76
- if ($this->useObjects()) {
77
- return new Google_AdUnits($data);
78
- } else {
79
- return $data;
80
- }
81
- }
82
- /**
83
- * Gets the specified ad unit in the specified ad client. (adunits.get)
84
- *
85
- * @param string $adClientId Ad client for which to get the ad unit.
86
- * @param string $adUnitId Ad unit to retrieve.
87
- * @param array $optParams Optional parameters.
88
- * @return Google_AdUnit
89
- */
90
- public function get($adClientId, $adUnitId, $optParams = array()) {
91
- $params = array('adClientId' => $adClientId, 'adUnitId' => $adUnitId);
92
- $params = array_merge($params, $optParams);
93
- $data = $this->__call('get', array($params));
94
- if ($this->useObjects()) {
95
- return new Google_AdUnit($data);
96
- } else {
97
- return $data;
98
- }
99
- }
100
- }
101
-
102
- /**
103
- * The "customchannels" collection of methods.
104
- * Typical usage is:
105
- * <code>
106
- * $adsenseService = new Google_AdsenseService(...);
107
- * $customchannels = $adsenseService->customchannels;
108
- * </code>
109
- */
110
- class Google_AdunitsCustomchannelsServiceResource extends Google_ServiceResource {
111
-
112
-
113
- /**
114
- * List all custom channels which the specified ad unit belongs to. (customchannels.list)
115
- *
116
- * @param string $adClientId Ad client which contains the ad unit.
117
- * @param string $adUnitId Ad unit for which to list custom channels.
118
- * @param array $optParams Optional parameters.
119
- *
120
- * @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
121
- * @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
122
- * @return Google_CustomChannels
123
- */
124
- public function listAdunitsCustomchannels($adClientId, $adUnitId, $optParams = array()) {
125
- $params = array('adClientId' => $adClientId, 'adUnitId' => $adUnitId);
126
- $params = array_merge($params, $optParams);
127
- $data = $this->__call('list', array($params));
128
- if ($this->useObjects()) {
129
- return new Google_CustomChannels($data);
130
- } else {
131
- return $data;
132
- }
133
- }
134
- }
135
-
136
- /**
137
- * The "adclients" collection of methods.
138
- * Typical usage is:
139
- * <code>
140
- * $adsenseService = new Google_AdsenseService(...);
141
- * $adclients = $adsenseService->adclients;
142
- * </code>
143
- */
144
- class Google_AdclientsServiceResource extends Google_ServiceResource {
145
-
146
-
147
- /**
148
- * List all ad clients in this AdSense account. (adclients.list)
149
- *
150
- * @param array $optParams Optional parameters.
151
- *
152
- * @opt_param string pageToken A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
153
- * @opt_param int maxResults The maximum number of ad clients to include in the response, used for paging.
154
- * @return Google_AdClients
155
- */
156
- public function listAdclients($optParams = array()) {
157
- $params = array();
158
- $params = array_merge($params, $optParams);
159
- $data = $this->__call('list', array($params));
160
- if ($this->useObjects()) {
161
- return new Google_AdClients($data);
162
- } else {
163
- return $data;
164
- }
165
- }
166
- }
167
-
168
- /**
169
- * The "reports" collection of methods.
170
- * Typical usage is:
171
- * <code>
172
- * $adsenseService = new Google_AdsenseService(...);
173
- * $reports = $adsenseService->reports;
174
- * </code>
175
- */
176
- class Google_ReportsServiceResource extends Google_ServiceResource {
177
-
178
-
179
- /**
180
- * Generate an AdSense report based on the report request sent in the query parameters. Returns the
181
- * result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter.
182
- * (reports.generate)
183
- *
184
- * @param string $startDate Start of the date range to report on in "YYYY-MM-DD" format, inclusive.
185
- * @param string $endDate End of the date range to report on in "YYYY-MM-DD" format, inclusive.
186
- * @param array $optParams Optional parameters.
187
- *
188
- * @opt_param string sort The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending.
189
- * @opt_param string locale Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified.
190
- * @opt_param string metric Numeric columns to include in the report.
191
- * @opt_param int maxResults The maximum number of rows of report data to return.
192
- * @opt_param string filter Filters to be run on the report.
193
- * @opt_param string currency Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.
194
- * @opt_param int startIndex Index of the first row of report data to return.
195
- * @opt_param string dimension Dimensions to base the report on.
196
- * @opt_param string accountId Accounts upon which to report.
197
- * @return Google_AdsenseReportsGenerateResponse
198
- */
199
- public function generate($startDate, $endDate, $optParams = array()) {
200
- $params = array('startDate' => $startDate, 'endDate' => $endDate);
201
- $params = array_merge($params, $optParams);
202
- $data = $this->__call('generate', array($params));
203
- if ($this->useObjects()) {
204
- return new Google_AdsenseReportsGenerateResponse($data);
205
- } else {
206
- return $data;
207
- }
208
- }
209
- }
210
-
211
- /**
212
- * The "accounts" collection of methods.
213
- * Typical usage is:
214
- * <code>
215
- * $adsenseService = new Google_AdsenseService(...);
216
- * $accounts = $adsenseService->accounts;
217
- * </code>
218
- */
219
- class Google_AccountsServiceResource extends Google_ServiceResource {
220
-
221
-
222
- /**
223
- * List all accounts available to this AdSense account. (accounts.list)
224
- *
225
- * @param array $optParams Optional parameters.
226
- *
227
- * @opt_param string pageToken A continuation token, used to page through accounts. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
228
- * @opt_param int maxResults The maximum number of accounts to include in the response, used for paging.
229
- * @return Google_Accounts
230
- */
231
- public function listAccounts($optParams = array()) {
232
- $params = array();
233
- $params = array_merge($params, $optParams);
234
- $data = $this->__call('list', array($params));
235
- if ($this->useObjects()) {
236
- return new Google_Accounts($data);
237
- } else {
238
- return $data;
239
- }
240
- }
241
- /**
242
- * Get information about the selected AdSense account. (accounts.get)
243
- *
244
- * @param string $accountId Account to get information about.
245
- * @param array $optParams Optional parameters.
246
- *
247
- * @opt_param bool tree Whether the tree of sub accounts should be returned.
248
- * @return Google_Account
249
- */
250
- public function get($accountId, $optParams = array()) {
251
- $params = array('accountId' => $accountId);
252
- $params = array_merge($params, $optParams);
253
- $data = $this->__call('get', array($params));
254
- if ($this->useObjects()) {
255
- return new Google_Account($data);
256
- } else {
257
- return $data;
258
- }
259
- }
260
- }
261
-
262
- /**
263
- * The "urlchannels" collection of methods.
264
- * Typical usage is:
265
- * <code>
266
- * $adsenseService = new Google_AdsenseService(...);
267
- * $urlchannels = $adsenseService->urlchannels;
268
- * </code>
269
- */
270
- class Google_AccountsUrlchannelsServiceResource extends Google_ServiceResource {
271
-
272
-
273
- /**
274
- * List all URL channels in the specified ad client for the specified account. (urlchannels.list)
275
- *
276
- * @param string $accountId Account to which the ad client belongs.
277
- * @param string $adClientId Ad client for which to list URL channels.
278
- * @param array $optParams Optional parameters.
279
- *
280
- * @opt_param string pageToken A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
281
- * @opt_param int maxResults The maximum number of URL channels to include in the response, used for paging.
282
- * @return Google_UrlChannels
283
- */
284
- public function listAccountsUrlchannels($accountId, $adClientId, $optParams = array()) {
285
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId);
286
- $params = array_merge($params, $optParams);
287
- $data = $this->__call('list', array($params));
288
- if ($this->useObjects()) {
289
- return new Google_UrlChannels($data);
290
- } else {
291
- return $data;
292
- }
293
- }
294
- }
295
- /**
296
- * The "adunits" collection of methods.
297
- * Typical usage is:
298
- * <code>
299
- * $adsenseService = new Google_AdsenseService(...);
300
- * $adunits = $adsenseService->adunits;
301
- * </code>
302
- */
303
- class Google_AccountsAdunitsServiceResource extends Google_ServiceResource {
304
-
305
-
306
- /**
307
- * List all ad units in the specified ad client for the specified account. (adunits.list)
308
- *
309
- * @param string $accountId Account to which the ad client belongs.
310
- * @param string $adClientId Ad client for which to list ad units.
311
- * @param array $optParams Optional parameters.
312
- *
313
- * @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
314
- * @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
315
- * @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
316
- * @return Google_AdUnits
317
- */
318
- public function listAccountsAdunits($accountId, $adClientId, $optParams = array()) {
319
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId);
320
- $params = array_merge($params, $optParams);
321
- $data = $this->__call('list', array($params));
322
- if ($this->useObjects()) {
323
- return new Google_AdUnits($data);
324
- } else {
325
- return $data;
326
- }
327
- }
328
- /**
329
- * Gets the specified ad unit in the specified ad client for the specified account. (adunits.get)
330
- *
331
- * @param string $accountId Account to which the ad client belongs.
332
- * @param string $adClientId Ad client for which to get the ad unit.
333
- * @param string $adUnitId Ad unit to retrieve.
334
- * @param array $optParams Optional parameters.
335
- * @return Google_AdUnit
336
- */
337
- public function get($accountId, $adClientId, $adUnitId, $optParams = array()) {
338
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'adUnitId' => $adUnitId);
339
- $params = array_merge($params, $optParams);
340
- $data = $this->__call('get', array($params));
341
- if ($this->useObjects()) {
342
- return new Google_AdUnit($data);
343
- } else {
344
- return $data;
345
- }
346
- }
347
- }
348
-
349
- /**
350
- * The "customchannels" collection of methods.
351
- * Typical usage is:
352
- * <code>
353
- * $adsenseService = new Google_AdsenseService(...);
354
- * $customchannels = $adsenseService->customchannels;
355
- * </code>
356
- */
357
- class Google_AccountsAdunitsCustomchannelsServiceResource extends Google_ServiceResource {
358
-
359
-
360
- /**
361
- * List all custom channels which the specified ad unit belongs to. (customchannels.list)
362
- *
363
- * @param string $accountId Account to which the ad client belongs.
364
- * @param string $adClientId Ad client which contains the ad unit.
365
- * @param string $adUnitId Ad unit for which to list custom channels.
366
- * @param array $optParams Optional parameters.
367
- *
368
- * @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
369
- * @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
370
- * @return Google_CustomChannels
371
- */
372
- public function listAccountsAdunitsCustomchannels($accountId, $adClientId, $adUnitId, $optParams = array()) {
373
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'adUnitId' => $adUnitId);
374
- $params = array_merge($params, $optParams);
375
- $data = $this->__call('list', array($params));
376
- if ($this->useObjects()) {
377
- return new Google_CustomChannels($data);
378
- } else {
379
- return $data;
380
- }
381
- }
382
- }
383
- /**
384
- * The "adclients" collection of methods.
385
- * Typical usage is:
386
- * <code>
387
- * $adsenseService = new Google_AdsenseService(...);
388
- * $adclients = $adsenseService->adclients;
389
- * </code>
390
- */
391
- class Google_AccountsAdclientsServiceResource extends Google_ServiceResource {
392
-
393
-
394
- /**
395
- * List all ad clients in the specified account. (adclients.list)
396
- *
397
- * @param string $accountId Account for which to list ad clients.
398
- * @param array $optParams Optional parameters.
399
- *
400
- * @opt_param string pageToken A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
401
- * @opt_param int maxResults The maximum number of ad clients to include in the response, used for paging.
402
- * @return Google_AdClients
403
- */
404
- public function listAccountsAdclients($accountId, $optParams = array()) {
405
- $params = array('accountId' => $accountId);
406
- $params = array_merge($params, $optParams);
407
- $data = $this->__call('list', array($params));
408
- if ($this->useObjects()) {
409
- return new Google_AdClients($data);
410
- } else {
411
- return $data;
412
- }
413
- }
414
- }
415
- /**
416
- * The "reports" collection of methods.
417
- * Typical usage is:
418
- * <code>
419
- * $adsenseService = new Google_AdsenseService(...);
420
- * $reports = $adsenseService->reports;
421
- * </code>
422
- */
423
- class Google_AccountsReportsServiceResource extends Google_ServiceResource {
424
-
425
-
426
- /**
427
- * Generate an AdSense report based on the report request sent in the query parameters. Returns the
428
- * result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter.
429
- * (reports.generate)
430
- *
431
- * @param string $accountId Account upon which to report.
432
- * @param string $startDate Start of the date range to report on in "YYYY-MM-DD" format, inclusive.
433
- * @param string $endDate End of the date range to report on in "YYYY-MM-DD" format, inclusive.
434
- * @param array $optParams Optional parameters.
435
- *
436
- * @opt_param string sort The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending.
437
- * @opt_param string locale Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified.
438
- * @opt_param string metric Numeric columns to include in the report.
439
- * @opt_param int maxResults The maximum number of rows of report data to return.
440
- * @opt_param string filter Filters to be run on the report.
441
- * @opt_param string currency Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.
442
- * @opt_param int startIndex Index of the first row of report data to return.
443
- * @opt_param string dimension Dimensions to base the report on.
444
- * @return Google_AdsenseReportsGenerateResponse
445
- */
446
- public function generate($accountId, $startDate, $endDate, $optParams = array()) {
447
- $params = array('accountId' => $accountId, 'startDate' => $startDate, 'endDate' => $endDate);
448
- $params = array_merge($params, $optParams);
449
- $data = $this->__call('generate', array($params));
450
- if ($this->useObjects()) {
451
- return new Google_AdsenseReportsGenerateResponse($data);
452
- } else {
453
- return $data;
454
- }
455
- }
456
- }
457
- /**
458
- * The "customchannels" collection of methods.
459
- * Typical usage is:
460
- * <code>
461
- * $adsenseService = new Google_AdsenseService(...);
462
- * $customchannels = $adsenseService->customchannels;
463
- * </code>
464
- */
465
- class Google_AccountsCustomchannelsServiceResource extends Google_ServiceResource {
466
-
467
-
468
- /**
469
- * List all custom channels in the specified ad client for the specified account.
470
- * (customchannels.list)
471
- *
472
- * @param string $accountId Account to which the ad client belongs.
473
- * @param string $adClientId Ad client for which to list custom channels.
474
- * @param array $optParams Optional parameters.
475
- *
476
- * @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
477
- * @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
478
- * @return Google_CustomChannels
479
- */
480
- public function listAccountsCustomchannels($accountId, $adClientId, $optParams = array()) {
481
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId);
482
- $params = array_merge($params, $optParams);
483
- $data = $this->__call('list', array($params));
484
- if ($this->useObjects()) {
485
- return new Google_CustomChannels($data);
486
- } else {
487
- return $data;
488
- }
489
- }
490
- /**
491
- * Get the specified custom channel from the specified ad client for the specified account.
492
- * (customchannels.get)
493
- *
494
- * @param string $accountId Account to which the ad client belongs.
495
- * @param string $adClientId Ad client which contains the custom channel.
496
- * @param string $customChannelId Custom channel to retrieve.
497
- * @param array $optParams Optional parameters.
498
- * @return Google_CustomChannel
499
- */
500
- public function get($accountId, $adClientId, $customChannelId, $optParams = array()) {
501
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'customChannelId' => $customChannelId);
502
- $params = array_merge($params, $optParams);
503
- $data = $this->__call('get', array($params));
504
- if ($this->useObjects()) {
505
- return new Google_CustomChannel($data);
506
- } else {
507
- return $data;
508
- }
509
- }
510
- }
511
-
512
- /**
513
- * The "adunits" collection of methods.
514
- * Typical usage is:
515
- * <code>
516
- * $adsenseService = new Google_AdsenseService(...);
517
- * $adunits = $adsenseService->adunits;
518
- * </code>
519
- */
520
- class Google_AccountsCustomchannelsAdunitsServiceResource extends Google_ServiceResource {
521
-
522
-
523
- /**
524
- * List all ad units in the specified custom channel. (adunits.list)
525
- *
526
- * @param string $accountId Account to which the ad client belongs.
527
- * @param string $adClientId Ad client which contains the custom channel.
528
- * @param string $customChannelId Custom channel for which to list ad units.
529
- * @param array $optParams Optional parameters.
530
- *
531
- * @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
532
- * @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
533
- * @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
534
- * @return Google_AdUnits
535
- */
536
- public function listAccountsCustomchannelsAdunits($accountId, $adClientId, $customChannelId, $optParams = array()) {
537
- $params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'customChannelId' => $customChannelId);
538
- $params = array_merge($params, $optParams);
539
- $data = $this->__call('list', array($params));
540
- if ($this->useObjects()) {
541
- return new Google_AdUnits($data);
542
- } else {
543
- return $data;
544
- }
545
- }
546
- }
547
-
548
- /**
549
- * The "customchannels" collection of methods.
550
- * Typical usage is:
551
- * <code>
552
- * $adsenseService = new Google_AdsenseService(...);
553
- * $customchannels = $adsenseService->customchannels;
554
- * </code>
555
- */
556
- class Google_CustomchannelsServiceResource extends Google_ServiceResource {
557
-
558
-
559
- /**
560
- * List all custom channels in the specified ad client for this AdSense account.
561
- * (customchannels.list)
562
- *
563
- * @param string $adClientId Ad client for which to list custom channels.
564
- * @param array $optParams Optional parameters.
565
- *
566
- * @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
567
- * @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
568
- * @return Google_CustomChannels
569
- */
570
- public function listCustomchannels($adClientId, $optParams = array()) {
571
- $params = array('adClientId' => $adClientId);
572
- $params = array_merge($params, $optParams);
573
- $data = $this->__call('list', array($params));
574
- if ($this->useObjects()) {
575
- return new Google_CustomChannels($data);
576
- } else {
577
- return $data;
578
- }
579
- }
580
- /**
581
- * Get the specified custom channel from the specified ad client. (customchannels.get)
582
- *
583
- * @param string $adClientId Ad client which contains the custom channel.
584
- * @param string $customChannelId Custom channel to retrieve.
585
- * @param array $optParams Optional parameters.
586
- * @return Google_CustomChannel
587
- */
588
- public function get($adClientId, $customChannelId, $optParams = array()) {
589
- $params = array('adClientId' => $adClientId, 'customChannelId' => $customChannelId);
590
- $params = array_merge($params, $optParams);
591
- $data = $this->__call('get', array($params));
592
- if ($this->useObjects()) {
593
- return new Google_CustomChannel($data);
594
- } else {
595
- return $data;
596
- }
597
- }
598
- }
599
-
600
- /**
601
- * The "adunits" collection of methods.
602
- * Typical usage is:
603
- * <code>
604
- * $adsenseService = new Google_AdsenseService(...);
605
- * $adunits = $adsenseService->adunits;
606
- * </code>
607
- */
608
- class Google_CustomchannelsAdunitsServiceResource extends Google_ServiceResource {
609
-
610
-
611
- /**
612
- * List all ad units in the specified custom channel. (adunits.list)
613
- *
614
- * @param string $adClientId Ad client which contains the custom channel.
615
- * @param string $customChannelId Custom channel for which to list ad units.
616
- * @param array $optParams Optional parameters.
617
- *
618
- * @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
619
- * @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
620
- * @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
621
- * @return Google_AdUnits
622
- */
623
- public function listCustomchannelsAdunits($adClientId, $customChannelId, $optParams = array()) {
624
- $params = array('adClientId' => $adClientId, 'customChannelId' => $customChannelId);
625
- $params = array_merge($params, $optParams);
626
- $data = $this->__call('list', array($params));
627
- if ($this->useObjects()) {
628
- return new Google_AdUnits($data);
629
- } else {
630
- return $data;
631
- }
632
- }
633
- }
634
-
635
- /**
636
- * Service definition for Google_Adsense (v1.1).
637
- *
638
- * <p>
639
- * Gives AdSense publishers access to their inventory and the ability to generate reports
640
- * </p>
641
- *
642
- * <p>
643
- * For more information about this service, see the
644
- * <a href="https://code.google.com/apis/adsense/management/" target="_blank">API Documentation</a>
645
- * </p>
646
- *
647
- * @author Google, Inc.
648
- */
649
- class Google_AdsenseService extends Google_Service {
650
- public $urlchannels;
651
- public $adunits;
652
- public $adunits_customchannels;
653
- public $adclients;
654
- public $reports;
655
- public $accounts;
656
- public $accounts_urlchannels;
657
- public $accounts_adunits;
658
- public $accounts_adunits_customchannels;
659
- public $accounts_adclients;
660
- public $accounts_reports;
661
- public $accounts_customchannels;
662
- public $accounts_customchannels_adunits;
663
- public $customchannels;
664
- public $customchannels_adunits;
665
- /**
666
- * Constructs the internal representation of the Adsense service.
667
- *
668
- * @param Google_Client $client
669
- */
670
- public function __construct(Google_Client $client) {
671
- $this->servicePath = 'adsense/v1.1/';
672
- $this->version = 'v1.1';
673
- $this->serviceName = 'adsense';
674
-
675
- $client->addService($this->serviceName, $this->version);
676
- $this->urlchannels = new Google_UrlchannelsServiceResource($this, $this->serviceName, 'urlchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "id": "adsense.urlchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/urlchannels", "response": {"$ref": "UrlChannels"}}}}', true));
677
- $this->adunits = new Google_AdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "id": "adsense.adunits.list", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits", "response": {"$ref": "AdUnits"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.adunits.get", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits/{adUnitId}", "response": {"$ref": "AdUnit"}}}}', true));
678
- $this->adunits_customchannels = new Google_AdunitsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "adUnitId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.adunits.customchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits/{adUnitId}/customchannels", "response": {"$ref": "CustomChannels"}}}}', true));
679
- $this->adclients = new Google_AdclientsServiceResource($this, $this->serviceName, 'adclients', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "response": {"$ref": "AdClients"}, "httpMethod": "GET", "path": "adclients", "id": "adsense.adclients.list"}}}', true));
680
- $this->reports = new Google_ReportsServiceResource($this, $this->serviceName, 'reports', json_decode('{"methods": {"generate": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"sort": {"repeated": true, "type": "string", "location": "query"}, "startDate": {"required": true, "type": "string", "location": "query"}, "endDate": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "metric": {"repeated": true, "type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "50000", "format": "int32"}, "filter": {"repeated": true, "type": "string", "location": "query"}, "currency": {"type": "string", "location": "query"}, "startIndex": {"location": "query", "minimum": "0", "type": "integer", "maximum": "5000", "format": "int32"}, "dimension": {"repeated": true, "type": "string", "location": "query"}, "accountId": {"repeated": true, "type": "string", "location": "query"}}, "id": "adsense.reports.generate", "httpMethod": "GET", "supportsMediaDownload": true, "path": "reports", "response": {"$ref": "AdsenseReportsGenerateResponse"}}}}', true));
681
- $this->accounts = new Google_AccountsServiceResource($this, $this->serviceName, 'accounts', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "response": {"$ref": "Accounts"}, "httpMethod": "GET", "path": "accounts", "id": "adsense.accounts.list"}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"tree": {"type": "boolean", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.get", "httpMethod": "GET", "path": "accounts/{accountId}", "response": {"$ref": "Account"}}}}', true));
682
- $this->accounts_urlchannels = new Google_AccountsUrlchannelsServiceResource($this, $this->serviceName, 'urlchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.urlchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/urlchannels", "response": {"$ref": "UrlChannels"}}}}', true));
683
- $this->accounts_adunits = new Google_AccountsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits", "response": {"$ref": "AdUnits"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.get", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}", "response": {"$ref": "AdUnit"}}}}', true));
684
- $this->accounts_adunits_customchannels = new Google_AccountsAdunitsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "adUnitId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.customchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/customchannels", "response": {"$ref": "CustomChannels"}}}}', true));
685
- $this->accounts_adclients = new Google_AccountsAdclientsServiceResource($this, $this->serviceName, 'adclients', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adclients.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients", "response": {"$ref": "AdClients"}}}}', true));
686
- $this->accounts_reports = new Google_AccountsReportsServiceResource($this, $this->serviceName, 'reports', json_decode('{"methods": {"generate": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"sort": {"repeated": true, "type": "string", "location": "query"}, "startDate": {"required": true, "type": "string", "location": "query"}, "endDate": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "metric": {"repeated": true, "type": "string", "location": "query"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "50000", "format": "int32"}, "filter": {"repeated": true, "type": "string", "location": "query"}, "currency": {"type": "string", "location": "query"}, "startIndex": {"location": "query", "minimum": "0", "type": "integer", "maximum": "5000", "format": "int32"}, "dimension": {"repeated": true, "type": "string", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.reports.generate", "httpMethod": "GET", "supportsMediaDownload": true, "path": "accounts/{accountId}/reports", "response": {"$ref": "AdsenseReportsGenerateResponse"}}}}', true));
687
- $this->accounts_customchannels = new Google_AccountsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels", "response": {"$ref": "CustomChannels"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.get", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}", "response": {"$ref": "CustomChannel"}}}}', true));
688
- $this->accounts_customchannels_adunits = new Google_AccountsCustomchannelsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}, "pageToken": {"type": "string", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.adunits.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}/adunits", "response": {"$ref": "AdUnits"}}}}', true));
689
- $this->customchannels = new Google_CustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "id": "adsense.customchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels", "response": {"$ref": "CustomChannels"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.customchannels.get", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels/{customChannelId}", "response": {"$ref": "CustomChannel"}}}}', true));
690
- $this->customchannels_adunits = new Google_CustomchannelsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"location": "query", "minimum": "0", "type": "integer", "maximum": "10000", "format": "int32"}}, "id": "adsense.customchannels.adunits.list", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels/{customChannelId}/adunits", "response": {"$ref": "AdUnits"}}}}', true));
691
-
692
- }
693
- }
694
-
695
- class Google_Account extends Google_Model {
696
- public $kind;
697
- public $id;
698
- protected $__subAccountsType = 'Google_Account';
699
- protected $__subAccountsDataType = 'array';
700
- public $subAccounts;
701
- public $name;
702
- public function setKind($kind) {
703
- $this->kind = $kind;
704
- }
705
- public function getKind() {
706
- return $this->kind;
707
- }
708
- public function setId($id) {
709
- $this->id = $id;
710
- }
711
- public function getId() {
712
- return $this->id;
713
- }
714
- public function setSubAccounts(/* array(Google_Account) */ $subAccounts) {
715
- $this->assertIsArray($subAccounts, 'Google_Account', __METHOD__);
716
- $this->subAccounts = $subAccounts;
717
- }
718
- public function getSubAccounts() {
719
- return $this->subAccounts;
720
- }
721
- public function setName($name) {
722
- $this->name = $name;
723
- }
724
- public function getName() {
725
- return $this->name;
726
- }
727
- }
728
-
729
- class Google_Accounts extends Google_Model {
730
- public $nextPageToken;
731
- protected $__itemsType = 'Google_Account';
732
- protected $__itemsDataType = 'array';
733
- public $items;
734
- public $kind;
735
- public $etag;
736
- public function setNextPageToken($nextPageToken) {
737
- $this->nextPageToken = $nextPageToken;
738
- }
739
- public function getNextPageToken() {
740
- return $this->nextPageToken;
741
- }
742
- public function setItems(/* array(Google_Account) */ $items) {
743
- $this->assertIsArray($items, 'Google_Account', __METHOD__);
744
- $this->items = $items;
745
- }
746
- public function getItems() {
747
- return $this->items;
748
- }
749
- public function setKind($kind) {
750
- $this->kind = $kind;
751
- }
752
- public function getKind() {
753
- return $this->kind;
754
- }
755
- public function setEtag($etag) {
756
- $this->etag = $etag;
757
- }
758
- public function getEtag() {
759
- return $this->etag;
760
- }
761
- }
762
-
763
- class Google_AdClient extends Google_Model {
764
- public $productCode;
765
- public $kind;
766
- public $id;
767
- public $supportsReporting;
768
- public function setProductCode($productCode) {
769
- $this->productCode = $productCode;
770
- }
771
- public function getProductCode() {
772
- return $this->productCode;
773
- }
774
- public function setKind($kind) {
775
- $this->kind = $kind;
776
- }
777
- public function getKind() {
778
- return $this->kind;
779
- }
780
- public function setId($id) {
781
- $this->id = $id;
782
- }
783
- public function getId() {
784
- return $this->id;
785
- }
786
- public function setSupportsReporting($supportsReporting) {
787
- $this->supportsReporting = $supportsReporting;
788
- }
789
- public function getSupportsReporting() {
790
- return $this->supportsReporting;
791
- }
792
- }
793
-
794
- class Google_AdClients extends Google_Model {
795
- public $nextPageToken;
796
- protected $__itemsType = 'Google_AdClient';
797
- protected $__itemsDataType = 'array';
798
- public $items;
799
- public $kind;
800
- public $etag;
801
- public function setNextPageToken($nextPageToken) {
802
- $this->nextPageToken = $nextPageToken;
803
- }
804
- public function getNextPageToken() {
805
- return $this->nextPageToken;
806
- }
807
- public function setItems(/* array(Google_AdClient) */ $items) {
808
- $this->assertIsArray($items, 'Google_AdClient', __METHOD__);
809
- $this->items = $items;
810
- }
811
- public function getItems() {
812
- return $this->items;
813
- }
814
- public function setKind($kind) {
815
- $this->kind = $kind;
816
- }
817
- public function getKind() {
818
- return $this->kind;
819
- }
820
- public function setEtag($etag) {
821
- $this->etag = $etag;
822
- }
823
- public function getEtag() {
824
- return $this->etag;
825
- }
826
- }
827
-
828
- class Google_AdUnit extends Google_Model {
829
- public $status;
830
- public $kind;
831
- public $code;
832
- public $id;
833
- public $name;
834
- public function setStatus($status) {
835
- $this->status = $status;
836
- }
837
- public function getStatus() {
838
- return $this->status;
839
- }
840
- public function setKind($kind) {
841
- $this->kind = $kind;
842
- }
843
- public function getKind() {
844
- return $this->kind;
845
- }
846
- public function setCode($code) {
847
- $this->code = $code;
848
- }
849
- public function getCode() {
850
- return $this->code;
851
- }
852
- public function setId($id) {
853
- $this->id = $id;
854
- }
855
- public function getId() {
856
- return $this->id;
857
- }
858
- public function setName($name) {
859
- $this->name = $name;
860
- }
861
- public function getName() {
862
- return $this->name;
863
- }
864
- }
865
-
866
- class Google_AdUnits extends Google_Model {
867
- public $nextPageToken;
868
- protected $__itemsType = 'Google_AdUnit';
869
- protected $__itemsDataType = 'array';
870
- public $items;
871
- public $kind;
872
- public $etag;
873
- public function setNextPageToken($nextPageToken) {
874
- $this->nextPageToken = $nextPageToken;
875
- }
876
- public function getNextPageToken() {
877
- return $this->nextPageToken;
878
- }
879
- public function setItems(/* array(Google_AdUnit) */ $items) {
880
- $this->assertIsArray($items, 'Google_AdUnit', __METHOD__);
881
- $this->items = $items;
882
- }
883
- public function getItems() {
884
- return $this->items;
885
- }
886
- public function setKind($kind) {
887
- $this->kind = $kind;
888
- }
889
- public function getKind() {
890
- return $this->kind;
891
- }
892
- public function setEtag($etag) {
893
- $this->etag = $etag;
894
- }
895
- public function getEtag() {
896
- return $this->etag;
897
- }
898
- }
899
-
900
- class Google_AdsenseReportsGenerateResponse extends Google_Model {
901
- public $kind;
902
- public $rows;
903
- public $warnings;
904
- public $totals;
905
- protected $__headersType = 'Google_AdsenseReportsGenerateResponseHeaders';
906
- protected $__headersDataType = 'array';
907
- public $headers;
908
- public $totalMatchedRows;
909
- public $averages;
910
- public function setKind($kind) {
911
- $this->kind = $kind;
912
- }
913
- public function getKind() {
914
- return $this->kind;
915
- }
916
- public function setRows(/* array(Google_string) */ $rows) {
917
- $this->assertIsArray($rows, 'Google_string', __METHOD__);
918
- $this->rows = $rows;
919
- }
920
- public function getRows() {
921
- return $this->rows;
922
- }
923
- public function setWarnings(/* array(Google_string) */ $warnings) {
924
- $this->assertIsArray($warnings, 'Google_string', __METHOD__);
925
- $this->warnings = $warnings;
926
- }
927
- public function getWarnings() {
928
- return $this->warnings;
929
- }
930
- public function setTotals(/* array(Google_string) */ $totals) {
931
- $this->assertIsArray($totals, 'Google_string', __METHOD__);
932
- $this->totals = $totals;
933
- }
934
- public function getTotals() {
935
- return $this->totals;
936
- }
937
- public function setHeaders(/* array(Google_AdsenseReportsGenerateResponseHeaders) */ $headers) {
938
- $this->assertIsArray($headers, 'Google_AdsenseReportsGenerateResponseHeaders', __METHOD__);
939
- $this->headers = $headers;
940
- }
941
- public function getHeaders() {
942
- return $this->headers;
943
- }
944
- public function setTotalMatchedRows($totalMatchedRows) {
945
- $this->totalMatchedRows = $totalMatchedRows;
946
- }
947
- public function getTotalMatchedRows() {
948
- return $this->totalMatchedRows;
949
- }
950
- public function setAverages(/* array(Google_string) */ $averages) {
951
- $this->assertIsArray($averages, 'Google_string', __METHOD__);
952
- $this->averages = $averages;
953
- }
954
- public function getAverages() {
955
- return $this->averages;
956
- }
957
- }
958
-
959
- class Google_AdsenseReportsGenerateResponseHeaders extends Google_Model {
960
- public $currency;
961
- public $type;
962
- public $name;
963
- public function setCurrency($currency) {
964
- $this->currency = $currency;
965
- }
966
- public function getCurrency() {
967
- return $this->currency;
968
- }
969
- public function setType($type) {
970
- $this->type = $type;
971
- }
972
- public function getType() {
973
- return $this->type;
974
- }
975
- public function setName($name) {
976
- $this->name = $name;
977
- }
978
- public function getName() {
979
- return $this->name;
980
- }
981
- }
982
-
983
- class Google_CustomChannel extends Google_Model {
984
- public $kind;
985
- public $code;
986
- protected $__targetingInfoType = 'Google_CustomChannelTargetingInfo';
987
- protected $__targetingInfoDataType = '';
988
- public $targetingInfo;
989
- public $id;
990
- public $name;
991
- public function setKind($kind) {
992
- $this->kind = $kind;
993
- }
994
- public function getKind() {
995
- return $this->kind;
996
- }
997
- public function setCode($code) {
998
- $this->code = $code;
999
- }
1000
- public function getCode() {
1001
- return $this->code;
1002
- }
1003
- public function setTargetingInfo(Google_CustomChannelTargetingInfo $targetingInfo) {
1004
- $this->targetingInfo = $targetingInfo;
1005
- }
1006
- public function getTargetingInfo() {
1007
- return $this->targetingInfo;
1008
- }
1009
- public function setId($id) {
1010
- $this->id = $id;
1011
- }
1012
- public function getId() {
1013
- return $this->id;
1014
- }
1015
- public function setName($name) {
1016
- $this->name = $name;
1017
- }
1018
- public function getName() {
1019
- return $this->name;
1020
- }
1021
- }
1022
-
1023
- class Google_CustomChannelTargetingInfo extends Google_Model {
1024
- public $location;
1025
- public $adsAppearOn;
1026
- public $siteLanguage;
1027
- public $description;
1028
- public function setLocation($location) {
1029
- $this->location = $location;
1030
- }
1031
- public function getLocation() {
1032
- return $this->location;
1033
- }
1034
- public function setAdsAppearOn($adsAppearOn) {
1035
- $this->adsAppearOn = $adsAppearOn;
1036
- }
1037
- public function getAdsAppearOn() {
1038
- return $this->adsAppearOn;
1039
- }
1040
- public function setSiteLanguage($siteLanguage) {
1041
- $this->siteLanguage = $siteLanguage;
1042
- }
1043
- public function getSiteLanguage() {
1044
- return $this->siteLanguage;
1045
- }
1046
- public function setDescription($description) {
1047
- $this->description = $description;
1048
- }
1049
- public function getDescription() {
1050
- return $this->description;
1051
- }
1052
- }
1053
-
1054
- class Google_CustomChannels extends Google_Model {
1055
- public $nextPageToken;
1056
- protected $__itemsType = 'Google_CustomChannel';
1057
- protected $__itemsDataType = 'array';
1058
- public $items;
1059
- public $kind;
1060
- public $etag;
1061
- public function setNextPageToken($nextPageToken) {
1062
- $this->nextPageToken = $nextPageToken;
1063
- }
1064
- public function getNextPageToken() {
1065
- return $this->nextPageToken;
1066
- }
1067
- public function setItems(/* array(Google_CustomChannel) */ $items) {
1068
- $this->assertIsArray($items, 'Google_CustomChannel', __METHOD__);
1069
- $this->items = $items;
1070
- }
1071
- public function getItems() {
1072
- return $this->items;
1073
- }
1074
- public function setKind($kind) {
1075
- $this->kind = $kind;
1076
- }
1077
- public function getKind() {
1078
- return $this->kind;
1079
- }
1080
- public function setEtag($etag) {
1081
- $this->etag = $etag;
1082
- }
1083
- public function getEtag() {
1084
- return $this->etag;
1085
- }
1086
- }
1087
-
1088
- class Google_UrlChannel extends Google_Model {
1089
- public $kind;
1090
- public $id;
1091
- public $urlPattern;
1092
- public function setKind($kind) {
1093
- $this->kind = $kind;
1094
- }
1095
- public function getKind() {
1096
- return $this->kind;
1097
- }
1098
- public function setId($id) {
1099
- $this->id = $id;
1100
- }
1101
- public function getId() {
1102
- return $this->id;
1103
- }
1104
- public function setUrlPattern($urlPattern) {
1105
- $this->urlPattern = $urlPattern;
1106
- }
1107
- public function getUrlPattern() {
1108
- return $this->urlPattern;
1109
- }
1110
- }
1111
-
1112
- class Google_UrlChannels extends Google_Model {
1113
- public $nextPageToken;
1114
- protected $__itemsType = 'Google_UrlChannel';
1115
- protected $__itemsDataType = 'array';
1116
- public $items;
1117
- public $kind;
1118
- public $etag;
1119
- public function setNextPageToken($nextPageToken) {
1120
- $this->nextPageToken = $nextPageToken;
1121
- }
1122
- public function getNextPageToken() {
1123
- return $this->nextPageToken;
1124
- }
1125
- public function setItems(/* array(Google_UrlChannel) */ $items) {
1126
- $this->assertIsArray($items, 'Google_UrlChannel', __METHOD__);
1127
- $this->items = $items;
1128
- }
1129
- public function getItems() {
1130
- return $this->items;
1131
- }
1132
- public function setKind($kind) {
1133
- $this->kind = $kind;
1134
- }
1135
- public function getKind() {
1136
- return $this->kind;
1137
- }
1138
- public function setEtag($etag) {
1139
- $this->etag = $etag;
1140
- }
1141
- public function getEtag() {
1142
- return $this->etag;
1143
- }
1144
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/contrib/Google_AnalyticsService.php DELETED
@@ -1,1887 +0,0 @@
1
- <?php
2
- /*
3
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
- * use this file except in compliance with the License. You may obtain a copy of
5
- * the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
- * License for the specific language governing permissions and limitations under
13
- * the License.
14
- */
15
-
16
-
17
- /**
18
- * The "management" collection of methods.
19
- * Typical usage is:
20
- * <code>
21
- * $analyticsService = new Google_AnalyticsService(...);
22
- * $management = $analyticsService->management;
23
- * </code>
24
- */
25
- class Google_ManagementServiceResource extends Google_ServiceResource {
26
-
27
-
28
- }
29
-
30
- /**
31
- * The "webproperties" collection of methods.
32
- * Typical usage is:
33
- * <code>
34
- * $analyticsService = new Google_AnalyticsService(...);
35
- * $webproperties = $analyticsService->webproperties;
36
- * </code>
37
- */
38
- class Google_ManagementWebpropertiesServiceResource extends Google_ServiceResource {
39
-
40
-
41
- /**
42
- * Lists web properties to which the user has access. (webproperties.list)
43
- *
44
- * @param string $accountId Account ID to retrieve web properties for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.
45
- * @param array $optParams Optional parameters.
46
- *
47
- * @opt_param int max-results The maximum number of web properties to include in this response.
48
- * @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
49
- * @return Google_Webproperties
50
- */
51
- public function listManagementWebproperties($accountId, $optParams = array()) {
52
- $params = array('accountId' => $accountId);
53
- $params = array_merge($params, $optParams);
54
- $data = $this->__call('list', array($params));
55
- if ($this->useObjects()) {
56
- return new Google_Webproperties($data);
57
- } else {
58
- return $data;
59
- }
60
- }
61
- }
62
- /**
63
- * The "segments" collection of methods.
64
- * Typical usage is:
65
- * <code>
66
- * $analyticsService = new Google_AnalyticsService(...);
67
- * $segments = $analyticsService->segments;
68
- * </code>
69
- */
70
- class Google_ManagementSegmentsServiceResource extends Google_ServiceResource {
71
-
72
-
73
- /**
74
- * Lists advanced segments to which the user has access. (segments.list)
75
- *
76
- * @param array $optParams Optional parameters.
77
- *
78
- * @opt_param int max-results The maximum number of advanced segments to include in this response.
79
- * @opt_param int start-index An index of the first advanced segment to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
80
- * @return Google_Segments
81
- */
82
- public function listManagementSegments($optParams = array()) {
83
- $params = array();
84
- $params = array_merge($params, $optParams);
85
- $data = $this->__call('list', array($params));
86
- if ($this->useObjects()) {
87
- return new Google_Segments($data);
88
- } else {
89
- return $data;
90
- }
91
- }
92
- }
93
- /**
94
- * The "accounts" collection of methods.
95
- * Typical usage is:
96
- * <code>
97
- * $analyticsService = new Google_AnalyticsService(...);
98
- * $accounts = $analyticsService->accounts;
99
- * </code>
100
- */
101
- class Google_ManagementAccountsServiceResource extends Google_ServiceResource {
102
-
103
-
104
- /**
105
- * Lists all accounts to which the user has access. (accounts.list)
106
- *
107
- * @param array $optParams Optional parameters.
108
- *
109
- * @opt_param int max-results The maximum number of accounts to include in this response.
110
- * @opt_param int start-index An index of the first account to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
111
- * @return Google_Accounts
112
- */
113
- public function listManagementAccounts($optParams = array()) {
114
- $params = array();
115
- $params = array_merge($params, $optParams);
116
- $data = $this->__call('list', array($params));
117
- if ($this->useObjects()) {
118
- return new Google_Accounts($data);
119
- } else {
120
- return $data;
121
- }
122
- }
123
- }
124
- /**
125
- * The "goals" collection of methods.
126
- * Typical usage is:
127
- * <code>
128
- * $analyticsService = new Google_AnalyticsService(...);
129
- * $goals = $analyticsService->goals;
130
- * </code>
131
- */
132
- class Google_ManagementGoalsServiceResource extends Google_ServiceResource {
133
-
134
-
135
- /**
136
- * Lists goals to which the user has access. (goals.list)
137
- *
138
- * @param string $accountId Account ID to retrieve goals for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.
139
- * @param string $webPropertyId Web property ID to retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to.
140
- * @param string $profileId Profile ID to retrieve goals for. Can either be a specific profile ID or '~all', which refers to all the profiles that user has access to.
141
- * @param array $optParams Optional parameters.
142
- *
143
- * @opt_param int max-results The maximum number of goals to include in this response.
144
- * @opt_param int start-index An index of the first goal to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
145
- * @return Google_Goals
146
- */
147
- public function listManagementGoals($accountId, $webPropertyId, $profileId, $optParams = array()) {
148
- $params = array('accountId' => $accountId, 'webPropertyId' => $webPropertyId, 'profileId' => $profileId);
149
- $params = array_merge($params, $optParams);
150
- $data = $this->__call('list', array($params));
151
- if ($this->useObjects()) {
152
- return new Google_Goals($data);
153
- } else {
154
- return $data;
155
- }
156
- }
157
- }
158
- /**
159
- * The "profiles" collection of methods.
160
- * Typical usage is:
161
- * <code>
162
- * $analyticsService = new Google_AnalyticsService(...);
163
- * $profiles = $analyticsService->profiles;
164
- * </code>
165
- */
166
- class Google_ManagementProfilesServiceResource extends Google_ServiceResource {
167
-
168
-
169
- /**
170
- * Lists profiles to which the user has access. (profiles.list)
171
- *
172
- * @param string $accountId Account ID for the profiles to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.
173
- * @param string $webPropertyId Web property ID for the profiles to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.
174
- * @param array $optParams Optional parameters.
175
- *
176
- * @opt_param int max-results The maximum number of profiles to include in this response.
177
- * @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
178
- * @return Google_Profiles
179
- */
180
- public function listManagementProfiles($accountId, $webPropertyId, $optParams = array()) {
181
- $params = array('accountId' => $accountId, 'webPropertyId' => $webPropertyId);
182
- $params = array_merge($params, $optParams);
183
- $data = $this->__call('list', array($params));
184
- if ($this->useObjects()) {
185
- return new Google_Profiles($data);
186
- } else {
187
- return $data;
188
- }
189
- }
190
- }
191
-
192
- /**
193
- * The "data" collection of methods.
194
- * Typical usage is:
195
- * <code>
196
- * $analyticsService = new Google_AnalyticsService(...);
197
- * $data = $analyticsService->data;
198
- * </code>
199
- */
200
- class Google_DataServiceResource extends Google_ServiceResource {
201
-
202
-
203
- }
204
-
205
- /**
206
- * The "mcf" collection of methods.
207
- * Typical usage is:
208
- * <code>
209
- * $analyticsService = new Google_AnalyticsService(...);
210
- * $mcf = $analyticsService->mcf;
211
- * </code>
212
- */
213
- class Google_DataMcfServiceResource extends Google_ServiceResource {
214
-
215
-
216
- /**
217
- * Returns Analytics Multi-Channel Funnels data for a profile. (mcf.get)
218
- *
219
- * @param string $ids Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID.
220
- * @param string $start_date Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD.
221
- * @param string $end_date End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD.
222
- * @param string $metrics A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified.
223
- * @param array $optParams Optional parameters.
224
- *
225
- * @opt_param int max-results The maximum number of entries to include in this feed.
226
- * @opt_param string sort A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data.
227
- * @opt_param string dimensions A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'.
228
- * @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
229
- * @opt_param string filters A comma-separated list of dimension or metric filters to be applied to the Analytics data.
230
- * @return Google_McfData
231
- */
232
- public function get($ids, $start_date, $end_date, $metrics, $optParams = array()) {
233
- $params = array('ids' => $ids, 'start-date' => $start_date, 'end-date' => $end_date, 'metrics' => $metrics);
234
- $params = array_merge($params, $optParams);
235
- $data = $this->__call('get', array($params));
236
- if ($this->useObjects()) {
237
- return new Google_McfData($data);
238
- } else {
239
- return $data;
240
- }
241
- }
242
- }
243
- /**
244
- * The "ga" collection of methods.
245
- * Typical usage is:
246
- * <code>
247
- * $analyticsService = new Google_AnalyticsService(...);
248
- * $ga = $analyticsService->ga;
249
- * </code>
250
- */
251
- class Google_DataGaServiceResource extends Google_ServiceResource {
252
-
253
-
254
- /**
255
- * Returns Analytics data for a profile. (ga.get)
256
- *
257
- * @param string $ids Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID.
258
- * @param string $start_date Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD.
259
- * @param string $end_date End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD.
260
- * @param string $metrics A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'. At least one metric must be specified.
261
- * @param array $optParams Optional parameters.
262
- *
263
- * @opt_param int max-results The maximum number of entries to include in this feed.
264
- * @opt_param string sort A comma-separated list of dimensions or metrics that determine the sort order for Analytics data.
265
- * @opt_param string dimensions A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.
266
- * @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
267
- * @opt_param string segment An Analytics advanced segment to be applied to data.
268
- * @opt_param string filters A comma-separated list of dimension or metric filters to be applied to Analytics data.
269
- * @return Google_GaData
270
- */
271
- public function get($ids, $start_date, $end_date, $metrics, $optParams = array()) {
272
- $params = array('ids' => $ids, 'start-date' => $start_date, 'end-date' => $end_date, 'metrics' => $metrics);
273
- $params = array_merge($params, $optParams);
274
- $data = $this->__call('get', array($params));
275
- if ($this->useObjects()) {
276
- return new Google_GaData($data);
277
- } else {
278
- return $data;
279
- }
280
- }
281
- }
282
-
283
- /**
284
- * Service definition for Google_Analytics (v3).
285
- *
286
- * <p>
287
- * View and manage your Google Analytics data
288
- * </p>
289
- *
290
- * <p>
291
- * For more information about this service, see the
292
- * <a href="http://code.google.com/apis/analytics" target="_blank">API Documentation</a>
293
- * </p>
294
- *
295
- * @author Google, Inc.
296
- */
297
- class Google_AnalyticsService extends Google_Service {
298
- public $management_webproperties;
299
- public $management_segments;
300
- public $management_accounts;
301
- public $management_goals;
302
- public $management_profiles;
303
- public $data_mcf;
304
- public $data_ga;
305
- /**
306
- * Constructs the internal representation of the Analytics service.
307
- *
308
- * @param Google_Client $client
309
- */
310
- public function __construct(Google_Client $client) {
311
- $this->servicePath = 'analytics/v3/';
312
- $this->version = 'v3';
313
- $this->serviceName = 'analytics';
314
-
315
- $client->addService($this->serviceName, $this->version);
316
- $this->management_webproperties = new Google_ManagementWebpropertiesServiceResource($this, $this->serviceName, 'webproperties', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.webproperties.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties", "response": {"$ref": "Webproperties"}}}}', true));
317
- $this->management_segments = new Google_ManagementSegmentsServiceResource($this, $this->serviceName, 'segments', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}}, "response": {"$ref": "Segments"}, "httpMethod": "GET", "path": "management/segments", "id": "analytics.management.segments.list"}}}', true));
318
- $this->management_accounts = new Google_ManagementAccountsServiceResource($this, $this->serviceName, 'accounts', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}}, "response": {"$ref": "Accounts"}, "httpMethod": "GET", "path": "management/accounts", "id": "analytics.management.accounts.list"}}}', true));
319
- $this->management_goals = new Google_ManagementGoalsServiceResource($this, $this->serviceName, 'goals', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "profileId": {"required": true, "type": "string", "location": "path"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}, "webPropertyId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.goals.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals", "response": {"$ref": "Goals"}}}}', true));
320
- $this->management_profiles = new Google_ManagementProfilesServiceResource($this, $this->serviceName, 'profiles', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}, "webPropertyId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.profiles.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles", "response": {"$ref": "Profiles"}}}}', true));
321
- $this->data_mcf = new Google_DataMcfServiceResource($this, $this->serviceName, 'mcf', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "sort": {"type": "string", "location": "query"}, "dimensions": {"type": "string", "location": "query"}, "start-date": {"required": true, "type": "string", "location": "query"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}, "ids": {"required": true, "type": "string", "location": "query"}, "metrics": {"required": true, "type": "string", "location": "query"}, "filters": {"type": "string", "location": "query"}, "end-date": {"required": true, "type": "string", "location": "query"}}, "id": "analytics.data.mcf.get", "httpMethod": "GET", "path": "data/mcf", "response": {"$ref": "McfData"}}}}', true));
322
- $this->data_ga = new Google_DataGaServiceResource($this, $this->serviceName, 'ga', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"type": "integer", "location": "query", "format": "int32"}, "sort": {"type": "string", "location": "query"}, "dimensions": {"type": "string", "location": "query"}, "start-date": {"required": true, "type": "string", "location": "query"}, "start-index": {"minimum": "1", "type": "integer", "location": "query", "format": "int32"}, "segment": {"type": "string", "location": "query"}, "ids": {"required": true, "type": "string", "location": "query"}, "metrics": {"required": true, "type": "string", "location": "query"}, "filters": {"type": "string", "location": "query"}, "end-date": {"required": true, "type": "string", "location": "query"}}, "id": "analytics.data.ga.get", "httpMethod": "GET", "path": "data/ga", "response": {"$ref": "GaData"}}}}', true));
323
-
324
- }
325
- }
326
-
327
- class Google_Account extends Google_Model {
328
- public $kind;
329
- public $name;
330
- public $created;
331
- public $updated;
332
- protected $__childLinkType = 'Google_AccountChildLink';
333
- protected $__childLinkDataType = '';
334
- public $childLink;
335
- public $id;
336
- public $selfLink;
337
- public function setKind($kind) {
338
- $this->kind = $kind;
339
- }
340
- public function getKind() {
341
- return $this->kind;
342
- }
343
- public function setName($name) {
344
- $this->name = $name;
345
- }
346
- public function getName() {
347
- return $this->name;
348
- }
349
- public function setCreated($created) {
350
- $this->created = $created;
351
- }
352
- public function getCreated() {
353
- return $this->created;
354
- }
355
- public function setUpdated($updated) {
356
- $this->updated = $updated;
357
- }
358
- public function getUpdated() {
359
- return $this->updated;
360
- }
361
- public function setChildLink(Google_AccountChildLink $childLink) {
362
- $this->childLink = $childLink;
363
- }
364
- public function getChildLink() {
365
- return $this->childLink;
366
- }
367
- public function setId($id) {
368
- $this->id = $id;
369
- }
370
- public function getId() {
371
- return $this->id;
372
- }
373
- public function setSelfLink($selfLink) {
374
- $this->selfLink = $selfLink;
375
- }
376
- public function getSelfLink() {
377
- return $this->selfLink;
378
- }
379
- }
380
-
381
- class Google_AccountChildLink extends Google_Model {
382
- public $href;
383
- public $type;
384
- public function setHref($href) {
385
- $this->href = $href;
386
- }
387
- public function getHref() {
388
- return $this->href;
389
- }
390
- public function setType($type) {
391
- $this->type = $type;
392
- }
393
- public function getType() {
394
- return $this->type;
395
- }
396
- }
397
-
398
- class Google_Accounts extends Google_Model {
399
- public $username;
400
- public $kind;
401
- protected $__itemsType = 'Google_Account';
402
- protected $__itemsDataType = 'array';
403
- public $items;
404
- public $itemsPerPage;
405
- public $previousLink;
406
- public $startIndex;
407
- public $nextLink;
408
- public $totalResults;
409
- public function setUsername($username) {
410
- $this->username = $username;
411
- }
412
- public function getUsername() {
413
- return $this->username;
414
- }
415
- public function setKind($kind) {
416
- $this->kind = $kind;
417
- }
418
- public function getKind() {
419
- return $this->kind;
420
- }
421
- public function setItems(/* array(Google_Account) */ $items) {
422
- $this->assertIsArray($items, 'Google_Account', __METHOD__);
423
- $this->items = $items;
424
- }
425
- public function getItems() {
426
- return $this->items;
427
- }
428
- public function setItemsPerPage($itemsPerPage) {
429
- $this->itemsPerPage = $itemsPerPage;
430
- }
431
- public function getItemsPerPage() {
432
- return $this->itemsPerPage;
433
- }
434
- public function setPreviousLink($previousLink) {
435
- $this->previousLink = $previousLink;
436
- }
437
- public function getPreviousLink() {
438
- return $this->previousLink;
439
- }
440
- public function setStartIndex($startIndex) {
441
- $this->startIndex = $startIndex;
442
- }
443
- public function getStartIndex() {
444
- return $this->startIndex;
445
- }
446
- public function setNextLink($nextLink) {
447
- $this->nextLink = $nextLink;
448
- }
449
- public function getNextLink() {
450
- return $this->nextLink;
451
- }
452
- public function setTotalResults($totalResults) {
453
- $this->totalResults = $totalResults;
454
- }
455
- public function getTotalResults() {
456
- return $this->totalResults;
457
- }
458
- }
459
-
460
- class Google_GaData extends Google_Model {
461
- public $kind;
462
- public $rows;
463
- public $containsSampledData;
464
- public $totalResults;
465
- public $itemsPerPage;
466
- public $totalsForAllResults;
467
- public $nextLink;
468
- public $id;
469
- protected $__queryType = 'Google_GaDataQuery';
470
- protected $__queryDataType = '';
471
- public $query;
472
- public $previousLink;
473
- protected $__profileInfoType = 'Google_GaDataProfileInfo';
474
- protected $__profileInfoDataType = '';
475
- public $profileInfo;
476
- protected $__columnHeadersType = 'Google_GaDataColumnHeaders';
477
- protected $__columnHeadersDataType = 'array';
478
- public $columnHeaders;
479
- public $selfLink;
480
- public function setKind($kind) {
481
- $this->kind = $kind;
482
- }
483
- public function getKind() {
484
- return $this->kind;
485
- }
486
- public function setRows(/* array(Google_string) */ $rows) {
487
- $this->assertIsArray($rows, 'Google_string', __METHOD__);
488
- $this->rows = $rows;
489
- }
490
- public function getRows() {
491
- return $this->rows;
492
- }
493
- public function setContainsSampledData($containsSampledData) {
494
- $this->containsSampledData = $containsSampledData;
495
- }
496
- public function getContainsSampledData() {
497
- return $this->containsSampledData;
498
- }
499
- public function setTotalResults($totalResults) {
500
- $this->totalResults = $totalResults;
501
- }
502
- public function getTotalResults() {
503
- return $this->totalResults;
504
- }
505
- public function setItemsPerPage($itemsPerPage) {
506
- $this->itemsPerPage = $itemsPerPage;
507
- }
508
- public function getItemsPerPage() {
509
- return $this->itemsPerPage;
510
- }
511
- public function setTotalsForAllResults($totalsForAllResults) {
512
- $this->totalsForAllResults = $totalsForAllResults;
513
- }
514
- public function getTotalsForAllResults() {
515
- return $this->totalsForAllResults;
516
- }
517
- public function setNextLink($nextLink) {
518
- $this->nextLink = $nextLink;
519
- }
520
- public function getNextLink() {
521
- return $this->nextLink;
522
- }
523
- public function setId($id) {
524
- $this->id = $id;
525
- }
526
- public function getId() {
527
- return $this->id;
528
- }
529
- public function setQuery(Google_GaDataQuery $query) {
530
- $this->query = $query;
531
- }
532
- public function getQuery() {
533
- return $this->query;
534
- }
535
- public function setPreviousLink($previousLink) {
536
- $this->previousLink = $previousLink;
537
- }
538
- public function getPreviousLink() {
539
- return $this->previousLink;
540
- }
541
- public function setProfileInfo(Google_GaDataProfileInfo $profileInfo) {
542
- $this->profileInfo = $profileInfo;
543
- }
544
- public function getProfileInfo() {
545
- return $this->profileInfo;
546
- }
547
- public function setColumnHeaders(/* array(Google_GaDataColumnHeaders) */ $columnHeaders) {
548
- $this->assertIsArray($columnHeaders, 'Google_GaDataColumnHeaders', __METHOD__);
549
- $this->columnHeaders = $columnHeaders;
550
- }
551
- public function getColumnHeaders() {
552
- return $this->columnHeaders;
553
- }
554
- public function setSelfLink($selfLink) {
555
- $this->selfLink = $selfLink;
556
- }
557
- public function getSelfLink() {
558
- return $this->selfLink;
559
- }
560
- }
561
-
562
- class Google_GaDataColumnHeaders extends Google_Model {
563
- public $dataType;
564
- public $columnType;
565
- public $name;
566
- public function setDataType($dataType) {
567
- $this->dataType = $dataType;
568
- }
569
- public function getDataType() {
570
- return $this->dataType;
571
- }
572
- public function setColumnType($columnType) {
573
- $this->columnType = $columnType;
574
- }
575
- public function getColumnType() {
576
- return $this->columnType;
577
- }
578
- public function setName($name) {
579
- $this->name = $name;
580
- }
581
- public function getName() {
582
- return $this->name;
583
- }
584
- }
585
-
586
- class Google_GaDataProfileInfo extends Google_Model {
587
- public $webPropertyId;
588
- public $internalWebPropertyId;
589
- public $tableId;
590
- public $profileId;
591
- public $profileName;
592
- public $accountId;
593
- public function setWebPropertyId($webPropertyId) {
594
- $this->webPropertyId = $webPropertyId;
595
- }
596
- public function getWebPropertyId() {
597
- return $this->webPropertyId;
598
- }
599
- public function setInternalWebPropertyId($internalWebPropertyId) {
600
- $this->internalWebPropertyId = $internalWebPropertyId;
601
- }
602
- public function getInternalWebPropertyId() {
603
- return $this->internalWebPropertyId;
604
- }
605
- public function setTableId($tableId) {
606
- $this->tableId = $tableId;
607
- }
608
- public function getTableId() {
609
- return $this->tableId;
610
- }
611
- public function setProfileId($profileId) {
612
- $this->profileId = $profileId;
613
- }
614
- public function getProfileId() {
615
- return $this->profileId;
616
- }
617
- public function setProfileName($profileName) {
618
- $this->profileName = $profileName;
619
- }
620
- public function getProfileName() {
621
- return $this->profileName;
622
- }
623
- public function setAccountId($accountId) {
624
- $this->accountId = $accountId;
625
- }
626
- public function getAccountId() {
627
- return $this->accountId;
628
- }
629
- }
630
-
631
- class Google_GaDataQuery extends Google_Model {
632
- public $max_results;
633
- public $sort;
634
- public $dimensions;
635
- public $start_date;
636
- public $start_index;
637
- public $segment;
638
- public $ids;
639
- public $metrics;
640
- public $filters;
641
- public $end_date;
642
- public function setMax_results($max_results) {
643
- $this->max_results = $max_results;
644
- }
645
- public function getMax_results() {
646
- return $this->max_results;
647
- }
648
- public function setSort(/* array(Google_string) */ $sort) {
649
- $this->assertIsArray($sort, 'Google_string', __METHOD__);
650
- $this->sort = $sort;
651
- }
652
- public function getSort() {
653
- return $this->sort;
654
- }
655
- public function setDimensions($dimensions) {
656
- $this->dimensions = $dimensions;
657
- }
658
- public function getDimensions() {
659
- return $this->dimensions;
660
- }
661
- public function setStart_date($start_date) {
662
- $this->start_date = $start_date;
663
- }
664
- public function getStart_date() {
665
- return $this->start_date;
666
- }
667
- public function setStart_index($start_index) {
668
- $this->start_index = $start_index;
669
- }
670
- public function getStart_index() {
671
- return $this->start_index;
672
- }
673
- public function setSegment($segment) {
674
- $this->segment = $segment;
675
- }
676
- public function getSegment() {
677
- return $this->segment;
678
- }
679
- public function setIds($ids) {
680
- $this->ids = $ids;
681
- }
682
- public function getIds() {
683
- return $this->ids;
684
- }
685
- public function setMetrics(/* array(Google_string) */ $metrics) {
686
- $this->assertIsArray($metrics, 'Google_string', __METHOD__);
687
- $this->metrics = $metrics;
688
- }
689
- public function getMetrics() {
690
- return $this->metrics;
691
- }
692
- public function setFilters($filters) {
693
- $this->filters = $filters;
694
- }
695
- public function getFilters() {
696
- return $this->filters;
697
- }
698
- public function setEnd_date($end_date) {
699
- $this->end_date = $end_date;
700
- }
701
- public function getEnd_date() {
702
- return $this->end_date;
703
- }
704
- }
705
-
706
- class Google_Goal extends Google_Model {
707
- public $kind;
708
- protected $__visitTimeOnSiteDetailsType = 'Google_GoalVisitTimeOnSiteDetails';
709
- protected $__visitTimeOnSiteDetailsDataType = '';
710
- public $visitTimeOnSiteDetails;
711
- public $name;
712
- public $created;
713
- protected $__urlDestinationDetailsType = 'Google_GoalUrlDestinationDetails';
714
- protected $__urlDestinationDetailsDataType = '';
715
- public $urlDestinationDetails;
716
- public $updated;
717
- public $value;
718
- protected $__visitNumPagesDetailsType = 'Google_GoalVisitNumPagesDetails';
719
- protected $__visitNumPagesDetailsDataType = '';
720
- public $visitNumPagesDetails;
721
- public $internalWebPropertyId;
722
- protected $__eventDetailsType = 'Google_GoalEventDetails';
723
- protected $__eventDetailsDataType = '';
724
- public $eventDetails;
725
- public $webPropertyId;
726
- public $active;
727
- public $profileId;
728
- protected $__parentLinkType = 'Google_GoalParentLink';
729
- protected $__parentLinkDataType = '';
730
- public $parentLink;
731
- public $type;
732
- public $id;
733
- public $selfLink;
734
- public $accountId;
735
- public function setKind($kind) {
736
- $this->kind = $kind;
737
- }
738
- public function getKind() {
739
- return $this->kind;
740
- }
741
- public function setVisitTimeOnSiteDetails(Google_GoalVisitTimeOnSiteDetails $visitTimeOnSiteDetails) {
742
- $this->visitTimeOnSiteDetails = $visitTimeOnSiteDetails;
743
- }
744
- public function getVisitTimeOnSiteDetails() {
745
- return $this->visitTimeOnSiteDetails;
746
- }
747
- public function setName($name) {
748
- $this->name = $name;
749
- }
750
- public function getName() {
751
- return $this->name;
752
- }
753
- public function setCreated($created) {
754
- $this->created = $created;
755
- }
756
- public function getCreated() {
757
- return $this->created;
758
- }
759
- public function setUrlDestinationDetails(Google_GoalUrlDestinationDetails $urlDestinationDetails) {
760
- $this->urlDestinationDetails = $urlDestinationDetails;
761
- }
762
- public function getUrlDestinationDetails() {
763
- return $this->urlDestinationDetails;
764
- }
765
- public function setUpdated($updated) {
766
- $this->updated = $updated;
767
- }
768
- public function getUpdated() {
769
- return $this->updated;
770
- }
771
- public function setValue($value) {
772
- $this->value = $value;
773
- }
774
- public function getValue() {
775
- return $this->value;
776
- }
777
- public function setVisitNumPagesDetails(Google_GoalVisitNumPagesDetails $visitNumPagesDetails) {
778
- $this->visitNumPagesDetails = $visitNumPagesDetails;
779
- }
780
- public function getVisitNumPagesDetails() {
781
- return $this->visitNumPagesDetails;
782
- }
783
- public function setInternalWebPropertyId($internalWebPropertyId) {
784
- $this->internalWebPropertyId = $internalWebPropertyId;
785
- }
786
- public function getInternalWebPropertyId() {
787
- return $this->internalWebPropertyId;
788
- }
789
- public function setEventDetails(Google_GoalEventDetails $eventDetails) {
790
- $this->eventDetails = $eventDetails;
791
- }
792
- public function getEventDetails() {
793
- return $this->eventDetails;
794
- }
795
- public function setWebPropertyId($webPropertyId) {
796
- $this->webPropertyId = $webPropertyId;
797
- }
798
- public function getWebPropertyId() {
799
- return $this->webPropertyId;
800
- }
801
- public function setActive($active) {
802
- $this->active = $active;
803
- }
804
- public function getActive() {
805
- return $this->active;
806
- }
807
- public function setProfileId($profileId) {
808
- $this->profileId = $profileId;
809
- }
810
- public function getProfileId() {
811
- return $this->profileId;
812
- }
813
- public function setParentLink(Google_GoalParentLink $parentLink) {
814
- $this->parentLink = $parentLink;
815
- }
816
- public function getParentLink() {
817
- return $this->parentLink;
818
- }
819
- public function setType($type) {
820
- $this->type = $type;
821
- }
822
- public function getType() {
823
- return $this->type;
824
- }
825
- public function setId($id) {
826
- $this->id = $id;
827
- }
828
- public function getId() {
829
- return $this->id;
830
- }
831
- public function setSelfLink($selfLink) {
832
- $this->selfLink = $selfLink;
833
- }
834
- public function getSelfLink() {
835
- return $this->selfLink;
836
- }
837
- public function setAccountId($accountId) {
838
- $this->accountId = $accountId;
839
- }
840
- public function getAccountId() {
841
- return $this->accountId;
842
- }
843
- }
844
-
845
- class Google_GoalEventDetails extends Google_Model {
846
- protected $__eventConditionsType = 'Google_GoalEventDetailsEventConditions';
847
- protected $__eventConditionsDataType = 'array';
848
- public $eventConditions;
849
- public $useEventValue;
850
- public function setEventConditions(/* array(Google_GoalEventDetailsEventConditions) */ $eventConditions) {
851
- $this->assertIsArray($eventConditions, 'Google_GoalEventDetailsEventConditions', __METHOD__);
852
- $this->eventConditions = $eventConditions;
853
- }
854
- public function getEventConditions() {
855
- return $this->eventConditions;
856
- }
857
- public function setUseEventValue($useEventValue) {
858
- $this->useEventValue = $useEventValue;
859
- }
860
- public function getUseEventValue() {
861
- return $this->useEventValue;
862
- }
863
- }
864
-
865
- class Google_GoalEventDetailsEventConditions extends Google_Model {
866
- public $type;
867
- public $matchType;
868
- public $expression;
869
- public $comparisonType;
870
- public $comparisonValue;
871
- public function setType($type) {
872
- $this->type = $type;
873
- }
874
- public function getType() {
875
- return $this->type;
876
- }
877
- public function setMatchType($matchType) {
878
- $this->matchType = $matchType;
879
- }
880
- public function getMatchType() {
881
- return $this->matchType;
882
- }
883
- public function setExpression($expression) {
884
- $this->expression = $expression;
885
- }
886
- public function getExpression() {
887
- return $this->expression;
888
- }
889
- public function setComparisonType($comparisonType) {
890
- $this->comparisonType = $comparisonType;
891
- }
892
- public function getComparisonType() {
893
- return $this->comparisonType;
894
- }
895
- public function setComparisonValue($comparisonValue) {
896
- $this->comparisonValue = $comparisonValue;
897
- }
898
- public function getComparisonValue() {
899
- return $this->comparisonValue;
900
- }
901
- }
902
-
903
- class Google_GoalParentLink extends Google_Model {
904
- public $href;
905
- public $type;
906
- public function setHref($href) {
907
- $this->href = $href;
908
- }
909
- public function getHref() {
910
- return $this->href;
911
- }
912
- public function setType($type) {
913
- $this->type = $type;
914
- }
915
- public function getType() {
916
- return $this->type;
917
- }
918
- }
919
-
920
- class Google_GoalUrlDestinationDetails extends Google_Model {
921
- public $url;
922
- public $caseSensitive;
923
- public $matchType;
924
- protected $__stepsType = 'Google_GoalUrlDestinationDetailsSteps';
925
- protected $__stepsDataType = 'array';
926
- public $steps;
927
- public $firstStepRequired;
928
- public function setUrl($url) {
929
- $this->url = $url;
930
- }
931
- public function getUrl() {
932
- return $this->url;
933
- }
934
- public function setCaseSensitive($caseSensitive) {
935
- $this->caseSensitive = $caseSensitive;
936
- }
937
- public function getCaseSensitive() {
938
- return $this->caseSensitive;
939
- }
940
- public function setMatchType($matchType) {
941
- $this->matchType = $matchType;
942
- }
943
- public function getMatchType() {
944
- return $this->matchType;
945
- }
946
- public function setSteps(/* array(Google_GoalUrlDestinationDetailsSteps) */ $steps) {
947
- $this->assertIsArray($steps, 'Google_GoalUrlDestinationDetailsSteps', __METHOD__);
948
- $this->steps = $steps;
949
- }
950
- public function getSteps() {
951
- return $this->steps;
952
- }
953
- public function setFirstStepRequired($firstStepRequired) {
954
- $this->firstStepRequired = $firstStepRequired;
955
- }
956
- public function getFirstStepRequired() {
957
- return $this->firstStepRequired;
958
- }
959
- }
960
-
961
- class Google_GoalUrlDestinationDetailsSteps extends Google_Model {
962
- public $url;
963
- public $name;
964
- public $number;
965
- public function setUrl($url) {
966
- $this->url = $url;
967
- }
968
- public function getUrl() {
969
- return $this->url;
970
- }
971
- public function setName($name) {
972
- $this->name = $name;
973
- }
974
- public function getName() {
975
- return $this->name;
976
- }
977
- public function setNumber($number) {
978
- $this->number = $number;
979
- }
980
- public function getNumber() {
981
- return $this->number;
982
- }
983
- }
984
-
985
- class Google_GoalVisitNumPagesDetails extends Google_Model {
986
- public $comparisonType;
987
- public $comparisonValue;
988
- public function setComparisonType($comparisonType) {
989
- $this->comparisonType = $comparisonType;
990
- }
991
- public function getComparisonType() {
992
- return $this->comparisonType;
993
- }
994
- public function setComparisonValue($comparisonValue) {
995
- $this->comparisonValue = $comparisonValue;
996
- }
997
- public function getComparisonValue() {
998
- return $this->comparisonValue;
999
- }
1000
- }
1001
-
1002
- class Google_GoalVisitTimeOnSiteDetails extends Google_Model {
1003
- public $comparisonType;
1004
- public $comparisonValue;
1005
- public function setComparisonType($comparisonType) {
1006
- $this->comparisonType = $comparisonType;
1007
- }
1008
- public function getComparisonType() {
1009
- return $this->comparisonType;
1010
- }
1011
- public function setComparisonValue($comparisonValue) {
1012
- $this->comparisonValue = $comparisonValue;
1013
- }
1014
- public function getComparisonValue() {
1015
- return $this->comparisonValue;
1016
- }
1017
- }
1018
-
1019
- class Google_Goals extends Google_Model {
1020
- public $username;
1021
- public $kind;
1022
- protected $__itemsType = 'Google_Goal';
1023
- protected $__itemsDataType = 'array';
1024
- public $items;
1025
- public $itemsPerPage;
1026
- public $previousLink;
1027
- public $startIndex;
1028
- public $nextLink;
1029
- public $totalResults;
1030
- public function setUsername($username) {
1031
- $this->username = $username;
1032
- }
1033
- public function getUsername() {
1034
- return $this->username;
1035
- }
1036
- public function setKind($kind) {
1037
- $this->kind = $kind;
1038
- }
1039
- public function getKind() {
1040
- return $this->kind;
1041
- }
1042
- public function setItems(/* array(Google_Goal) */ $items) {
1043
- $this->assertIsArray($items, 'Google_Goal', __METHOD__);
1044
- $this->items = $items;
1045
- }
1046
- public function getItems() {
1047
- return $this->items;
1048
- }
1049
- public function setItemsPerPage($itemsPerPage) {
1050
- $this->itemsPerPage = $itemsPerPage;
1051
- }
1052
- public function getItemsPerPage() {
1053
- return $this->itemsPerPage;
1054
- }
1055
- public function setPreviousLink($previousLink) {
1056
- $this->previousLink = $previousLink;
1057
- }
1058
- public function getPreviousLink() {
1059
- return $this->previousLink;
1060
- }
1061
- public function setStartIndex($startIndex) {
1062
- $this->startIndex = $startIndex;
1063
- }
1064
- public function getStartIndex() {
1065
- return $this->startIndex;
1066
- }
1067
- public function setNextLink($nextLink) {
1068
- $this->nextLink = $nextLink;
1069
- }
1070
- public function getNextLink() {
1071
- return $this->nextLink;
1072
- }
1073
- public function setTotalResults($totalResults) {
1074
- $this->totalResults = $totalResults;
1075
- }
1076
- public function getTotalResults() {
1077
- return $this->totalResults;
1078
- }
1079
- }
1080
-
1081
- class Google_McfData extends Google_Model {
1082
- public $kind;
1083
- protected $__rowsType = 'Google_McfDataRows';
1084
- protected $__rowsDataType = 'array';
1085
- public $rows;
1086
- public $containsSampledData;
1087
- public $totalResults;
1088
- public $itemsPerPage;
1089
- public $totalsForAllResults;
1090
- public $nextLink;
1091
- public $id;
1092
- protected $__queryType = 'Google_McfDataQuery';
1093
- protected $__queryDataType = '';
1094
- public $query;
1095
- public $previousLink;
1096
- protected $__profileInfoType = 'Google_McfDataProfileInfo';
1097
- protected $__profileInfoDataType = '';
1098
- public $profileInfo;
1099
- protected $__columnHeadersType = 'Google_McfDataColumnHeaders';
1100
- protected $__columnHeadersDataType = 'array';
1101
- public $columnHeaders;
1102
- public $selfLink;
1103
- public function setKind($kind) {
1104
- $this->kind = $kind;
1105
- }
1106
- public function getKind() {
1107
- return $this->kind;
1108
- }
1109
- public function setRows(/* array(Google_McfDataRows) */ $rows) {
1110
- $this->assertIsArray($rows, 'Google_McfDataRows', __METHOD__);
1111
- $this->rows = $rows;
1112
- }
1113
- public function getRows() {
1114
- return $this->rows;
1115
- }
1116
- public function setContainsSampledData($containsSampledData) {
1117
- $this->containsSampledData = $containsSampledData;
1118
- }
1119
- public function getContainsSampledData() {
1120
- return $this->containsSampledData;
1121
- }
1122
- public function setTotalResults($totalResults) {
1123
- $this->totalResults = $totalResults;
1124
- }
1125
- public function getTotalResults() {
1126
- return $this->totalResults;
1127
- }
1128
- public function setItemsPerPage($itemsPerPage) {
1129
- $this->itemsPerPage = $itemsPerPage;
1130
- }
1131
- public function getItemsPerPage() {
1132
- return $this->itemsPerPage;
1133
- }
1134
- public function setTotalsForAllResults($totalsForAllResults) {
1135
- $this->totalsForAllResults = $totalsForAllResults;
1136
- }
1137
- public function getTotalsForAllResults() {
1138
- return $this->totalsForAllResults;
1139
- }
1140
- public function setNextLink($nextLink) {
1141
- $this->nextLink = $nextLink;
1142
- }
1143
- public function getNextLink() {
1144
- return $this->nextLink;
1145
- }
1146
- public function setId($id) {
1147
- $this->id = $id;
1148
- }
1149
- public function getId() {
1150
- return $this->id;
1151
- }
1152
- public function setQuery(Google_McfDataQuery $query) {
1153
- $this->query = $query;
1154
- }
1155
- public function getQuery() {
1156
- return $this->query;
1157
- }
1158
- public function setPreviousLink($previousLink) {
1159
- $this->previousLink = $previousLink;
1160
- }
1161
- public function getPreviousLink() {
1162
- return $this->previousLink;
1163
- }
1164
- public function setProfileInfo(Google_McfDataProfileInfo $profileInfo) {
1165
- $this->profileInfo = $profileInfo;
1166
- }
1167
- public function getProfileInfo() {
1168
- return $this->profileInfo;
1169
- }
1170
- public function setColumnHeaders(/* array(Google_McfDataColumnHeaders) */ $columnHeaders) {
1171
- $this->assertIsArray($columnHeaders, 'Google_McfDataColumnHeaders', __METHOD__);
1172
- $this->columnHeaders = $columnHeaders;
1173
- }
1174
- public function getColumnHeaders() {
1175
- return $this->columnHeaders;
1176
- }
1177
- public function setSelfLink($selfLink) {
1178
- $this->selfLink = $selfLink;
1179
- }
1180
- public function getSelfLink() {
1181
- return $this->selfLink;
1182
- }
1183
- }
1184
-
1185
- class Google_McfDataColumnHeaders extends Google_Model {
1186
- public $dataType;
1187
- public $columnType;
1188
- public $name;
1189
- public function setDataType($dataType) {
1190
- $this->dataType = $dataType;
1191
- }
1192
- public function getDataType() {
1193
- return $this->dataType;
1194
- }
1195
- public function setColumnType($columnType) {
1196
- $this->columnType = $columnType;
1197
- }
1198
- public function getColumnType() {
1199
- return $this->columnType;
1200
- }
1201
- public function setName($name) {
1202
- $this->name = $name;
1203
- }
1204
- public function getName() {
1205
- return $this->name;
1206
- }
1207
- }
1208
-
1209
- class Google_McfDataProfileInfo extends Google_Model {
1210
- public $webPropertyId;
1211
- public $internalWebPropertyId;
1212
- public $tableId;
1213
- public $profileId;
1214
- public $profileName;
1215
- public $accountId;
1216
- public function setWebPropertyId($webPropertyId) {
1217
- $this->webPropertyId = $webPropertyId;
1218
- }
1219
- public function getWebPropertyId() {
1220
- return $this->webPropertyId;
1221
- }
1222
- public function setInternalWebPropertyId($internalWebPropertyId) {
1223
- $this->internalWebPropertyId = $internalWebPropertyId;
1224
- }
1225
- public function getInternalWebPropertyId() {
1226
- return $this->internalWebPropertyId;
1227
- }
1228
- public function setTableId($tableId) {
1229
- $this->tableId = $tableId;
1230
- }
1231
- public function getTableId() {
1232
- return $this->tableId;
1233
- }
1234
- public function setProfileId($profileId) {
1235
- $this->profileId = $profileId;
1236
- }
1237
- public function getProfileId() {
1238
- return $this->profileId;
1239
- }
1240
- public function setProfileName($profileName) {
1241
- $this->profileName = $profileName;
1242
- }
1243
- public function getProfileName() {
1244
- return $this->profileName;
1245
- }
1246
- public function setAccountId($accountId) {
1247
- $this->accountId = $accountId;
1248
- }
1249
- public function getAccountId() {
1250
- return $this->accountId;
1251
- }
1252
- }
1253
-
1254
- class Google_McfDataQuery extends Google_Model {
1255
- public $max_results;
1256
- public $sort;
1257
- public $dimensions;
1258
- public $start_date;
1259
- public $start_index;
1260
- public $segment;
1261
- public $ids;
1262
- public $metrics;
1263
- public $filters;
1264
- public $end_date;
1265
- public function setMax_results($max_results) {
1266
- $this->max_results = $max_results;
1267
- }
1268
- public function getMax_results() {
1269
- return $this->max_results;
1270
- }
1271
- public function setSort(/* array(Google_string) */ $sort) {
1272
- $this->assertIsArray($sort, 'Google_string', __METHOD__);
1273
- $this->sort = $sort;
1274
- }
1275
- public function getSort() {
1276
- return $this->sort;
1277
- }
1278
- public function setDimensions($dimensions) {
1279
- $this->dimensions = $dimensions;
1280
- }
1281
- public function getDimensions() {
1282
- return $this->dimensions;
1283
- }
1284
- public function setStart_date($start_date) {
1285
- $this->start_date = $start_date;
1286
- }
1287
- public function getStart_date() {
1288
- return $this->start_date;
1289
- }
1290
- public function setStart_index($start_index) {
1291
- $this->start_index = $start_index;
1292
- }
1293
- public function getStart_index() {
1294
- return $this->start_index;
1295
- }
1296
- public function setSegment($segment) {
1297
- $this->segment = $segment;
1298
- }
1299
- public function getSegment() {
1300
- return $this->segment;
1301
- }
1302
- public function setIds($ids) {
1303
- $this->ids = $ids;
1304
- }
1305
- public function getIds() {
1306
- return $this->ids;
1307
- }
1308
- public function setMetrics(/* array(Google_string) */ $metrics) {
1309
- $this->assertIsArray($metrics, 'Google_string', __METHOD__);
1310
- $this->metrics = $metrics;
1311
- }
1312
- public function getMetrics() {
1313
- return $this->metrics;
1314
- }
1315
- public function setFilters($filters) {
1316
- $this->filters = $filters;
1317
- }
1318
- public function getFilters() {
1319
- return $this->filters;
1320
- }
1321
- public function setEnd_date($end_date) {
1322
- $this->end_date = $end_date;
1323
- }
1324
- public function getEnd_date() {
1325
- return $this->end_date;
1326
- }
1327
- }
1328
-
1329
- class Google_McfDataRows extends Google_Model {
1330
- public $primitiveValue;
1331
- protected $__conversionPathValueType = 'Google_McfDataRowsConversionPathValue';
1332
- protected $__conversionPathValueDataType = 'array';
1333
- public $conversionPathValue;
1334
- public function setPrimitiveValue($primitiveValue) {
1335
- $this->primitiveValue = $primitiveValue;
1336
- }
1337
- public function getPrimitiveValue() {
1338
- return $this->primitiveValue;
1339
- }
1340
- public function setConversionPathValue(/* array(Google_McfDataRowsConversionPathValue) */ $conversionPathValue) {
1341
- $this->assertIsArray($conversionPathValue, 'Google_McfDataRowsConversionPathValue', __METHOD__);
1342
- $this->conversionPathValue = $conversionPathValue;
1343
- }
1344
- public function getConversionPathValue() {
1345
- return $this->conversionPathValue;
1346
- }
1347
- }
1348
-
1349
- class Google_McfDataRowsConversionPathValue extends Google_Model {
1350
- public $nodeValue;
1351
- public $interactionType;
1352
- public function setNodeValue($nodeValue) {
1353
- $this->nodeValue = $nodeValue;
1354
- }
1355
- public function getNodeValue() {
1356
- return $this->nodeValue;
1357
- }
1358
- public function setInteractionType($interactionType) {
1359
- $this->interactionType = $interactionType;
1360
- }
1361
- public function getInteractionType() {
1362
- return $this->interactionType;
1363
- }
1364
- }
1365
-
1366
- class Google_Profile extends Google_Model {
1367
- public $defaultPage;
1368
- public $kind;
1369
- public $excludeQueryParameters;
1370
- public $name;
1371
- public $created;
1372
- public $webPropertyId;
1373
- public $updated;
1374
- public $siteSearchQueryParameters;
1375
- public $currency;
1376
- public $internalWebPropertyId;
1377
- protected $__childLinkType = 'Google_ProfileChildLink';
1378
- protected $__childLinkDataType = '';
1379
- public $childLink;
1380
- public $timezone;
1381
- public $siteSearchCategoryParameters;
1382
- protected $__parentLinkType = 'Google_ProfileParentLink';
1383
- protected $__parentLinkDataType = '';
1384
- public $parentLink;
1385
- public $id;
1386
- public $selfLink;
1387
- public $accountId;
1388
- public function setDefaultPage($defaultPage) {
1389
- $this->defaultPage = $defaultPage;
1390
- }
1391
- public function getDefaultPage() {
1392
- return $this->defaultPage;
1393
- }
1394
- public function setKind($kind) {
1395
- $this->kind = $kind;
1396
- }
1397
- public function getKind() {
1398
- return $this->kind;
1399
- }
1400
- public function setExcludeQueryParameters($excludeQueryParameters) {
1401
- $this->excludeQueryParameters = $excludeQueryParameters;
1402
- }
1403
- public function getExcludeQueryParameters() {
1404
- return $this->excludeQueryParameters;
1405
- }
1406
- public function setName($name) {
1407
- $this->name = $name;
1408
- }
1409
- public function getName() {
1410
- return $this->name;
1411
- }
1412
- public function setCreated($created) {
1413
- $this->created = $created;
1414
- }
1415
- public function getCreated() {
1416
- return $this->created;
1417
- }
1418
- public function setWebPropertyId($webPropertyId) {
1419
- $this->webPropertyId = $webPropertyId;
1420
- }
1421
- public function getWebPropertyId() {
1422
- return $this->webPropertyId;
1423
- }
1424
- public function setUpdated($updated) {
1425
- $this->updated = $updated;
1426
- }
1427
- public function getUpdated() {
1428
- return $this->updated;
1429
- }
1430
- public function setSiteSearchQueryParameters($siteSearchQueryParameters) {
1431
- $this->siteSearchQueryParameters = $siteSearchQueryParameters;
1432
- }
1433
- public function getSiteSearchQueryParameters() {
1434
- return $this->siteSearchQueryParameters;
1435
- }
1436
- public function setCurrency($currency) {
1437
- $this->currency = $currency;
1438
- }
1439
- public function getCurrency() {
1440
- return $this->currency;
1441
- }
1442
- public function setInternalWebPropertyId($internalWebPropertyId) {
1443
- $this->internalWebPropertyId = $internalWebPropertyId;
1444
- }
1445
- public function getInternalWebPropertyId() {
1446
- return $this->internalWebPropertyId;
1447
- }
1448
- public function setChildLink(Google_ProfileChildLink $childLink) {
1449
- $this->childLink = $childLink;
1450
- }
1451
- public function getChildLink() {
1452
- return $this->childLink;
1453
- }
1454
- public function setTimezone($timezone) {
1455
- $this->timezone = $timezone;
1456
- }
1457
- public function getTimezone() {
1458
- return $this->timezone;
1459
- }
1460
- public function setSiteSearchCategoryParameters($siteSearchCategoryParameters) {
1461
- $this->siteSearchCategoryParameters = $siteSearchCategoryParameters;
1462
- }
1463
- public function getSiteSearchCategoryParameters() {
1464
- return $this->siteSearchCategoryParameters;
1465
- }
1466
- public function setParentLink(Google_ProfileParentLink $parentLink) {
1467
- $this->parentLink = $parentLink;
1468
- }
1469
- public function getParentLink() {
1470
- return $this->parentLink;
1471
- }
1472
- public function setId($id) {
1473
- $this->id = $id;
1474
- }
1475
- public function getId() {
1476
- return $this->id;
1477
- }
1478
- public function setSelfLink($selfLink) {
1479
- $this->selfLink = $selfLink;
1480
- }
1481
- public function getSelfLink() {
1482
- return $this->selfLink;
1483
- }
1484
- public function setAccountId($accountId) {
1485
- $this->accountId = $accountId;
1486
- }
1487
- public function getAccountId() {
1488
- return $this->accountId;
1489
- }
1490
- }
1491
-
1492
- class Google_ProfileChildLink extends Google_Model {
1493
- public $href;
1494
- public $type;
1495
- public function setHref($href) {
1496
- $this->href = $href;
1497
- }
1498
- public function getHref() {
1499
- return $this->href;
1500
- }
1501
- public function setType($type) {
1502
- $this->type = $type;
1503
- }
1504
- public function getType() {
1505
- return $this->type;
1506
- }
1507
- }
1508
-
1509
- class Google_ProfileParentLink extends Google_Model {
1510
- public $href;
1511
- public $type;
1512
- public function setHref($href) {
1513
- $this->href = $href;
1514
- }
1515
- public function getHref() {
1516
- return $this->href;
1517
- }
1518
- public function setType($type) {
1519
- $this->type = $type;
1520
- }
1521
- public function getType() {
1522
- return $this->type;
1523
- }
1524
- }
1525
-
1526
- class Google_Profiles extends Google_Model {
1527
- public $username;
1528
- public $kind;
1529
- protected $__itemsType = 'Google_Profile';
1530
- protected $__itemsDataType = 'array';
1531
- public $items;
1532
- public $itemsPerPage;
1533
- public $previousLink;
1534
- public $startIndex;
1535
- public $nextLink;
1536
- public $totalResults;
1537
- public function setUsername($username) {
1538
- $this->username = $username;
1539
- }
1540
- public function getUsername() {
1541
- return $this->username;
1542
- }
1543
- public function setKind($kind) {
1544
- $this->kind = $kind;
1545
- }
1546
- public function getKind() {
1547
- return $this->kind;
1548
- }
1549
- public function setItems(/* array(Google_Profile) */ $items) {
1550
- $this->assertIsArray($items, 'Google_Profile', __METHOD__);
1551
- $this->items = $items;
1552
- }
1553
- public function getItems() {
1554
- return $this->items;
1555
- }
1556
- public function setItemsPerPage($itemsPerPage) {
1557
- $this->itemsPerPage = $itemsPerPage;
1558
- }
1559
- public function getItemsPerPage() {
1560
- return $this->itemsPerPage;
1561
- }
1562
- public function setPreviousLink($previousLink) {
1563
- $this->previousLink = $previousLink;
1564
- }
1565
- public function getPreviousLink() {
1566
- return $this->previousLink;
1567
- }
1568
- public function setStartIndex($startIndex) {
1569
- $this->startIndex = $startIndex;
1570
- }
1571
- public function getStartIndex() {
1572
- return $this->startIndex;
1573
- }
1574
- public function setNextLink($nextLink) {
1575
- $this->nextLink = $nextLink;
1576
- }
1577
- public function getNextLink() {
1578
- return $this->nextLink;
1579
- }
1580
- public function setTotalResults($totalResults) {
1581
- $this->totalResults = $totalResults;
1582
- }
1583
- public function getTotalResults() {
1584
- return $this->totalResults;
1585
- }
1586
- }
1587
-
1588
- class Google_Segment extends Google_Model {
1589
- public $definition;
1590
- public $kind;
1591
- public $segmentId;
1592
- public $created;
1593
- public $updated;
1594
- public $id;
1595
- public $selfLink;
1596
- public $name;
1597
- public function setDefinition($definition) {
1598
- $this->definition = $definition;
1599
- }
1600
- public function getDefinition() {
1601
- return $this->definition;
1602
- }
1603
- public function setKind($kind) {
1604
- $this->kind = $kind;
1605
- }
1606
- public function getKind() {
1607
- return $this->kind;
1608
- }
1609
- public function setSegmentId($segmentId) {
1610
- $this->segmentId = $segmentId;
1611
- }
1612
- public function getSegmentId() {
1613
- return $this->segmentId;
1614
- }
1615
- public function setCreated($created) {
1616
- $this->created = $created;
1617
- }
1618
- public function getCreated() {
1619
- return $this->created;
1620
- }
1621
- public function setUpdated($updated) {
1622
- $this->updated = $updated;
1623
- }
1624
- public function getUpdated() {
1625
- return $this->updated;
1626
- }
1627
- public function setId($id) {
1628
- $this->id = $id;
1629
- }
1630
- public function getId() {
1631
- return $this->id;
1632
- }
1633
- public function setSelfLink($selfLink) {
1634
- $this->selfLink = $selfLink;
1635
- }
1636
- public function getSelfLink() {
1637
- return $this->selfLink;
1638
- }
1639
- public function setName($name) {
1640
- $this->name = $name;
1641
- }
1642
- public function getName() {
1643
- return $this->name;
1644
- }
1645
- }
1646
-
1647
- class Google_Segments extends Google_Model {
1648
- public $username;
1649
- public $kind;
1650
- protected $__itemsType = 'Google_Segment';
1651
- protected $__itemsDataType = 'array';
1652
- public $items;
1653
- public $itemsPerPage;
1654
- public $previousLink;
1655
- public $startIndex;
1656
- public $nextLink;
1657
- public $totalResults;
1658
- public function setUsername($username) {
1659
- $this->username = $username;
1660
- }
1661
- public function getUsername() {
1662
- return $this->username;
1663
- }
1664
- public function setKind($kind) {
1665
- $this->kind = $kind;
1666
- }
1667
- public function getKind() {
1668
- return $this->kind;
1669
- }
1670
- public function setItems(/* array(Google_Segment) */ $items) {
1671
- $this->assertIsArray($items, 'Google_Segment', __METHOD__);
1672
- $this->items = $items;
1673
- }
1674
- public function getItems() {
1675
- return $this->items;
1676
- }
1677
- public function setItemsPerPage($itemsPerPage) {
1678
- $this->itemsPerPage = $itemsPerPage;
1679
- }
1680
- public function getItemsPerPage() {
1681
- return $this->itemsPerPage;
1682
- }
1683
- public function setPreviousLink($previousLink) {
1684
- $this->previousLink = $previousLink;
1685
- }
1686
- public function getPreviousLink() {
1687
- return $this->previousLink;
1688
- }
1689
- public function setStartIndex($startIndex) {
1690
- $this->startIndex = $startIndex;
1691
- }
1692
- public function getStartIndex() {
1693
- return $this->startIndex;
1694
- }
1695
- public function setNextLink($nextLink) {
1696
- $this->nextLink = $nextLink;
1697
- }
1698
- public function getNextLink() {
1699
- return $this->nextLink;
1700
- }
1701
- public function setTotalResults($totalResults) {
1702
- $this->totalResults = $totalResults;
1703
- }
1704
- public function getTotalResults() {
1705
- return $this->totalResults;
1706
- }
1707
- }
1708
-
1709
- class Google_Webproperties extends Google_Model {
1710
- public $username;
1711
- public $kind;
1712
- protected $__itemsType = 'Google_Webproperty';
1713
- protected $__itemsDataType = 'array';
1714
- public $items;
1715
- public $itemsPerPage;
1716
- public $previousLink;
1717
- public $startIndex;
1718
- public $nextLink;
1719
- public $totalResults;
1720
- public function setUsername($username) {
1721
- $this->username = $username;
1722
- }
1723
- public function getUsername() {
1724
- return $this->username;
1725
- }
1726
- public function setKind($kind) {
1727
- $this->kind = $kind;
1728
- }
1729
- public function getKind() {
1730
- return $this->kind;
1731
- }
1732
- public function setItems(/* array(Google_Webproperty) */ $items) {
1733
- $this->assertIsArray($items, 'Google_Webproperty', __METHOD__);
1734
- $this->items = $items;
1735
- }
1736
- public function getItems() {
1737
- return $this->items;
1738
- }
1739
- public function setItemsPerPage($itemsPerPage) {
1740
- $this->itemsPerPage = $itemsPerPage;
1741
- }
1742
- public function getItemsPerPage() {
1743
- return $this->itemsPerPage;
1744
- }
1745
- public function setPreviousLink($previousLink) {
1746
- $this->previousLink = $previousLink;
1747
- }
1748
- public function getPreviousLink() {
1749
- return $this->previousLink;
1750
- }
1751
- public function setStartIndex($startIndex) {
1752
- $this->startIndex = $startIndex;
1753
- }
1754
- public function getStartIndex() {
1755
- return $this->startIndex;
1756
- }
1757
- public function setNextLink($nextLink) {
1758
- $this->nextLink = $nextLink;
1759
- }
1760
- public function getNextLink() {
1761
- return $this->nextLink;
1762
- }
1763
- public function setTotalResults($totalResults) {
1764
- $this->totalResults = $totalResults;
1765
- }
1766
- public function getTotalResults() {
1767
- return $this->totalResults;
1768
- }
1769
- }
1770
-
1771
- class Google_Webproperty extends Google_Model {
1772
- public $kind;
1773
- public $name;
1774
- public $created;
1775
- public $updated;
1776
- public $websiteUrl;
1777
- public $internalWebPropertyId;
1778
- protected $__childLinkType = 'Google_WebpropertyChildLink';
1779
- protected $__childLinkDataType = '';
1780
- public $childLink;
1781
- protected $__parentLinkType = 'Google_WebpropertyParentLink';
1782
- protected $__parentLinkDataType = '';
1783
- public $parentLink;
1784
- public $id;
1785
- public $selfLink;
1786
- public $accountId;
1787
- public function setKind($kind) {
1788
- $this->kind = $kind;
1789
- }
1790
- public function getKind() {
1791
- return $this->kind;
1792
- }
1793
- public function setName($name) {
1794
- $this->name = $name;
1795
- }
1796
- public function getName() {
1797
- return $this->name;
1798
- }
1799
- public function setCreated($created) {
1800
- $this->created = $created;
1801
- }
1802
- public function getCreated() {
1803
- return $this->created;
1804
- }
1805
- public function setUpdated($updated) {
1806
- $this->updated = $updated;
1807
- }
1808
- public function getUpdated() {
1809
- return $this->updated;
1810
- }
1811
- public function setWebsiteUrl($websiteUrl) {
1812
- $this->websiteUrl = $websiteUrl;
1813
- }
1814
- public function getWebsiteUrl() {
1815
- return $this->websiteUrl;
1816
- }
1817
- public function setInternalWebPropertyId($internalWebPropertyId) {
1818
- $this->internalWebPropertyId = $internalWebPropertyId;
1819
- }
1820
- public function getInternalWebPropertyId() {
1821
- return $this->internalWebPropertyId;
1822
- }
1823
- public function setChildLink(Google_WebpropertyChildLink $childLink) {
1824
- $this->childLink = $childLink;
1825
- }
1826
- public function getChildLink() {
1827
- return $this->childLink;
1828
- }
1829
- public function setParentLink(Google_WebpropertyParentLink $parentLink) {
1830
- $this->parentLink = $parentLink;
1831
- }
1832
- public function getParentLink() {
1833
- return $this->parentLink;
1834
- }
1835
- public function setId($id) {
1836
- $this->id = $id;
1837
- }
1838
- public function getId() {
1839
- return $this->id;
1840
- }
1841
- public function setSelfLink($selfLink) {
1842
- $this->selfLink = $selfLink;
1843
- }
1844
- public function getSelfLink() {
1845
- return $this->selfLink;
1846
- }
1847
- public function setAccountId($accountId) {
1848
- $this->accountId = $accountId;
1849
- }
1850
- public function getAccountId() {
1851
- return $this->accountId;
1852
- }
1853
- }
1854
-
1855
- class Google_WebpropertyChildLink extends Google_Model {
1856
- public $href;
1857
- public $type;
1858
- public function setHref($href) {
1859
- $this->href = $href;
1860
- }
1861
- public function getHref() {
1862
- return $this->href;
1863
- }
1864
- public function setType($type) {
1865
- $this->type = $type;
1866
- }
1867
- public function getType() {
1868
- return $this->type;
1869
- }
1870
- }
1871
-
1872
- class Google_WebpropertyParentLink extends Google_Model {
1873
- public $href;
1874
- public $type;
1875
- public function setHref($href) {
1876
- $this->href = $href;
1877
- }
1878
- public function getHref() {
1879
- return $this->href;
1880
- }
1881
- public function setType($type) {
1882
- $this->type = $type;
1883
- }
1884
- public function getType() {
1885
- return $this->type;
1886
- }
1887
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/google-api-client/contrib/Google_BigqueryService.php DELETED
@@ -1,1821 +0,0 @@
1
- <?php
2
- /*
3
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
- * use this file except in compliance with the License. You may obtain a copy of
5
- * the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
- * License for the specific language governing permissions and limitations under
13
- * the License.
14
- */
15
-
16
-
17
- /**
18
- * The "tables" collection of methods.
19
- * Typical usage is:
20
- * <code>
21
- * $bigqueryService = new Google_BigqueryService(...);
22
- * $tables = $bigqueryService->tables;
23
- * </code>
24
- */
25
- class Google_TablesServiceResource extends Google_ServiceResource {
26
-
27
-
28
- /**
29
- * Creates a new, empty table in the dataset. (tables.insert)
30
- *
31
- * @param string $projectId Project ID of the new table
32
- * @param string $datasetId Dataset ID of the new table
33
- * @param Google_Table $postBody
34
- * @param array $optParams Optional parameters.
35
- * @return Google_Table
36
- */
37
- public function insert($projectId, $datasetId, Google_Table $postBody, $optParams = array()) {
38
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'postBody' => $postBody);
39
- $params = array_merge($params, $optParams);
40
- $data = $this->__call('insert', array($params));
41
- if ($this->useObjects()) {
42
- return new Google_Table($data);
43
- } else {
44
- return $data;
45
- }
46
- }
47
- /**
48
- * Gets the specified table resource by table ID. This method does not return the data in the table,
49
- * it only returns the table resource, which describes the structure of this table. (tables.get)
50
- *
51
- * @param string $projectId Project ID of the requested table
52
- * @param string $datasetId Dataset ID of the requested table
53
- * @param string $tableId Table ID of the requested table
54
- * @param array $optParams Optional parameters.
55
- * @return Google_Table
56
- */
57
- public function get($projectId, $datasetId, $tableId, $optParams = array()) {
58
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
59
- $params = array_merge($params, $optParams);
60
- $data = $this->__call('get', array($params));
61
- if ($this->useObjects()) {
62
- return new Google_Table($data);
63
- } else {
64
- return $data;
65
- }
66
- }
67
- /**
68
- * Lists all tables in the specified dataset. (tables.list)
69
- *
70
- * @param string $projectId Project ID of the tables to list
71
- * @param string $datasetId Dataset ID of the tables to list
72
- * @param array $optParams Optional parameters.
73
- *
74
- * @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
75
- * @opt_param string maxResults Maximum number of results to return
76
- * @return Google_TableList
77
- */
78
- public function listTables($projectId, $datasetId, $optParams = array()) {
79
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId);
80
- $params = array_merge($params, $optParams);
81
- $data = $this->__call('list', array($params));
82
- if ($this->useObjects()) {
83
- return new Google_TableList($data);
84
- } else {
85
- return $data;
86
- }
87
- }
88
- /**
89
- * Updates information in an existing table, specified by tableId. (tables.update)
90
- *
91
- * @param string $projectId Project ID of the table to update
92
- * @param string $datasetId Dataset ID of the table to update
93
- * @param string $tableId Table ID of the table to update
94
- * @param Google_Table $postBody
95
- * @param array $optParams Optional parameters.
96
- * @return Google_Table
97
- */
98
- public function update($projectId, $datasetId, $tableId, Google_Table $postBody, $optParams = array()) {
99
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId, 'postBody' => $postBody);
100
- $params = array_merge($params, $optParams);
101
- $data = $this->__call('update', array($params));
102
- if ($this->useObjects()) {
103
- return new Google_Table($data);
104
- } else {
105
- return $data;
106
- }
107
- }
108
- /**
109
- * Updates information in an existing table, specified by tableId. This method supports patch
110
- * semantics. (tables.patch)
111
- *
112
- * @param string $projectId Project ID of the table to update
113
- * @param string $datasetId Dataset ID of the table to update
114
- * @param string $tableId Table ID of the table to update
115
- * @param Google_Table $postBody
116
- * @param array $optParams Optional parameters.
117
- * @return Google_Table
118
- */
119
- public function patch($projectId, $datasetId, $tableId, Google_Table $postBody, $optParams = array()) {
120
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId, 'postBody' => $postBody);
121
- $params = array_merge($params, $optParams);
122
- $data = $this->__call('patch', array($params));
123
- if ($this->useObjects()) {
124
- return new Google_Table($data);
125
- } else {
126
- return $data;
127
- }
128
- }
129
- /**
130
- * Deletes the table specified by tableId from the dataset. If the table contains data, all the data
131
- * will be deleted. (tables.delete)
132
- *
133
- * @param string $projectId Project ID of the table to delete
134
- * @param string $datasetId Dataset ID of the table to delete
135
- * @param string $tableId Table ID of the table to delete
136
- * @param array $optParams Optional parameters.
137
- */
138
- public function delete($projectId, $datasetId, $tableId, $optParams = array()) {
139
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
140
- $params = array_merge($params, $optParams);
141
- $data = $this->__call('delete', array($params));
142
- return $data;
143
- }
144
- }
145
-
146
- /**
147
- * The "datasets" collection of methods.
148
- * Typical usage is:
149
- * <code>
150
- * $bigqueryService = new Google_BigqueryService(...);
151
- * $datasets = $bigqueryService->datasets;
152
- * </code>
153
- */
154
- class Google_DatasetsServiceResource extends Google_ServiceResource {
155
-
156
-
157
- /**
158
- * Creates a new empty dataset. (datasets.insert)
159
- *
160
- * @param string $projectId Project ID of the new dataset
161
- * @param Google_Dataset $postBody
162
- * @param array $optParams Optional parameters.
163
- * @return Google_Dataset
164
- */
165
- public function insert($projectId, Google_Dataset $postBody, $optParams = array()) {
166
- $params = array('projectId' => $projectId, 'postBody' => $postBody);
167
- $params = array_merge($params, $optParams);
168
- $data = $this->__call('insert', array($params));
169
- if ($this->useObjects()) {
170
- return new Google_Dataset($data);
171
- } else {
172
- return $data;
173
- }
174
- }
175
- /**
176
- * Returns the dataset specified by datasetID. (datasets.get)
177
- *
178
- * @param string $projectId Project ID of the requested dataset
179
- * @param string $datasetId Dataset ID of the requested dataset
180
- * @param array $optParams Optional parameters.
181
- * @return Google_Dataset
182
- */
183
- public function get($projectId, $datasetId, $optParams = array()) {
184
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId);
185
- $params = array_merge($params, $optParams);
186
- $data = $this->__call('get', array($params));
187
- if ($this->useObjects()) {
188
- return new Google_Dataset($data);
189
- } else {
190
- return $data;
191
- }
192
- }
193
- /**
194
- * Lists all the datasets in the specified project to which the caller has read access; however, a
195
- * project owner can list (but not necessarily get) all datasets in his project. (datasets.list)
196
- *
197
- * @param string $projectId Project ID of the datasets to be listed
198
- * @param array $optParams Optional parameters.
199
- *
200
- * @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
201
- * @opt_param string maxResults The maximum number of results to return
202
- * @return Google_DatasetList
203
- */
204
- public function listDatasets($projectId, $optParams = array()) {
205
- $params = array('projectId' => $projectId);
206
- $params = array_merge($params, $optParams);
207
- $data = $this->__call('list', array($params));
208
- if ($this->useObjects()) {
209
- return new Google_DatasetList($data);
210
- } else {
211
- return $data;
212
- }
213
- }
214
- /**
215
- * Updates information in an existing dataset, specified by datasetId. Properties not included in
216
- * the submitted resource will not be changed. If you include the access property without any values
217
- * assigned, the request will fail as you must specify at least one owner for a dataset.
218
- * (datasets.update)
219
- *
220
- * @param string $projectId Project ID of the dataset being updated
221
- * @param string $datasetId Dataset ID of the dataset being updated
222
- * @param Google_Dataset $postBody
223
- * @param array $optParams Optional parameters.
224
- * @return Google_Dataset
225
- */
226
- public function update($projectId, $datasetId, Google_Dataset $postBody, $optParams = array()) {
227
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'postBody' => $postBody);
228
- $params = array_merge($params, $optParams);
229
- $data = $this->__call('update', array($params));
230
- if ($this->useObjects()) {
231
- return new Google_Dataset($data);
232
- } else {
233
- return $data;
234
- }
235
- }
236
- /**
237
- * Updates information in an existing dataset, specified by datasetId. Properties not included in
238
- * the submitted resource will not be changed. If you include the access property without any values
239
- * assigned, the request will fail as you must specify at least one owner for a dataset. This method
240
- * supports patch semantics. (datasets.patch)
241
- *
242
- * @param string $projectId Project ID of the dataset being updated
243
- * @param string $datasetId Dataset ID of the dataset being updated
244
- * @param Google_Dataset $postBody
245
- * @param array $optParams Optional parameters.
246
- * @return Google_Dataset
247
- */
248
- public function patch($projectId, $datasetId, Google_Dataset $postBody, $optParams = array()) {
249
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'postBody' => $postBody);
250
- $params = array_merge($params, $optParams);
251
- $data = $this->__call('patch', array($params));
252
- if ($this->useObjects()) {
253
- return new Google_Dataset($data);
254
- } else {
255
- return $data;
256
- }
257
- }
258
- /**
259
- * Deletes the dataset specified by datasetId value. Before you can delete a dataset, you must
260
- * delete all its tables, either manually or by specifying deleteContents. Immediately after
261
- * deletion, you can create another dataset with the same name. (datasets.delete)
262
- *
263
- * @param string $projectId Project ID of the dataset being deleted
264
- * @param string $datasetId Dataset ID of dataset being deleted
265
- * @param array $optParams Optional parameters.
266
- *
267
- * @opt_param bool deleteContents If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False
268
- */
269
- public function delete($projectId, $datasetId, $optParams = array()) {
270
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId);
271
- $params = array_merge($params, $optParams);
272
- $data = $this->__call('delete', array($params));
273
- return $data;
274
- }
275
- }
276
-
277
- /**
278
- * The "jobs" collection of methods.
279
- * Typical usage is:
280
- * <code>
281
- * $bigqueryService = new Google_BigqueryService(...);
282
- * $jobs = $bigqueryService->jobs;
283
- * </code>
284
- */
285
- class Google_JobsServiceResource extends Google_ServiceResource {
286
-
287
-
288
- /**
289
- * Starts a new asynchronous job. (jobs.insert)
290
- *
291
- * @param string $projectId Project ID of the project that will be billed for the job
292
- * @param Google_Job $postBody
293
- * @param array $optParams Optional parameters.
294
- * @return Google_Job
295
- */
296
- public function insert($projectId, Google_Job $postBody, $optParams = array()) {
297
- $params = array('projectId' => $projectId, 'postBody' => $postBody);
298
- $params = array_merge($params, $optParams);
299
- $data = $this->__call('insert', array($params));
300
- if ($this->useObjects()) {
301
- return new Google_Job($data);
302
- } else {
303
- return $data;
304
- }
305
- }
306
- /**
307
- * Runs a BigQuery SQL query synchronously and returns query results if the query completes within a
308
- * specified timeout. (jobs.query)
309
- *
310
- * @param string $projectId Project ID of the project billed for the query
311
- * @param Google_QueryRequest $postBody
312
- * @param array $optParams Optional parameters.
313
- * @return Google_QueryResponse
314
- */
315
- public function query($projectId, Google_QueryRequest $postBody, $optParams = array()) {
316
- $params = array('projectId' => $projectId, 'postBody' => $postBody);
317
- $params = array_merge($params, $optParams);
318
- $data = $this->__call('query', array($params));
319
- if ($this->useObjects()) {
320
- return new Google_QueryResponse($data);
321
- } else {
322
- return $data;
323
- }
324
- }
325
- /**
326
- * Lists all the Jobs in the specified project that were started by the user. (jobs.list)
327
- *
328
- * @param string $projectId Project ID of the jobs to list
329
- * @param array $optParams Optional parameters.
330
- *
331
- * @opt_param string projection Restrict information returned to a set of selected fields
332
- * @opt_param string stateFilter Filter for job state
333
- * @opt_param bool allUsers Whether to display jobs owned by all users in the project. Default false
334
- * @opt_param string maxResults Maximum number of results to return
335
- * @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
336
- * @return Google_JobList
337
- */
338
- public function listJobs($projectId, $optParams = array()) {
339
- $params = array('projectId' => $projectId);
340
- $params = array_merge($params, $optParams);
341
- $data = $this->__call('list', array($params));
342
- if ($this->useObjects()) {
343
- return new Google_JobList($data);
344
- } else {
345
- return $data;
346
- }
347
- }
348
- /**
349
- * Retrieves the results of a query job. (jobs.getQueryResults)
350
- *
351
- * @param string $projectId Project ID of the query job
352
- * @param string $jobId Job ID of the query job
353
- * @param array $optParams Optional parameters.
354
- *
355
- * @opt_param string timeoutMs How long to wait for the query to complete, in milliseconds, before returning. Default is to return immediately. If the timeout passes before the job completes, the request will fail with a TIMEOUT error
356
- * @opt_param string startIndex Zero-based index of the starting row
357
- * @opt_param string maxResults Maximum number of results to read
358
- * @return Google_GetQueryResultsResponse
359
- */
360
- public function getQueryResults($projectId, $jobId, $optParams = array()) {
361
- $params = array('projectId' => $projectId, 'jobId' => $jobId);
362
- $params = array_merge($params, $optParams);
363
- $data = $this->__call('getQueryResults', array($params));
364
- if ($this->useObjects()) {
365
- return new Google_GetQueryResultsResponse($data);
366
- } else {
367
- return $data;
368
- }
369
- }
370
- /**
371
- * Retrieves the specified job by ID. (jobs.get)
372
- *
373
- * @param string $projectId Project ID of the requested job
374
- * @param string $jobId Job ID of the requested job
375
- * @param array $optParams Optional parameters.
376
- * @return Google_Job
377
- */
378
- public function get($projectId, $jobId, $optParams = array()) {
379
- $params = array('projectId' => $projectId, 'jobId' => $jobId);
380
- $params = array_merge($params, $optParams);
381
- $data = $this->__call('get', array($params));
382
- if ($this->useObjects()) {
383
- return new Google_Job($data);
384
- } else {
385
- return $data;
386
- }
387
- }
388
- }
389
-
390
- /**
391
- * The "tabledata" collection of methods.
392
- * Typical usage is:
393
- * <code>
394
- * $bigqueryService = new Google_BigqueryService(...);
395
- * $tabledata = $bigqueryService->tabledata;
396
- * </code>
397
- */
398
- class Google_TabledataServiceResource extends Google_ServiceResource {
399
-
400
-
401
- /**
402
- * Retrieves table data from a specified set of rows. (tabledata.list)
403
- *
404
- * @param string $projectId Project ID of the table to read
405
- * @param string $datasetId Dataset ID of the table to read
406
- * @param string $tableId Table ID of the table to read
407
- * @param array $optParams Optional parameters.
408
- *
409
- * @opt_param string maxResults Maximum number of results to return
410
- * @opt_param string pageToken Page token, returned by a previous call, identifying the result set
411
- * @opt_param string startIndex Zero-based index of the starting row to read
412
- * @return Google_TableDataList
413
- */
414
- public function listTabledata($projectId, $datasetId, $tableId, $optParams = array()) {
415
- $params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
416
- $params = array_merge($params, $optParams);
417
- $data = $this->__call('list', array($params));
418
- if ($this->useObjects()) {
419
- return new Google_TableDataList($data);
420
- } else {
421
- return $data;
422
- }
423
- }
424
- }
425
-
426
- /**
427
- * The "projects" collection of methods.
428
- * Typical usage is:
429
- * <code>
430
- * $bigqueryService = new Google_BigqueryService(...);
431
- * $projects = $bigqueryService->projects;
432
- * </code>
433
- */
434
- class Google_ProjectsServiceResource extends Google_ServiceResource {
435
-
436
-
437
- /**
438
- * Lists the projects to which you have at least read access. (projects.list)
439
- *
440
- * @param array $optParams Optional parameters.
441
- *
442
- * @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
443
- * @opt_param string maxResults Maximum number of results to return
444
- * @return Google_ProjectList
445
- */
446
- public function listProjects($optParams = array()) {
447
- $params = array();
448
- $params = array_merge($params, $optParams);
449
- $data = $this->__call('list', array($params));
450
- if ($this->useObjects()) {
451
- return new Google_ProjectList($data);
452
- } else {
453
- return $data;
454
- }
455
- }
456
- }
457
-
458
- /**
459
- * Service definition for Google_Bigquery (v2).
460
- *
461
- * <p>
462
- * A data platform for customers to create, manage, share and query data.
463
- * </p>
464
- *
465
- * <p>
466
- * For more information about this service, see the
467
- * <a href="https://code.google.com/apis/bigquery/docs/v2/" target="_blank">API Documentation</a>
468
- * </p>
469
- *
470
- * @author Google, Inc.
471
- */
472
- class Google_BigqueryService extends Google_Service {
473
- public $tables;
474
- public $datasets;
475
- public $jobs;
476
- public $tabledata;
477
- public $projects;
478
- /**
479
- * Constructs the internal representation of the Bigquery service.
480
- *
481
- * @param Google_Client $client
482
- */
483
- public function __construct(Google_Client $client) {
484
- $this->servicePath = 'bigquery/v2/';
485
- $this->version = 'v2';
486
- $this->serviceName = 'bigquery';
487
-
488
- $client->addService($this->serviceName, $this->version);
489
- $this->tables = new Google_TablesServiceResource($this, $this->serviceName, 'tables', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "response": {"$ref": "Table"}, "httpMethod": "POST", "path": "projects/{projectId}/datasets/{datasetId}/tables", "id": "bigquery.tables.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.tables.get", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "response": {"$ref": "Table"}}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}, "datasetId": {"required": true, "type": "string", "location": "path"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.tables.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables", "response": {"$ref": "TableList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "response": {"$ref": "Table"}, "httpMethod": "PUT", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "id": "bigquery.tables.update"}, "patch": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "response": {"$ref": "Table"}, "httpMethod": "PATCH", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "id": "bigquery.tables.patch"}, "delete": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "id": "bigquery.tables.delete", "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE"}}}', true));
490
- $this->datasets = new Google_DatasetsServiceResource($this, $this->serviceName, 'datasets', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "response": {"$ref": "Dataset"}, "httpMethod": "POST", "path": "projects/{projectId}/datasets", "id": "bigquery.datasets.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.datasets.get", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}", "response": {"$ref": "Dataset"}}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.datasets.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets", "response": {"$ref": "DatasetList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "response": {"$ref": "Dataset"}, "httpMethod": "PUT", "path": "projects/{projectId}/datasets/{datasetId}", "id": "bigquery.datasets.update"}, "patch": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "response": {"$ref": "Dataset"}, "httpMethod": "PATCH", "path": "projects/{projectId}/datasets/{datasetId}", "id": "bigquery.datasets.patch"}, "delete": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "path": "projects/{projectId}/datasets/{datasetId}", "id": "bigquery.datasets.delete", "parameters": {"deleteContents": {"type": "boolean", "location": "query"}, "datasetId": {"required": true, "type": "string", "location": "path"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE"}}}', true));
491
- $this->jobs = new Google_JobsServiceResource($this, $this->serviceName, 'jobs', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}}, "supportsMediaUpload": true, "request": {"$ref": "Job"}, "mediaUpload": {"protocols": {"simple": {"path": "/upload/bigquery/v2/projects/{projectId}/jobs", "multipart": true}, "resumable": {"path": "/resumable/upload/bigquery/v2/projects/{projectId}/jobs", "multipart": true}}, "accept": ["application/octet-stream"]}, "response": {"$ref": "Job"}, "httpMethod": "POST", "path": "projects/{projectId}/jobs", "id": "bigquery.jobs.insert"}, "query": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "QueryRequest"}, "response": {"$ref": "QueryResponse"}, "httpMethod": "POST", "path": "projects/{projectId}/queries", "id": "bigquery.jobs.query"}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projection": {"enum": ["full", "minimal"], "type": "string", "location": "query"}, "stateFilter": {"repeated": true, "enum": ["done", "pending", "running"], "type": "string", "location": "query"}, "projectId": {"required": true, "type": "string", "location": "path"}, "allUsers": {"type": "boolean", "location": "query"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}, "pageToken": {"type": "string", "location": "query"}}, "id": "bigquery.jobs.list", "httpMethod": "GET", "path": "projects/{projectId}/jobs", "response": {"$ref": "JobList"}}, "getQueryResults": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"timeoutMs": {"type": "integer", "location": "query", "format": "uint32"}, "projectId": {"required": true, "type": "string", "location": "path"}, "startIndex": {"type": "string", "location": "query", "format": "uint64"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}, "jobId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.jobs.getQueryResults", "httpMethod": "GET", "path": "projects/{projectId}/queries/{jobId}", "response": {"$ref": "GetQueryResultsResponse"}}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "jobId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.jobs.get", "httpMethod": "GET", "path": "projects/{projectId}/jobs/{jobId}", "response": {"$ref": "Job"}}}}', true));
492
- $this->tabledata = new Google_TabledataServiceResource($this, $this->serviceName, 'tabledata', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}, "pageToken": {"type": "string", "location": "query"}, "startIndex": {"type": "string", "location": "query", "format": "uint64"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.tabledata.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data", "response": {"$ref": "TableDataList"}}}}', true));
493
- $this->projects = new Google_ProjectsServiceResource($this, $this->serviceName, 'projects', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"type": "integer", "location": "query", "format": "uint32"}}, "response": {"$ref": "ProjectList"}, "httpMethod": "GET", "path": "projects", "id": "bigquery.projects.list"}}}', true));
494
-
495
- }
496
- }
497
-
498
- class Google_Dataset extends Google_Model {
499
- public $kind;
500
- public $description;
501
- protected $__datasetReferenceType = 'Google_DatasetReference';
502
- protected $__datasetReferenceDataType = '';
503
- public $datasetReference;
504
- public $creationTime;
505
- protected $__accessType = 'Google_DatasetAccess';
506
- protected $__accessDataType = 'array';
507
- public $access;
508
- public $etag;
509
- public $friendlyName;
510
- public $lastModifiedTime;
511
- public $id;
512
- public $selfLink;
513
- public function setKind($kind) {
514
- $this->kind = $kind;
515
- }
516
- public function getKind() {
517
- return $this->kind;
518
- }
519
- public function setDescription($description) {
520
- $this->description = $description;
521
- }
522
- public function getDescription() {
523
- return $this->description;
524
- }
525
- public function setDatasetReference(Google_DatasetReference $datasetReference) {
526
- $this->datasetReference = $datasetReference;
527
- }
528
- public function getDatasetReference() {
529
- return $this->datasetReference;
530
- }
531
- public function setCreationTime($creationTime) {
532
- $this->creationTime = $creationTime;
533
- }
534
- public function getCreationTime() {
535
- return $this->creationTime;
536
- }
537
- public function setAccess(/* array(Google_DatasetAccess) */ $access) {
538
- $this->assertIsArray($access, 'Google_DatasetAccess', __METHOD__);
539
- $this->access = $access;
540
- }
541
- public function getAccess() {
542
- return $this->access;
543
- }
544
- public function setEtag($etag) {
545
- $this->etag = $etag;
546
- }
547
- public function getEtag() {
548
- return $this->etag;
549
- }
550
- public function setFriendlyName($friendlyName) {
551
- $this->friendlyName = $friendlyName;
552
- }
553
- public function getFriendlyName() {
554
- return $this->friendlyName;
555
- }
556
- public function setLastModifiedTime($lastModifiedTime) {
557
- $this->lastModifiedTime = $lastModifiedTime;
558
- }
559
- public function getLastModifiedTime() {
560
- return $this->lastModifiedTime;
561
- }
562
- public function setId($id) {
563
- $this->id = $id;
564
- }
565
- public function getId() {
566
- return $this->id;
567
- }
568
- public function setSelfLink($selfLink) {
569
- $this->selfLink = $selfLink;
570
- }
571
- public function getSelfLink() {
572
- return $this->selfLink;
573
- }
574
- }
575
-
576
- class Google_DatasetAccess extends Google_Model {
577
- public $specialGroup;
578
- public $domain;
579
- public $role;
580
- public $groupByEmail;
581
- public $userByEmail;
582
- public function setSpecialGroup($specialGroup) {
583
- $this->specialGroup = $specialGroup;
584
- }
585
- public function getSpecialGroup() {
586
- return $this->specialGroup;
587
- }
588
- public function setDomain($domain) {
589
- $this->domain = $domain;
590
- }
591
- public function getDomain() {
592
- return $this->domain;
593
- }
594
- public function setRole($role) {
595
- $this->role = $role;
596
- }
597
- public function getRole() {
598
- return $this->role;
599
- }
600
- public function setGroupByEmail($groupByEmail) {
601
- $this->groupByEmail = $groupByEmail;
602
- }
603
- public function getGroupByEmail() {
604
- return $this->groupByEmail;
605
- }
606
- public function setUserByEmail($userByEmail) {
607
- $this->userByEmail = $userByEmail;
608
- }
609
- public function getUserByEmail() {
610
- return $this->userByEmail;
611
- }
612
- }
613
-
614
- class Google_DatasetList extends Google_Model {
615
- public $nextPageToken;
616
- public $kind;
617
- protected $__datasetsType = 'Google_DatasetListDatasets';
618
- protected $__datasetsDataType = 'array';
619
- public $datasets;
620
- public $etag;
621
- public function setNextPageToken($nextPageToken) {
622
- $this->nextPageToken = $nextPageToken;
623
- }
624
- public function getNextPageToken() {
625
- return $this->nextPageToken;
626
- }
627
- public function setKind($kind) {
628
- $this->kind = $kind;
629
- }
630
- public function getKind() {
631
- return $this->kind;
632
- }
633
- public function setDatasets(/* array(Google_DatasetListDatasets) */ $datasets) {
634
- $this->assertIsArray($datasets, 'Google_DatasetListDatasets', __METHOD__);
635
- $this->datasets = $datasets;
636
- }
637
- public function getDatasets() {
638
- return $this->datasets;
639
- }
640
- public function setEtag($etag) {
641
- $this->etag = $etag;
642
- }
643
- public function getEtag() {
644
- return $this->etag;
645
- }
646
- }
647
-
648
- class Google_DatasetListDatasets extends Google_Model {
649
- public $friendlyName;
650
- public $kind;
651
- public $id;
652
- protected $__datasetReferenceType = 'Google_DatasetReference';
653
- protected $__datasetReferenceDataType = '';
654
- public $datasetReference;
655
- public function setFriendlyName($friendlyName) {
656
- $this->friendlyName = $friendlyName;
657
- }
658
- public function getFriendlyName() {
659
- return $this->friendlyName;
660
- }
661
- public function setKind($kind) {
662
- $this->kind = $kind;
663
- }
664
- public function getKind() {
665
- return $this->kind;
666
- }
667
- public function setId($id) {
668
- $this->id = $id;
669
- }
670
- public function getId() {
671
- return $this->id;
672
- }
673
- public function setDatasetReference(Google_DatasetReference $datasetReference) {
674
- $this->datasetReference = $datasetReference;
675
- }
676
- public function getDatasetReference() {
677
- return $this->datasetReference;
678
- }
679
- }
680
-
681
- class Google_DatasetReference extends Google_Model {
682
- public $projectId;
683
- public $datasetId;
684
- public function setProjectId($projectId) {
685
- $this->projectId = $projectId;
686
- }
687
- public function getProjectId() {
688
- return $this->projectId;
689
- }
690
- public function setDatasetId($datasetId) {
691
- $this->datasetId = $datasetId;
692
- }
693
- public function getDatasetId() {
694
- return $this->datasetId;
695
- }
696
- }
697
-
698
- class Google_ErrorProto extends Google_Model {
699
- public $debugInfo;
700
- public $message;
701
- public $reason;
702
- public $location;
703
- public function setDebugInfo($debugInfo) {
704
- $this->debugInfo = $debugInfo;
705
- }
706
- public function getDebugInfo() {
707
- return $this->debugInfo;
708
- }
709
- public function setMessage($message) {
710
- $this->message = $message;
711
- }
712
- public function getMessage() {
713
- return $this->message;
714
- }
715
- public function setReason($reason) {
716
- $this->reason = $reason;
717
- }
718
- public function getReason() {
719
- return $this->reason;
720
- }
721
- public function setLocation($location) {
722
- $this->location = $location;
723
- }
724
- public function getLocation() {
725
- return $this->location;
726
- }
727
- }
728
-
729
- class Google_GetQueryResultsResponse extends Google_Model {
730
- public $kind;
731
- protected $__rowsType = 'Google_TableRow';
732
- protected $__rowsDataType = 'array';
733
- public $rows;
734
- protected $__jobReferenceType = 'Google_JobReference';
735
- protected $__jobReferenceDataType = '';
736
- public $jobReference;
737
- public $jobComplete;
738
- public $totalRows;
739
- public $etag;
740
- protected $__schemaType = 'Google_TableSchema';
741
- protected $__schemaDataType = '';
742
- public $schema;
743
- public function setKind($kind) {
744
- $this->kind = $kind;
745
- }
746
- public function getKind() {
747
- return $this->kind;
748
- }
749
- public function setRows(/* array(Google_TableRow) */ $rows) {
750
- $this->assertIsArray($rows, 'Google_TableRow', __METHOD__);
751
- $this->rows = $rows;
752
- }
753
- public function getRows() {
754
- return $this->rows;
755
- }
756
- public function setJobReference(Google_JobReference $jobReference) {
757
- $this->jobReference = $jobReference;
758
- }
759
- public function getJobReference() {
760
- return $this->jobReference;
761
- }
762
- public function setJobComplete($jobComplete) {
763
- $this->jobComplete = $jobComplete;
764
- }
765
- public function getJobComplete() {
766
- return $this->jobComplete;
767
- }
768
- public function setTotalRows($totalRows) {
769
- $this->totalRows = $totalRows;
770
- }
771
- public function getTotalRows() {
772
- return $this->totalRows;
773
- }
774
- public function setEtag($etag) {
775
- $this->etag = $etag;
776
- }
777
- public function getEtag() {
778
- return $this->etag;
779
- }
780
- public function setSchema(Google_TableSchema $schema) {
781
- $this->schema = $schema;
782
- }
783
- public function getSchema() {
784
- return $this->schema;
785
- }
786
- }
787
-
788
- class Google_Job extends Google_Model {
789
- protected $__statusType = 'Google_JobStatus';
790
- protected $__statusDataType = '';
791
- public $status;
792
- public $kind;
793
- protected $__statisticsType = 'Google_JobStatistics';
794
- protected $__statisticsDataType = '';
795
- public $statistics;
796
- protected $__jobReferenceType = 'Google_JobReference';
797
- protected $__jobReferenceDataType = '';
798
- public $jobReference;
799
- public $etag;
800
- protected $__configurationType = 'Google_JobConfiguration';
801
- protected $__configurationDataType = '';
802
- public $configuration;
803
- public $id;
804
- public $selfLink;
805
- public function setStatus(Google_JobStatus $status) {
806
- $this->status = $status;
807
- }
808
- public function getStatus() {
809
- return $this->status;
810
- }
811
- public function setKind($kind) {
812
- $this->kind = $kind;
813
- }
814
- public function getKind() {
815
- return $this->kind;
816
- }
817
- public function setStatistics(Google_JobStatistics $statistics) {
818
- $this->statistics = $statistics;
819
- }
820
- public function getStatistics() {
821
- return $this->statistics;
822
- }
823
- public function setJobReference(Google_JobReference $jobReference) {
824
- $this->jobReference = $jobReference;
825
- }
826
- public function getJobReference() {
827
- return $this->jobReference;
828
- }
829
- public function setEtag($etag) {
830
- $this->etag = $etag;
831
- }
832
- public function getEtag() {
833
- return $this->etag;
834
- }
835
- public function setConfiguration(Google_JobConfiguration $configuration) {
836
- $this->configuration = $configuration;
837
- }
838
- public function getConfiguration() {
839
- return $this->configuration;
840
- }
841
- public function setId($id) {
842
- $this->id = $id;
843
- }
844
- public function getId() {
845
- return $this->id;
846
- }
847
- public function setSelfLink($selfLink) {
848
- $this->selfLink = $selfLink;
849
- }
850
- public function getSelfLink() {
851
- return $this->selfLink;
852
- }
853
- }
854
-
855
- class Google_JobConfiguration extends Google_Model {
856
- protected $__loadType = 'Google_JobConfigurationLoad';
857
- protected $__loadDataType = '';
858
- public $load;
859
- protected $__linkType = 'Google_JobConfigurationLink';
860
- protected $__linkDataType = '';
861
- public $link;
862
- protected $__queryType = 'Google_JobConfigurationQuery';
863
- protected $__queryDataType = '';
864
- public $query;
865
- protected $__copyType = 'Google_JobConfigurationTableCopy';
866
- protected $__copyDataType = '';
867
- public $copy;
868
- protected $__extractType = 'Google_JobConfigurationExtract';
869
- protected $__extractDataType = '';
870
- public $extract;
871
- public $properties;
872
- public function setLoad(Google_JobConfigurationLoad $load) {
873
- $this->load = $load;
874
- }
875
- public function getLoad() {
876
- return $this->load;
877
- }
878
- public function setLink(Google_JobConfigurationLink $link) {
879
- $this->link = $link;
880
- }
881
- public function getLink() {
882
- return $this->link;
883
- }
884
- public function setQuery(Google_JobConfigurationQuery $query) {
885
- $this->query = $query;
886
- }
887
- public function getQuery() {
888
- return $this->query;
889
- }
890
- public function setCopy(Google_JobConfigurationTableCopy $copy) {
891
- $this->copy = $copy;
892
- }
893
- public function getCopy() {
894
- return $this->copy;
895
- }
896
- public function setExtract(Google_JobConfigurationExtract $extract) {
897
- $this->extract = $extract;
898
- }
899
- public function getExtract() {
900
- return $this->extract;
901
- }
902
- public function setProperties($properties) {
903
- $this->properties = $properties;
904
- }
905
- public function getProperties() {
906
- return $this->properties;
907
- }
908
- }
909
-
910
- class Google_JobConfigurationExtract extends Google_Model {
911
- public $destinationUri;
912
- public $fieldDelimiter;
913
- protected $__sourceTableType = 'Google_TableReference';
914
- protected $__sourceTableDataType = '';
915
- public $sourceTable;
916
- public $printHeader;
917
- public function setDestinationUri($destinationUri) {
918
- $this->destinationUri = $destinationUri;
919
- }
920
- public function getDestinationUri() {
921
- return $this->destinationUri;
922
- }
923
- public function setFieldDelimiter($fieldDelimiter) {
924
- $this->fieldDelimiter = $fieldDelimiter;
925
- }
926
- public function getFieldDelimiter() {
927
- return $this->fieldDelimiter;
928
- }
929
- public function setSourceTable(Google_TableReference $sourceTable) {
930
- $this->sourceTable = $sourceTable;
931
- }
932
- public function getSourceTable() {
933
- return $this->sourceTable;
934
- }
935
- public function setPrintHeader($printHeader) {
936
- $this->printHeader = $printHeader;
937
- }
938
- public function getPrintHeader() {
939
- return $this->printHeader;
940
- }
941
- }
942
-
943
- class Google_JobConfigurationLink extends Google_Model {
944
- public $createDisposition;
945
- public $writeDisposition;
946
- protected $__destinationTableType = 'Google_TableReference';
947
- protected $__destinationTableDataType = '';
948
- public $destinationTable;
949
- public $sourceUri;
950
- public function setCreateDisposition($createDisposition) {
951
- $this->createDisposition = $createDisposition;
952
- }
953
- public function getCreateDisposition() {
954
- return $this->createDisposition;
955
- }
956
- public function setWriteDisposition($writeDisposition) {
957
- $this->writeDisposition = $writeDisposition;
958
- }
959
- public function getWriteDisposition() {
960
- return $this->writeDisposition;
961
- }
962
- public function setDestinationTable(Google_TableReference $destinationTable) {
963
- $this->destinationTable = $destinationTable;
964
- }
965
- public function getDestinationTable() {
966
- return $this->destinationTable;
967
- }
968
- public function setSourceUri(/* array(Google_string) */ $sourceUri) {
969
- $this->assertIsArray($sourceUri, 'Google_string', __METHOD__);
970
- $this->sourceUri = $sourceUri;
971
- }
972
- public function getSourceUri() {
973
- return $this->sourceUri;
974
- }
975
- }
976
-
977
- class Google_JobConfigurationLoad extends Google_Model {
978
- public $encoding;
979
- public $fieldDelimiter;
980
- protected $__destinationTableType = 'Google_TableReference';
981
- protected $__destinationTableDataType = '';
982
- public $destinationTable;
983
- public $writeDisposition;
984
- public $maxBadRecords;
985
- public $skipLeadingRows;
986
- public $sourceUris;
987
- public $quote;
988
- public $createDisposition;
989
- public $schemaInlineFormat;
990
- public $schemaInline;
991
- protected $__schemaType = 'Google_TableSchema';
992
- protected $__schemaDataType = '';
993
- public $schema;
994
- public function setEncoding($encoding) {
995
- $this->encoding = $encoding;
996
- }
997
- public function getEncoding() {
998
- return $this->encoding;
999
- }
1000
- public function setFieldDelimiter($fieldDelimiter) {
1001
- $this->fieldDelimiter = $fieldDelimiter;
1002
- }
1003
- public function getFieldDelimiter() {
1004
- return $this->fieldDelimiter;
1005
- }
1006
- public function setDestinationTable(Google_TableReference $destinationTable) {
1007
- $this->destinationTable = $destinationTable;
1008
- }
1009
- public function getDestinationTable() {
1010
- return $this->destinationTable;
1011
- }
1012
- public function setWriteDisposition($writeDisposition) {
1013
- $this->writeDisposition = $writeDisposition;
1014
- }
1015
- public function getWriteDisposition() {
1016
- return $this->writeDisposition;
1017
- }
1018
- public function setMaxBadRecords($maxBadRecords) {
1019
- $this->maxBadRecords = $maxBadRecords;
1020
- }
1021
- public function getMaxBadRecords() {
1022
- return $this->maxBadRecords;
1023
- }
1024
- public function setSkipLeadingRows($skipLeadingRows) {
1025
- $this->skipLeadingRows = $skipLeadingRows;
1026
- }
1027
- public function getSkipLeadingRows() {
1028
- return $this->skipLeadingRows;
1029
- }
1030
- public function setSourceUris(/* array(Google_string) */ $sourceUris) {
1031
- $this->assertIsArray($sourceUris, 'Google_string', __METHOD__);
1032
- $this->sourceUris = $sourceUris;
1033
- }
1034
- public function getSourceUris() {
1035
- return $this->sourceUris;
1036
- }
1037
- public function setQuote($quote) {
1038
- $this->quote = $quote;
1039
- }
1040
- public function getQuote() {
1041
- return $this->quote;
1042
- }
1043
- public function setCreateDisposition($createDisposition) {
1044
- $this->createDisposition = $createDisposition;
1045
- }
1046
- public function getCreateDisposition() {
1047
- return $this->createDisposition;
1048
- }
1049
- public function setSchemaInlineFormat($schemaInlineFormat) {
1050
- $this->schemaInlineFormat = $schemaInlineFormat;
1051
- }
1052
- public function getSchemaInlineFormat() {
1053
- return $this->schemaInlineFormat;
1054
- }
1055
- public function setSchemaInline($schemaInline) {
1056
- $this->schemaInline = $schemaInline;
1057
- }
1058
- public function getSchemaInline() {
1059
- return $this->schemaInline;
1060
- }
1061
- public function setSchema(Google_TableSchema $schema) {
1062
- $this->schema = $schema;
1063
- }
1064
- public function getSchema() {
1065
- return $this->schema;
1066
- }
1067
- }
1068
-
1069
- class Google_JobConfigurationQuery extends Google_Model {
1070
- protected $__defaultDatasetType = 'Google_DatasetReference';
1071
- protected $__defaultDatasetDataType = '';
1072
- public $defaultDataset;
1073
- protected $__destinationTableType = 'Google_TableReference';
1074
- protected $__destinationTableDataType = '';
1075
- public $destinationTable;
1076
- public $priority;
1077
- public $writeDisposition;
1078
- public $createDisposition;
1079
- public $query;
1080
- public function setDefaultDataset(Google_DatasetReference $defaultDataset) {
1081
- $this->defaultDataset = $defaultDataset;
1082
- }
1083
- public function getDefaultDataset() {
1084
- return $this->defaultDataset;
1085
- }
1086
- public function setDestinationTable(Google_TableReference $destinationTable) {
1087
- $this->destinationTable = $destinationTable;
1088
- }
1089
- public function getDestinationTable() {
1090
- return $this->destinationTable;
1091
- }
1092
- public function setPriority($priority) {
1093
- $this->priority = $priority;
1094
- }
1095
- public function getPriority() {
1096
- return $this->priority;
1097
- }
1098
- public function setWriteDisposition($writeDisposition) {
1099
- $this->writeDisposition = $writeDisposition;
1100
- }
1101
- public function getWriteDisposition() {
1102
- return $this->writeDisposition;
1103
- }
1104
- public function setCreateDisposition($createDisposition) {
1105
- $this->createDisposition = $createDisposition;
1106
- }
1107
- public function getCreateDisposition() {
1108
- return $this->createDisposition;
1109
- }
1110
- public function setQuery($query) {
1111
- $this->query = $query;
1112
- }
1113
- public function getQuery() {
1114
- return $this->query;
1115
- }
1116
- }
1117
-
1118
- class Google_JobConfigurationTableCopy extends Google_Model {
1119
- public $createDisposition;
1120
- public $writeDisposition;
1121
- protected $__destinationTableType = 'Google_TableReference';
1122
- protected $__destinationTableDataType = '';
1123
- public $destinationTable;
1124
- protected $__sourceTableType = 'Google_TableReference';
1125
- protected $__sourceTableDataType = '';
1126
- public $sourceTable;
1127
- public function setCreateDisposition($createDisposition) {
1128
- $this->createDisposition = $createDisposition;
1129
- }
1130
- public function getCreateDisposition() {
1131
- return $this->createDisposition;
1132
- }
1133
- public function setWriteDisposition($writeDisposition) {
1134
- $this->writeDisposition = $writeDisposition;
1135
- }
1136
- public function getWriteDisposition() {
1137
- return $this->writeDisposition;
1138
- }
1139
- public function setDestinationTable(Google_TableReference $destinationTable) {
1140
- $this->destinationTable = $destinationTable;
1141
- }
1142
- public function getDestinationTable() {
1143
- return $this->destinationTable;
1144
- }
1145
- public function setSourceTable(Google_TableReference $sourceTable) {
1146
- $this->sourceTable = $sourceTable;
1147
- }
1148
- public function getSourceTable() {
1149
- return $this->sourceTable;
1150
- }
1151
- }
1152
-
1153
- class Google_JobList extends Google_Model {
1154
- public $nextPageToken;
1155
- public $totalItems;
1156
- public $kind;
1157
- public $etag;
1158
- protected $__jobsType = 'Google_JobListJobs';
1159
- protected $__jobsDataType = 'array';
1160
- public $jobs;
1161
- public function setNextPageToken($nextPageToken) {
1162
- $this->nextPageToken = $nextPageToken;
1163
- }
1164
- public function getNextPageToken() {
1165
- return $this->nextPageToken;
1166
- }
1167
- public function setTotalItems($totalItems) {
1168
- $this->totalItems = $totalItems;
1169
- }
1170
- public function getTotalItems() {
1171
- return $this->totalItems;
1172
- }
1173
- public function setKind($kind) {
1174
- $this->kind = $kind;
1175
- }
1176
- public function getKind() {
1177
- return $this->kind;
1178
- }
1179
- public function setEtag($etag) {
1180
- $this->etag = $etag;
1181
- }
1182
- public function getEtag() {
1183
- return $this->etag;
1184
- }
1185
- public function setJobs(/* array(Google_JobListJobs) */ $jobs) {
1186
- $this->assertIsArray($jobs, 'Google_JobListJobs', __METHOD__);
1187
- $this->jobs = $jobs;
1188
- }
1189
- public function getJobs() {
1190
- return $this->jobs;
1191
- }
1192
- }
1193
-
1194
- class Google_JobListJobs extends Google_Model {
1195
- protected $__statusType = 'Google_JobStatus';
1196
- protected $__statusDataType = '';
1197
- public $status;
1198
- public $kind;
1199
- protected $__statisticsType = 'Google_JobStatistics';
1200
- protected $__statisticsDataType = '';
1201
- public $statistics;
1202
- protected $__jobReferenceType = 'Google_JobReference';
1203
- protected $__jobReferenceDataType = '';
1204
- public $jobReference;
1205
- public $state;
1206
- protected $__configurationType = 'Google_JobConfiguration';
1207
- protected $__configurationDataType = '';
1208
- public $configuration;
1209
- public $id;
1210
- protected $__errorResultType = 'Google_ErrorProto';
1211
- protected $__errorResultDataType = '';
1212
- public $errorResult;
1213
- public function setStatus(Google_JobStatus $status) {
1214
- $this->status = $status;
1215
- }
1216
- public function getStatus() {
1217
- return $this->status;
1218
- }
1219
- public function setKind($kind) {
1220
- $this->kind = $kind;
1221
- }
1222
- public function getKind() {
1223
- return $this->kind;
1224
- }
1225
- public function setStatistics(Google_JobStatistics $statistics) {
1226
- $this->statistics = $statistics;
1227
- }
1228
- public function getStatistics() {
1229
- return $this->statistics;
1230
- }
1231
- public function setJobReference(Google_JobReference $jobReference) {
1232
- $this->jobReference = $jobReference;
1233
- }
1234
- public function getJobReference() {
1235
- return $this->jobReference;
1236
- }
1237
- public function setState($state) {
1238
- $this->state = $state;
1239
- }
1240
- public function getState() {
1241
- return $this->state;
1242
- }
1243
- public function setConfiguration(Google_JobConfiguration $configuration) {
1244
- $this->configuration = $configuration;
1245
- }
1246
- public function getConfiguration() {
1247
- return $this->configuration;
1248
- }
1249
- public function setId($id) {
1250
- $this->id = $id;
1251
- }
1252
- public function getId() {
1253
- return $this->id;
1254
- }
1255
- public function setErrorResult(Google_ErrorProto $errorResult) {
1256
- $this->errorResult = $errorResult;
1257
- }
1258
- public function getErrorResult() {
1259
- return $this->errorResult;
1260
- }
1261
- }
1262
-
1263
- class Google_JobReference extends Google_Model {
1264
- public $projectId;
1265
- public $jobId;
1266
- public function setProjectId($projectId) {
1267
- $this->projectId = $projectId;
1268
- }
1269
- public function getProjectId() {
1270
- return $this->projectId;
1271
- }
1272
- public function setJobId($jobId) {
1273
- $this->jobId = $jobId;
1274
- }
1275
- public function getJobId() {
1276
- return $this->jobId;
1277
- }
1278
- }
1279
-
1280
- class Google_JobStatistics extends Google_Model {
1281
- public $endTime;
1282
- public $totalBytesProcessed;
1283
- public $startTime;
1284
- public function setEndTime($endTime) {
1285
- $this->endTime = $endTime;
1286
- }
1287
- public function getEndTime() {
1288
- return $this->endTime;
1289
- }
1290
- public function setTotalBytesProcessed($totalBytesProcessed) {
1291
- $this->totalBytesProcessed = $totalBytesProcessed;
1292
- }
1293
- public function getTotalBytesProcessed() {
1294
- return $this->totalBytesProcessed;
1295
- }
1296
- public function setStartTime($startTime) {
1297
- $this->startTime = $startTime;
1298
- }
1299
- public function getStartTime() {
1300
- return $this->startTime;
1301
- }
1302
- }
1303
-
1304
- class Google_JobStatus extends Google_Model {
1305
- public $state;
1306
- protected $__errorsType = 'Google_ErrorProto';
1307
- protected $__errorsDataType = 'array';
1308
- public $errors;
1309
- protected $__errorResultType = 'Google_ErrorProto';
1310
- protected $__errorResultDataType = '';
1311
- public $errorResult;
1312
- public function setState($state) {
1313
- $this->state = $state;
1314
- }
1315
- public function getState() {
1316
- return $this->state;
1317
- }
1318
- public function setErrors(/* array(Google_ErrorProto) */ $errors) {
1319
- $this->assertIsArray($errors, 'Google_ErrorProto', __METHOD__);
1320
- $this->errors = $errors;
1321
- }
1322
- public function getErrors() {
1323
- return $this->errors;
1324
- }
1325
- public function setErrorResult(Google_ErrorProto $errorResult) {
1326
- $this->errorResult = $errorResult;
1327
- }
1328
- public function getErrorResult() {
1329
- return $this->errorResult;
1330
- }
1331
- }
1332
-
1333
- class Google_ProjectList extends Google_Model {
1334
- public $nextPageToken;
1335
- public $totalItems;
1336
- public $kind;
1337
- public $etag;
1338
- protected $__projectsType = 'Google_ProjectListProjects';
1339
- protected $__projectsDataType = 'array';
1340
- public $projects;
1341
- public function setNextPageToken($nextPageToken) {
1342
- $this->nextPageToken = $nextPageToken;
1343
- }
1344
- public function getNextPageToken() {
1345
- return $this->nextPageToken;
1346
- }
1347
- public function setTotalItems($totalItems) {
1348
- $this->totalItems = $totalItems;
1349
- }
1350
- public function getTotalItems() {
1351
- return $this->totalItems;
1352
- }
1353
- public function setKind($kind) {
1354
- $this->kind = $kind;
1355
- }
1356
- public function getKind() {
1357
- return $this->kind;
1358
- }
1359
- public function setEtag($etag) {
1360
- $this->etag = $etag;
1361
- }
1362
- public function getEtag() {
1363
- return $this->etag;
1364
- }
1365
- public function setProjects(/* array(Google_ProjectListProjects) */ $projects) {
1366
- $this->assertIsArray($projects, 'Google_ProjectListProjects', __METHOD__);
1367
- $this->projects = $projects;
1368
- }
1369
- public function getProjects() {
1370
- return $this->projects;
1371
- }
1372
- }
1373
-
1374
- class Google_ProjectListProjects extends Google_Model {
1375
- public $friendlyName;
1376
- public $kind;
1377
- public $id;
1378
- protected $__projectReferenceType = 'Google_ProjectReference';
1379
- protected $__projectReferenceDataType = '';
1380
- public $projectReference;
1381
- public function setFriendlyName($friendlyName) {
1382
- $this->friendlyName = $friendlyName;
1383
- }
1384
- public function getFriendlyName() {
1385
- return $this->friendlyName;
1386
- }
1387
- public function setKind($kind) {
1388
- $this->kind = $kind;
1389
- }
1390
- public function getKind() {
1391
- return $this->kind;
1392
- }
1393
- public function setId($id) {
1394
- $this->id = $id;
1395
- }
1396
- public function getId() {
1397
- return $this->id;
1398
- }
1399
- public function setProjectReference(Google_ProjectReference $projectReference) {
1400
- $this->projectReference = $projectReference;
1401
- }
1402
- public function getProjectReference() {
1403
- return $this->projectReference;
1404
- }
1405
- }
1406
-
1407
- class Google_ProjectReference extends Google_Model {
1408
- public $projectId;
1409
- public function setProjectId($projectId) {
1410
- $this->projectId = $projectId;
1411
- }
1412
- public function getProjectId() {
1413
- return $this->projectId;
1414
- }
1415
- }
1416
-
1417
- class Google_QueryRequest extends Google_Model {
1418
- public $timeoutMs;
1419
- public $kind;
1420
- public $dryRun;
1421
- protected $__defaultDatasetType = 'Google_DatasetReference';
1422
- protected $__defaultDatasetDataType = '';
1423
- public $defaultDataset;
1424
- public $maxResults;
1425
- public $query;
1426
- public function setTimeoutMs($timeoutMs) {
1427
- $this->timeoutMs = $timeoutMs;
1428
- }
1429
- public function getTimeoutMs() {
1430
- return $this->timeoutMs;
1431
- }
1432
- public function setKind($kind) {
1433
- $this->kind = $kind;
1434
- }
1435
- public function getKind() {
1436
- return $this->kind;
1437
- }
1438
- public function setDryRun($dryRun) {
1439
- $this->dryRun = $dryRun;
1440
- }
1441
- public function getDryRun() {
1442
- return $this->dryRun;
1443
- }
1444
- public function setDefaultDataset(Google_DatasetReference $defaultDataset) {
1445
- $this->defaultDataset = $defaultDataset;
1446
- }
1447
- public function getDefaultDataset() {
1448
- return $this->defaultDataset;
1449
- }
1450
- public function setMaxResults($maxResults) {
1451
- $this->maxResults = $maxResults;
1452
- }
1453
- public function getMaxResults() {
1454
- return $this->maxResults;
1455
- }
1456
- public function setQuery($query) {
1457
- $this->query = $query;
1458
- }
1459
- public function getQuery() {
1460
- return $this->query;
1461
- }
1462
- }
1463
-
1464
- class Google_QueryResponse extends Google_Model {
1465
- public $kind;
1466
- protected $__rowsType = 'Google_TableRow';
1467
- protected $__rowsDataType = 'array';
1468
- public $rows;
1469
- protected $__jobReferenceType = 'Google_JobReference';
1470
- protected $__jobReferenceDataType = '';
1471
- public $jobReference;
1472
- public $jobComplete;
1473
- public $totalRows;
1474
- protected $__schemaType = 'Google_TableSchema';
1475
- protected $__schemaDataType = '';
1476
- public $schema;
1477
- public function setKind($kind) {
1478
- $this->kind = $kind;
1479
- }
1480
- public function getKind() {
1481
- return $this->kind;
1482
- }
1483
- public function setRows(/* array(Google_TableRow) */ $rows) {
1484
- $this->assertIsArray($rows, 'Google_TableRow', __METHOD__);
1485
- $this->rows = $rows;
1486
- }
1487
- public function getRows() {
1488
- return $this->rows;
1489
- }
1490
- public function setJobReference(Google_JobReference $jobReference) {
1491
- $this->jobReference = $jobReference;
1492
- }
1493
- public function getJobReference() {
1494
- return $this->jobReference;
1495
- }
1496
- public function setJobComplete($jobComplete) {
1497
- $this->jobComplete = $jobComplete;
1498
- }
1499
- public function getJobComplete() {
1500
- return $this->jobComplete;
1501
- }
1502
- public function setTotalRows($totalRows) {
1503
- $this->totalRows = $totalRows;
1504
- }
1505
- public function getTotalRows() {
1506
- return $this->totalRows;
1507
- }
1508
- public function setSchema(Google_TableSchema $schema) {
1509
- $this->schema = $schema;
1510
- }
1511
- public function getSchema() {
1512
- return $this->schema;
1513
- }
1514
- }
1515
-
1516
- class Google_Table extends Google_Model {
1517
- public $kind;
1518
- public $lastModifiedTime;
1519
- public $description;
1520
- public $creationTime;
1521
- protected $__tableReferenceType = 'Google_TableReference';
1522
- protected $__tableReferenceDataType = '';
1523
- public $tableReference;
1524
- public $numRows;
1525
- public $numBytes;
1526
- public $etag;
1527
- public $friendlyName;
1528
- public $expirationTime;
1529
- public $id;
1530
- public $selfLink;
1531
- protected $__schemaType = 'Google_TableSchema';
1532
- protected $__schemaDataType = '';
1533
- public $schema;
1534
- public function setKind($kind) {
1535
- $this->kind = $kind;
1536
- }
1537
- public function getKind() {
1538
- return $this->kind;
1539
- }
1540
- public function setLastModifiedTime($lastModifiedTime) {
1541
- $this->lastModifiedTime = $lastModifiedTime;
1542
- }
1543
- public function getLastModifiedTime() {
1544
- return $this->lastModifiedTime;
1545
- }
1546
- public function setDescription($description) {
1547
- $this->description = $description;
1548
- }
1549
- public function getDescription() {
1550
- return $this->description;
1551
- }
1552
- public function setCreationTime($creationTime) {
1553
- $this->creationTime = $creationTime;
1554
- }
1555
- public function getCreationTime() {
1556
- return $this->creationTime;
1557
- }
1558
- public function setTableReference(Google_TableReference $tableReference) {
1559
- $this->tableReference = $tableReference;
1560
- }
1561
- public function getTableReference() {
1562
- return $this->tableReference;
1563
- }
1564
- public function setNumRows($numRows) {
1565
- $this->numRows = $numRows;
1566
- }
1567
- public function getNumRows() {
1568
- return $this->numRows;
1569
- }
1570
- public function setNumBytes($numBytes) {
1571
- $this->numBytes = $numBytes;
1572
- }
1573
- public function getNumBytes() {
1574
- return $this->numBytes;
1575
- }
1576
- public function setEtag($etag) {
1577
- $this->etag = $etag;
1578
- }
1579
- public function getEtag() {
1580
- return $this->etag;
1581
- }
1582
- public function setFriendlyName($friendlyName) {
1583
- $this->friendlyName = $friendlyName;
1584
- }
1585
- public function getFriendlyName() {
1586
- return $this->friendlyName;
1587
- }
1588
- public function setExpirationTime($expirationTime) {
1589
- $this->expirationTime = $expirationTime;
1590
- }
1591
- public function getExpirationTime() {
1592
- return $this->expirationTime;
1593
- }
1594
- public function setId($id) {
1595
- $this->id = $id;
1596
- }
1597
- public function getId() {
1598
- return $this->id;
1599
- }
1600
- public function setSelfLink($selfLink) {
1601
- $this->selfLink = $selfLink;
1602
- }
1603
- public function getSelfLink() {
1604
- return $this->selfLink;
1605
- }
1606
- public function setSchema(Google_TableSchema $schema) {
1607
- $this->schema = $schema;
1608
- }
1609
- public function getSchema() {
1610
- return $this->schema;
1611
- }
1612
- }
1613
-
1614
- class Google_TableDataList extends Google_Model {
1615
- public $pageToken;
1616
- public $kind;
1617
- public $etag;
1618
- protected $__rowsType = 'Google_TableRow';
1619
- protected $__rowsDataType = 'array';
1620
- public $rows;
1621
- public $totalRows;
1622
- public function setPageToken($pageToken) {
1623
- $this->pageToken = $pageToken;
1624
- }
1625
- public function getPageToken() {
1626
- return $this->pageToken;
1627
- }
1628
- public function setKind($kind) {
1629
- $this->kind = $kind;
1630
- }
1631
- public function getKind() {
1632
- return $this->kind;
1633
- }
1634
- public function setEtag($etag) {
1635
- $this->etag = $etag;
1636
- }
1637
- public function getEtag() {
1638
- return $this->etag;
1639
- }
1640
- public function setRows(/* array(Google_TableRow) */ $rows) {
1641
- $this->assertIsArray($rows, 'Google_TableRow', __METHOD__);
1642
- $this->rows = $rows;
1643
- }
1644
- public function getRows() {
1645
- return $this->rows;
1646
- }
1647
- public function setTotalRows($totalRows) {
1648
- $this->totalRows = $totalRows;
1649
- }
1650
- public function getTotalRows() {
1651
- return $this->totalRows;
1652
- }
1653
- }
1654
-
1655
- class Google_TableFieldSchema extends Google_Model {
1656
- protected $__fieldsType = 'Google_TableFieldSchema';
1657
- protected $__fieldsDataType = 'array';
1658
- public $fields;
1659
- public $type;
1660
- public $mode;
1661
- public $name;
1662
- public function setFields(/* array(Google_TableFieldSchema) */ $fields) {
1663
- $this->assertIsArray($fields, 'Google_TableFieldSchema', __METHOD__);
1664
- $this->fields = $fields;
1665
- }
1666
- public function getFields() {
1667
- return $this->fields;
1668
- }
1669
- public function setType($type) {
1670
- $this->type = $type;
1671
- }
1672
- public function getType() {
1673
- return $this->t