Import any XML or CSV File to WordPress - Version 3.6.4

Version Description

  • improvement: better sanitization and escaping of data in WP All Import interface
  • improvement: use libraries included in WordPress Core
Download this release

Release Info

Developer soflyy
Plugin Icon 128x128 Import any XML or CSV File to WordPress
Version 3.6.4
Comparing to
See all releases

Code changes from version 3.6.3 to 3.6.4

Files changed (59) hide show
  1. actions/admin_head.php +3 -3
  2. actions/admin_notices.php +2 -2
  3. actions/wp_ajax_dismiss_notifications.php +1 -1
  4. actions/wp_ajax_import_failed.php +2 -2
  5. classes/PHPExcel/Shared/ZipArchive.php +1 -1
  6. classes/api.php +33 -33
  7. classes/render.php +6 -6
  8. classes/upload.php +6 -2
  9. controllers/admin/history.php +1 -1
  10. controllers/admin/import.php +1 -1
  11. controllers/admin/manage.php +4 -4
  12. controllers/admin/settings.php +9 -9
  13. controllers/controller/admin.php +1 -5
  14. helpers/reverse_taxonomies_html.php +1 -1
  15. helpers/wp_all_import_addon_notifications.php +1 -1
  16. helpers/wp_all_import_get_import_id.php +2 -2
  17. helpers/wp_all_import_template_notifications.php +2 -2
  18. helpers/wp_redirect_or_javascript.php +1 -1
  19. libraries/XmlImportCsvParse.php +3 -3
  20. libraries/pclzip.lib.php +0 -5178
  21. plugin.php +7 -5
  22. readme.txt +5 -1
  23. static/codemirror/clike.js +0 -647
  24. static/codemirror/codemirror.css +0 -337
  25. static/codemirror/codemirror.js +0 -8840
  26. static/codemirror/htmlmixed.js +0 -150
  27. static/codemirror/javascript.js +0 -710
  28. static/codemirror/matchbrackets.js +0 -120
  29. static/codemirror/php.js +0 -234
  30. static/codemirror/xml.js +0 -385
  31. static/css/codemirror.css +0 -337
  32. static/js/jquery/moment.js +0 -6
  33. views/admin/addons/index.php +14 -14
  34. views/admin/history/index.php +10 -10
  35. views/admin/home/index.php +0 -16
  36. views/admin/import/element.php +4 -4
  37. views/admin/import/error.php +1 -1
  38. views/admin/import/evaluate_variations.php +1 -1
  39. views/admin/import/index.php +5 -5
  40. views/admin/import/options.php +2 -2
  41. views/admin/import/options/_import_file.php +1 -1
  42. views/admin/import/options/_settings_template.php +5 -5
  43. views/admin/import/preview_images.php +7 -7
  44. views/admin/import/preview_taxonomies.php +3 -3
  45. views/admin/import/process.php +11 -11
  46. views/admin/import/template.php +2 -2
  47. views/admin/import/template/_custom_fields_template.php +10 -10
  48. views/admin/import/template/_featured_template.php +81 -81
  49. views/admin/import/template/_nested_template.php +1 -1
  50. views/admin/import/template/_other_template.php +4 -4
  51. views/admin/import/template/_taxonomies_template.php +68 -68
  52. views/admin/import/warning.php +1 -1
  53. views/admin/manage/delete.php +1 -1
  54. views/admin/manage/index.php +12 -12
  55. views/admin/manage/scheduling.php +4 -4
  56. views/admin/promotion/acf.php +3 -3
  57. views/admin/settings/index.php +1 -1
  58. views/controller/error.php +1 -1
  59. views/controller/warning.php +1 -1
actions/admin_head.php CHANGED
@@ -17,7 +17,7 @@ function pmxi_admin_head(){
17
  if ($get_params['id']){
18
  ?>
19
  <script type="text/javascript">
20
- var import_id = '<?php echo $get_params["id"]; ?>';
21
  </script>
22
  <?php
23
  }
@@ -33,8 +33,8 @@ function pmxi_admin_head(){
33
  ?>
34
  <script type="text/javascript">
35
  var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>';
36
- var import_action = '<?php echo $get_params["action"]; ?>';
37
- var wp_all_import_security = '<?php echo $wp_all_import_ajax_nonce; ?>';
38
  </script>
39
  <?php
40
  }
17
  if ($get_params['id']){
18
  ?>
19
  <script type="text/javascript">
20
+ var import_id = '<?php echo intval($get_params["id"]); ?>';
21
  </script>
22
  <?php
23
  }
33
  ?>
34
  <script type="text/javascript">
35
  var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>';
36
+ var import_action = '<?php echo esc_js($get_params["action"]); ?>';
37
+ var wp_all_import_security = '<?php echo wp_unslash($wp_all_import_ajax_nonce); ?>';
38
  </script>
39
  <?php
40
  }
actions/admin_notices.php CHANGED
@@ -104,7 +104,7 @@ function pmxi_admin_notices() {
104
  foreach ($messages as $type => $m) {
105
  in_array((string)$type, array('updated', 'error')) or $type = 'updated';
106
  ?>
107
- <div class="<?php echo $type ?>"><p><?php echo $m ?></p></div>
108
  <?php
109
  }
110
  }
@@ -131,7 +131,7 @@ function pmxi_admin_notices() {
131
  }
132
  if ($m):
133
  ?>
134
- <div class="error"><p><?php echo $m ?></p></div>
135
  <?php
136
  endif;
137
  }
104
  foreach ($messages as $type => $m) {
105
  in_array((string)$type, array('updated', 'error')) or $type = 'updated';
106
  ?>
107
+ <div class="<?php echo esc_attr($type); ?>"><p><?php echo wp_kses_post($m); ?></p></div>
108
  <?php
109
  }
110
  }
131
  }
132
  if ($m):
133
  ?>
134
+ <div class="error"><p><?php echo wp_kses_post($m); ?></p></div>
135
  <?php
136
  endif;
137
  }
actions/wp_ajax_dismiss_notifications.php CHANGED
@@ -10,7 +10,7 @@ function pmxi_wp_ajax_dismiss_notifications(){
10
  }
11
 
12
  if (isset($_POST['addon']) ) {
13
- update_option($_POST['addon'] . '_notice_ignore', 'true', false);
14
  }
15
  exit( json_encode( array('result' => true)));
16
  }
10
  }
11
 
12
  if (isset($_POST['addon']) ) {
13
+ update_option(sanitize_key($_POST['addon']) . '_notice_ignore', 'true', false);
14
  }
15
  exit( json_encode( array('result' => true)));
16
  }
actions/wp_ajax_import_failed.php CHANGED
@@ -12,7 +12,7 @@ function pmxi_wp_ajax_import_failed(){
12
  $result = false;
13
  if (!empty($_POST['id'])) {
14
  $import = new PMXI_Import_record();
15
- $import->getbyId($_POST['id']);
16
  if ( ! $import->isEmpty()) {
17
  $import->set(array(
18
  'executing' => 0,
@@ -21,7 +21,7 @@ function pmxi_wp_ajax_import_failed(){
21
  'failed_on' => date('Y-m-d H:i:s')
22
  ))->save();
23
  $result = true;
24
- do_action('pmxi_import_failed', $_POST['id']);
25
  }
26
  }
27
  exit( json_encode( array('result' => $result)));
12
  $result = false;
13
  if (!empty($_POST['id'])) {
14
  $import = new PMXI_Import_record();
15
+ $import->getbyId(intval($_POST['id']));
16
  if ( ! $import->isEmpty()) {
17
  $import->set(array(
18
  'executing' => 0,
21
  'failed_on' => date('Y-m-d H:i:s')
22
  ))->save();
23
  $result = true;
24
+ do_action('pmxi_import_failed', intval($_POST['id']));
25
  }
26
  }
27
  exit( json_encode( array('result' => $result)));
classes/PHPExcel/Shared/ZipArchive.php CHANGED
@@ -3,7 +3,7 @@
3
  if (!defined('PCLZIP_TEMPORARY_DIR')) {
4
  define('PCLZIP_TEMPORARY_DIR', PHPExcel_Shared_File::sys_get_temp_dir() . DIRECTORY_SEPARATOR);
5
  }
6
- require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/PCLZip/pclzip.lib.php';
7
 
8
  /**
9
  * PHPExcel_Shared_ZipArchive
3
  if (!defined('PCLZIP_TEMPORARY_DIR')) {
4
  define('PCLZIP_TEMPORARY_DIR', PHPExcel_Shared_File::sys_get_temp_dir() . DIRECTORY_SEPARATOR);
5
  }
6
+ require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
7
 
8
  /**
9
  * PHPExcel_Shared_ZipArchive
classes/api.php CHANGED
@@ -36,7 +36,7 @@ class PMXI_API
36
  ob_start();
37
  if ($label != "" and $field_type != "accordion"){
38
  ?>
39
- <label for="<?php echo sanitize_title($params['field_name']); ?>"><?php echo $label;?></label>
40
  <?php
41
  }
42
  if ( ! empty($params['tooltip'])){
@@ -55,15 +55,15 @@ class PMXI_API
55
 
56
  case 'simple':
57
  ?>
58
- <input type="text" name="<?php echo $params['field_name']; ?>" id="<?php echo sanitize_title($params['field_name']); ?>" value="<?php echo esc_attr($params['field_value']); ?>" style="width:100%;"/>
59
  <?php
60
  break;
61
  case 'enum':
62
 
63
  $is_set_with_xpath_visible = true;
64
  foreach ($params['enum_values'] as $key => $value): ?>
65
- <div class="form-field wpallimport-radio-field wpallimport-<?php echo sanitize_title($params['field_name']); ?>_<?php echo sanitize_title($key); ?>">
66
- <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_<?php echo sanitize_title($key); ?>" class="switcher" name="<?php echo $params['field_name']; ?>" value="<?php echo $key; ?>" <?php echo $key == $params['field_value'] ? 'checked="checked"': '' ?>/>
67
  <?php
68
  $label = '';
69
  $tooltip = '';
@@ -74,7 +74,7 @@ class PMXI_API
74
  $label = $value;
75
  }
76
  ?>
77
- <label for="<?php echo sanitize_title($params['field_name']); ?>_<?php echo sanitize_title($key); ?>"><?php echo $label; ?></label>
78
  <?php
79
  if (is_array($value) and ! empty($value)){
80
  foreach ($value as $k => $p) {
@@ -90,7 +90,7 @@ class PMXI_API
90
  <?php
91
  if (! empty($params['sub_fields'][$key])){
92
  ?>
93
- <div class="switcher-target-<?php echo sanitize_title($params['field_name']); ?>_<?php echo $key; ?>">
94
  <div class="input sub_input">
95
  <?php
96
  foreach ($params['sub_fields'][$key] as $sub_field) {
@@ -107,16 +107,16 @@ class PMXI_API
107
  </div>
108
  <?php endforeach;?>
109
  <?php if ( $is_set_with_xpath_visible ): ?>
110
- <div class="form-field wpallimport-radio-field wpallimport-<?php echo sanitize_title($params['field_name']); ?>_xpath">
111
- <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_xpath" class="switcher" name="<?php echo $params['field_name']; ?>" value="xpath" <?php echo 'xpath' === $params['field_value'] ? 'checked="checked"': '' ?>/>
112
- <label for="<?php echo sanitize_title($params['field_name']); ?>_xpath"><?php _e('Set with XPath', 'wp_all_import_plugin' )?></label>
113
  <span class="wpallimport-clear"></span>
114
- <div class="switcher-target-<?php echo sanitize_title($params['field_name']); ?>_xpath set_with_xpath">
115
  <span class="wpallimport-slide-content" style="padding-left:0px;">
116
  <table class="form-table custom-params" style="max-width:none; border:none;">
117
  <tr class="form-field">
118
  <td class="wpallimport-enum-input-wrapper">
119
- <input type="text" class="smaller-text" name="<?php echo $params['addon_prefix'];?>[xpaths][<?php echo $params['field_key']; ?>]" value="<?php echo esc_attr($params['xpath']) ?>"/>
120
  </td>
121
  <td class="action">
122
 
@@ -126,15 +126,15 @@ class PMXI_API
126
 
127
  <div class="input wpallimport-custom-fields-actions">
128
  <a href="javascript:void(0);" class="wpallimport-cf-options"><?php _e('Field Options...', 'wp_all_import_plugin'); ?></a>
129
- <ul id="wpallimport-cf-menu-<?php echo sanitize_title($params['field_name']);?>" class="wpallimport-cf-menu">
130
  <li class="<?php echo ( ! empty($custom_mapping_rules) ) ? 'active' : ''; ?>">
131
- <a href="javascript:void(0);" class="set_mapping pmxi_cf_mapping" rel="cf_mapping_<?php echo sanitize_title($params['field_name']); ?>"><?php _e('Mapping', 'wp_all_import_plugin'); ?></a>
132
  </li>
133
  </ul>
134
  </div>
135
- <div id="cf_mapping_<?php echo sanitize_title($params['field_name']); ?>" class="custom_type" rel="mapping" style="display:none;">
136
  <fieldset>
137
- <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="cf_mapping_<?php echo sanitize_title($params['field_name']); ?>">
138
  <thead>
139
  <tr>
140
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
@@ -179,7 +179,7 @@ class PMXI_API
179
  <input type="text" class="mapping_from widefat">
180
  </td>
181
  <td>
182
- <input type="text" class="mapping_to widefat" value="<?php echo $key; ?>">
183
  </td>
184
  <td class="action remove">
185
  <a href="#remove" style="right:-10px;"></a>
@@ -229,7 +229,7 @@ class PMXI_API
229
  </tr>
230
  </tbody>
231
  </table>
232
- <input type="hidden" class="pmre_mapping_rules" name="<?php echo $params['addon_prefix'];?>[mapping][<?php echo $params['field_key']; ?>]" value="<?php if (!empty($params['mapping_rules'])) echo esc_html($params['mapping_rules']); ?>"/>
233
  </fieldset>
234
  </div>
235
  <?php endif; ?>
@@ -245,17 +245,17 @@ class PMXI_API
245
 
246
  case 'textarea':
247
  ?>
248
- <textarea name="<?php echo $params['field_name']; ?>" id="<?php echo sanitize_title($params['field_name']); ?>" class="rad4 newline" style="height: 70px;margin: 5px 0;padding-top: 5px;width: 70%;"><?php echo esc_attr($params['field_value']); ?></textarea>
249
  <?php
250
  break;
251
 
252
  case 'wp_editor':
253
  ?>
254
- <div id="<?php echo ( user_can_richedit() ? 'postdivrich' : 'postdiv' ) . sanitize_title($params['field_name']); ?>" class="postarea">
255
- <?php wp_editor( empty($params['field_value']) ? '' : $params['field_value'], sanitize_title($params['field_name']), array(
256
  'teeny' => true,
257
  'media_buttons' => false,
258
- 'textarea_name' => $params['field_name'],
259
  'editor_height' => 200));
260
  ?>
261
  </div>
@@ -266,17 +266,17 @@ class PMXI_API
266
  ?>
267
  <div class="input">
268
  <div class="input" style="margin: 0px;">
269
- <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="yes" id="<?php echo sanitize_title($params['field_name']); ?>_yes" <?php echo ("yes" == $params['download_image']) ? 'checked="checked"' : '';?>/>
270
- <label for="<?php echo sanitize_title($params['field_name']); ?>_yes"><?php _e('Download image hosted elsewhere'); ?></label>
271
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
272
  </div>
273
  <div class="input" style="margin: 0px;">
274
  <?php $wp_uploads = wp_upload_dir(); ?>
275
- <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="no" id="<?php echo sanitize_title($params['field_name']); ?>_no" <?php echo ("yes" != $params['download_image']) ? 'checked="checked"' : '';?>/>
276
- <label for="<?php echo sanitize_title($params['field_name']); ?>_no"><?php printf(__('Use image(s) currently uploaded in %s', 'wp_all_import_plugin'), $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR); ?></label>
277
  </div>
278
  <div class="input">
279
- <input type="text" name="<?php echo $params['field_name']; ?>" style="width:100%;" placeholder="" value="<?php echo esc_attr($params['field_value']); ?>"/>
280
  </div>
281
  </div>
282
  <?php
@@ -286,17 +286,17 @@ class PMXI_API
286
  ?>
287
  <div class="input">
288
  <div class="input" style="margin: 0px;">
289
- <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="yes" id="<?php echo sanitize_title($params['field_name']); ?>_yes" <?php echo ("yes" == $params['download_image']) ? 'checked="checked"' : '';?>/>
290
- <label for="<?php echo sanitize_title($params['field_name']); ?>_yes"><?php _e('Download file hosted elsewhere'); ?></label>
291
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
292
  </div>
293
  <div class="input" style="margin: 0px;">
294
  <?php $wp_uploads = wp_upload_dir(); ?>
295
- <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="no" id="<?php echo sanitize_title($params['field_name']); ?>_no" <?php echo ("yes" != $params['download_image']) ? 'checked="checked"' : '';?>/>
296
- <label for="<?php echo sanitize_title($params['field_name']); ?>_no"><?php printf(__('Use file(s) currently uploaded in %s', 'wp_all_import_plugin'), $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR); ?></label>
297
  </div>
298
  <div class="input">
299
- <input type="text" name="<?php echo $params['field_name']; ?>" style="width:100%;" placeholder="" value="<?php echo esc_attr($params['field_value']); ?>"/>
300
  </div>
301
  </div>
302
  <?php
@@ -322,10 +322,10 @@ class PMXI_API
322
  if ( ! $in_the_bottom and $is_full_width ) $styles = 'wpallimport-full-with-not-bottom';
323
 
324
  ?>
325
- <div class="wpallimport-collapsed closed wpallimport-section <?php echo (($in_the_bottom and $is_full_width) ? 'wpallimport-sub-options-full-width' : 'wpallimport-sub-options'); echo ((!$is_full_width) ? ' wpallimport-dependent-options' : '');?> <?php echo $styles; ?>">
326
  <div class="wpallimport-content-section <?php echo (($is_full_width and !$in_the_bottom) ? 'rad4' : 'wpallimport-bottom-radius');?>">
327
  <div class="wpallimport-collapsed-header">
328
- <h3 style="color:#40acad;"><?php echo $label; ?></h3>
329
  </div>
330
  <div class="wpallimport-collapsed-content" style="padding: 0;">
331
  <div class="wpallimport-collapsed-content-inner">
36
  ob_start();
37
  if ($label != "" and $field_type != "accordion"){
38
  ?>
39
+ <label for="<?php echo esc_attr($params['field_name']); ?>"><?php echo wp_kses_post($label);?></label>
40
  <?php
41
  }
42
  if ( ! empty($params['tooltip'])){
55
 
56
  case 'simple':
57
  ?>
58
+ <input type="text" name="<?php echo esc_attr($params['field_name']); ?>" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>" value="<?php echo esc_attr($params['field_value']); ?>" style="width:100%;"/>
59
  <?php
60
  break;
61
  case 'enum':
62
 
63
  $is_set_with_xpath_visible = true;
64
  foreach ($params['enum_values'] as $key => $value): ?>
65
+ <div class="form-field wpallimport-radio-field wpallimport-<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_<?php echo sanitize_title(esc_attr($key)); ?>">
66
+ <input type="radio" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_<?php echo sanitize_title(esc_attr($key)); ?>" class="switcher" name="<?php echo esc_attr($params['field_name']); ?>" value="<?php echo esc_attr($key); ?>" <?php echo $key == $params['field_value'] ? 'checked="checked"': '' ?>/>
67
  <?php
68
  $label = '';
69
  $tooltip = '';
74
  $label = $value;
75
  }
76
  ?>
77
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_<?php echo sanitize_title(esc_attr($key)); ?>"><?php echo wp_kses_post($label); ?></label>
78
  <?php
79
  if (is_array($value) and ! empty($value)){
80
  foreach ($value as $k => $p) {
90
  <?php
91
  if (! empty($params['sub_fields'][$key])){
92
  ?>
93
+ <div class="switcher-target-<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_<?php echo esc_attr($key); ?>">
94
  <div class="input sub_input">
95
  <?php
96
  foreach ($params['sub_fields'][$key] as $sub_field) {
107
  </div>
108
  <?php endforeach;?>
109
  <?php if ( $is_set_with_xpath_visible ): ?>
110
+ <div class="form-field wpallimport-radio-field wpallimport-<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_xpath">
111
+ <input type="radio" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_xpath" class="switcher" name="<?php echo esc_attr($params['field_name']); ?>" value="xpath" <?php echo 'xpath' === $params['field_value'] ? 'checked="checked"': '' ?>/>
112
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_xpath"><?php _e('Set with XPath', 'wp_all_import_plugin' )?></label>
113
  <span class="wpallimport-clear"></span>
114
+ <div class="switcher-target-<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_xpath set_with_xpath">
115
  <span class="wpallimport-slide-content" style="padding-left:0px;">
116
  <table class="form-table custom-params" style="max-width:none; border:none;">
117
  <tr class="form-field">
118
  <td class="wpallimport-enum-input-wrapper">
119
+ <input type="text" class="smaller-text" name="<?php echo esc_attr($params['addon_prefix']);?>[xpaths][<?php echo esc_attr($params['field_key']); ?>]" value="<?php echo esc_attr($params['xpath']) ?>"/>
120
  </td>
121
  <td class="action">
122
 
126
 
127
  <div class="input wpallimport-custom-fields-actions">
128
  <a href="javascript:void(0);" class="wpallimport-cf-options"><?php _e('Field Options...', 'wp_all_import_plugin'); ?></a>
129
+ <ul id="wpallimport-cf-menu-<?php echo sanitize_title(esc_attr($params['field_name']));?>" class="wpallimport-cf-menu">
130
  <li class="<?php echo ( ! empty($custom_mapping_rules) ) ? 'active' : ''; ?>">
131
+ <a href="javascript:void(0);" class="set_mapping pmxi_cf_mapping" rel="cf_mapping_<?php echo sanitize_title(esc_attr($params['field_name'])); ?>"><?php _e('Mapping', 'wp_all_import_plugin'); ?></a>
132
  </li>
133
  </ul>
134
  </div>
135
+ <div id="cf_mapping_<?php echo sanitize_title(esc_attr($params['field_name'])); ?>" class="custom_type" rel="mapping" style="display:none;">
136
  <fieldset>
137
+ <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="cf_mapping_<?php echo sanitize_title(esc_attr($params['field_name'])); ?>">
138
  <thead>
139
  <tr>
140
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
179
  <input type="text" class="mapping_from widefat">
180
  </td>
181
  <td>
182
+ <input type="text" class="mapping_to widefat" value="<?php echo esc_attr($key); ?>">
183
  </td>
184
  <td class="action remove">
185
  <a href="#remove" style="right:-10px;"></a>
229
  </tr>
230
  </tbody>
231
  </table>
232
+ <input type="hidden" class="pmre_mapping_rules" name="<?php echo esc_attr($params['addon_prefix']);?>[mapping][<?php echo esc_attr($params['field_key']); ?>]" value="<?php if (!empty($params['mapping_rules'])) echo esc_attr($params['mapping_rules']); ?>"/>
233
  </fieldset>
234
  </div>
235
  <?php endif; ?>
245
 
246
  case 'textarea':
247
  ?>
248
+ <textarea name="<?php echo esc_attr($params['field_name']); ?>" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>" class="rad4 newline" style="height: 70px;margin: 5px 0;padding-top: 5px;width: 70%;"><?php echo esc_attr($params['field_value']); ?></textarea>
249
  <?php
250
  break;
251
 
252
  case 'wp_editor':
253
  ?>
254
+ <div id="<?php echo ( user_can_richedit() ? 'postdivrich' : 'postdiv' ) . sanitize_title(esc_attr($params['field_name'])); ?>" class="postarea">
255
+ <?php wp_editor( empty($params['field_value']) ? '' : esc_textarea($params['field_value']), sanitize_title(esc_attr($params['field_name'])), array(
256
  'teeny' => true,
257
  'media_buttons' => false,
258
+ 'textarea_name' => esc_attr($params['field_name']),
259
  'editor_height' => 200));
260
  ?>
261
  </div>
266
  ?>
267
  <div class="input">
268
  <div class="input" style="margin: 0px;">
269
+ <input type="radio" name="<?php echo esc_attr($params['addon_prefix']);?>[download_image][<?php echo esc_attr($params['field_key']);?>]" value="yes" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_yes" <?php echo ("yes" == $params['download_image']) ? 'checked="checked"' : '';?>/>
270
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_yes"><?php _e('Download image hosted elsewhere'); ?></label>
271
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
272
  </div>
273
  <div class="input" style="margin: 0px;">
274
  <?php $wp_uploads = wp_upload_dir(); ?>
275
+ <input type="radio" name="<?php echo esc_attr($params['addon_prefix']);?>[download_image][<?php echo esc_attr($params['field_key']);?>]" value="no" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_no" <?php echo ("yes" != $params['download_image']) ? 'checked="checked"' : '';?>/>
276
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_no"><?php printf(__('Use image(s) currently uploaded in %s', 'wp_all_import_plugin'), $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR); ?></label>
277
  </div>
278
  <div class="input">
279
+ <input type="text" name="<?php echo esc_attr($params['field_name']); ?>" style="width:100%;" placeholder="" value="<?php echo esc_attr($params['field_value']); ?>"/>
280
  </div>
281
  </div>
282
  <?php
286
  ?>
287
  <div class="input">
288
  <div class="input" style="margin: 0px;">
289
+ <input type="radio" name="<?php echo esc_attr($params['addon_prefix']);?>[download_image][<?php echo esc_attr($params['field_key']);?>]" value="yes" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_yes" <?php echo ("yes" == $params['download_image']) ? 'checked="checked"' : '';?>/>
290
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_yes"><?php _e('Download file hosted elsewhere'); ?></label>
291
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
292
  </div>
293
  <div class="input" style="margin: 0px;">
294
  <?php $wp_uploads = wp_upload_dir(); ?>
295
+ <input type="radio" name="<?php echo esc_attr($params['addon_prefix']);?>[download_image][<?php echo esc_attr($params['field_key']);?>]" value="no" id="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_no" <?php echo ("yes" != $params['download_image']) ? 'checked="checked"' : '';?>/>
296
+ <label for="<?php echo sanitize_title(esc_attr($params['field_name'])); ?>_no"><?php printf(__('Use file(s) currently uploaded in %s', 'wp_all_import_plugin'), $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR); ?></label>
297
  </div>
298
  <div class="input">
299
+ <input type="text" name="<?php echo esc_attr($params['field_name']); ?>" style="width:100%;" placeholder="" value="<?php echo esc_attr($params['field_value']); ?>"/>
300
  </div>
301
  </div>
302
  <?php
322
  if ( ! $in_the_bottom and $is_full_width ) $styles = 'wpallimport-full-with-not-bottom';
323
 
324
  ?>
325
+ <div class="wpallimport-collapsed closed wpallimport-section <?php echo (($in_the_bottom and $is_full_width) ? 'wpallimport-sub-options-full-width' : 'wpallimport-sub-options'); echo ((!$is_full_width) ? ' wpallimport-dependent-options' : '');?> <?php echo esc_attr($styles); ?>">
326
  <div class="wpallimport-content-section <?php echo (($is_full_width and !$in_the_bottom) ? 'rad4' : 'wpallimport-bottom-radius');?>">
327
  <div class="wpallimport-collapsed-header">
328
+ <h3 style="color:#40acad;"><?php echo wp_kses_post($label); ?></h3>
329
  </div>
330
  <div class="wpallimport-collapsed-content" style="padding: 0;">
331
  <div class="wpallimport-collapsed-content-inner">
classes/render.php CHANGED
@@ -47,10 +47,10 @@ if ( ! class_exists('PMXI_Render')){
47
  $path .= "[$ind]";
48
  }
49
 
50
- echo '<div class="xml-element csv_element lvl-' . $lvl . ' lvl-mod4-' . ($lvl % 4) . '" title="' . $path . '">';
51
  if ($el->hasChildNodes()) {
52
  $is_render_collapsed = $ind > 1;
53
- if ($lvl) echo '<div class="csv-tag opening"><span class="csv-tag-name">' . $el->nodeName . '</span>'; echo '</div>';
54
  if (1 == $el->childNodes->length and $el->childNodes->item(0) instanceof DOMText) {
55
  $child = $el->childNodes->item(0);
56
  if (!empty($child->wholeText)){
@@ -247,10 +247,10 @@ if ( ! class_exists('PMXI_Render')){
247
  <ul id="menu-<?php echo str_replace('/', '-', esc_attr($path)); ?>" class="ui-helper-hidden">
248
  <?php foreach ($el->attributes as $attr) : if ( empty($attr->value) ) continue; ?>
249
  <li data-command="action1" title="<?php echo esc_attr($path . '[@'. $attr->nodeName .' = "' . esc_attr($attr->value) . '"]'); ?>">
250
- <a href="#"><?php echo $path . '[@'. $attr->nodeName .' = "' . esc_attr($attr->value) . '"]'; ?></a>
251
  </li>
252
  <li data-command="action2" title="<?php echo esc_attr($path . '[@'. $attr->nodeName .'[contains(.,"' . esc_attr($attr->value) . '")]]'); ?>">
253
- <a href="#"><?php echo $path . '[@'. $attr->nodeName .'[contains(.,"' . esc_attr($attr->value) . '")]]'; ?></a>
254
  </li>
255
  <?php endforeach; ?>
256
  <?php
@@ -299,8 +299,8 @@ if ( ! class_exists('PMXI_Render')){
299
  array_pop($pathArgs);
300
  $vpath = esc_attr(implode('/', $pathArgs) . '/' . $parentNode->nodeName . '[contains('. $altNode->nodeName .',"' . esc_attr($altNodeText->wholeText) . '")]/' . $el->nodeName);
301
  ?>
302
- <li data-command="action3" title="<?php echo $vpath; ?>">
303
- <a href="#"><?php echo $vpath; ?></a>
304
  </li>
305
  <?php
306
 
47
  $path .= "[$ind]";
48
  }
49
 
50
+ echo '<div class="xml-element csv_element lvl-' . $lvl . ' lvl-mod4-' . ($lvl % 4) . '" title="' . esc_attr($path) . '">';
51
  if ($el->hasChildNodes()) {
52
  $is_render_collapsed = $ind > 1;
53
+ if ($lvl) echo '<div class="csv-tag opening"><span class="csv-tag-name">' . esc_html($el->nodeName) . '</span>'; echo '</div>';
54
  if (1 == $el->childNodes->length and $el->childNodes->item(0) instanceof DOMText) {
55
  $child = $el->childNodes->item(0);
56
  if (!empty($child->wholeText)){
247
  <ul id="menu-<?php echo str_replace('/', '-', esc_attr($path)); ?>" class="ui-helper-hidden">
248
  <?php foreach ($el->attributes as $attr) : if ( empty($attr->value) ) continue; ?>
249
  <li data-command="action1" title="<?php echo esc_attr($path . '[@'. $attr->nodeName .' = "' . esc_attr($attr->value) . '"]'); ?>">
250
+ <a href="#"><?php echo esc_html($path) . '[@'. $attr->nodeName .' = "' . esc_attr($attr->value) . '"]'; ?></a>
251
  </li>
252
  <li data-command="action2" title="<?php echo esc_attr($path . '[@'. $attr->nodeName .'[contains(.,"' . esc_attr($attr->value) . '")]]'); ?>">
253
+ <a href="#"><?php echo esc_html($path) . '[@'. $attr->nodeName .'[contains(.,"' . esc_attr($attr->value) . '")]]'; ?></a>
254
  </li>
255
  <?php endforeach; ?>
256
  <?php
299
  array_pop($pathArgs);
300
  $vpath = esc_attr(implode('/', $pathArgs) . '/' . $parentNode->nodeName . '[contains('. $altNode->nodeName .',"' . esc_attr($altNodeText->wholeText) . '")]/' . $el->nodeName);
301
  ?>
302
+ <li data-command="action3" title="<?php echo esc_attr($vpath); ?>">
303
+ <a href="#"><?php echo esc_html($vpath); ?></a>
304
  </li>
305
  <?php
306
 
classes/upload.php CHANGED
@@ -59,7 +59,9 @@ if ( ! class_exists('PMXI_Upload')){
59
  $this->errors->add('form-validation', __('Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV', 'wp_all_import_plugin'));
60
  } elseif (preg_match('%\W(zip)$%i', trim(basename($this->file)))) {
61
 
62
- if (!class_exists('PclZip')) include_once(PMXI_Plugin::ROOT_DIR.'/libraries/pclzip.lib.php');
 
 
63
 
64
  $archive = new PclZip($this->file);
65
  if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, $this->uploadsPath, PCLZIP_OPT_REPLACE_NEWER)) == 0) {
@@ -308,7 +310,9 @@ if ( ! class_exists('PMXI_Upload')){
308
  if (!file_exists($tmpname)) $this->errors->add('form-validation', __('Failed upload ZIP archive', 'wp_all_import_plugin'));
309
  }
310
 
311
- if (!class_exists('PclZip')) include_once(PMXI_Plugin::ROOT_DIR.'/libraries/pclzip.lib.php');
 
 
312
 
313
  $archive = new PclZip($tmpname);
314
  if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, $this->uploadsPath, PCLZIP_OPT_REPLACE_NEWER)) == 0) {
59
  $this->errors->add('form-validation', __('Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV', 'wp_all_import_plugin'));
60
  } elseif (preg_match('%\W(zip)$%i', trim(basename($this->file)))) {
61
 
62
+ if (!class_exists('PclZip')) {
63
+ require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
64
+ }
65
 
66
  $archive = new PclZip($this->file);
67
  if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, $this->uploadsPath, PCLZIP_OPT_REPLACE_NEWER)) == 0) {
310
  if (!file_exists($tmpname)) $this->errors->add('form-validation', __('Failed upload ZIP archive', 'wp_all_import_plugin'));
311
  }
312
 
313
+ if (!class_exists('PclZip')) {
314
+ require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
315
+ }
316
 
317
  $archive = new PclZip($tmpname);
318
  if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, $this->uploadsPath, PCLZIP_OPT_REPLACE_NEWER)) == 0) {
controllers/admin/history.php CHANGED
@@ -69,7 +69,7 @@ class PMXI_Admin_History extends PMXI_Controller_Admin {
69
  */
70
  public function log(){
71
 
72
- $nonce = (!empty($_REQUEST['_wpnonce'])) ? $_REQUEST['_wpnonce'] : '';
73
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_log' ) ) {
74
  die( __('Security check', 'wp_all_import_plugin') );
75
  } else {
69
  */
70
  public function log(){
71
 
72
+ $nonce = (!empty($_REQUEST['_wpnonce'])) ? wp_unslash($_REQUEST['_wpnonce']) : '';
73
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_log' ) ) {
74
  die( __('Security check', 'wp_all_import_plugin') );
75
  } else {
controllers/admin/import.php CHANGED
@@ -150,7 +150,7 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
150
 
151
  if ( $id ) { // update requested but corresponding import is not found
152
  if ( $import->getById($id)->isEmpty() ) {
153
- if ( ! empty($_GET['deligate']) and $_GET['deligate'] == 'wpallexport' ) {
154
  wp_redirect(add_query_arg('pmxi_nt', array('error' => urlencode(__('The import associated with this export has been deleted.', 'wp_all_import_plugin')), 'updated' => urlencode(__('Please re-run your export by clicking Run Export on the All Export -> Manage Exports page. Then try your import again.', 'wp_all_import_plugin'))), remove_query_arg('id', $this->baseUrl))); die();
155
  } else {
156
  wp_redirect(add_query_arg('pmxi_nt', array('error' => urlencode(__('This import has been deleted.', 'wp_all_import_plugin'))), remove_query_arg('id', $this->baseUrl))); die();
150
 
151
  if ( $id ) { // update requested but corresponding import is not found
152
  if ( $import->getById($id)->isEmpty() ) {
153
+ if ( ! empty($_GET['deligate']) and sanitize_key($_GET['deligate']) == 'wpallexport' ) {
154
  wp_redirect(add_query_arg('pmxi_nt', array('error' => urlencode(__('The import associated with this export has been deleted.', 'wp_all_import_plugin')), 'updated' => urlencode(__('Please re-run your export by clicking Run Export on the All Export -> Manage Exports page. Then try your import again.', 'wp_all_import_plugin'))), remove_query_arg('id', $this->baseUrl))); die();
155
  } else {
156
  wp_redirect(add_query_arg('pmxi_nt', array('error' => urlencode(__('This import has been deleted.', 'wp_all_import_plugin'))), remove_query_arg('id', $this->baseUrl))); die();
controllers/admin/manage.php CHANGED
@@ -151,7 +151,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
151
  }
152
 
153
  public function get_template(){
154
- $nonce = (!empty($_REQUEST['_wpnonce'])) ? $_REQUEST['_wpnonce'] : '';
155
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_template' ) ) {
156
  die( __('Security check', 'wp_all_import_plugin') );
157
  } else {
@@ -194,7 +194,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
194
  */
195
  public function bundle(){
196
 
197
- $nonce = (!empty($_REQUEST['_wpnonce'])) ? $_REQUEST['_wpnonce'] : '';
198
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_bundle' ) ) {
199
  die( __('Security check', 'wp_all_import_plugin') );
200
  } else {
@@ -308,7 +308,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
308
  */
309
  public function cancel(){
310
 
311
- $nonce = (!empty($_REQUEST['_wpnonce'])) ? $_REQUEST['_wpnonce'] : '';
312
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-cancel_import' ) ) {
313
  die( __('Security check', 'wp_all_import_plugin') );
314
  } else {
@@ -516,7 +516,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
516
  */
517
  public function feed(){
518
 
519
- $nonce = (!empty($_REQUEST['_wpnonce'])) ? $_REQUEST['_wpnonce'] : '';
520
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_feed' ) ) {
521
  die( __('Security check', 'wp_all_import_plugin') );
522
  } else {
151
  }
152
 
153
  public function get_template(){
154
+ $nonce = (!empty($_REQUEST['_wpnonce'])) ? wp_unslash($_REQUEST['_wpnonce']) : '';
155
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_template' ) ) {
156
  die( __('Security check', 'wp_all_import_plugin') );
157
  } else {
194
  */
195
  public function bundle(){
196
 
197
+ $nonce = (!empty($_REQUEST['_wpnonce'])) ? wp_unslash($_REQUEST['_wpnonce']) : '';
198
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_bundle' ) ) {
199
  die( __('Security check', 'wp_all_import_plugin') );
200
  } else {
308
  */
309
  public function cancel(){
310
 
311
+ $nonce = (!empty($_REQUEST['_wpnonce'])) ? wp_unslash($_REQUEST['_wpnonce']) : '';
312
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-cancel_import' ) ) {
313
  die( __('Security check', 'wp_all_import_plugin') );
314
  } else {
516
  */
517
  public function feed(){
518
 
519
+ $nonce = (!empty($_REQUEST['_wpnonce'])) ? wp_unslash($_REQUEST['_wpnonce']) : '';
520
  if ( ! wp_verify_nonce( $nonce, '_wpnonce-download_feed' ) ) {
521
  die( __('Security check', 'wp_all_import_plugin') );
522
  } else {
controllers/admin/settings.php CHANGED
@@ -89,9 +89,9 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
89
  if ($this->input->post('import_templates')){
90
 
91
  if (!empty($_FILES)){
92
- $file_name = $_FILES['template_file']['name'];
93
- $file_size = $_FILES['template_file']['size'];
94
- $tmp_name = $_FILES['template_file']['tmp_name'];
95
 
96
  if(isset($file_name))
97
  {
@@ -407,7 +407,7 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
407
 
408
  global $wpdb;
409
 
410
- $meta_key = $_POST['key'];
411
 
412
  $r = $wpdb->get_results("
413
  SELECT DISTINCT postmeta.meta_value
@@ -471,7 +471,7 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
471
  // Get parameters
472
  $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
473
  $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
474
- $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
475
 
476
  // Clean the fileName for security reasons
477
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
@@ -526,12 +526,12 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
526
 
527
  // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
528
  if (strpos($contentType, "multipart") !== false) {
529
- if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file($_FILES['async-upload']['tmp_name'])) {
530
  // Open temp file
531
  $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
532
  if ($out) {
533
  // Read binary input stream and append it to temp file
534
- $in = fopen($_FILES['async-upload']['tmp_name'], "rb");
535
 
536
  if ($in) {
537
  while ($buff = fread($in, 4096))
@@ -542,7 +542,7 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
542
  }
543
  fclose($in);
544
  fclose($out);
545
- @unlink($_FILES['async-upload']['tmp_name']);
546
  } else{
547
  delete_transient( self::$upload_transient );
548
  exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
@@ -604,7 +604,7 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
604
  ob_start();
605
  ?>
606
  <?php foreach ($msgs as $msg): ?>
607
- <p><?php echo $msg ?></p>
608
  <?php endforeach ?>
609
  <?php
610
  $response = ob_get_clean();
89
  if ($this->input->post('import_templates')){
90
 
91
  if (!empty($_FILES)){
92
+ $file_name = sanitize_file_name($_FILES['template_file']['name']);
93
+ $file_size = intval($_FILES['template_file']['size']);
94
+ $tmp_name = realpath($_FILES['template_file']['tmp_name']);
95
 
96
  if(isset($file_name))
97
  {
407
 
408
  global $wpdb;
409
 
410
+ $meta_key = sanitize_key($_POST['key']);
411
 
412
  $r = $wpdb->get_results("
413
  SELECT DISTINCT postmeta.meta_value
471
  // Get parameters
472
  $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
473
  $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
474
+ $fileName = isset($_REQUEST["name"]) ? sanitize_file_name($_REQUEST["name"]) : '';
475
 
476
  // Clean the fileName for security reasons
477
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
526
 
527
  // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
528
  if (strpos($contentType, "multipart") !== false) {
529
+ if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file(realpath($_FILES['async-upload']['tmp_name']))) {
530
  // Open temp file
531
  $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
532
  if ($out) {
533
  // Read binary input stream and append it to temp file
534
+ $in = fopen(realpath($_FILES['async-upload']['tmp_name']), "rb");
535
 
536
  if ($in) {
537
  while ($buff = fread($in, 4096))
542
  }
543
  fclose($in);
544
  fclose($out);
545
+ @unlink(realpath($_FILES['async-upload']['tmp_name']));
546
  } else{
547
  delete_transient( self::$upload_transient );
548
  exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
604
  ob_start();
605
  ?>
606
  <?php foreach ($msgs as $msg): ?>
607
+ <p><?php echo wp_kses_post($msg); ?></p>
608
  <?php endforeach ?>
609
  <?php
610
  $response = ob_get_clean();
controllers/controller/admin.php CHANGED
@@ -74,8 +74,6 @@ abstract class PMXI_Controller_Admin extends PMXI_Controller {
74
  wp_enqueue_style('jquery-select2', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/select2/select2-bootstrap.css');
75
  wp_enqueue_style('jquery-chosen', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/chosen/chosen.css');
76
  add_editor_style( WP_ALL_IMPORT_ROOT_URL . '/static/css/custom-editor-style.css' );
77
- //wp_deregister_style('wp-codemirror');
78
- wp_enqueue_style('jquery-codemirror', WP_ALL_IMPORT_ROOT_URL . '/static/css/codemirror.css', array(), PMXI_VERSION);
79
 
80
  wp_enqueue_style('jquery-timepicker', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/timepicker/jquery.timepicker.css', array(), PMXI_VERSION);
81
 
@@ -98,10 +96,8 @@ abstract class PMXI_Controller_Admin extends PMXI_Controller {
98
  }
99
 
100
  wp_enqueue_script('jquery-ui-datepicker', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/ui.datepicker.js', 'jquery-ui-core');
101
- //wp_enqueue_script('wp-all-import-autocomplete', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/ui.autocomplete.js', array('jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position'));
102
  wp_enqueue_script('tipsy', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.tipsy.js', 'jquery', PMXI_VERSION);
103
  wp_enqueue_script('jquery-nestable', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.mjs.nestedSortable.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-tabs', 'jquery-ui-progressbar'));
104
- wp_enqueue_script('jquery-moment', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/moment.js', 'jquery', PMXI_VERSION);
105
  wp_enqueue_script('jquery-select2', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/select2.min.js', 'jquery');
106
  wp_enqueue_script('jquery-chosen', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/chosen.jquery.min.js', 'jquery');
107
  wp_enqueue_script('jquery-ddslick', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.ddslick.min.js', 'jquery');
@@ -120,7 +116,7 @@ abstract class PMXI_Controller_Admin extends PMXI_Controller {
120
 
121
  wp_enqueue_script('jquery-plupload', WP_ALL_IMPORT_ROOT_URL . '/static/js/plupload/wplupload.js', array('plupload', 'jquery'));
122
 
123
- wp_enqueue_script('pmxi-admin-script', WP_ALL_IMPORT_ROOT_URL . '/static/js/admin.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-datepicker', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position', 'jquery-ui-autocomplete', 'wp-theme-plugin-editor'), PMXI_VERSION);
124
 
125
  }
126
 
74
  wp_enqueue_style('jquery-select2', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/select2/select2-bootstrap.css');
75
  wp_enqueue_style('jquery-chosen', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/chosen/chosen.css');
76
  add_editor_style( WP_ALL_IMPORT_ROOT_URL . '/static/css/custom-editor-style.css' );
 
 
77
 
78
  wp_enqueue_style('jquery-timepicker', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/css/timepicker/jquery.timepicker.css', array(), PMXI_VERSION);
79
 
96
  }
97
 
98
  wp_enqueue_script('jquery-ui-datepicker', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/ui.datepicker.js', 'jquery-ui-core');
 
99
  wp_enqueue_script('tipsy', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.tipsy.js', 'jquery', PMXI_VERSION);
100
  wp_enqueue_script('jquery-nestable', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.mjs.nestedSortable.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-tabs', 'jquery-ui-progressbar'));
 
101
  wp_enqueue_script('jquery-select2', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/select2.min.js', 'jquery');
102
  wp_enqueue_script('jquery-chosen', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/chosen.jquery.min.js', 'jquery');
103
  wp_enqueue_script('jquery-ddslick', WP_ALL_IMPORT_ROOT_URL . '/static/js/jquery/jquery.ddslick.min.js', 'jquery');
116
 
117
  wp_enqueue_script('jquery-plupload', WP_ALL_IMPORT_ROOT_URL . '/static/js/plupload/wplupload.js', array('plupload', 'jquery'));
118
 
119
+ wp_enqueue_script('pmxi-admin-script', WP_ALL_IMPORT_ROOT_URL . '/static/js/admin.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-datepicker', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position', 'jquery-ui-autocomplete', 'wp-theme-plugin-editor', 'moment'), PMXI_VERSION);
120
 
121
  }
122
 
helpers/reverse_taxonomies_html.php CHANGED
@@ -13,7 +13,7 @@ if ( ! function_exists('reverse_taxonomies_html') ) {
13
  foreach ($childs as $child_cat){
14
  $i++;
15
  ?>
16
- <li id="item_<?php echo $i; ?>" class="dragging">
17
  <div class="drag-element">
18
  <input type="hidden" class="assign_term" value="1" />
19
  <input class="widefat xpath_field" type="text" value="<?php echo esc_textarea($child_cat->xpath); ?>"/>
13
  foreach ($childs as $child_cat){
14
  $i++;
15
  ?>
16
+ <li id="item_<?php echo esc_attr($i); ?>" class="dragging">
17
  <div class="drag-element">
18
  <input type="hidden" class="assign_term" value="1" />
19
  <input class="widefat xpath_field" type="text" value="<?php echo esc_textarea($child_cat->xpath); ?>"/>
helpers/wp_all_import_addon_notifications.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
  if ( ! function_exists('wp_all_import_addon_notifications') ){
3
  function wp_all_import_addon_notifications(){
4
- if ( ! empty($_GET['page']) and preg_match('%(pmxi-admin)%i', $_GET['page']))
5
  {
6
  if ( ! function_exists( 'is_plugin_active' ) ) require_once ABSPATH . 'wp-admin/includes/plugin.php';
7
 
1
  <?php
2
  if ( ! function_exists('wp_all_import_addon_notifications') ){
3
  function wp_all_import_addon_notifications(){
4
+ if ( ! empty($_GET['page']) and preg_match('%(pmxi-admin)%i', sanitize_key($_GET['page'])))
5
  {
6
  if ( ! function_exists( 'is_plugin_active' ) ) require_once ABSPATH . 'wp-admin/includes/plugin.php';
7
 
helpers/wp_all_import_get_import_id.php CHANGED
@@ -17,9 +17,9 @@ if ( ! function_exists( 'wp_all_import_get_import_id' ) ) {
17
 
18
  if ( $import_id == 'new' ) {
19
  if ( isset( $_GET['import_id'] ) ) {
20
- $import_id = $_GET['import_id'];
21
  } elseif ( isset( $_GET['id'] ) ) {
22
- $import_id = $_GET['id'];
23
  }
24
  }
25
 
17
 
18
  if ( $import_id == 'new' ) {
19
  if ( isset( $_GET['import_id'] ) ) {
20
+ $import_id = intval($_GET['import_id']);
21
  } elseif ( isset( $_GET['id'] ) ) {
22
+ $import_id = intval($_GET['id']);
23
  }
24
  }
25
 
helpers/wp_all_import_template_notifications.php CHANGED
@@ -103,7 +103,7 @@ if ( ! function_exists('wp_all_import_template_notifications') )
103
  {
104
  ?>
105
  <div class="error inline">
106
- <p><?php printf(__('<strong>Warning:</strong>', 'wp_all_import_plugin') . ' %s', $notification);?></p>
107
  </div>
108
  <?php
109
  }
@@ -111,7 +111,7 @@ if ( ! function_exists('wp_all_import_template_notifications') )
111
  {
112
  ?>
113
  <div class="wpallimport-free-edition-notice" style="text-align:center; margin-top:0; margin-bottom: 20px;">
114
- <p class="upgrade_link"><?php echo $notification;?></p>
115
  </div>
116
  <?php
117
  }
103
  {
104
  ?>
105
  <div class="error inline">
106
+ <p><?php printf(__('<strong>Warning:</strong>', 'wp_all_import_plugin') . ' %s', wp_kses_post($notification));?></p>
107
  </div>
108
  <?php
109
  }
111
  {
112
  ?>
113
  <div class="wpallimport-free-edition-notice" style="text-align:center; margin-top:0; margin-bottom: 20px;">
114
+ <p class="upgrade_link"><?php echo wp_kses_post($notification);?></p>
115
  </div>
116
  <?php
117
  }
helpers/wp_redirect_or_javascript.php CHANGED
@@ -9,7 +9,7 @@ if ( ! function_exists('wp_redirect_or_javascript')):
9
  function wp_redirect_or_javascript($location, $javascript = NULL, $status = 302) {
10
  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
11
  is_null($javascript) and $javascript = 'location.href="' . addslashes($location) . '";';
12
- echo '<script type="text/javascript">' . $javascript . '</script>';
13
  } else {
14
  return wp_redirect($location, $status);
15
  }
9
  function wp_redirect_or_javascript($location, $javascript = NULL, $status = 302) {
10
  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
11
  is_null($javascript) and $javascript = 'location.href="' . addslashes($location) . '";';
12
+ echo '<script type="text/javascript">' . esc_js($javascript) . '</script>';
13
  } else {
14
  return wp_redirect($location, $status);
15
  }
libraries/XmlImportCsvParse.php CHANGED
@@ -77,7 +77,7 @@ class PMXI_CsvParser
77
 
78
  PMXI_Plugin::$csv_path = $options['filename'];
79
 
80
- $this->xpath = (!empty($options['xpath']) ? $options['xpath'] : ((!empty($_POST['xpath'])) ? $_POST['xpath'] : '/node'));
81
 
82
  if ( ! empty($options['delimiter']) ){
83
  $this->delimiter = $options['delimiter'];
@@ -964,9 +964,9 @@ class PMXI_CsvParser
964
 
965
  $import_id = 0;
966
 
967
- if ( ! empty($_GET['id']) ) $import_id = $_GET['id'];
968
 
969
- if ( ! empty($_GET['import_id']) ) $import_id = $_GET['import_id'];
970
 
971
  $create_new_headers = false;
972
  $skip_x_rows = apply_filters('wp_all_import_skip_x_csv_rows', false, $import_id);
77
 
78
  PMXI_Plugin::$csv_path = $options['filename'];
79
 
80
+ $this->xpath = (!empty($options['xpath']) ? $options['xpath'] : ((!empty($_POST['xpath'])) ? sanitize_text_field($_POST['xpath']) : '/node'));
81
 
82
  if ( ! empty($options['delimiter']) ){
83
  $this->delimiter = $options['delimiter'];
964
 
965
  $import_id = 0;
966
 
967
+ if ( ! empty($_GET['id']) ) $import_id = intval($_GET['id']);
968
 
969
+ if ( ! empty($_GET['import_id']) ) $import_id = intval($_GET['import_id']);
970
 
971
  $create_new_headers = false;
972
  $skip_x_rows = apply_filters('wp_all_import_skip_x_csv_rows', false, $import_id);
libraries/pclzip.lib.php DELETED
@@ -1,5178 +0,0 @@
1
- <?php
2
- // --------------------------------------------------------------------------------
3
- // PhpConcept Library - Zip Module 2.8.2
4
- // --------------------------------------------------------------------------------
5
- // License GNU/LGPL - Vincent Blavet - August 2009
6
- // http://www.phpconcept.net
7
- // --------------------------------------------------------------------------------
8
- //
9
- // Presentation :
10
- // PclZip is a PHP library that manage ZIP archives.
11
- // So far tests show that archives generated by PclZip are readable by
12
- // WinZip application and other tools.
13
- //
14
- // Description :
15
- // See readme.txt and http://www.phpconcept.net
16
- //
17
- // Warning :
18
- // This library and the associated files are non commercial, non professional
19
- // work.
20
- // It should not have unexpected results. However if any damage is caused by
21
- // this software the author can not be responsible.
22
- // The use of this software is at the risk of the user.
23
- //
24
- // --------------------------------------------------------------------------------
25
- // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $
26
- // --------------------------------------------------------------------------------
27
-
28
- if (!class_exists('PclZip')):
29
-
30
- // ----- Constants
31
- if (!defined('PCLZIP_READ_BLOCK_SIZE')) {
32
- define('PCLZIP_READ_BLOCK_SIZE', 2048);
33
- }
34
-
35
- // ----- File list separator
36
- // In version 1.x of PclZip, the separator for file list is a space
37
- // (which is not a very smart choice, specifically for windows paths !).
38
- // A better separator should be a comma (,). This constant gives you the
39
- // abilty to change that.
40
- // However notice that changing this value, may have impact on existing
41
- // scripts, using space separated filenames.
42
- // Recommanded values for compatibility with older versions :
43
- //define('PCLZIP_SEPARATOR', ' ');
44
- // Recommanded values for smart separation of filenames.
45
- if (!defined('PCLZIP_SEPARATOR')) {
46
- define('PCLZIP_SEPARATOR', ',');
47
- }
48
-
49
- // ----- Error configuration
50
- // 0 : PclZip Class integrated error handling
51
- // 1 : PclError external library error handling. By enabling this
52
- // you must ensure that you have included PclError library.
53
- // [2,...] : reserved for futur use
54
- if (!defined('PCLZIP_ERROR_EXTERNAL')) {
55
- define('PCLZIP_ERROR_EXTERNAL', 0);
56
- }
57
-
58
- // ----- Optional static temporary directory
59
- // By default temporary files are generated in the script current
60
- // path.
61
- // If defined :
62
- // - MUST BE terminated by a '/'.
63
- // - MUST be a valid, already created directory
64
- // Samples :
65
- // define('PCLZIP_TEMPORARY_DIR', '/temp/');
66
- // define('PCLZIP_TEMPORARY_DIR', 'C:/Temp/');
67
- if (!defined('PCLZIP_TEMPORARY_DIR')) {
68
- define('PCLZIP_TEMPORARY_DIR', '');
69
- }
70
-
71
- // ----- Optional threshold ratio for use of temporary files
72
- // Pclzip sense the size of the file to add/extract and decide to
73
- // use or not temporary file. The algorythm is looking for
74
- // memory_limit of PHP and apply a ratio.
75
- // threshold = memory_limit * ratio.
76
- // Recommended values are under 0.5. Default 0.47.
77
- // Samples :
78
- // define('PCLZIP_TEMPORARY_FILE_RATIO', 0.5);
79
- if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) {
80
- define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47);
81
- }
82
-
83
- // --------------------------------------------------------------------------------
84
- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
85
- // --------------------------------------------------------------------------------
86
-
87
- // ----- Global variables
88
- $g_pclzip_version = "2.8.2";
89
-
90
- // ----- Error codes
91
- // -1 : Unable to open file in binary write mode
92
- // -2 : Unable to open file in binary read mode
93
- // -3 : Invalid parameters
94
- // -4 : File does not exist
95
- // -5 : Filename is too long (max. 255)
96
- // -6 : Not a valid zip file
97
- // -7 : Invalid extracted file size
98
- // -8 : Unable to create directory
99
- // -9 : Invalid archive extension
100
- // -10 : Invalid archive format
101
- // -11 : Unable to delete file (unlink)
102
- // -12 : Unable to rename file (rename)
103
- // -13 : Invalid header checksum
104
- // -14 : Invalid archive size
105
- define('PCLZIP_ERR_USER_ABORTED', 2);
106
- define('PCLZIP_ERR_NO_ERROR', 0);
107
- define('PCLZIP_ERR_WRITE_OPEN_FAIL', -1);
108
- define('PCLZIP_ERR_READ_OPEN_FAIL', -2);
109
- define('PCLZIP_ERR_INVALID_PARAMETER', -3);
110
- define('PCLZIP_ERR_MISSING_FILE', -4);
111
- define('PCLZIP_ERR_FILENAME_TOO_LONG', -5);
112
- define('PCLZIP_ERR_INVALID_ZIP', -6);
113
- define('PCLZIP_ERR_BAD_EXTRACTED_FILE', -7);
114
- define('PCLZIP_ERR_DIR_CREATE_FAIL', -8);
115
- define('PCLZIP_ERR_BAD_EXTENSION', -9);
116
- define('PCLZIP_ERR_BAD_FORMAT', -10);
117
- define('PCLZIP_ERR_DELETE_FILE_FAIL', -11);
118
- define('PCLZIP_ERR_RENAME_FILE_FAIL', -12);
119
- define('PCLZIP_ERR_BAD_CHECKSUM', -13);
120
- define('PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14);
121
- define('PCLZIP_ERR_MISSING_OPTION_VALUE', -15);
122
- define('PCLZIP_ERR_INVALID_OPTION_VALUE', -16);
123
- define('PCLZIP_ERR_ALREADY_A_DIRECTORY', -17);
124
- define('PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18);
125
- define('PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19);
126
- define('PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20);
127
- define('PCLZIP_ERR_DIRECTORY_RESTRICTION', -21);
128
-
129
- // ----- Options values
130
- define('PCLZIP_OPT_PATH', 77001);
131
- define('PCLZIP_OPT_ADD_PATH', 77002);
132
- define('PCLZIP_OPT_REMOVE_PATH', 77003);
133
- define('PCLZIP_OPT_REMOVE_ALL_PATH', 77004);
134
- define('PCLZIP_OPT_SET_CHMOD', 77005);
135
- define('PCLZIP_OPT_EXTRACT_AS_STRING', 77006);
136
- define('PCLZIP_OPT_NO_COMPRESSION', 77007);
137
- define('PCLZIP_OPT_BY_NAME', 77008);
138
- define('PCLZIP_OPT_BY_INDEX', 77009);
139
- define('PCLZIP_OPT_BY_EREG', 77010);
140
- define('PCLZIP_OPT_BY_PREG', 77011);
141
- define('PCLZIP_OPT_COMMENT', 77012);
142
- define('PCLZIP_OPT_ADD_COMMENT', 77013);
143
- define('PCLZIP_OPT_PREPEND_COMMENT', 77014);
144
- define('PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015);
145
- define('PCLZIP_OPT_REPLACE_NEWER', 77016);
146
- define('PCLZIP_OPT_STOP_ON_ERROR', 77017);
147
- // Having big trouble with crypt. Need to multiply 2 long int
148
- // which is not correctly supported by PHP ...
149
- //define('PCLZIP_OPT_CRYPT', 77018);
150
- define('PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019);
151
- define('PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020);
152
- define('PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020); // alias
153
- define('PCLZIP_OPT_TEMP_FILE_ON', 77021);
154
- define('PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021); // alias
155
- define('PCLZIP_OPT_TEMP_FILE_OFF', 77022);
156
- define('PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022); // alias
157
-
158
- // ----- File description attributes
159
- define('PCLZIP_ATT_FILE_NAME', 79001);
160
- define('PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002);
161
- define('PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003);
162
- define('PCLZIP_ATT_FILE_MTIME', 79004);
163
- define('PCLZIP_ATT_FILE_CONTENT', 79005);
164
- define('PCLZIP_ATT_FILE_COMMENT', 79006);
165
-
166
- // ----- Call backs values
167
- define('PCLZIP_CB_PRE_EXTRACT', 78001);
168
- define('PCLZIP_CB_POST_EXTRACT', 78002);
169
- define('PCLZIP_CB_PRE_ADD', 78003);
170
- define('PCLZIP_CB_POST_ADD', 78004);
171
- /* For futur use
172
- define('PCLZIP_CB_PRE_LIST', 78005);
173
- define('PCLZIP_CB_POST_LIST', 78006);
174
- define('PCLZIP_CB_PRE_DELETE', 78007);
175
- define('PCLZIP_CB_POST_DELETE', 78008);
176
- */
177
-
178
- // --------------------------------------------------------------------------------
179
- // Class : PclZip
180
- // Description :
181
- // PclZip is the class that represent a Zip archive.
182
- // The public methods allow the manipulation of the archive.
183
- // Attributes :
184
- // Attributes must not be accessed directly.
185
- // Methods :
186
- // PclZip() : Object creator
187
- // create() : Creates the Zip archive
188
- // listContent() : List the content of the Zip archive
189
- // extract() : Extract the content of the archive
190
- // properties() : List the properties of the archive
191
- // --------------------------------------------------------------------------------
192
- class PclZip
193
- {
194
- // ----- Filename of the zip file
195
- public $zipname = '';
196
-
197
- // ----- File descriptor of the zip file
198
- public $zip_fd = 0;
199
-
200
- // ----- Internal error handling
201
- public $error_code = 1;
202
- public $error_string = '';
203
-
204
- // ----- Current status of the magic_quotes_runtime
205
- // This value store the php configuration for magic_quotes
206
- // The class can then disable the magic_quotes and reset it after
207
- public $magic_quotes_status;
208
-
209
- // --------------------------------------------------------------------------------
210
- // Function : PclZip()
211
- // Description :
212
- // Creates a PclZip object and set the name of the associated Zip archive
213
- // filename.
214
- // Note that no real action is taken, if the archive does not exist it is not
215
- // created. Use create() for that.
216
- // --------------------------------------------------------------------------------
217
- public function __construct($p_zipname)
218
- {
219
-
220
- // ----- Tests the zlib
221
- if (!function_exists('gzopen')) {
222
- die('Abort '.basename(__FILE__).' : Missing zlib extensions');
223
- }
224
-
225
- // ----- Set the attributes
226
- $this->zipname = $p_zipname;
227
- $this->zip_fd = 0;
228
- $this->magic_quotes_status = -1;
229
-
230
- // ----- Return
231
- return;
232
- }
233
- // --------------------------------------------------------------------------------
234
-
235
- // --------------------------------------------------------------------------------
236
- // Function :
237
- // create($p_filelist, $p_add_dir="", $p_remove_dir="")
238
- // create($p_filelist, $p_option, $p_option_value, ...)
239
- // Description :
240
- // This method supports two different synopsis. The first one is historical.
241
- // This method creates a Zip Archive. The Zip file is created in the
242
- // filesystem. The files and directories indicated in $p_filelist
243
- // are added in the archive. See the parameters description for the
244
- // supported format of $p_filelist.
245
- // When a directory is in the list, the directory and its content is added
246
- // in the archive.
247
- // In this synopsis, the function takes an optional variable list of
248
- // options. See bellow the supported options.
249
- // Parameters :
250
- // $p_filelist : An array containing file or directory names, or
251
- // a string containing one filename or one directory name, or
252
- // a string containing a list of filenames and/or directory
253
- // names separated by spaces.
254
- // $p_add_dir : A path to add before the real path of the archived file,
255
- // in order to have it memorized in the archive.
256
- // $p_remove_dir : A path to remove from the real path of the file to archive,
257
- // in order to have a shorter path memorized in the archive.
258
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
259
- // is removed first, before $p_add_dir is added.
260
- // Options :
261
- // PCLZIP_OPT_ADD_PATH :
262
- // PCLZIP_OPT_REMOVE_PATH :
263
- // PCLZIP_OPT_REMOVE_ALL_PATH :
264
- // PCLZIP_OPT_COMMENT :
265
- // PCLZIP_CB_PRE_ADD :
266
- // PCLZIP_CB_POST_ADD :
267
- // Return Values :
268
- // 0 on failure,
269
- // The list of the added files, with a status of the add action.
270
- // (see PclZip::listContent() for list entry format)
271
- // --------------------------------------------------------------------------------
272
- public function create($p_filelist)
273
- {
274
- $v_result=1;
275
-
276
- // ----- Reset the error handler
277
- $this->privErrorReset();
278
-
279
- // ----- Set default values
280
- $v_options = array();
281
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = false;
282
-
283
- // ----- Look for variable options arguments
284
- $v_size = func_num_args();
285
-
286
- // ----- Look for arguments
287
- if ($v_size > 1) {
288
- // ----- Get the arguments
289
- $v_arg_list = func_get_args();
290
-
291
- // ----- Remove from the options list the first argument
292
- array_shift($v_arg_list);
293
- $v_size--;
294
-
295
- // ----- Look for first arg
296
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
297
- // ----- Parse the options
298
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (
299
- PCLZIP_OPT_REMOVE_PATH => 'optional',
300
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
301
- PCLZIP_OPT_ADD_PATH => 'optional',
302
- PCLZIP_CB_PRE_ADD => 'optional',
303
- PCLZIP_CB_POST_ADD => 'optional',
304
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
305
- PCLZIP_OPT_COMMENT => 'optional',
306
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
307
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
308
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
309
- //, PCLZIP_OPT_CRYPT => 'optional'
310
- ));
311
- if ($v_result != 1) {
312
- return 0;
313
- }
314
- } else {
315
- // ----- Look for 2 args
316
- // Here we need to support the first historic synopsis of the
317
- // method.
318
- // ----- Get the first argument
319
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
320
-
321
- // ----- Look for the optional second argument
322
- if ($v_size == 2) {
323
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
324
- } elseif ($v_size > 2) {
325
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
326
- return 0;
327
- }
328
- }
329
- }
330
-
331
- // ----- Look for default option values
332
- $this->privOptionDefaultThreshold($v_options);
333
-
334
- // ----- Init
335
- $v_string_list = array();
336
- $v_att_list = array();
337
- $v_filedescr_list = array();
338
- $p_result_list = array();
339
-
340
- // ----- Look if the $p_filelist is really an array
341
- if (is_array($p_filelist)) {
342
- // ----- Look if the first element is also an array
343
- // This will mean that this is a file description entry
344
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
345
- $v_att_list = $p_filelist;
346
- } else {
347
- // ----- The list is a list of string names
348
- $v_string_list = $p_filelist;
349
- }
350
- } elseif (is_string($p_filelist)) {
351
- // ----- Look if the $p_filelist is a string
352
- // ----- Create a list from the string
353
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
354
- } else {
355
- // ----- Invalid variable type for $p_filelist
356
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
357
- return 0;
358
- }
359
-
360
- // ----- Reformat the string list
361
- if (sizeof($v_string_list) != 0) {
362
- foreach ($v_string_list as $v_string) {
363
- if ($v_string != '') {
364
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
365
- } else {
366
- }
367
- }
368
- }
369
-
370
- // ----- For each file in the list check the attributes
371
- $v_supported_attributes = array(
372
- PCLZIP_ATT_FILE_NAME => 'mandatory',
373
- PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional',
374
- PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional',
375
- PCLZIP_ATT_FILE_MTIME => 'optional',
376
- PCLZIP_ATT_FILE_CONTENT => 'optional',
377
- PCLZIP_ATT_FILE_COMMENT => 'optional'
378
- );
379
- foreach ($v_att_list as $v_entry) {
380
- $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes);
381
- if ($v_result != 1) {
382
- return 0;
383
- }
384
- }
385
-
386
- // ----- Expand the filelist (expand directories)
387
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
388
- if ($v_result != 1) {
389
- return 0;
390
- }
391
-
392
- // ----- Call the create fct
393
- $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
394
- if ($v_result != 1) {
395
- return 0;
396
- }
397
-
398
- // ----- Return
399
- return $p_result_list;
400
- }
401
- // --------------------------------------------------------------------------------
402
-
403
- // --------------------------------------------------------------------------------
404
- // Function :
405
- // add($p_filelist, $p_add_dir="", $p_remove_dir="")
406
- // add($p_filelist, $p_option, $p_option_value, ...)
407
- // Description :
408
- // This method supports two synopsis. The first one is historical.
409
- // This methods add the list of files in an existing archive.
410
- // If a file with the same name already exists, it is added at the end of the
411
- // archive, the first one is still present.
412
- // If the archive does not exist, it is created.
413
- // Parameters :
414
- // $p_filelist : An array containing file or directory names, or
415
- // a string containing one filename or one directory name, or
416
- // a string containing a list of filenames and/or directory
417
- // names separated by spaces.
418
- // $p_add_dir : A path to add before the real path of the archived file,
419
- // in order to have it memorized in the archive.
420
- // $p_remove_dir : A path to remove from the real path of the file to archive,
421
- // in order to have a shorter path memorized in the archive.
422
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
423
- // is removed first, before $p_add_dir is added.
424
- // Options :
425
- // PCLZIP_OPT_ADD_PATH :
426
- // PCLZIP_OPT_REMOVE_PATH :
427
- // PCLZIP_OPT_REMOVE_ALL_PATH :
428
- // PCLZIP_OPT_COMMENT :
429
- // PCLZIP_OPT_ADD_COMMENT :
430
- // PCLZIP_OPT_PREPEND_COMMENT :
431
- // PCLZIP_CB_PRE_ADD :
432
- // PCLZIP_CB_POST_ADD :
433
- // Return Values :
434
- // 0 on failure,
435
- // The list of the added files, with a status of the add action.
436
- // (see PclZip::listContent() for list entry format)
437
- // --------------------------------------------------------------------------------
438
- public function add($p_filelist)
439
- {
440
- $v_result=1;
441
-
442
- // ----- Reset the error handler
443
- $this->privErrorReset();
444
-
445
- // ----- Set default values
446
- $v_options = array();
447
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = false;
448
-
449
- // ----- Look for variable options arguments
450
- $v_size = func_num_args();
451
-
452
- // ----- Look for arguments
453
- if ($v_size > 1) {
454
- // ----- Get the arguments
455
- $v_arg_list = func_get_args();
456
-
457
- // ----- Remove form the options list the first argument
458
- array_shift($v_arg_list);
459
- $v_size--;
460
-
461
- // ----- Look for first arg
462
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
463
- // ----- Parse the options
464
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (
465
- PCLZIP_OPT_REMOVE_PATH => 'optional',
466
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
467
- PCLZIP_OPT_ADD_PATH => 'optional',
468
- PCLZIP_CB_PRE_ADD => 'optional',
469
- PCLZIP_CB_POST_ADD => 'optional',
470
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
471
- PCLZIP_OPT_COMMENT => 'optional',
472
- PCLZIP_OPT_ADD_COMMENT => 'optional',
473
- PCLZIP_OPT_PREPEND_COMMENT => 'optional',
474
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
475
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
476
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
477
- //, PCLZIP_OPT_CRYPT => 'optional'
478
- ));
479
- if ($v_result != 1) {
480
- return 0;
481
- }
482
- } else {
483
- // ----- Look for 2 args
484
- // Here we need to support the first historic synopsis of the
485
- // method.
486
- // ----- Get the first argument
487
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
488
-
489
- // ----- Look for the optional second argument
490
- if ($v_size == 2) {
491
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
492
- } elseif ($v_size > 2) {
493
- // ----- Error log
494
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
495
-
496
- // ----- Return
497
- return 0;
498
- }
499
- }
500
- }
501
-
502
- // ----- Look for default option values
503
- $this->privOptionDefaultThreshold($v_options);
504
-
505
- // ----- Init
506
- $v_string_list = array();
507
- $v_att_list = array();
508
- $v_filedescr_list = array();
509
- $p_result_list = array();
510
-
511
- // ----- Look if the $p_filelist is really an array
512
- if (is_array($p_filelist)) {
513
- // ----- Look if the first element is also an array
514
- // This will mean that this is a file description entry
515
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
516
- $v_att_list = $p_filelist;
517
- } else {
518
- // ----- The list is a list of string names
519
- $v_string_list = $p_filelist;
520
- }
521
- } elseif (is_string($p_filelist)) {
522
- // ----- Look if the $p_filelist is a string
523
- // ----- Create a list from the string
524
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
525
- } else {
526
- // ----- Invalid variable type for $p_filelist
527
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
528
- return 0;
529
- }
530
-
531
- // ----- Reformat the string list
532
- if (sizeof($v_string_list) != 0) {
533
- foreach ($v_string_list as $v_string) {
534
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
535
- }
536
- }
537
-
538
- // ----- For each file in the list check the attributes
539
- $v_supported_attributes = array(
540
- PCLZIP_ATT_FILE_NAME => 'mandatory',
541
- PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional',
542
- PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional',
543
- PCLZIP_ATT_FILE_MTIME => 'optional',
544
- PCLZIP_ATT_FILE_CONTENT => 'optional',
545
- PCLZIP_ATT_FILE_COMMENT => 'optional',
546
- );
547
- foreach ($v_att_list as $v_entry) {
548
- $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes);
549
- if ($v_result != 1) {
550
- return 0;
551
- }
552
- }
553
-
554
- // ----- Expand the filelist (expand directories)
555
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
556
- if ($v_result != 1) {
557
- return 0;
558
- }
559
-
560
- // ----- Call the create fct
561
- $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
562
- if ($v_result != 1) {
563
- return 0;
564
- }
565
-
566
- // ----- Return
567
- return $p_result_list;
568
- }
569
- // --------------------------------------------------------------------------------
570
-
571
- // --------------------------------------------------------------------------------
572
- // Function : listContent()
573
- // Description :
574
- // This public method, gives the list of the files and directories, with their
575
- // properties.
576
- // The properties of each entries in the list are (used also in other functions) :
577
- // filename : Name of the file. For a create or add action it is the filename
578
- // given by the user. For an extract function it is the filename
579
- // of the extracted file.
580
- // stored_filename : Name of the file / directory stored in the archive.
581
- // size : Size of the stored file.
582
- // compressed_size : Size of the file's data compressed in the archive
583
- // (without the headers overhead)
584
- // mtime : Last known modification date of the file (UNIX timestamp)
585
- // comment : Comment associated with the file
586
- // folder : true | false
587
- // index : index of the file in the archive
588
- // status : status of the action (depending of the action) :
589
- // Values are :
590
- // ok : OK !
591
- // filtered : the file / dir is not extracted (filtered by user)
592
- // already_a_directory : the file can not be extracted because a
593
- // directory with the same name already exists
594
- // write_protected : the file can not be extracted because a file
595
- // with the same name already exists and is
596
- // write protected
597
- // newer_exist : the file was not extracted because a newer file exists
598
- // path_creation_fail : the file is not extracted because the folder
599
- // does not exist and can not be created
600
- // write_error : the file was not extracted because there was a
601
- // error while writing the file
602
- // read_error : the file was not extracted because there was a error
603
- // while reading the file
604
- // invalid_header : the file was not extracted because of an archive
605
- // format error (bad file header)
606
- // Note that each time a method can continue operating when there
607
- // is an action error on a file, the error is only logged in the file status.
608
- // Return Values :
609
- // 0 on an unrecoverable failure,
610
- // The list of the files in the archive.
611
- // --------------------------------------------------------------------------------
612
- public function listContent()
613
- {
614
- $v_result=1;
615
-
616
- // ----- Reset the error handler
617
- $this->privErrorReset();
618
-
619
- // ----- Check archive
620
- if (!$this->privCheckFormat()) {
621
- return(0);
622
- }
623
-
624
- // ----- Call the extracting fct
625
- $p_list = array();
626
- if (($v_result = $this->privList($p_list)) != 1) {
627
- unset($p_list);
628
- return(0);
629
- }
630
-
631
- // ----- Return
632
- return $p_list;
633
- }
634
- // --------------------------------------------------------------------------------
635
-
636
- // --------------------------------------------------------------------------------
637
- // Function :
638
- // extract($p_path="./", $p_remove_path="")
639
- // extract([$p_option, $p_option_value, ...])
640
- // Description :
641
- // This method supports two synopsis. The first one is historical.
642
- // This method extract all the files / directories from the archive to the
643
- // folder indicated in $p_path.
644
- // If you want to ignore the 'root' part of path of the memorized files
645
- // you can indicate this in the optional $p_remove_path parameter.
646
- // By default, if a newer file with the same name already exists, the
647
- // file is not extracted.
648
- //
649
- // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
650
- // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
651
- // at the end of the path value of PCLZIP_OPT_PATH.
652
- // Parameters :
653
- // $p_path : Path where the files and directories are to be extracted
654
- // $p_remove_path : First part ('root' part) of the memorized path
655
- // (if any similar) to remove while extracting.
656
- // Options :
657
- // PCLZIP_OPT_PATH :
658
- // PCLZIP_OPT_ADD_PATH :
659
- // PCLZIP_OPT_REMOVE_PATH :
660
- // PCLZIP_OPT_REMOVE_ALL_PATH :
661
- // PCLZIP_CB_PRE_EXTRACT :
662
- // PCLZIP_CB_POST_EXTRACT :
663
- // Return Values :
664
- // 0 or a negative value on failure,
665
- // The list of the extracted files, with a status of the action.
666
- // (see PclZip::listContent() for list entry format)
667
- // --------------------------------------------------------------------------------
668
- public function extract()
669
- {
670
- $v_result=1;
671
-
672
- // ----- Reset the error handler
673
- $this->privErrorReset();
674
-
675
- // ----- Check archive
676
- if (!$this->privCheckFormat()) {
677
- return(0);
678
- }
679
-
680
- // ----- Set default values
681
- $v_options = array();
682
- // $v_path = "./";
683
- $v_path = '';
684
- $v_remove_path = "";
685
- $v_remove_all_path = false;
686
-
687
- // ----- Look for variable options arguments
688
- $v_size = func_num_args();
689
-
690
- // ----- Default values for option
691
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
692
-
693
- // ----- Look for arguments
694
- if ($v_size > 0) {
695
- // ----- Get the arguments
696
- $v_arg_list = func_get_args();
697
-
698
- // ----- Look for first arg
699
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
700
- // ----- Parse the options
701
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (
702
- PCLZIP_OPT_PATH => 'optional',
703
- PCLZIP_OPT_REMOVE_PATH => 'optional',
704
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
705
- PCLZIP_OPT_ADD_PATH => 'optional',
706
- PCLZIP_CB_PRE_EXTRACT => 'optional',
707
- PCLZIP_CB_POST_EXTRACT => 'optional',
708
- PCLZIP_OPT_SET_CHMOD => 'optional',
709
- PCLZIP_OPT_BY_NAME => 'optional',
710
- PCLZIP_OPT_BY_EREG => 'optional',
711
- PCLZIP_OPT_BY_PREG => 'optional',
712
- PCLZIP_OPT_BY_INDEX => 'optional',
713
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
714
- PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
715
- PCLZIP_OPT_REPLACE_NEWER => 'optional',
716
- PCLZIP_OPT_STOP_ON_ERROR => 'optional',
717
- PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
718
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
719
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
720
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
721
- ));
722
- if ($v_result != 1) {
723
- return 0;
724
- }
725
-
726
- // ----- Set the arguments
727
- if (isset($v_options[PCLZIP_OPT_PATH])) {
728
- $v_path = $v_options[PCLZIP_OPT_PATH];
729
- }
730
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
731
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
732
- }
733
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
734
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
735
- }
736
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
737
- // ----- Check for '/' in last path char
738
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
739
- $v_path .= '/';
740
- }
741
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
742
- }
743
- } else {
744
- // ----- Look for 2 args
745
- // Here we need to support the first historic synopsis of the
746
- // method.
747
- // ----- Get the first argument
748
- $v_path = $v_arg_list[0];
749
-
750
- // ----- Look for the optional second argument
751
- if ($v_size == 2) {
752
- $v_remove_path = $v_arg_list[1];
753
- } elseif ($v_size > 2) {
754
- // ----- Error log
755
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
756
-
757
- // ----- Return
758
- return 0;
759
- }
760
- }
761
- }
762
-
763
- // ----- Look for default option values
764
- $this->privOptionDefaultThreshold($v_options);
765
-
766
- // ----- Trace
767
-
768
- // ----- Call the extracting fct
769
- $p_list = array();
770
- $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options);
771
- if ($v_result < 1) {
772
- unset($p_list);
773
- return(0);
774
- }
775
-
776
- // ----- Return
777
- return $p_list;
778
- }
779
- // --------------------------------------------------------------------------------
780
-
781
-
782
- // --------------------------------------------------------------------------------
783
- // Function :
784
- // extractByIndex($p_index, $p_path="./", $p_remove_path="")
785
- // extractByIndex($p_index, [$p_option, $p_option_value, ...])
786
- // Description :
787
- // This method supports two synopsis. The first one is historical.
788
- // This method is doing a partial extract of the archive.
789
- // The extracted files or folders are identified by their index in the
790
- // archive (from 0 to n).
791
- // Note that if the index identify a folder, only the folder entry is
792
- // extracted, not all the files included in the archive.
793
- // Parameters :
794
- // $p_index : A single index (integer) or a string of indexes of files to
795
- // extract. The form of the string is "0,4-6,8-12" with only numbers
796
- // and '-' for range or ',' to separate ranges. No spaces or ';'
797
- // are allowed.
798
- // $p_path : Path where the files and directories are to be extracted
799
- // $p_remove_path : First part ('root' part) of the memorized path
800
- // (if any similar) to remove while extracting.
801
- // Options :
802
- // PCLZIP_OPT_PATH :
803
- // PCLZIP_OPT_ADD_PATH :
804
- // PCLZIP_OPT_REMOVE_PATH :
805
- // PCLZIP_OPT_REMOVE_ALL_PATH :
806
- // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
807
- // not as files.
808
- // The resulting content is in a new field 'content' in the file
809
- // structure.
810
- // This option must be used alone (any other options are ignored).
811
- // PCLZIP_CB_PRE_EXTRACT :
812
- // PCLZIP_CB_POST_EXTRACT :
813
- // Return Values :
814
- // 0 on failure,
815
- // The list of the extracted files, with a status of the action.
816
- // (see PclZip::listContent() for list entry format)
817
- // --------------------------------------------------------------------------------
818
- //function extractByIndex($p_index, options...)
819
- public function extractByIndex($p_index)
820
- {
821
- $v_result=1;
822
-
823
- // ----- Reset the error handler
824
- $this->privErrorReset();
825
-
826
- // ----- Check archive
827
- if (!$this->privCheckFormat()) {
828
- return(0);
829
- }
830
-
831
- // ----- Set default values
832
- $v_options = array();
833
- // $v_path = "./";
834
- $v_path = '';
835
- $v_remove_path = "";
836
- $v_remove_all_path = false;
837
-
838
- // ----- Look for variable options arguments
839
- $v_size = func_num_args();
840
-
841
- // ----- Default values for option
842
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
843
-
844
- // ----- Look for arguments
845
- if ($v_size > 1) {
846
- // ----- Get the arguments
847
- $v_arg_list = func_get_args();
848
-
849
- // ----- Remove form the options list the first argument
850
- array_shift($v_arg_list);
851
- $v_size--;
852
-
853
- // ----- Look for first arg
854
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
855
- // ----- Parse the options
856
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
857
- PCLZIP_OPT_PATH => 'optional',
858
- PCLZIP_OPT_REMOVE_PATH => 'optional',
859
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
860
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
861
- PCLZIP_OPT_ADD_PATH => 'optional',
862
- PCLZIP_CB_PRE_EXTRACT => 'optional',
863
- PCLZIP_CB_POST_EXTRACT => 'optional',
864
- PCLZIP_OPT_SET_CHMOD => 'optional',
865
- PCLZIP_OPT_REPLACE_NEWER => 'optional',
866
- PCLZIP_OPT_STOP_ON_ERROR => 'optional',
867
- PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
868
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
869
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
870
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
871
- ));
872
- if ($v_result != 1) {
873
- return 0;
874
- }
875
-
876
- // ----- Set the arguments
877
- if (isset($v_options[PCLZIP_OPT_PATH])) {
878
- $v_path = $v_options[PCLZIP_OPT_PATH];
879
- }
880
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
881
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
882
- }
883
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
884
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
885
- }
886
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
887
- // ----- Check for '/' in last path char
888
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
889
- $v_path .= '/';
890
- }
891
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
892
- }
893
- if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
894
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
895
- } else {
896
- }
897
- } else {
898
- // ----- Look for 2 args
899
- // Here we need to support the first historic synopsis of the
900
- // method.
901
-
902
- // ----- Get the first argument
903
- $v_path = $v_arg_list[0];
904
-
905
- // ----- Look for the optional second argument
906
- if ($v_size == 2) {
907
- $v_remove_path = $v_arg_list[1];
908
- } elseif ($v_size > 2) {
909
- // ----- Error log
910
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
911
-
912
- // ----- Return
913
- return 0;
914
- }
915
- }
916
- }
917
-
918
- // ----- Trace
919
-
920
- // ----- Trick
921
- // Here I want to reuse extractByRule(), so I need to parse the $p_index
922
- // with privParseOptions()
923
- $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
924
- $v_options_trick = array();
925
- $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array (PCLZIP_OPT_BY_INDEX => 'optional'));
926
- if ($v_result != 1) {
927
- return 0;
928
- }
929
- $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
930
-
931
- // ----- Look for default option values
932
- $this->privOptionDefaultThreshold($v_options);
933
-
934
- // ----- Call the extracting fct
935
- if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
936
- return(0);
937
- }
938
-
939
- // ----- Return
940
- return $p_list;
941
- }
942
- // --------------------------------------------------------------------------------
943
-
944
- // --------------------------------------------------------------------------------
945
- // Function :
946
- // delete([$p_option, $p_option_value, ...])
947
- // Description :
948
- // This method removes files from the archive.
949
- // If no parameters are given, then all the archive is emptied.
950
- // Parameters :
951
- // None or optional arguments.
952
- // Options :
953
- // PCLZIP_OPT_BY_INDEX :
954
- // PCLZIP_OPT_BY_NAME :
955
- // PCLZIP_OPT_BY_EREG :
956
- // PCLZIP_OPT_BY_PREG :
957
- // Return Values :
958
- // 0 on failure,
959
- // The list of the files which are still present in the archive.
960
- // (see PclZip::listContent() for list entry format)
961
- // --------------------------------------------------------------------------------
962
- public function delete()
963
- {
964
- $v_result=1;
965
-
966
- // ----- Reset the error handler
967
- $this->privErrorReset();
968
-
969
- // ----- Check archive
970
- if (!$this->privCheckFormat()) {
971
- return(0);
972
- }
973
-
974
- // ----- Set default values
975
- $v_options = array();
976
-
977
- // ----- Look for variable options arguments
978
- $v_size = func_num_args();
979
-
980
- // ----- Look for arguments
981
- if ($v_size > 0) {
982
- // ----- Get the arguments
983
- $v_arg_list = func_get_args();
984
-
985
- // ----- Parse the options
986
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (
987
- PCLZIP_OPT_BY_NAME => 'optional',
988
- PCLZIP_OPT_BY_EREG => 'optional',
989
- PCLZIP_OPT_BY_PREG => 'optional',
990
- PCLZIP_OPT_BY_INDEX => 'optional'
991
- ));
992
- if ($v_result != 1) {
993
- return 0;
994
- }
995
- }
996
-
997
- // ----- Magic quotes trick
998
- $this->privDisableMagicQuotes();
999
-
1000
- // ----- Call the delete fct
1001
- $v_list = array();
1002
- if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
1003
- $this->privSwapBackMagicQuotes();
1004
- unset($v_list);
1005
- return(0);
1006
- }
1007
-
1008
- // ----- Magic quotes trick
1009
- $this->privSwapBackMagicQuotes();
1010
-
1011
- // ----- Return
1012
- return $v_list;
1013
- }
1014
- // --------------------------------------------------------------------------------
1015
-
1016
- // --------------------------------------------------------------------------------
1017
- // Function : deleteByIndex()
1018
- // Description :
1019
- // ***** Deprecated *****
1020
- // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
1021
- // --------------------------------------------------------------------------------
1022
- public function deleteByIndex($p_index)
1023
- {
1024
-
1025
- $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
1026
-
1027
- // ----- Return
1028
- return $p_list;
1029
- }
1030
- // --------------------------------------------------------------------------------
1031
-
1032
- // --------------------------------------------------------------------------------
1033
- // Function : properties()
1034
- // Description :
1035
- // This method gives the properties of the archive.
1036
- // The properties are :
1037
- // nb : Number of files in the archive
1038
- // comment : Comment associated with the archive file
1039
- // status : not_exist, ok
1040
- // Parameters :
1041
- // None
1042
- // Return Values :
1043
- // 0 on failure,
1044
- // An array with the archive properties.
1045
- // --------------------------------------------------------------------------------
1046
- public function properties()
1047
- {
1048
-
1049
- // ----- Reset the error handler
1050
- $this->privErrorReset();
1051
-
1052
- // ----- Magic quotes trick
1053
- $this->privDisableMagicQuotes();
1054
-
1055
- // ----- Check archive
1056
- if (!$this->privCheckFormat()) {
1057
- $this->privSwapBackMagicQuotes();
1058
- return(0);
1059
- }
1060
-
1061
- // ----- Default properties
1062
- $v_prop = array();
1063
- $v_prop['comment'] = '';
1064
- $v_prop['nb'] = 0;
1065
- $v_prop['status'] = 'not_exist';
1066
-
1067
- // ----- Look if file exists
1068
- if (@is_file($this->zipname)) {
1069
- // ----- Open the zip file
1070
- if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
1071
- $this->privSwapBackMagicQuotes();
1072
-
1073
- // ----- Error log
1074
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
1075
-
1076
- // ----- Return
1077
- return 0;
1078
- }
1079
-
1080
- // ----- Read the central directory informations
1081
- $v_central_dir = array();
1082
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
1083
- $this->privSwapBackMagicQuotes();
1084
- return 0;
1085
- }
1086
-
1087
- // ----- Close the zip file
1088
- $this->privCloseFd();
1089
-
1090
- // ----- Set the user attributes
1091
- $v_prop['comment'] = $v_central_dir['comment'];
1092
- $v_prop['nb'] = $v_central_dir['entries'];
1093
- $v_prop['status'] = 'ok';
1094
- }
1095
-
1096
- // ----- Magic quotes trick
1097
- $this->privSwapBackMagicQuotes();
1098
-
1099
- // ----- Return
1100
- return $v_prop;
1101
- }
1102
- // --------------------------------------------------------------------------------
1103
-
1104
- // --------------------------------------------------------------------------------
1105
- // Function : duplicate()
1106
- // Description :
1107
- // This method creates an archive by copying the content of an other one. If
1108
- // the archive already exist, it is replaced by the new one without any warning.
1109
- // Parameters :
1110
- // $p_archive : The filename of a valid archive, or
1111
- // a valid PclZip object.
1112
- // Return Values :
1113
- // 1 on success.
1114
- // 0 or a negative value on error (error code).
1115
- // --------------------------------------------------------------------------------
1116
- public function duplicate($p_archive)
1117
- {
1118
- $v_result = 1;
1119
-
1120
- // ----- Reset the error handler
1121
- $this->privErrorReset();
1122
-
1123
- // ----- Look if the $p_archive is a PclZip object
1124
- if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) {
1125
- // ----- Duplicate the archive
1126
- $v_result = $this->privDuplicate($p_archive->zipname);
1127
- } elseif (is_string($p_archive)) {
1128
- // ----- Look if the $p_archive is a string (so a filename)
1129
- // ----- Check that $p_archive is a valid zip file
1130
- // TBC : Should also check the archive format
1131
- if (!is_file($p_archive)) {
1132
- // ----- Error log
1133
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
1134
- $v_result = PCLZIP_ERR_MISSING_FILE;
1135
- } else {
1136
- // ----- Duplicate the archive
1137
- $v_result = $this->privDuplicate($p_archive);
1138
- }
1139
- } else {
1140
- // ----- Invalid variable
1141
- // ----- Error log
1142
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
1143
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
1144
- }
1145
-
1146
- // ----- Return
1147
- return $v_result;
1148
- }
1149
- // --------------------------------------------------------------------------------
1150
-
1151
- // --------------------------------------------------------------------------------
1152
- // Function : merge()
1153
- // Description :
1154
- // This method merge the $p_archive_to_add archive at the end of the current
1155
- // one ($this).
1156
- // If the archive ($this) does not exist, the merge becomes a duplicate.
1157
- // If the $p_archive_to_add archive does not exist, the merge is a success.
1158
- // Parameters :
1159
- // $p_archive_to_add : It can be directly the filename of a valid zip archive,
1160
- // or a PclZip object archive.
1161
- // Return Values :
1162
- // 1 on success,
1163
- // 0 or negative values on error (see below).
1164
- // --------------------------------------------------------------------------------
1165
- public function merge($p_archive_to_add)
1166
- {
1167
- $v_result = 1;
1168
-
1169
- // ----- Reset the error handler
1170
- $this->privErrorReset();
1171
-
1172
- // ----- Check archive
1173
- if (!$this->privCheckFormat()) {
1174
- return(0);
1175
- }
1176
-
1177
- // ----- Look if the $p_archive_to_add is a PclZip object
1178
- if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) {
1179
- // ----- Merge the archive
1180
- $v_result = $this->privMerge($p_archive_to_add);
1181
- } elseif (is_string($p_archive_to_add)) {
1182
- // ----- Look if the $p_archive_to_add is a string (so a filename)
1183
- // ----- Create a temporary archive
1184
- $v_object_archive = new PclZip($p_archive_to_add);
1185
-
1186
- // ----- Merge the archive
1187
- $v_result = $this->privMerge($v_object_archive);
1188
- } else {
1189
- // ----- Invalid variable
1190
- // ----- Error log
1191
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
1192
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
1193
- }
1194
-
1195
- // ----- Return
1196
- return $v_result;
1197
- }
1198
- // --------------------------------------------------------------------------------
1199
-
1200
-
1201
-
1202
- // --------------------------------------------------------------------------------
1203
- // Function : errorCode()
1204
- // Description :
1205
- // Parameters :
1206
- // --------------------------------------------------------------------------------
1207
- public function errorCode()
1208
- {
1209
- if (PCLZIP_ERROR_EXTERNAL == 1) {
1210
- return(PclErrorCode());
1211
- } else {
1212
- return($this->error_code);
1213
- }
1214
- }
1215
- // --------------------------------------------------------------------------------
1216
-
1217
- // --------------------------------------------------------------------------------
1218
- // Function : errorName()
1219
- // Description :
1220
- // Parameters :
1221
- // --------------------------------------------------------------------------------
1222
- public function errorName($p_with_code = false)
1223
- {
1224
- $v_name = array(
1225
- PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
1226
- PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
1227
- PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
1228
- PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
1229
- PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
1230
- PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
1231
- PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
1232
- PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
1233
- PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
1234
- PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
1235
- PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
1236
- PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
1237
- PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
1238
- PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
1239
- PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
1240
- PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
1241
- PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
1242
- PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
1243
- PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION',
1244
- PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE',
1245
- PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION',
1246
- );
1247
-
1248
- if (isset($v_name[$this->error_code])) {
1249
- $v_value = $v_name[$this->error_code];
1250
- } else {
1251
- $v_value = 'NoName';
1252
- }
1253
-
1254
- if ($p_with_code) {
1255
- return($v_value.' ('.$this->error_code.')');
1256
- } else {
1257
- return($v_value);
1258
- }
1259
- }
1260
- // --------------------------------------------------------------------------------
1261
-
1262
- // --------------------------------------------------------------------------------
1263
- // Function : errorInfo()
1264
- // Description :
1265
- // Parameters :
1266
- // --------------------------------------------------------------------------------
1267
- public function errorInfo($p_full = false)
1268
- {
1269
- if (PCLZIP_ERROR_EXTERNAL == 1) {
1270
- return(PclErrorString());
1271
- } else {
1272
- if ($p_full) {
1273
- return($this->errorName(true)." : ".$this->error_string);
1274
- } else {
1275
- return($this->error_string." [code ".$this->error_code."]");
1276
- }
1277
- }
1278
- }
1279
- // --------------------------------------------------------------------------------
1280
-
1281
-
1282
- // --------------------------------------------------------------------------------
1283
- // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
1284
- // ***** *****
1285
- // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
1286
- // --------------------------------------------------------------------------------
1287
-
1288
-
1289
-
1290
- // --------------------------------------------------------------------------------
1291
- // Function : privCheckFormat()
1292
- // Description :
1293
- // This method check that the archive exists and is a valid zip archive.
1294
- // Several level of check exists. (futur)
1295
- // Parameters :
1296
- // $p_level : Level of check. Default 0.
1297
- // 0 : Check the first bytes (magic codes) (default value))
1298
- // 1 : 0 + Check the central directory (futur)
1299
- // 2 : 1 + Check each file header (futur)
1300
- // Return Values :
1301
- // true on success,
1302
- // false on error, the error code is set.
1303
- // --------------------------------------------------------------------------------
1304
- public function privCheckFormat($p_level = 0)
1305
- {
1306
- $v_result = true;
1307
-
1308
- // ----- Reset the file system cache
1309
- clearstatcache();
1310
-
1311
- // ----- Reset the error handler
1312
- $this->privErrorReset();
1313
-
1314
- // ----- Look if the file exits
1315
- if (!is_file($this->zipname)) {
1316
- // ----- Error log
1317
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
1318
- return(false);
1319
- }
1320
-
1321
- // ----- Check that the file is readeable
1322
- if (!is_readable($this->zipname)) {
1323
- // ----- Error log
1324
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
1325
- return(false);
1326
- }
1327
-
1328
- // ----- Check the magic code
1329
- // TBC
1330
-
1331
- // ----- Check the central header
1332
- // TBC
1333
-
1334
- // ----- Check each file header
1335
- // TBC
1336
-
1337
- // ----- Return
1338
- return $v_result;
1339
- }
1340
- // --------------------------------------------------------------------------------
1341
-
1342
- // --------------------------------------------------------------------------------
1343
- // Function : privParseOptions()
1344
- // Description :
1345
- // This internal methods reads the variable list of arguments ($p_options_list,
1346
- // $p_size) and generate an array with the options and values ($v_result_list).
1347
- // $v_requested_options contains the options that can be present and those that
1348
- // must be present.
1349
- // $v_requested_options is an array, with the option value as key, and 'optional',
1350
- // or 'mandatory' as value.
1351
- // Parameters :
1352
- // See above.
1353
- // Return Values :
1354
- // 1 on success.
1355
- // 0 on failure.
1356
- // --------------------------------------------------------------------------------
1357
- public function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options = false)
1358
- {
1359
- $v_result=1;
1360
-
1361
- // ----- Read the options
1362
- $i=0;
1363
- while ($i<$p_size) {
1364
- // ----- Check if the option is supported
1365
- if (!isset($v_requested_options[$p_options_list[$i]])) {
1366
- // ----- Error log
1367
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
1368
-
1369
- // ----- Return
1370
- return PclZip::errorCode();
1371
- }
1372
-
1373
- // ----- Look for next option
1374
- switch ($p_options_list[$i]) {
1375
- // ----- Look for options that request a path value
1376
- case PCLZIP_OPT_PATH:
1377
- case PCLZIP_OPT_REMOVE_PATH:
1378
- case PCLZIP_OPT_ADD_PATH:
1379
- // ----- Check the number of parameters
1380
- if (($i+1) >= $p_size) {
1381
- // ----- Error log
1382
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1383
-
1384
- // ----- Return
1385
- return PclZip::errorCode();
1386
- }
1387
-
1388
- // ----- Get the value
1389
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false);
1390
- $i++;
1391
- break;
1392
-
1393
- case PCLZIP_OPT_TEMP_FILE_THRESHOLD:
1394
- // ----- Check the number of parameters
1395
- if (($i+1) >= $p_size) {
1396
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1397
- return PclZip::errorCode();
1398
- }
1399
-
1400
- // ----- Check for incompatible options
1401
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
1402
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
1403
- return PclZip::errorCode();
1404
- }
1405
-
1406
- // ----- Check the value
1407
- $v_value = $p_options_list[$i+1];
1408
- if ((!is_integer($v_value)) || ($v_value<0)) {
1409
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1410
- return PclZip::errorCode();
1411
- }
1412
-
1413
- // ----- Get the value (and convert it in bytes)
1414
- $v_result_list[$p_options_list[$i]] = $v_value*1048576;
1415
- $i++;
1416
- break;
1417
-
1418
- case PCLZIP_OPT_TEMP_FILE_ON:
1419
- // ----- Check for incompatible options
1420
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
1421
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
1422
- return PclZip::errorCode();
1423
- }
1424
-
1425
- $v_result_list[$p_options_list[$i]] = true;
1426
- break;
1427
-
1428
- case PCLZIP_OPT_TEMP_FILE_OFF:
1429
- // ----- Check for incompatible options
1430
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
1431
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
1432
- return PclZip::errorCode();
1433
- }
1434
- // ----- Check for incompatible options
1435
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
1436
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
1437
- return PclZip::errorCode();
1438
- }
1439
- $v_result_list[$p_options_list[$i]] = true;
1440
- break;
1441
-
1442
- case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION:
1443
- // ----- Check the number of parameters
1444
- if (($i+1) >= $p_size) {
1445
- // ----- Error log
1446
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1447
- // ----- Return
1448
- return PclZip::errorCode();
1449
- }
1450
-
1451
- // ----- Get the value
1452
- if (is_string($p_options_list[$i+1]) && ($p_options_list[$i+1] != '')) {
1453
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false);
1454
- $i++;
1455
- } else {
1456
- }
1457
- break;
1458
- // ----- Look for options that request an array of string for value
1459
- case PCLZIP_OPT_BY_NAME:
1460
- // ----- Check the number of parameters
1461
- if (($i+1) >= $p_size) {
1462
- // ----- Error log
1463
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1464
- // ----- Return
1465
- return PclZip::errorCode();
1466
- }
1467
-
1468
- // ----- Get the value
1469
- if (is_string($p_options_list[$i+1])) {
1470
- $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
1471
- } elseif (is_array($p_options_list[$i+1])) {
1472
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
1473
- } else {
1474
- // ----- Error log
1475
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1476
- // ----- Return
1477
- return PclZip::errorCode();
1478
- }
1479
- $i++;
1480
- break;
1481
- // ----- Look for options that request an EREG or PREG expression
1482
- case PCLZIP_OPT_BY_EREG:
1483
- // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
1484
- // to PCLZIP_OPT_BY_PREG
1485
- $p_options_list[$i] = PCLZIP_OPT_BY_PREG;
1486
- case PCLZIP_OPT_BY_PREG:
1487
- //case PCLZIP_OPT_CRYPT :
1488
- // ----- Check the number of parameters
1489
- if (($i+1) >= $p_size) {
1490
- // ----- Error log
1491
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1492
- // ----- Return
1493
- return PclZip::errorCode();
1494
- }
1495
-
1496
- // ----- Get the value
1497
- if (is_string($p_options_list[$i+1])) {
1498
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
1499
- } else {
1500
- // ----- Error log
1501
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1502
- // ----- Return
1503
- return PclZip::errorCode();
1504
- }
1505
- $i++;
1506
- break;
1507
-
1508
- // ----- Look for options that takes a string
1509
- case PCLZIP_OPT_COMMENT:
1510
- case PCLZIP_OPT_ADD_COMMENT:
1511
- case PCLZIP_OPT_PREPEND_COMMENT:
1512
- // ----- Check the number of parameters
1513
- if (($i+1) >= $p_size) {
1514
- // ----- Error log
1515
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1516
-
1517
- // ----- Return
1518
- return PclZip::errorCode();
1519
- }
1520
-
1521
- // ----- Get the value
1522
- if (is_string($p_options_list[$i+1])) {
1523
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
1524
- } else {
1525
- // ----- Error log
1526
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'");
1527
-
1528
- // ----- Return
1529
- return PclZip::errorCode();
1530
- }
1531
- $i++;
1532
- break;
1533
-
1534
- // ----- Look for options that request an array of index
1535
- case PCLZIP_OPT_BY_INDEX:
1536
- // ----- Check the number of parameters
1537
- if (($i+1) >= $p_size) {
1538
- // ----- Error log
1539
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1540
-
1541
- // ----- Return
1542
- return PclZip::errorCode();
1543
- }
1544
-
1545
- // ----- Get the value
1546
- $v_work_list = array();
1547
- if (is_string($p_options_list[$i+1])) {
1548
- // ----- Remove spaces
1549
- $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
1550
-
1551
- // ----- Parse items
1552
- $v_work_list = explode(",", $p_options_list[$i+1]);
1553
- } elseif (is_integer($p_options_list[$i+1])) {
1554
- $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
1555
- } elseif (is_array($p_options_list[$i+1])) {
1556
- $v_work_list = $p_options_list[$i+1];
1557
- } else {
1558
- // ----- Error log
1559
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1560
-
1561
- // ----- Return
1562
- return PclZip::errorCode();
1563
- }
1564
-
1565
- // ----- Reduce the index list
1566
- // each index item in the list must be a couple with a start and
1567
- // an end value : [0,3], [5-5], [8-10], ...
1568
- // ----- Check the format of each item
1569
- $v_sort_flag=false;
1570
- $v_sort_value=0;
1571
- for ($j=0; $j<sizeof($v_work_list); $j++) {
1572
- // ----- Explode the item
1573
- $v_item_list = explode("-", $v_work_list[$j]);
1574
- $v_size_item_list = sizeof($v_item_list);
1575
-
1576
- // ----- TBC : Here we might check that each item is a
1577
- // real integer ...
1578
-
1579
- // ----- Look for single value
1580
- if ($v_size_item_list == 1) {
1581
- // ----- Set the option value
1582
- $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
1583
- $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
1584
- } elseif ($v_size_item_list == 2) {
1585
- // ----- Set the option value
1586
- $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
1587
- $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
1588
- } else {
1589
- // ----- Error log
1590
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1591
-
1592
- // ----- Return
1593
- return PclZip::errorCode();
1594
- }
1595
-
1596
-
1597
- // ----- Look for list sort
1598
- if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
1599
- $v_sort_flag=true;
1600
-
1601
- // ----- TBC : An automatic sort should be writen ...
1602
- // ----- Error log
1603
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1604
-
1605
- // ----- Return
1606
- return PclZip::errorCode();
1607
- }
1608
- $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
1609
- }
1610
-
1611
- // ----- Sort the items
1612
- if ($v_sort_flag) {
1613
- // TBC : To Be Completed
1614
- }
1615
- // ----- Next option
1616
- $i++;
1617
- break;
1618
- // ----- Look for options that request no value
1619
- case PCLZIP_OPT_REMOVE_ALL_PATH:
1620
- case PCLZIP_OPT_EXTRACT_AS_STRING:
1621
- case PCLZIP_OPT_NO_COMPRESSION:
1622
- case PCLZIP_OPT_EXTRACT_IN_OUTPUT:
1623
- case PCLZIP_OPT_REPLACE_NEWER:
1624
- case PCLZIP_OPT_STOP_ON_ERROR:
1625
- $v_result_list[$p_options_list[$i]] = true;
1626
- break;
1627
- // ----- Look for options that request an octal value
1628
- case PCLZIP_OPT_SET_CHMOD:
1629
- // ----- Check the number of parameters
1630
- if (($i+1) >= $p_size) {
1631
- // ----- Error log
1632
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1633
- // ----- Return
1634
- return PclZip::errorCode();
1635
- }
1636
- // ----- Get the value
1637
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
1638
- $i++;
1639
- break;
1640
-
1641
- // ----- Look for options that request a call-back
1642
- case PCLZIP_CB_PRE_EXTRACT:
1643
- case PCLZIP_CB_POST_EXTRACT:
1644
- case PCLZIP_CB_PRE_ADD:
1645
- case PCLZIP_CB_POST_ADD:
1646
- /* for futur use
1647
- case PCLZIP_CB_PRE_DELETE :
1648
- case PCLZIP_CB_POST_DELETE :
1649
- case PCLZIP_CB_PRE_LIST :
1650
- case PCLZIP_CB_POST_LIST :
1651
- */
1652
- // ----- Check the number of parameters
1653
- if (($i+1) >= $p_size) {
1654
- // ----- Error log
1655
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1656
- // ----- Return
1657
- return PclZip::errorCode();
1658
- }
1659
-
1660
- // ----- Get the value
1661
- $v_function_name = $p_options_list[$i+1];
1662
-
1663
- // ----- Check that the value is a valid existing function
1664
- if (!function_exists($v_function_name)) {
1665
- // ----- Error log
1666
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
1667
- // ----- Return
1668
- return PclZip::errorCode();
1669
- }
1670
-
1671
- // ----- Set the attribute
1672
- $v_result_list[$p_options_list[$i]] = $v_function_name;
1673
- $i++;
1674
- break;
1675
- default:
1676
- // ----- Error log
1677
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" .$p_options_list[$i]."'");
1678
-
1679
- // ----- Return
1680
- return PclZip::errorCode();
1681
- }
1682
-
1683
- // ----- Next options
1684
- $i++;
1685
- }
1686
-
1687
- // ----- Look for mandatory options
1688
- if ($v_requested_options !== false) {
1689
- for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
1690
- // ----- Look for mandatory option
1691
- if ($v_requested_options[$key] == 'mandatory') {
1692
- // ----- Look if present
1693
- if (!isset($v_result_list[$key])) {
1694
- // ----- Error log
1695
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
1696
-
1697
- // ----- Return
1698
- return PclZip::errorCode();
1699
- }
1700
- }
1701
- }
1702
- }
1703
-
1704
- // ----- Look for default values
1705
- if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
1706
- }
1707
-
1708
- // ----- Return
1709
- return $v_result;
1710
- }
1711
- // --------------------------------------------------------------------------------
1712
-
1713
- // --------------------------------------------------------------------------------
1714
- // Function : privOptionDefaultThreshold()
1715
- // Description :
1716
- // Parameters :
1717
- // Return Values :
1718
- // --------------------------------------------------------------------------------
1719
- public function privOptionDefaultThreshold(&$p_options)
1720
- {
1721
- $v_result=1;
1722
-
1723
- if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) {
1724
- return $v_result;
1725
- }
1726
-
1727
- // ----- Get 'memory_limit' configuration value
1728
- $v_memory_limit = ini_get('memory_limit');
1729
- $v_memory_limit = trim($v_memory_limit);
1730
- $last = substr($v_memory_limit, -1);
1731
- $v_memory_limit = trim($v_memory_limit, $last);
1732
- $last = strtolower($last);
1733
-
1734
- if ($last == 'g') {
1735
- //$v_memory_limit = $v_memory_limit*1024*1024*1024;
1736
- $v_memory_limit = $v_memory_limit*1073741824;
1737
- }
1738
- if ($last == 'm') {
1739
- //$v_memory_limit = $v_memory_limit*1024*1024;
1740
- $v_memory_limit = $v_memory_limit*1048576;
1741
- }
1742
- if ($last == 'k') {
1743
- $v_memory_limit = $v_memory_limit*1024;
1744
- }
1745
-
1746
- $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = is_numeric($v_memory_limit) ? floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO) : 0;
1747
-
1748
- // ----- Sanity check : No threshold if value lower than 1M
1749
- if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
1750
- unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
1751
- }
1752
-
1753
- // ----- Return
1754
- return $v_result;
1755
- }
1756
- // --------------------------------------------------------------------------------
1757
-
1758
- // --------------------------------------------------------------------------------
1759
- // Function : privFileDescrParseAtt()
1760
- // Description :
1761
- // Parameters :
1762
- // Return Values :
1763
- // 1 on success.
1764
- // 0 on failure.
1765
- // --------------------------------------------------------------------------------
1766
- public function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options = false)
1767
- {
1768
- $v_result=1;
1769
-
1770
- // ----- For each file in the list check the attributes
1771
- foreach ($p_file_list as $v_key => $v_value) {
1772
- // ----- Check if the option is supported
1773
- if (!isset($v_requested_options[$v_key])) {
1774
- // ----- Error log
1775
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
1776
-
1777
- // ----- Return
1778
- return PclZip::errorCode();
1779
- }
1780
-
1781
- // ----- Look for attribute
1782
- switch ($v_key) {
1783
- case PCLZIP_ATT_FILE_NAME:
1784
- if (!is_string($v_value)) {
1785
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
1786
- return PclZip::errorCode();
1787
- }
1788
-
1789
- $p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
1790
-
1791
- if ($p_filedescr['filename'] == '') {
1792
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'");
1793
- return PclZip::errorCode();
1794
- }
1795
- break;
1796
- case PCLZIP_ATT_FILE_NEW_SHORT_NAME:
1797
- if (!is_string($v_value)) {
1798
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
1799
- return PclZip::errorCode();
1800
- }
1801
-
1802
- $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
1803
-
1804
- if ($p_filedescr['new_short_name'] == '') {
1805
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'");
1806
- return PclZip::errorCode();
1807
- }
1808
- break;
1809
- case PCLZIP_ATT_FILE_NEW_FULL_NAME:
1810
- if (!is_string($v_value)) {
1811
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
1812
- return PclZip::errorCode();
1813
- }
1814
-
1815
- $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
1816
-
1817
- if ($p_filedescr['new_full_name'] == '') {
1818
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'");
1819
- return PclZip::errorCode();
1820
- }
1821
- break;
1822
- // ----- Look for options that takes a string
1823
- case PCLZIP_ATT_FILE_COMMENT:
1824
- if (!is_string($v_value)) {
1825
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
1826
- return PclZip::errorCode();
1827
- }
1828
- $p_filedescr['comment'] = $v_value;
1829
- break;
1830
- case PCLZIP_ATT_FILE_MTIME:
1831
- if (!is_integer($v_value)) {
1832
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'");
1833
- return PclZip::errorCode();
1834
- }
1835
- $p_filedescr['mtime'] = $v_value;
1836
- break;
1837
- case PCLZIP_ATT_FILE_CONTENT:
1838
- $p_filedescr['content'] = $v_value;
1839
- break;
1840
- default:
1841
- // ----- Error log
1842
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '".$v_key."'");
1843
-
1844
- // ----- Return
1845
- return PclZip::errorCode();
1846
- }
1847
-
1848
- // ----- Look for mandatory options
1849
- if ($v_requested_options !== false) {
1850
- for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) {
1851
- // ----- Look for mandatory option
1852
- if ($v_requested_options[$key] == 'mandatory') {
1853
- // ----- Look if present
1854
- if (!isset($p_file_list[$key])) {
1855
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
1856
- return PclZip::errorCode();
1857
- }
1858
- }
1859
- }
1860
- }
1861
- }
1862
-
1863
- // ----- Return
1864
- return $v_result;
1865
- }
1866
- // --------------------------------------------------------------------------------
1867
-
1868
- // --------------------------------------------------------------------------------
1869
- // Function : privFileDescrExpand()
1870
- // Description :
1871
- // This method look for each item of the list to see if its a file, a folder
1872
- // or a string to be added as file. For any other type of files (link, other)
1873
- // just ignore the item.
1874
- // Then prepare the information that will be stored for that file.
1875
- // When its a folder, expand the folder with all the files that are in that
1876
- // folder (recursively).
1877
- // Parameters :
1878
- // Return Values :
1879
- // 1 on success.
1880
- // 0 on failure.
1881
- // --------------------------------------------------------------------------------
1882
- public function privFileDescrExpand(&$p_filedescr_list, &$p_options)
1883
- {
1884
- $v_result=1;
1885
-
1886
- // ----- Create a result list
1887
- $v_result_list = array();
1888
-
1889
- // ----- Look each entry
1890
- for ($i=0; $i<sizeof($p_filedescr_list); $i++) {
1891
- // ----- Get filedescr
1892
- $v_descr = $p_filedescr_list[$i];
1893
-
1894
- // ----- Reduce the filename
1895
- $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false);
1896
- $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']);
1897
-
1898
- // ----- Look for real file or folder
1899
- if (file_exists($v_descr['filename'])) {
1900
- if (@is_file($v_descr['filename'])) {
1901
- $v_descr['type'] = 'file';
1902
- } elseif (@is_dir($v_descr['filename'])) {
1903
- $v_descr['type'] = 'folder';
1904
- } elseif (@is_link($v_descr['filename'])) {
1905
- // skip
1906
- continue;
1907
- } else {
1908
- // skip
1909
- continue;
1910
- }
1911
- } elseif (isset($v_descr['content'])) {
1912
- // ----- Look for string added as file
1913
- $v_descr['type'] = 'virtual_file';
1914
- } else {
1915
- // ----- Missing file
1916
- // ----- Error log
1917
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist");
1918
-
1919
- // ----- Return
1920
- return PclZip::errorCode();
1921
- }
1922
-
1923
- // ----- Calculate the stored filename
1924
- $this->privCalculateStoredFilename($v_descr, $p_options);
1925
-
1926
- // ----- Add the descriptor in result list
1927
- $v_result_list[sizeof($v_result_list)] = $v_descr;
1928
-
1929
- // ----- Look for folder
1930
- if ($v_descr['type'] == 'folder') {
1931
- // ----- List of items in folder
1932
- $v_dirlist_descr = array();
1933
- $v_dirlist_nb = 0;
1934
- if ($v_folder_handler = @opendir($v_descr['filename'])) {
1935
- while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
1936
- // ----- Skip '.' and '..'
1937
- if (($v_item_handler == '.') || ($v_item_handler == '..')) {
1938
- continue;
1939
- }
1940
-
1941
- // ----- Compose the full filename
1942
- $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
1943
-
1944
- // ----- Look for different stored filename
1945
- // Because the name of the folder was changed, the name of the
1946
- // files/sub-folders also change
1947
- if (($v_descr['stored_filename'] != $v_descr['filename'])
1948
- && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
1949
- if ($v_descr['stored_filename'] != '') {
1950
- $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
1951
- } else {
1952
- $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
1953
- }
1954
- }
1955
- $v_dirlist_nb++;
1956
- }
1957
-
1958
- @closedir($v_folder_handler);
1959
- } else {
1960
- // TBC : unable to open folder in read mode
1961
- }
1962
-
1963
- // ----- Expand each element of the list
1964
- if ($v_dirlist_nb != 0) {
1965
- // ----- Expand
1966
- if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
1967
- return $v_result;
1968
- }
1969
-
1970
- // ----- Concat the resulting list
1971
- $v_result_list = array_merge($v_result_list, $v_dirlist_descr);
1972
- }
1973
-
1974
- // ----- Free local array
1975
- unset($v_dirlist_descr);
1976
- }
1977
- }
1978
-
1979
- // ----- Get the result list
1980
- $p_filedescr_list = $v_result_list;
1981
-
1982
- // ----- Return
1983
- return $v_result;
1984
- }
1985
- // --------------------------------------------------------------------------------
1986
-
1987
- // --------------------------------------------------------------------------------
1988
- // Function : privCreate()
1989
- // Description :
1990
- // Parameters :
1991
- // Return Values :
1992
- // --------------------------------------------------------------------------------
1993
- public function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
1994
- {
1995
- $v_result=1;
1996
- $v_list_detail = array();
1997
-
1998
- // ----- Magic quotes trick
1999
- $this->privDisableMagicQuotes();
2000
-
2001
- // ----- Open the file in write mode
2002
- if (($v_result = $this->privOpenFd('wb')) != 1) {
2003
- // ----- Return
2004
- return $v_result;
2005
- }
2006
-
2007
- // ----- Add the list of files
2008
- $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
2009
-
2010
- // ----- Close
2011
- $this->privCloseFd();
2012
-
2013
- // ----- Magic quotes trick
2014
- $this->privSwapBackMagicQuotes();
2015
-
2016
- // ----- Return
2017
- return $v_result;
2018
- }
2019
- // --------------------------------------------------------------------------------
2020
-
2021
- // --------------------------------------------------------------------------------
2022
- // Function : privAdd()
2023
- // Description :
2024
- // Parameters :
2025
- // Return Values :
2026
- // --------------------------------------------------------------------------------
2027
- public function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
2028
- {
2029
- $v_result=1;
2030
- $v_list_detail = array();
2031
-
2032
- // ----- Look if the archive exists or is empty
2033
- if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) {
2034
- // ----- Do a create
2035
- $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
2036
-
2037
- // ----- Return
2038
- return $v_result;
2039
- }
2040
- // ----- Magic quotes trick
2041
- $this->privDisableMagicQuotes();
2042
-
2043
- // ----- Open the zip file
2044
- if (($v_result=$this->privOpenFd('rb')) != 1) {
2045
- // ----- Magic quotes trick
2046
- $this->privSwapBackMagicQuotes();
2047
-
2048
- // ----- Return
2049
- return $v_result;
2050
- }
2051
-
2052
- // ----- Read the central directory informations
2053
- $v_central_dir = array();
2054
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
2055
- $this->privCloseFd();
2056
- $this->privSwapBackMagicQuotes();
2057
- return $v_result;
2058
- }
2059
-
2060
- // ----- Go to beginning of File
2061
- @rewind($this->zip_fd);
2062
-
2063
- // ----- Creates a temporay file
2064
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
2065
-
2066
- // ----- Open the temporary file in write mode
2067
- if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
2068
- $this->privCloseFd();
2069
- $this->privSwapBackMagicQuotes();
2070
-
2071
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
2072
-
2073
- // ----- Return
2074
- return PclZip::errorCode();
2075
- }
2076
-
2077
- // ----- Copy the files from the archive to the temporary file
2078
- // TBC : Here I should better append the file and go back to erase the central dir
2079
- $v_size = $v_central_dir['offset'];
2080
- while ($v_size != 0) {
2081
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
2082
- $v_buffer = fread($this->zip_fd, $v_read_size);
2083
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
2084
- $v_size -= $v_read_size;
2085
- }
2086
-
2087
- // ----- Swap the file descriptor
2088
- // Here is a trick : I swap the temporary fd with the zip fd, in order to use
2089
- // the following methods on the temporary fil and not the real archive
2090
- $v_swap = $this->zip_fd;
2091
- $this->zip_fd = $v_zip_temp_fd;
2092
- $v_zip_temp_fd = $v_swap;
2093
-
2094
- // ----- Add the files
2095
- $v_header_list = array();
2096
- if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
2097
- fclose($v_zip_temp_fd);
2098
- $this->privCloseFd();
2099
- @unlink($v_zip_temp_name);
2100
- $this->privSwapBackMagicQuotes();
2101
-
2102
- // ----- Return
2103
- return $v_result;
2104
- }
2105
-
2106
- // ----- Store the offset of the central dir
2107
- $v_offset = @ftell($this->zip_fd);
2108
-
2109
- // ----- Copy the block of file headers from the old archive
2110
- $v_size = $v_central_dir['size'];
2111
- while ($v_size != 0) {
2112
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
2113
- $v_buffer = @fread($v_zip_temp_fd, $v_read_size);
2114
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
2115
- $v_size -= $v_read_size;
2116
- }
2117
-
2118
- // ----- Create the Central Dir files header
2119
- for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) {
2120
- // ----- Create the file header
2121
- if ($v_header_list[$i]['status'] == 'ok') {
2122
- if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
2123
- fclose($v_zip_temp_fd);
2124
- $this->privCloseFd();
2125
- @unlink($v_zip_temp_name);
2126
- $this->privSwapBackMagicQuotes();
2127
-
2128
- // ----- Return
2129
- return $v_result;
2130
- }
2131
- $v_count++;
2132
- }
2133
-
2134
- // ----- Transform the header to a 'usable' info
2135
- $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
2136
- }
2137
-
2138
- // ----- Zip file comment
2139
- $v_comment = $v_central_dir['comment'];
2140
- if (isset($p_options[PCLZIP_OPT_COMMENT])) {
2141
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
2142
- }
2143
- if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
2144
- $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT];
2145
- }
2146
- if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
2147
- $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
2148
- }
2149
-
2150
- // ----- Calculate the size of the central header
2151
- $v_size = @ftell($this->zip_fd)-$v_offset;
2152
-
2153
- // ----- Create the central dir footer
2154
- if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) {
2155
- // ----- Reset the file list
2156
- unset($v_header_list);
2157
- $this->privSwapBackMagicQuotes();
2158
-
2159
- // ----- Return
2160
- return $v_result;
2161
- }
2162
-
2163
- // ----- Swap back the file descriptor
2164
- $v_swap = $this->zip_fd;
2165
- $this->zip_fd = $v_zip_temp_fd;
2166
- $v_zip_temp_fd = $v_swap;
2167
-
2168
- // ----- Close
2169
- $this->privCloseFd();
2170
-
2171
- // ----- Close the temporary file
2172
- @fclose($v_zip_temp_fd);
2173
-
2174
- // ----- Magic quotes trick
2175
- $this->privSwapBackMagicQuotes();
2176
-
2177
- // ----- Delete the zip file
2178
- // TBC : I should test the result ...
2179
- @unlink($this->zipname);
2180
-
2181
- // ----- Rename the temporary file
2182
- // TBC : I should test the result ...
2183
- //@rename($v_zip_temp_name, $this->zipname);
2184
- PclZipUtilRename($v_zip_temp_name, $this->zipname);
2185
-
2186
- // ----- Return
2187
- return $v_result;
2188
- }
2189
- // --------------------------------------------------------------------------------
2190
-
2191
- // --------------------------------------------------------------------------------
2192
- // Function : privOpenFd()
2193
- // Description :
2194
- // Parameters :
2195
- // --------------------------------------------------------------------------------
2196
- public function privOpenFd($p_mode)
2197
- {
2198
- $v_result=1;
2199
-
2200
- // ----- Look if already open
2201
- if ($this->zip_fd != 0) {
2202
- // ----- Error log
2203
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
2204
-
2205
- // ----- Return
2206
- return PclZip::errorCode();
2207
- }
2208
-
2209
- // ----- Open the zip file
2210
- if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) {
2211
- // ----- Error log
2212
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
2213
-
2214
- // ----- Return
2215
- return PclZip::errorCode();
2216
- }
2217
-
2218
- // ----- Return
2219
- return $v_result;
2220
- }
2221
- // --------------------------------------------------------------------------------
2222
-
2223
- // --------------------------------------------------------------------------------
2224
- // Function : privCloseFd()
2225
- // Description :
2226
- // Parameters :
2227
- // --------------------------------------------------------------------------------
2228
- public function privCloseFd()
2229
- {
2230
- $v_result=1;
2231
-
2232
- if ($this->zip_fd != 0) {
2233
- @fclose($this->zip_fd);
2234
- }
2235
- $this->zip_fd = 0;
2236
-
2237
- // ----- Return
2238
- return $v_result;
2239
- }
2240
- // --------------------------------------------------------------------------------
2241
-
2242
- // --------------------------------------------------------------------------------
2243
- // Function : privAddList()
2244
- // Description :
2245
- // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
2246
- // different from the real path of the file. This is usefull if you want to have PclTar
2247
- // running in any directory, and memorize relative path from an other directory.
2248
- // Parameters :
2249
- // $p_list : An array containing the file or directory names to add in the tar
2250
- // $p_result_list : list of added files with their properties (specially the status field)
2251
- // $p_add_dir : Path to add in the filename path archived
2252
- // $p_remove_dir : Path to remove in the filename path archived
2253
- // Return Values :
2254
- // --------------------------------------------------------------------------------
2255
- // public function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
2256
- public function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
2257
- {
2258
- $v_result=1;
2259
-
2260
- // ----- Add the files
2261
- $v_header_list = array();
2262
- if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
2263
- // ----- Return
2264
- return $v_result;
2265
- }
2266
-
2267
- // ----- Store the offset of the central dir
2268
- $v_offset = @ftell($this->zip_fd);
2269
-
2270
- // ----- Create the Central Dir files header
2271
- for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) {
2272
- // ----- Create the file header
2273
- if ($v_header_list[$i]['status'] == 'ok') {
2274
- if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
2275
- // ----- Return
2276
- return $v_result;
2277
- }
2278
- $v_count++;
2279
- }
2280
-
2281
- // ----- Transform the header to a 'usable' info
2282
- $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
2283
- }
2284
-
2285
- // ----- Zip file comment
2286
- $v_comment = '';
2287
- if (isset($p_options[PCLZIP_OPT_COMMENT])) {
2288
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
2289
- }
2290
-
2291
- // ----- Calculate the size of the central header
2292
- $v_size = @ftell($this->zip_fd)-$v_offset;
2293
-
2294
- // ----- Create the central dir footer
2295
- if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) {
2296
- // ----- Reset the file list
2297
- unset($v_header_list);
2298
-
2299
- // ----- Return
2300
- return $v_result;
2301
- }
2302
-
2303
- // ----- Return
2304
- return $v_result;
2305
- }
2306
- // --------------------------------------------------------------------------------
2307
-
2308
- // --------------------------------------------------------------------------------
2309
- // Function : privAddFileList()
2310
- // Description :
2311
- // Parameters :
2312
- // $p_filedescr_list : An array containing the file description
2313
- // or directory names to add in the zip
2314
- // $p_result_list : list of added files with their properties (specially the status field)
2315
- // Return Values :
2316
- // --------------------------------------------------------------------------------
2317
- public function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
2318
- {
2319
- $v_result=1;
2320
- $v_header = array();
2321
-
2322
- // ----- Recuperate the current number of elt in list
2323
- $v_nb = sizeof($p_result_list);
2324
-
2325
- // ----- Loop on the files
2326
- for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) {
2327
- // ----- Format the filename
2328
- $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
2329
-
2330
- // ----- Skip empty file names
2331
- // TBC : Can this be possible ? not checked in DescrParseAtt ?
2332
- if ($p_filedescr_list[$j]['filename'] == "") {
2333
- continue;
2334
- }
2335
-
2336
- // ----- Check the filename
2337
- if (($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) {
2338
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist");
2339
- return PclZip::errorCode();
2340
- }
2341
-
2342
- // ----- Look if it is a file or a dir with no all path remove option
2343
- // or a dir with all its path removed
2344
- // if ( (is_file($p_filedescr_list[$j]['filename']))
2345
- // || ( is_dir($p_filedescr_list[$j]['filename'])
2346
- if (($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || (($p_filedescr_list[$j]['type'] == 'folder') && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
2347
- // ----- Add the file
2348
- $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options);
2349
- if ($v_result != 1) {
2350
- return $v_result;
2351
- }
2352
-
2353
- // ----- Store the file infos
2354
- $p_result_list[$v_nb++] = $v_header;
2355
- }
2356
- }
2357
-
2358
- // ----- Return
2359
- return $v_result;
2360
- }
2361
- // --------------------------------------------------------------------------------
2362
-
2363
- // --------------------------------------------------------------------------------
2364
- // Function : privAddFile()
2365
- // Description :
2366
- // Parameters :
2367
- // Return Values :
2368
- // --------------------------------------------------------------------------------
2369
- public function privAddFile($p_filedescr, &$p_header, &$p_options)
2370
- {
2371
- $v_result=1;
2372
-
2373
- // ----- Working variable
2374
- $p_filename = $p_filedescr['filename'];
2375
-
2376
- // TBC : Already done in the fileAtt check ... ?
2377
- if ($p_filename == "") {
2378
- // ----- Error log
2379
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
2380
-
2381
- // ----- Return
2382
- return PclZip::errorCode();
2383
- }
2384
-
2385
- // ----- Look for a stored different filename
2386
- /* TBC : Removed
2387
- if (isset($p_filedescr['stored_filename'])) {
2388
- $v_stored_filename = $p_filedescr['stored_filename'];
2389
- }
2390
- else {
2391
- $v_stored_filename = $p_filedescr['stored_filename'];
2392
- }
2393
- */
2394
-
2395
- // ----- Set the file properties
2396
- clearstatcache();
2397
- $p_header['version'] = 20;
2398
- $p_header['version_extracted'] = 10;
2399
- $p_header['flag'] = 0;
2400
- $p_header['compression'] = 0;
2401
- $p_header['crc'] = 0;
2402
- $p_header['compressed_size'] = 0;
2403
- $p_header['filename_len'] = strlen($p_filename);
2404
- $p_header['extra_len'] = 0;
2405
- $p_header['disk'] = 0;
2406
- $p_header['internal'] = 0;
2407
- $p_header['offset'] = 0;
2408
- $p_header['filename'] = $p_filename;
2409
- // TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
2410
- $p_header['stored_filename'] = $p_filedescr['stored_filename'];
2411
- $p_header['extra'] = '';
2412
- $p_header['status'] = 'ok';
2413
- $p_header['index'] = -1;
2414
-
2415
- // ----- Look for regular file
2416
- if ($p_filedescr['type']=='file') {
2417
- $p_header['external'] = 0x00000000;
2418
- $p_header['size'] = filesize($p_filename);
2419
- } elseif ($p_filedescr['type']=='folder') {
2420
- // ----- Look for regular folder
2421
- $p_header['external'] = 0x00000010;
2422
- $p_header['mtime'] = filemtime($p_filename);
2423
- $p_header['size'] = filesize($p_filename);
2424
- } elseif ($p_filedescr['type'] == 'virtual_file') {
2425
- // ----- Look for virtual file
2426
- $p_header['external'] = 0x00000000;
2427
- $p_header['size'] = strlen($p_filedescr['content']);
2428
- }
2429
-
2430
- // ----- Look for filetime
2431
- if (isset($p_filedescr['mtime'])) {
2432
- $p_header['mtime'] = $p_filedescr['mtime'];
2433
- } elseif ($p_filedescr['type'] == 'virtual_file') {
2434
- $p_header['mtime'] = time();
2435
- } else {
2436
- $p_header['mtime'] = filemtime($p_filename);
2437
- }
2438
-
2439
- // ------ Look for file comment
2440
- if (isset($p_filedescr['comment'])) {
2441
- $p_header['comment_len'] = strlen($p_filedescr['comment']);
2442
- $p_header['comment'] = $p_filedescr['comment'];
2443
- } else {
2444
- $p_header['comment_len'] = 0;
2445
- $p_header['comment'] = '';
2446
- }
2447
-
2448
- // ----- Look for pre-add callback
2449
- if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
2450
- // ----- Generate a local information
2451
- $v_local_header = array();
2452
- $this->privConvertHeader2FileInfo($p_header, $v_local_header);
2453
-
2454
- // ----- Call the callback
2455
- // Here I do not use call_user_func() because I need to send a reference to the
2456
- // header.
2457
- // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');
2458
- $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);
2459
- if ($v_result == 0) {
2460
- // ----- Change the file status
2461
- $p_header['status'] = "skipped";
2462
- $v_result = 1;
2463
- }
2464
-
2465
- // ----- Update the informations
2466
- // Only some fields can be modified
2467
- if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
2468
- $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
2469
- }
2470
- }
2471
-
2472
- // ----- Look for empty stored filename
2473
- if ($p_header['stored_filename'] == "") {
2474
- $p_header['status'] = "filtered";
2475
- }
2476
-
2477
- // ----- Check the path length
2478
- if (strlen($p_header['stored_filename']) > 0xFF) {
2479
- $p_header['status'] = 'filename_too_long';
2480
- }
2481
-
2482
- // ----- Look if no error, or file not skipped
2483
- if ($p_header['status'] == 'ok') {
2484
- // ----- Look for a file
2485
- if ($p_filedescr['type'] == 'file') {
2486
- // ----- Look for using temporary file to zip
2487
- if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])))) {
2488
- $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
2489
- if ($v_result < PCLZIP_ERR_NO_ERROR) {
2490
- return $v_result;
2491
- }
2492
- } else {
2493
- // ----- Use "in memory" zip algo
2494
- // ----- Open the source file
2495
- if (($v_file = @fopen($p_filename, "rb")) == 0) {
2496
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
2497
- return PclZip::errorCode();
2498
- }
2499
-
2500
- // ----- Read the file content
2501
- $v_content = @fread($v_file, $p_header['size']);
2502
-
2503
- // ----- Close the file
2504
- @fclose($v_file);
2505
-
2506
- // ----- Calculate the CRC
2507
- $p_header['crc'] = @crc32($v_content);
2508
-
2509
- // ----- Look for no compression
2510
- if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
2511
- // ----- Set header parameters
2512
- $p_header['compressed_size'] = $p_header['size'];
2513
- $p_header['compression'] = 0;
2514
- } else {
2515
- // ----- Look for normal compression
2516
- // ----- Compress the content
2517
- $v_content = @gzdeflate($v_content);
2518
-
2519
- // ----- Set header parameters
2520
- $p_header['compressed_size'] = strlen($v_content);
2521
- $p_header['compression'] = 8;
2522
- }
2523
-
2524
- // ----- Call the header generation
2525
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2526
- @fclose($v_file);
2527
- return $v_result;
2528
- }
2529
-
2530
- // ----- Write the compressed (or not) content
2531
- @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
2532
- }
2533
- } elseif ($p_filedescr['type'] == 'virtual_file') {
2534
- // ----- Look for a virtual file (a file from string)
2535
- $v_content = $p_filedescr['content'];
2536
-
2537
- // ----- Calculate the CRC
2538
- $p_header['crc'] = @crc32($v_content);
2539
-
2540
- // ----- Look for no compression
2541
- if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
2542
- // ----- Set header parameters
2543
- $p_header['compressed_size'] = $p_header['size'];
2544
- $p_header['compression'] = 0;
2545
- } else {
2546
- // ----- Look for normal compression
2547
- // ----- Compress the content
2548
- $v_content = @gzdeflate($v_content);
2549
-
2550
- // ----- Set header parameters
2551
- $p_header['compressed_size'] = strlen($v_content);
2552
- $p_header['compression'] = 8;
2553
- }
2554
-
2555
- // ----- Call the header generation
2556
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2557
- @fclose($v_file);
2558
- return $v_result;
2559
- }
2560
-
2561
- // ----- Write the compressed (or not) content
2562
- @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
2563
- } elseif ($p_filedescr['type'] == 'folder') {
2564
- // ----- Look for a directory
2565
- // ----- Look for directory last '/'
2566
- if (@substr($p_header['stored_filename'], -1) != '/') {
2567
- $p_header['stored_filename'] .= '/';
2568
- }
2569
-
2570
- // ----- Set the file properties
2571
- $p_header['size'] = 0;
2572
- //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
2573
- $p_header['external'] = 0x00000010; // Value for a folder : to be checked
2574
-
2575
- // ----- Call the header generation
2576
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2577
- return $v_result;
2578
- }
2579
- }
2580
- }
2581
-
2582
- // ----- Look for post-add callback
2583
- if (isset($p_options[PCLZIP_CB_POST_ADD])) {
2584
- // ----- Generate a local information
2585
- $v_local_header = array();
2586
- $this->privConvertHeader2FileInfo($p_header, $v_local_header);
2587
-
2588
- // ----- Call the callback
2589
- // Here I do not use call_user_func() because I need to send a reference to the
2590
- // header.
2591
- // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
2592
- $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);
2593
- if ($v_result == 0) {
2594
- // ----- Ignored
2595
- $v_result = 1;
2596
- }
2597
-
2598
- // ----- Update the informations
2599
- // Nothing can be modified
2600
- }
2601
-
2602
- // ----- Return
2603
- return $v_result;
2604
- }
2605
- // --------------------------------------------------------------------------------
2606
-
2607
- // --------------------------------------------------------------------------------
2608
- // Function : privAddFileUsingTempFile()
2609
- // Description :
2610
- // Parameters :
2611
- // Return Values :
2612
- // --------------------------------------------------------------------------------
2613
- public function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
2614
- {
2615
- $v_result=PCLZIP_ERR_NO_ERROR;
2616
-
2617
- // ----- Working variable
2618
- $p_filename = $p_filedescr['filename'];
2619
-
2620
-
2621
- // ----- Open the source file
2622
- if (($v_file = @fopen($p_filename, "rb")) == 0) {
2623
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
2624
- return PclZip::errorCode();
2625
- }
2626
-
2627
- // ----- Creates a compressed temporary file
2628
- $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
2629
- if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
2630
- fclose($v_file);
2631
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
2632
- return PclZip::errorCode();
2633
- }
2634
-
2635
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
2636
- $v_size = filesize($p_filename);
2637
- while ($v_size != 0) {
2638
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
2639
- $v_buffer = @fread($v_file, $v_read_size);
2640
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
2641
- @gzputs($v_file_compressed, $v_buffer, $v_read_size);
2642
- $v_size -= $v_read_size;
2643
- }
2644
-
2645
- // ----- Close the file
2646
- @fclose($v_file);
2647
- @gzclose($v_file_compressed);
2648
-
2649
- // ----- Check the minimum file size
2650
- if (filesize($v_gzip_temp_name) < 18) {
2651
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes');
2652
- return PclZip::errorCode();
2653
- }
2654
-
2655
- // ----- Extract the compressed attributes
2656
- if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
2657
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
2658
- return PclZip::errorCode();
2659
- }
2660
-
2661
- // ----- Read the gzip file header
2662
- $v_binary_data = @fread($v_file_compressed, 10);
2663
- $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
2664
-
2665
- // ----- Check some parameters
2666
- $v_data_header['os'] = bin2hex($v_data_header['os']);
2667
-
2668
- // ----- Read the gzip file footer
2669
- @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
2670
- $v_binary_data = @fread($v_file_compressed, 8);
2671
- $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
2672
-
2673
- // ----- Set the attributes
2674
- $p_header['compression'] = ord($v_data_header['cm']);
2675
- //$p_header['mtime'] = $v_data_header['mtime'];
2676
- $p_header['crc'] = $v_data_footer['crc'];
2677
- $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
2678
-
2679
- // ----- Close the file
2680
- @fclose($v_file_compressed);
2681
-
2682
- // ----- Call the header generation
2683
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2684
- return $v_result;
2685
- }
2686
-
2687
- // ----- Add the compressed data
2688
- if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
2689
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
2690
- return PclZip::errorCode();
2691
- }
2692
-
2693
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
2694
- fseek($v_file_compressed, 10);
2695
- $v_size = $p_header['compressed_size'];
2696
- while ($v_size != 0) {
2697
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
2698
- $v_buffer = @fread($v_file_compressed, $v_read_size);
2699
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
2700
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
2701
- $v_size -= $v_read_size;
2702
- }
2703
-
2704
- // ----- Close the file
2705
- @fclose($v_file_compressed);
2706
-
2707
- // ----- Unlink the temporary file
2708
- @unlink($v_gzip_temp_name);
2709
-
2710
- // ----- Return
2711
- return $v_result;
2712
- }
2713
- // --------------------------------------------------------------------------------
2714
-
2715
- // --------------------------------------------------------------------------------
2716
- // Function : privCalculateStoredFilename()
2717
- // Description :
2718
- // Based on file descriptor properties and global options, this method
2719
- // calculate the filename that will be stored in the archive.
2720
- // Parameters :
2721
- // Return Values :
2722
- // --------------------------------------------------------------------------------
2723
- public function privCalculateStoredFilename(&$p_filedescr, &$p_options)
2724
- {
2725
- $v_result=1;
2726
-
2727
- // ----- Working variables
2728
- $p_filename = $p_filedescr['filename'];
2729
- if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
2730
- $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
2731
- } else {
2732
- $p_add_dir = '';
2733
- }
2734
- if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
2735
- $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
2736
- } else {
2737
- $p_remove_dir = '';
2738
- }
2739
- if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
2740
- $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
2741
- } else {
2742
- $p_remove_all_dir = 0;
2743
- }
2744
-
2745
- // ----- Look for full name change
2746
- if (isset($p_filedescr['new_full_name'])) {
2747
- // ----- Remove drive letter if any
2748
- $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
2749
- } else {
2750
- // ----- Look for path and/or short name change
2751
- // ----- Look for short name change
2752
- // Its when we cahnge just the filename but not the path
2753
- if (isset($p_filedescr['new_short_name'])) {
2754
- $v_path_info = pathinfo($p_filename);
2755
- $v_dir = '';
2756
- if ($v_path_info['dirname'] != '') {
2757
- $v_dir = $v_path_info['dirname'].'/';
2758
- }
2759
- $v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
2760
- } else {
2761
- // ----- Calculate the stored filename
2762
- $v_stored_filename = $p_filename;
2763
- }
2764
-
2765
- // ----- Look for all path to remove
2766
- if ($p_remove_all_dir) {
2767
- $v_stored_filename = basename($p_filename);
2768
- } elseif ($p_remove_dir != "") {
2769
- // ----- Look for partial path remove
2770
- if (substr($p_remove_dir, -1) != '/') {
2771
- $p_remove_dir .= "/";
2772
- }
2773
-
2774
- if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) {
2775
- if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) {
2776
- $p_remove_dir = "./".$p_remove_dir;
2777
- }
2778
- if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) {
2779
- $p_remove_dir = substr($p_remove_dir, 2);
2780
- }
2781
- }
2782
-
2783
- $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename);
2784
- if ($v_compare > 0) {
2785
- if ($v_compare == 2) {
2786
- $v_stored_filename = "";
2787
- } else {
2788
- $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir));
2789
- }
2790
- }
2791
- }
2792
-
2793
- // ----- Remove drive letter if any
2794
- $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename);
2795
-
2796
- // ----- Look for path to add
2797
- if ($p_add_dir != "") {
2798
- if (substr($p_add_dir, -1) == "/") {
2799
- $v_stored_filename = $p_add_dir.$v_stored_filename;
2800
- } else {
2801
- $v_stored_filename = $p_add_dir."/".$v_stored_filename;
2802
- }
2803
- }
2804
- }
2805
-
2806
- // ----- Filename (reduce the path of stored name)
2807
- $v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
2808
- $p_filedescr['stored_filename'] = $v_stored_filename;
2809
-
2810
- // ----- Return
2811
- return $v_result;
2812
- }
2813
- // --------------------------------------------------------------------------------
2814
-
2815
- // --------------------------------------------------------------------------------
2816
- // Function : privWriteFileHeader()
2817
- // Description :
2818
- // Parameters :
2819
- // Return Values :
2820
- // --------------------------------------------------------------------------------
2821
- public function privWriteFileHeader(&$p_header)
2822
- {
2823
- $v_result=1;
2824
-
2825
- // ----- Store the offset position of the file
2826
- $p_header['offset'] = ftell($this->zip_fd);
2827
-
2828
- // ----- Transform UNIX mtime to DOS format mdate/mtime
2829
- $v_date = getdate($p_header['mtime']);
2830
- $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
2831
- $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
2832
-
2833
- // ----- Packed data
2834
- $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']);
2835
-
2836
- // ----- Write the first 148 bytes of the header in the archive
2837
- fputs($this->zip_fd, $v_binary_data, 30);
2838
-
2839
- // ----- Write the variable fields
2840
- if (strlen($p_header['stored_filename']) != 0) {
2841
- fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
2842
- }
2843
- if ($p_header['extra_len'] != 0) {
2844
- fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
2845
- }
2846
-
2847
- // ----- Return
2848
- return $v_result;
2849
- }
2850
- // --------------------------------------------------------------------------------
2851
-
2852
- // --------------------------------------------------------------------------------
2853
- // Function : privWriteCentralFileHeader()
2854
- // Description :
2855
- // Parameters :
2856
- // Return Values :
2857
- // --------------------------------------------------------------------------------
2858
- public function privWriteCentralFileHeader(&$p_header)
2859
- {
2860
- $v_result=1;
2861
-
2862
- // TBC
2863
- //for(reset($p_header); $key = key($p_header); next($p_header)) {
2864
- //}
2865
-
2866
- // ----- Transform UNIX mtime to DOS format mdate/mtime
2867
- $v_date = getdate($p_header['mtime']);
2868
- $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
2869
- $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
2870
-
2871
-
2872
- // ----- Packed data
2873
- $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']);
2874
-
2875
- // ----- Write the 42 bytes of the header in the zip file
2876
- fputs($this->zip_fd, $v_binary_data, 46);
2877
-
2878
- // ----- Write the variable fields
2879
- if (strlen($p_header['stored_filename']) != 0) {
2880
- fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
2881
- }
2882
- if ($p_header['extra_len'] != 0) {
2883
- fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
2884
- }
2885
- if ($p_header['comment_len'] != 0) {
2886
- fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
2887
- }
2888
-
2889
- // ----- Return
2890
- return $v_result;
2891
- }
2892
- // --------------------------------------------------------------------------------
2893
-
2894
- // --------------------------------------------------------------------------------
2895
- // Function : privWriteCentralHeader()
2896
- // Description :
2897
- // Parameters :
2898
- // Return Values :
2899
- // --------------------------------------------------------------------------------
2900
- public function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
2901
- {
2902
- $v_result = 1;
2903
-
2904
- // ----- Packed data
2905
- $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment));
2906
-
2907
- // ----- Write the 22 bytes of the header in the zip file
2908
- fputs($this->zip_fd, $v_binary_data, 22);
2909
-
2910
- // ----- Write the variable fields
2911
- if (strlen($p_comment) != 0) {
2912
- fputs($this->zip_fd, $p_comment, strlen($p_comment));
2913
- }
2914
-
2915
- // ----- Return
2916
- return $v_result;
2917
- }
2918
- // --------------------------------------------------------------------------------
2919
-
2920
- // --------------------------------------------------------------------------------
2921
- // Function : privList()
2922
- // Description :
2923
- // Parameters :
2924
- // Return Values :
2925
- // --------------------------------------------------------------------------------
2926
- public function privList(&$p_list)
2927
- {
2928
- $v_result = 1;
2929
-
2930
- // ----- Magic quotes trick
2931
- $this->privDisableMagicQuotes();
2932
-
2933
- // ----- Open the zip file
2934
- if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
2935
- // ----- Magic quotes trick
2936
- $this->privSwapBackMagicQuotes();
2937
-
2938
- // ----- Error log
2939
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
2940
-
2941
- // ----- Return
2942
- return PclZip::errorCode();
2943
- }
2944
-
2945
- // ----- Read the central directory informations
2946
- $v_central_dir = array();
2947
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
2948
- $this->privSwapBackMagicQuotes();
2949
- return $v_result;
2950
- }
2951
-
2952
- // ----- Go to beginning of Central Dir
2953
- @rewind($this->zip_fd);
2954
- if (@fseek($this->zip_fd, $v_central_dir['offset'])) {
2955
- $this->privSwapBackMagicQuotes();
2956
-
2957
- // ----- Error log
2958
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
2959
-
2960
- // ----- Return
2961
- return PclZip::errorCode();
2962
- }
2963
-
2964
- // ----- Read each entry
2965
- for ($i=0; $i<$v_central_dir['entries']; $i++) {
2966
- // ----- Read the file header
2967
- if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
2968
- $this->privSwapBackMagicQuotes();
2969
- return $v_result;
2970
- }
2971
- $v_header['index'] = $i;
2972
-
2973
- // ----- Get the only interesting attributes
2974
- $this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
2975
- unset($v_header);
2976
- }
2977
-
2978
- // ----- Close the zip file
2979
- $this->privCloseFd();
2980
-
2981
- // ----- Magic quotes trick
2982
- $this->privSwapBackMagicQuotes();
2983
-
2984
- // ----- Return
2985
- return $v_result;
2986
- }
2987
- // --------------------------------------------------------------------------------
2988
-
2989
- // --------------------------------------------------------------------------------
2990
- // Function : privConvertHeader2FileInfo()
2991
- // Description :
2992
- // This function takes the file informations from the central directory
2993
- // entries and extract the interesting parameters that will be given back.
2994
- // The resulting file infos are set in the array $p_info
2995
- // $p_info['filename'] : Filename with full path. Given by user (add),
2996
- // extracted in the filesystem (extract).
2997
- // $p_info['stored_filename'] : Stored filename in the archive.
2998
- // $p_info['size'] = Size of the file.
2999
- // $p_info['compressed_size'] = Compressed size of the file.
3000
- // $p_info['mtime'] = Last modification date of the file.
3001
- // $p_info['comment'] = Comment associated with the file.
3002
- // $p_info['folder'] = true/false : indicates if the entry is a folder or not.
3003
- // $p_info['status'] = status of the action on the file.
3004
- // $p_info['crc'] = CRC of the file content.
3005
- // Parameters :
3006
- // Return Values :
3007
- // --------------------------------------------------------------------------------
3008
- public function privConvertHeader2FileInfo($p_header, &$p_info)
3009
- {
3010
- $v_result=1;
3011
-
3012
- // ----- Get the interesting attributes
3013
- $v_temp_path = PclZipUtilPathReduction($p_header['filename']);
3014
- $p_info['filename'] = $v_temp_path;
3015
- $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']);
3016
- $p_info['stored_filename'] = $v_temp_path;
3017
- $p_info['size'] = $p_header['size'];
3018
- $p_info['compressed_size'] = $p_header['compressed_size'];
3019
- $p_info['mtime'] = $p_header['mtime'];
3020
- $p_info['comment'] = $p_header['comment'];
3021
- $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
3022
- $p_info['index'] = $p_header['index'];
3023
- $p_info['status'] = $p_header['status'];
3024
- $p_info['crc'] = $p_header['crc'];
3025
-
3026
- // ----- Return
3027
- return $v_result;
3028
- }
3029
- // --------------------------------------------------------------------------------
3030
-
3031
- // --------------------------------------------------------------------------------
3032
- // Function : privExtractByRule()
3033
- // Description :
3034
- // Extract a file or directory depending of rules (by index, by name, ...)
3035
- // Parameters :
3036
- // $p_file_list : An array where will be placed the properties of each
3037
- // extracted file
3038
- // $p_path : Path to add while writing the extracted files
3039
- // $p_remove_path : Path to remove (from the file memorized path) while writing the
3040
- // extracted files. If the path does not match the file path,
3041
- // the file is extracted with its memorized path.
3042
- // $p_remove_path does not apply to 'list' mode.
3043
- // $p_path and $p_remove_path are commulative.
3044
- // Return Values :
3045
- // 1 on success,0 or less on error (see error code list)
3046
- // --------------------------------------------------------------------------------
3047
- public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
3048
- {
3049
- $v_result=1;
3050
-
3051
- // ----- Magic quotes trick
3052
- $this->privDisableMagicQuotes();
3053
-
3054
- // ----- Check the path
3055
- if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2)!=":/"))) {
3056
- $p_path = "./".$p_path;
3057
- }
3058
-
3059
- // ----- Reduce the path last (and duplicated) '/'
3060
- if (($p_path != "./") && ($p_path != "/")) {
3061
- // ----- Look for the path end '/'
3062
- while (substr($p_path, -1) == "/") {
3063
- $p_path = substr($p_path, 0, strlen($p_path)-1);
3064
- }
3065
- }
3066
-
3067
- // ----- Look for path to remove format (should end by /)
3068
- if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) {
3069
- $p_remove_path .= '/';
3070
- }
3071
- $p_remove_path_size = strlen($p_remove_path);
3072
-
3073
- // ----- Open the zip file
3074
- if (($v_result = $this->privOpenFd('rb')) != 1) {
3075
- $this->privSwapBackMagicQuotes();
3076
- return $v_result;
3077
- }
3078
-
3079
- // ----- Read the central directory informations
3080
- $v_central_dir = array();
3081
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
3082
- // ----- Close the zip file
3083
- $this->privCloseFd();
3084
- $this->privSwapBackMagicQuotes();
3085
-
3086
- return $v_result;
3087
- }
3088
-
3089
- // ----- Start at beginning of Central Dir
3090
- $v_pos_entry = $v_central_dir['offset'];
3091
-
3092
- // ----- Read each entry
3093
- $j_start = 0;
3094
- for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) {
3095
- // ----- Read next Central dir entry
3096
- @rewind($this->zip_fd);
3097
- if (@fseek($this->zip_fd, $v_pos_entry)) {
3098
- // ----- Close the zip file
3099
- $this->privCloseFd();
3100
- $this->privSwapBackMagicQuotes();
3101
-
3102
- // ----- Error log
3103
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
3104
-
3105
- // ----- Return
3106
- return PclZip::errorCode();
3107
- }
3108
-
3109
- // ----- Read the file header
3110
- $v_header = array();
3111
- if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
3112
- // ----- Close the zip file
3113
- $this->privCloseFd();
3114
- $this->privSwapBackMagicQuotes();
3115
-
3116
- return $v_result;
3117
- }
3118
-
3119
- // ----- Store the index
3120
- $v_header['index'] = $i;
3121
-
3122
- // ----- Store the file position
3123
- $v_pos_entry = ftell($this->zip_fd);
3124
-
3125
- // ----- Look for the specific extract rules
3126
- $v_extract = false;
3127
-
3128
- // ----- Look for extract by name rule
3129
- if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
3130
- // ----- Look if the filename is in the list
3131
- for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
3132
- // ----- Look for a directory
3133
- if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
3134
- // ----- Look if the directory is in the filename path
3135
- if ((strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
3136
- $v_extract = true;
3137
- }
3138
- } elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
3139
- // ----- Look for a filename
3140
- $v_extract = true;
3141
- }
3142
- }
3143
- } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
3144
- // ----- Look for extract by preg rule
3145
- if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
3146
- $v_extract = true;
3147
- }
3148
- } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
3149
- // ----- Look for extract by index rule
3150
- // ----- Look if the index is in the list
3151
- for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
3152
- if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
3153
- $v_extract = true;
3154
- }
3155
- if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
3156
- $j_start = $j+1;
3157
- }
3158
-
3159
- if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
3160
- break;
3161
- }
3162
- }
3163
- } else {
3164
- // ----- Look for no rule, which means extract all the archive
3165
- $v_extract = true;
3166
- }
3167
-
3168
- // ----- Check compression method
3169
- if (($v_extract) && (($v_header['compression'] != 8) && ($v_header['compression'] != 0))) {
3170
- $v_header['status'] = 'unsupported_compression';
3171
-
3172
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
3173
- if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
3174
- $this->privSwapBackMagicQuotes();
3175
-
3176
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is compressed by an unsupported compression method (".$v_header['compression'].") ");
3177
-
3178
- return PclZip::errorCode();
3179
- }
3180
- }
3181
-
3182
- // ----- Check encrypted files
3183
- if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
3184
- $v_header['status'] = 'unsupported_encryption';
3185
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
3186
- if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
3187
- $this->privSwapBackMagicQuotes();
3188
-
3189
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for filename '".$v_header['stored_filename']."'");
3190
-
3191
- return PclZip::errorCode();
3192
- }
3193
- }
3194
-
3195
- // ----- Look for real extraction
3196
- if (($v_extract) && ($v_header['status'] != 'ok')) {
3197
- $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]);
3198
- if ($v_result != 1) {
3199
- $this->privCloseFd();
3200
- $this->privSwapBackMagicQuotes();
3201
- return $v_result;
3202
- }
3203
-
3204
- $v_extract = false;
3205
- }
3206
-
3207
- // ----- Look for real extraction
3208
- if ($v_extract) {
3209
- // ----- Go to the file position
3210
- @rewind($this->zip_fd);
3211
- if (@fseek($this->zip_fd, $v_header['offset'])) {
3212
- // ----- Close the zip file
3213
- $this->privCloseFd();
3214
-
3215
- $this->privSwapBackMagicQuotes();
3216
-
3217
- // ----- Error log
3218
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
3219
-
3220
- // ----- Return
3221
- return PclZip::errorCode();
3222
- }
3223
-
3224
- // ----- Look for extraction as string
3225
- if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
3226
- $v_string = '';
3227
-
3228
- // ----- Extracting the file
3229
- $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
3230
- if ($v_result1 < 1) {
3231
- $this->privCloseFd();
3232
- $this->privSwapBackMagicQuotes();
3233
- return $v_result1;
3234
- }
3235
-
3236
- // ----- Get the only interesting attributes
3237
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) {
3238
- // ----- Close the zip file
3239
- $this->privCloseFd();
3240
- $this->privSwapBackMagicQuotes();
3241
-
3242
- return $v_result;
3243
- }
3244
-
3245
- // ----- Set the file content
3246
- $p_file_list[$v_nb_extracted]['content'] = $v_string;
3247
-
3248
- // ----- Next extracted file
3249
- $v_nb_extracted++;
3250
-
3251
- // ----- Look for user callback abort
3252
- if ($v_result1 == 2) {
3253
- break;
3254
- }
3255
- } elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
3256
- // ----- Look for extraction in standard output
3257
- // ----- Extracting the file in standard output
3258
- $v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
3259
- if ($v_result1 < 1) {
3260
- $this->privCloseFd();
3261
- $this->privSwapBackMagicQuotes();
3262
- return $v_result1;
3263
- }
3264
-
3265
- // ----- Get the only interesting attributes
3266
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
3267
- $this->privCloseFd();
3268
- $this->privSwapBackMagicQuotes();
3269
- return $v_result;
3270
- }
3271
-
3272
- // ----- Look for user callback abort
3273
- if ($v_result1 == 2) {
3274
- break;
3275
- }
3276
- } else {
3277
- // ----- Look for normal extraction
3278
- // ----- Extracting the file
3279
- $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options);
3280
- if ($v_result1 < 1) {
3281
- $this->privCloseFd();
3282
- $this->privSwapBackMagicQuotes();
3283
- return $v_result1;
3284
- }
3285
-
3286
- // ----- Get the only interesting attributes
3287
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
3288
- // ----- Close the zip file
3289
- $this->privCloseFd();
3290
- $this->privSwapBackMagicQuotes();
3291
-
3292
- return $v_result;
3293
- }
3294
-
3295
- // ----- Look for user callback abort
3296
- if ($v_result1 == 2) {
3297
- break;
3298
- }
3299
- }
3300
- }
3301
- }
3302
-
3303
- // ----- Close the zip file
3304
- $this->privCloseFd();
3305
- $this->privSwapBackMagicQuotes();
3306
-
3307
- // ----- Return
3308
- return $v_result;
3309
- }
3310
- // --------------------------------------------------------------------------------
3311
-
3312
- // --------------------------------------------------------------------------------
3313
- // Function : privExtractFile()
3314
- // Description :
3315
- // Parameters :
3316
- // Return Values :
3317
- //
3318
- // 1 : ... ?
3319
- // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
3320
- // --------------------------------------------------------------------------------
3321
- public function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
3322
- {
3323
- $v_result=1;
3324
-
3325
- // ----- Read the file header
3326
- if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3327
- // ----- Return
3328
- return $v_result;
3329
- }
3330
-
3331
-
3332
- // ----- Check that the file header is coherent with $p_entry info
3333
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3334
- // TBC
3335
- }
3336
-
3337
- // ----- Look for all path to remove
3338
- if ($p_remove_all_path == true) {
3339
- // ----- Look for folder entry that not need to be extracted
3340
- if (($p_entry['external']&0x00000010)==0x00000010) {
3341
- $p_entry['status'] = "filtered";
3342
-
3343
- return $v_result;
3344
- }
3345
-
3346
- // ----- Get the basename of the path
3347
- $p_entry['filename'] = basename($p_entry['filename']);
3348
- } elseif ($p_remove_path != "") {
3349
- // ----- Look for path to remove
3350
- if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) {
3351
- // ----- Change the file status
3352
- $p_entry['status'] = "filtered";
3353
-
3354
- // ----- Return
3355
- return $v_result;
3356
- }
3357
-
3358
- $p_remove_path_size = strlen($p_remove_path);
3359
- if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) {
3360
- // ----- Remove the path
3361
- $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
3362
- }
3363
- }
3364
-
3365
- // ----- Add the path
3366
- if ($p_path != '') {
3367
- $p_entry['filename'] = $p_path."/".$p_entry['filename'];
3368
- }
3369
-
3370
- // ----- Check a base_dir_restriction
3371
- if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
3372
- $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']);
3373
- if ($v_inclusion == 0) {
3374
- PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '".$p_entry['filename']."' is outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
3375
-
3376
- return PclZip::errorCode();
3377
- }
3378
- }
3379
-
3380
- // ----- Look for pre-extract callback
3381
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
3382
- // ----- Generate a local information
3383
- $v_local_header = array();
3384
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3385
-
3386
- // ----- Call the callback
3387
- // Here I do not use call_user_func() because I need to send a reference to the
3388
- // header.
3389
- // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
3390
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
3391
- if ($v_result == 0) {
3392
- // ----- Change the file status
3393
- $p_entry['status'] = "skipped";
3394
- $v_result = 1;
3395
- }
3396
-
3397
- // ----- Look for abort result
3398
- if ($v_result == 2) {
3399
- // ----- This status is internal and will be changed in 'skipped'
3400
- $p_entry['status'] = "aborted";
3401
- $v_result = PCLZIP_ERR_USER_ABORTED;
3402
- }
3403
-
3404
- // ----- Update the informations
3405
- // Only some fields can be modified
3406
- $p_entry['filename'] = $v_local_header['filename'];
3407
- }
3408
-
3409
- // ----- Look if extraction should be done
3410
- if ($p_entry['status'] == 'ok') {
3411
- // ----- Look for specific actions while the file exist
3412
- if (file_exists($p_entry['filename'])) {
3413
- // ----- Look if file is a directory
3414
- if (is_dir($p_entry['filename'])) {
3415
- // ----- Change the file status
3416
- $p_entry['status'] = "already_a_directory";
3417
-
3418
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
3419
- // For historical reason first PclZip implementation does not stop
3420
- // when this kind of error occurs.
3421
- if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
3422
- PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '".$p_entry['filename']."' is already used by an existing directory");
3423
- return PclZip::errorCode();
3424
- }
3425
- } elseif (!is_writeable($p_entry['filename'])) {
3426
- // ----- Look if file is write protected
3427
- // ----- Change the file status
3428
- $p_entry['status'] = "write_protected";
3429
-
3430
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
3431
- // For historical reason first PclZip implementation does not stop
3432
- // when this kind of error occurs.
3433
- if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
3434
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '".$p_entry['filename']."' exists and is write protected");
3435
- return PclZip::errorCode();
3436
- }
3437
- } elseif (filemtime($p_entry['filename']) > $p_entry['mtime']) {
3438
- // ----- Look if the extracted file is older
3439
- // ----- Change the file status
3440
- if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER] === true)) {
3441
- } else {
3442
- $p_entry['status'] = "newer_exist";
3443
-
3444
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
3445
- // For historical reason first PclZip implementation does not stop
3446
- // when this kind of error occurs.
3447
- if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
3448
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '".$p_entry['filename']."' exists and option PCLZIP_OPT_REPLACE_NEWER is not selected");
3449
- return PclZip::errorCode();
3450
- }
3451
- }
3452
- } else {
3453
- }
3454
- } else {
3455
- // ----- Check the directory availability and create it if necessary
3456
- if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) {
3457
- $v_dir_to_check = $p_entry['filename'];
3458
- } elseif (!strstr($p_entry['filename'], "/")) {
3459
- $v_dir_to_check = "";
3460
- } else {
3461
- $v_dir_to_check = dirname($p_entry['filename']);
3462
- }
3463
-
3464
- if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
3465
- // ----- Change the file status
3466
- $p_entry['status'] = "path_creation_fail";
3467
-
3468
- // ----- Return
3469
- //return $v_result;
3470
- $v_result = 1;
3471
- }
3472
- }
3473
- }
3474
-
3475
- // ----- Look if extraction should be done
3476
- if ($p_entry['status'] == 'ok') {
3477
- // ----- Do the extraction (if not a folder)
3478
- if (!(($p_entry['external']&0x00000010) == 0x00000010)) {
3479
- // ----- Look for not compressed file
3480
- if ($p_entry['compression'] == 0) {
3481
- // ----- Opening destination file
3482
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3483
- // ----- Change the file status
3484
- $p_entry['status'] = "write_error";
3485
-
3486
- // ----- Return
3487
- return $v_result;
3488
- }
3489
-
3490
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
3491
- $v_size = $p_entry['compressed_size'];
3492
- while ($v_size != 0) {
3493
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
3494
- $v_buffer = @fread($this->zip_fd, $v_read_size);
3495
- /* Try to speed up the code
3496
- $v_binary_data = pack('a'.$v_read_size, $v_buffer);
3497
- @fwrite($v_dest_file, $v_binary_data, $v_read_size);
3498
- */
3499
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
3500
- $v_size -= $v_read_size;
3501
- }
3502
-
3503
- // ----- Closing the destination file
3504
- fclose($v_dest_file);
3505
-
3506
- // ----- Change the file mtime
3507
- touch($p_entry['filename'], $p_entry['mtime']);
3508
- } else {
3509
- // ----- TBC
3510
- // Need to be finished
3511
- if (($p_entry['flag'] & 1) == 1) {
3512
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.');
3513
- return PclZip::errorCode();
3514
- }
3515
-
3516
- // ----- Look for using temporary file to unzip
3517
- if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) {
3518
- $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
3519
- if ($v_result < PCLZIP_ERR_NO_ERROR) {
3520
- return $v_result;
3521
- }
3522
- } else {
3523
- // ----- Look for extract in memory
3524
- // ----- Read the compressed file in a buffer (one shot)
3525
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3526
-
3527
- // ----- Decompress the file
3528
- $v_file_content = @gzinflate($v_buffer);
3529
- unset($v_buffer);
3530
- if ($v_file_content === false) {
3531
- // ----- Change the file status
3532
- // TBC
3533
- $p_entry['status'] = "error";
3534
-
3535
- return $v_result;
3536
- }
3537
-
3538
- // ----- Opening destination file
3539
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3540
- // ----- Change the file status
3541
- $p_entry['status'] = "write_error";
3542
-
3543
- return $v_result;
3544
- }
3545
-
3546
- // ----- Write the uncompressed data
3547
- @fwrite($v_dest_file, $v_file_content, $p_entry['size']);
3548
- unset($v_file_content);
3549
-
3550
- // ----- Closing the destination file
3551
- @fclose($v_dest_file);
3552
- }
3553
-
3554
- // ----- Change the file mtime
3555
- @touch($p_entry['filename'], $p_entry['mtime']);
3556
- }
3557
-
3558
- // ----- Look for chmod option
3559
- if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
3560
- // ----- Change the mode of the file
3561
- @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
3562
- }
3563
- }
3564
- }
3565
-
3566
- // ----- Change abort status
3567
- if ($p_entry['status'] == "aborted") {
3568
- $p_entry['status'] = "skipped";
3569
- } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
3570
- // ----- Look for post-extract callback
3571
- // ----- Generate a local information
3572
- $v_local_header = array();
3573
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3574
-
3575
- // ----- Call the callback
3576
- // Here I do not use call_user_func() because I need to send a reference to the
3577
- // header.
3578
- // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
3579
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
3580
-
3581
- // ----- Look for abort result
3582
- if ($v_result == 2) {
3583
- $v_result = PCLZIP_ERR_USER_ABORTED;
3584
- }
3585
- }
3586
-
3587
- // ----- Return
3588
- return $v_result;
3589
- }
3590
- // --------------------------------------------------------------------------------
3591
-
3592
- // --------------------------------------------------------------------------------
3593
- // Function : privExtractFileUsingTempFile()
3594
- // Description :
3595
- // Parameters :
3596
- // Return Values :
3597
- // --------------------------------------------------------------------------------
3598
- public function privExtractFileUsingTempFile(&$p_entry, &$p_options)
3599
- {
3600
- $v_result=1;
3601
-
3602
- // ----- Creates a temporary file
3603
- $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
3604
- if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
3605
- fclose($v_file);
3606
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
3607
- return PclZip::errorCode();
3608
- }
3609
-
3610
- // ----- Write gz file format header
3611
- $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
3612
- @fwrite($v_dest_file, $v_binary_data, 10);
3613
-
3614
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
3615
- $v_size = $p_entry['compressed_size'];
3616
- while ($v_size != 0) {
3617
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
3618
- $v_buffer = @fread($this->zip_fd, $v_read_size);
3619
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
3620
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
3621
- $v_size -= $v_read_size;
3622
- }
3623
-
3624
- // ----- Write gz file format footer
3625
- $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
3626
- @fwrite($v_dest_file, $v_binary_data, 8);
3627
-
3628
- // ----- Close the temporary file
3629
- @fclose($v_dest_file);
3630
-
3631
- // ----- Opening destination file
3632
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3633
- $p_entry['status'] = "write_error";
3634
- return $v_result;
3635
- }
3636
-
3637
- // ----- Open the temporary gz file
3638
- if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
3639
- @fclose($v_dest_file);
3640
- $p_entry['status'] = "read_error";
3641
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
3642
- return PclZip::errorCode();
3643
- }
3644
-
3645
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
3646
- $v_size = $p_entry['size'];
3647
- while ($v_size != 0) {
3648
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
3649
- $v_buffer = @gzread($v_src_file, $v_read_size);
3650
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
3651
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
3652
- $v_size -= $v_read_size;
3653
- }
3654
- @fclose($v_dest_file);
3655
- @gzclose($v_src_file);
3656
-
3657
- // ----- Delete the temporary file
3658
- @unlink($v_gzip_temp_name);
3659
-
3660
- // ----- Return
3661
- return $v_result;
3662
- }
3663
- // --------------------------------------------------------------------------------
3664
-
3665
- // --------------------------------------------------------------------------------
3666
- // Function : privExtractFileInOutput()
3667
- // Description :
3668
- // Parameters :
3669
- // Return Values :
3670
- // --------------------------------------------------------------------------------
3671
- public function privExtractFileInOutput(&$p_entry, &$p_options)
3672
- {
3673
- $v_result=1;
3674
-
3675
- // ----- Read the file header
3676
- if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3677
- return $v_result;
3678
- }
3679
-
3680
- // ----- Check that the file header is coherent with $p_entry info
3681
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3682
- // TBC
3683
- }
3684
-
3685
- // ----- Look for pre-extract callback
3686
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
3687
- // ----- Generate a local information
3688
- $v_local_header = array();
3689
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3690
-
3691
- // ----- Call the callback
3692
- // Here I do not use call_user_func() because I need to send a reference to the
3693
- // header.
3694
- // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
3695
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
3696
- if ($v_result == 0) {
3697
- // ----- Change the file status
3698
- $p_entry['status'] = "skipped";
3699
- $v_result = 1;
3700
- }
3701
-
3702
- // ----- Look for abort result
3703
- if ($v_result == 2) {
3704
- // ----- This status is internal and will be changed in 'skipped'
3705
- $p_entry['status'] = "aborted";
3706
- $v_result = PCLZIP_ERR_USER_ABORTED;
3707
- }
3708
-
3709
- // ----- Update the informations
3710
- // Only some fields can be modified
3711
- $p_entry['filename'] = $v_local_header['filename'];
3712
- }
3713
-
3714
- // ----- Trace
3715
-
3716
- // ----- Look if extraction should be done
3717
- if ($p_entry['status'] == 'ok') {
3718
- // ----- Do the extraction (if not a folder)
3719
- if (!(($p_entry['external']&0x00000010)==0x00000010)) {
3720
- // ----- Look for not compressed file
3721
- if ($p_entry['compressed_size'] == $p_entry['size']) {
3722
- // ----- Read the file in a buffer (one shot)
3723
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3724
-
3725
- // ----- Send the file to the output
3726
- echo $v_buffer;
3727
- unset($v_buffer);
3728
- } else {
3729
- // ----- Read the compressed file in a buffer (one shot)
3730
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3731
-
3732
- // ----- Decompress the file
3733
- $v_file_content = gzinflate($v_buffer);
3734
- unset($v_buffer);
3735
-
3736
- // ----- Send the file to the output
3737
- echo $v_file_content;
3738
- unset($v_file_content);
3739
- }
3740
- }
3741
- }
3742
-
3743
- // ----- Change abort status
3744
- if ($p_entry['status'] == "aborted") {
3745
- $p_entry['status'] = "skipped";
3746
- } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
3747
- // ----- Look for post-extract callback
3748
-
3749
- // ----- Generate a local information
3750
- $v_local_header = array();
3751
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3752
-
3753
- // ----- Call the callback
3754
- // Here I do not use call_user_func() because I need to send a reference to the
3755
- // header.
3756
- // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
3757
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
3758
-
3759
- // ----- Look for abort result
3760
- if ($v_result == 2) {
3761
- $v_result = PCLZIP_ERR_USER_ABORTED;
3762
- }
3763
- }
3764
-
3765
- return $v_result;
3766
- }
3767
- // --------------------------------------------------------------------------------
3768
-
3769
- // --------------------------------------------------------------------------------
3770
- // Function : privExtractFileAsString()
3771
- // Description :
3772
- // Parameters :
3773
- // Return Values :
3774
- // --------------------------------------------------------------------------------
3775
- public function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
3776
- {
3777
- $v_result=1;
3778
-
3779
- // ----- Read the file header
3780
- $v_header = array();
3781
- if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3782
- // ----- Return
3783
- return $v_result;
3784
- }
3785
-
3786
- // ----- Check that the file header is coherent with $p_entry info
3787
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3788
- // TBC
3789
- }
3790
-
3791
- // ----- Look for pre-extract callback
3792
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
3793
- // ----- Generate a local information
3794
- $v_local_header = array();
3795
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3796
-
3797
- // ----- Call the callback
3798
- // Here I do not use call_user_func() because I need to send a reference to the
3799
- // header.
3800
- // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
3801
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
3802
- if ($v_result == 0) {
3803
- // ----- Change the file status
3804
- $p_entry['status'] = "skipped";
3805
- $v_result = 1;
3806
- }
3807
-
3808
- // ----- Look for abort result
3809
- if ($v_result == 2) {
3810
- // ----- This status is internal and will be changed in 'skipped'
3811
- $p_entry['status'] = "aborted";
3812
- $v_result = PCLZIP_ERR_USER_ABORTED;
3813
- }
3814
-
3815
- // ----- Update the informations
3816
- // Only some fields can be modified
3817
- $p_entry['filename'] = $v_local_header['filename'];
3818
- }
3819
-
3820
- // ----- Look if extraction should be done
3821
- if ($p_entry['status'] == 'ok') {
3822
- // ----- Do the extraction (if not a folder)
3823
- if (!(($p_entry['external']&0x00000010)==0x00000010)) {
3824
- // ----- Look for not compressed file
3825
- // if ($p_entry['compressed_size'] == $p_entry['size'])
3826
- if ($p_entry['compression'] == 0) {
3827
- // ----- Reading the file
3828
- $p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
3829
- } else {
3830
- // ----- Reading the file
3831
- $v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
3832
-
3833
- // ----- Decompress the file
3834
- if (($p_string = @gzinflate($v_data)) === false) {
3835
- // TBC
3836
- }
3837
- }
3838
- // ----- Trace
3839
- } else {
3840
- // TBC : error : can not extract a folder in a string
3841
- }
3842
- }
3843
-
3844
- // ----- Change abort status
3845
- if ($p_entry['status'] == "aborted") {
3846
- $p_entry['status'] = "skipped";
3847
- } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
3848
- // ----- Look for post-extract callback
3849
- // ----- Generate a local information
3850
- $v_local_header = array();
3851
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3852
-
3853
- // ----- Swap the content to header
3854
- $v_local_header['content'] = $p_string;
3855
- $p_string = '';
3856
-
3857
- // ----- Call the callback
3858
- // Here I do not use call_user_func() because I need to send a reference to the
3859
- // header.
3860
- // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
3861
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
3862
-
3863
- // ----- Swap back the content to header
3864
- $p_string = $v_local_header['content'];
3865
- unset($v_local_header['content']);
3866
-
3867
- // ----- Look for abort result
3868
- if ($v_result == 2) {
3869
- $v_result = PCLZIP_ERR_USER_ABORTED;
3870
- }
3871
- }
3872
-
3873
- // ----- Return
3874
- return $v_result;
3875
- }
3876
- // --------------------------------------------------------------------------------
3877
-
3878
- // --------------------------------------------------------------------------------
3879
- // Function : privReadFileHeader()
3880
- // Description :
3881
- // Parameters :
3882
- // Return Values :
3883
- // --------------------------------------------------------------------------------
3884
- public function privReadFileHeader(&$p_header)
3885
- {
3886
- $v_result=1;
3887
-
3888
- // ----- Read the 4 bytes signature
3889
- $v_binary_data = @fread($this->zip_fd, 4);
3890
- $v_data = unpack('Vid', $v_binary_data);
3891
-
3892
- // ----- Check signature
3893
- if ($v_data['id'] != 0x04034b50) {
3894
- // ----- Error log
3895
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
3896
-
3897
- // ----- Return
3898
- return PclZip::errorCode();
3899
- }
3900
-
3901
- // ----- Read the first 42 bytes of the header
3902
- $v_binary_data = fread($this->zip_fd, 26);
3903
-
3904
- // ----- Look for invalid block size
3905
- if (strlen($v_binary_data) != 26) {
3906
- $p_header['filename'] = "";
3907
- $p_header['status'] = "invalid_header";
3908
-
3909
- // ----- Error log
3910
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
3911
-
3912
- // ----- Return
3913
- return PclZip::errorCode();
3914
- }
3915
-
3916
- // ----- Extract the values
3917
- $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
3918
-
3919
- // ----- Get filename
3920
- $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
3921
-
3922
- // ----- Get extra_fields
3923
- if ($v_data['extra_len'] != 0) {
3924
- $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
3925
- } else {
3926
- $p_header['extra'] = '';
3927
- }
3928
-
3929
- // ----- Extract properties
3930
- $p_header['version_extracted'] = $v_data['version'];
3931
- $p_header['compression'] = $v_data['compression'];
3932
- $p_header['size'] = $v_data['size'];
3933
- $p_header['compressed_size'] = $v_data['compressed_size'];
3934
- $p_header['crc'] = $v_data['crc'];
3935
- $p_header['flag'] = $v_data['flag'];
3936
- $p_header['filename_len'] = $v_data['filename_len'];
3937
-
3938
- // ----- Recuperate date in UNIX format
3939
- $p_header['mdate'] = $v_data['mdate'];
3940
- $p_header['mtime'] = $v_data['mtime'];
3941
- if ($p_header['mdate'] && $p_header['mtime']) {
3942
- // ----- Extract time
3943
- $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
3944
- $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
3945
- $v_seconde = ($p_header['mtime'] & 0x001F)*2;
3946
-
3947
- // ----- Extract date
3948
- $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
3949
- $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
3950
- $v_day = $p_header['mdate'] & 0x001F;
3951
-
3952
- // ----- Get UNIX date format
3953
- $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
3954
-
3955
- } else {
3956
- $p_header['mtime'] = time();
3957
- }
3958
-
3959
- // TBC
3960
- //for(reset($v_data); $key = key($v_data); next($v_data)) {
3961
- //}
3962
-
3963
- // ----- Set the stored filename
3964
- $p_header['stored_filename'] = $p_header['filename'];
3965
-
3966
- // ----- Set the status field
3967
- $p_header['status'] = "ok";
3968
-
3969
- // ----- Return
3970
- return $v_result;
3971
- }
3972
- // --------------------------------------------------------------------------------
3973
-
3974
- // --------------------------------------------------------------------------------
3975
- // Function : privReadCentralFileHeader()
3976
- // Description :
3977
- // Parameters :
3978
- // Return Values :
3979
- // --------------------------------------------------------------------------------
3980
- public function privReadCentralFileHeader(&$p_header)
3981
- {
3982
- $v_result = 1;
3983
-
3984
- // ----- Read the 4 bytes signature
3985
- $v_binary_data = @fread($this->zip_fd, 4);
3986
- $v_data = unpack('Vid', $v_binary_data);
3987
-
3988
- // ----- Check signature
3989
- if ($v_data['id'] != 0x02014b50) {
3990
- // ----- Error log
3991
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
3992
-
3993
- // ----- Return
3994
- return PclZip::errorCode();
3995
- }
3996
-
3997
- // ----- Read the first 42 bytes of the header
3998
- $v_binary_data = fread($this->zip_fd, 42);
3999
-
4000
- // ----- Look for invalid block size
4001
- if (strlen($v_binary_data) != 42) {
4002
- $p_header['filename'] = "";
4003
- $p_header['status'] = "invalid_header";
4004
-
4005
- // ----- Error log
4006
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
4007
-
4008
- // ----- Return
4009
- return PclZip::errorCode();
4010
- }
4011
-
4012
- // ----- Extract the values
4013
- $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
4014
-
4015
- // ----- Get filename
4016
- if ($p_header['filename_len'] != 0) {
4017
- $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
4018
- } else {
4019
- $p_header['filename'] = '';
4020
- }
4021
-
4022
- // ----- Get extra
4023
- if ($p_header['extra_len'] != 0) {
4024
- $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
4025
- } else {
4026
- $p_header['extra'] = '';
4027
- }
4028
-
4029
- // ----- Get comment
4030
- if ($p_header['comment_len'] != 0) {
4031
- $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
4032
- } else {
4033
- $p_header['comment'] = '';
4034
- }
4035
-
4036
- // ----- Extract properties
4037
-
4038
- // ----- Recuperate date in UNIX format
4039
- //if ($p_header['mdate'] && $p_header['mtime'])
4040
- // TBC : bug : this was ignoring time with 0/0/0
4041
- if (1) {
4042
- // ----- Extract time
4043
- $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
4044
- $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
4045
- $v_seconde = ($p_header['mtime'] & 0x001F)*2;
4046
-
4047
- // ----- Extract date
4048
- $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
4049
- $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
4050
- $v_day = $p_header['mdate'] & 0x001F;
4051
-
4052
- // ----- Get UNIX date format
4053
- $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
4054
-
4055
- } else {
4056
- $p_header['mtime'] = time();
4057
- }
4058
-
4059
- // ----- Set the stored filename
4060
- $p_header['stored_filename'] = $p_header['filename'];
4061
-
4062
- // ----- Set default status to ok
4063
- $p_header['status'] = 'ok';
4064
-
4065
- // ----- Look if it is a directory
4066
- if (substr($p_header['filename'], -1) == '/') {
4067
- //$p_header['external'] = 0x41FF0010;
4068
- $p_header['external'] = 0x00000010;
4069
- }
4070
-
4071
-
4072
- // ----- Return
4073
- return $v_result;
4074
- }
4075
- // --------------------------------------------------------------------------------
4076
-
4077
- // --------------------------------------------------------------------------------
4078
- // Function : privCheckFileHeaders()
4079
- // Description :
4080
- // Parameters :
4081
- // Return Values :
4082
- // 1 on success,
4083
- // 0 on error;
4084
- // --------------------------------------------------------------------------------
4085
- public function privCheckFileHeaders(&$p_local_header, &$p_central_header)
4086
- {
4087
- $v_result=1;
4088
-
4089
- // ----- Check the static values
4090
- // TBC
4091
- if ($p_local_header['filename'] != $p_central_header['filename']) {
4092
- }
4093
- if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
4094
- }
4095
- if ($p_local_header['flag'] != $p_central_header['flag']) {
4096
- }
4097
- if ($p_local_header['compression'] != $p_central_header['compression']) {
4098
- }
4099
- if ($p_local_header['mtime'] != $p_central_header['mtime']) {
4100
- }
4101
- if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
4102
- }
4103
-
4104
- // ----- Look for flag bit 3
4105
- if (($p_local_header['flag'] & 8) == 8) {
4106
- $p_local_header['size'] = $p_central_header['size'];
4107
- $p_local_header['compressed_size'] = $p_central_header['compressed_size'];
4108
- $p_local_header['crc'] = $p_central_header['crc'];
4109
- }
4110
-
4111
- // ----- Return
4112
- return $v_result;
4113
- }
4114
- // --------------------------------------------------------------------------------
4115
-
4116
- // --------------------------------------------------------------------------------
4117
- // Function : privReadEndCentralDir()
4118
- // Description :
4119
- // Parameters :
4120
- // Return Values :
4121
- // --------------------------------------------------------------------------------
4122
- public function privReadEndCentralDir(&$p_central_dir)
4123
- {
4124
- $v_result=1;
4125
-
4126
- // ----- Go to the end of the zip file
4127
- $v_size = filesize($this->zipname);
4128
- @fseek($this->zip_fd, $v_size);
4129
- if (@ftell($this->zip_fd) != $v_size) {
4130
- // ----- Error log
4131
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
4132
-
4133
- // ----- Return
4134
- return PclZip::errorCode();
4135
- }
4136
-
4137
- // ----- First try : look if this is an archive with no commentaries (most of the time)
4138
- // in this case the end of central dir is at 22 bytes of the file end
4139
- $v_found = 0;
4140
- if ($v_size > 26) {
4141
- @fseek($this->zip_fd, $v_size-22);
4142
- if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) {
4143
- // ----- Error log
4144
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
4145
-
4146
- // ----- Return
4147
- return PclZip::errorCode();
4148
- }
4149
-
4150
- // ----- Read for bytes
4151
- $v_binary_data = @fread($this->zip_fd, 4);
4152
- $v_data = @unpack('Vid', $v_binary_data);
4153
-
4154
- // ----- Check signature
4155
- if ($v_data['id'] == 0x06054b50) {
4156
- $v_found = 1;
4157
- }
4158
-
4159
- $v_pos = ftell($this->zip_fd);
4160
- }
4161
-
4162
- // ----- Go back to the maximum possible size of the Central Dir End Record
4163
- if (!$v_found) {
4164
- $v_maximum_size = 65557; // 0xFFFF + 22;
4165
- if ($v_maximum_size > $v_size) {
4166
- $v_maximum_size = $v_size;
4167
- }
4168
- @fseek($this->zip_fd, $v_size-$v_maximum_size);
4169
- if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) {
4170
- // ----- Error log
4171
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
4172
-
4173
- // ----- Return
4174
- return PclZip::errorCode();
4175
- }
4176
-
4177
- // ----- Read byte per byte in order to find the signature
4178
- $v_pos = ftell($this->zip_fd);
4179
- $v_bytes = 0x00000000;
4180
- while ($v_pos < $v_size) {
4181
- // ----- Read a byte
4182
- $v_byte = @fread($this->zip_fd, 1);
4183
-
4184
- // ----- Add the byte
4185
- //$v_bytes = ($v_bytes << 8) | Ord($v_byte);
4186
- // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
4187
- // Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
4188
- $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
4189
-
4190
- // ----- Compare the bytes
4191
- if ($v_bytes == 0x504b0506) {
4192
- $v_pos++;
4193
- break;
4194
- }
4195
-
4196
- $v_pos++;
4197
- }
4198
-
4199
- // ----- Look if not found end of central dir
4200
- if ($v_pos == $v_size) {
4201
- // ----- Error log
4202
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
4203
-
4204
- // ----- Return
4205
- return PclZip::errorCode();
4206
- }
4207
- }
4208
-
4209
- // ----- Read the first 18 bytes of the header
4210
- $v_binary_data = fread($this->zip_fd, 18);
4211
-
4212
- // ----- Look for invalid block size
4213
- if (strlen($v_binary_data) != 18) {
4214
- // ----- Error log
4215
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
4216
-
4217
- // ----- Return
4218
- return PclZip::errorCode();
4219
- }
4220
-
4221
- // ----- Extract the values
4222
- $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
4223
-
4224
- // ----- Check the global size
4225
- if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
4226
- // ----- Removed in release 2.2 see readme file
4227
- // The check of the file size is a little too strict.
4228
- // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
4229
- // While decrypted, zip has training 0 bytes
4230
- if (0) {
4231
- // ----- Error log
4232
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive. Some trailing bytes exists after the archive.');
4233
-
4234
- // ----- Return
4235
- return PclZip::errorCode();
4236
- }
4237
- }
4238
-
4239
- // ----- Get comment
4240
- if ($v_data['comment_size'] != 0) {
4241
- $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
4242
- } else {
4243
- $p_central_dir['comment'] = '';
4244
- }
4245
-
4246
- $p_central_dir['entries'] = $v_data['entries'];
4247
- $p_central_dir['disk_entries'] = $v_data['disk_entries'];
4248
- $p_central_dir['offset'] = $v_data['offset'];
4249
- $p_central_dir['size'] = $v_data['size'];
4250
- $p_central_dir['disk'] = $v_data['disk'];
4251
- $p_central_dir['disk_start'] = $v_data['disk_start'];
4252
-
4253
- // TBC
4254
- //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
4255
- //}
4256
-
4257
- // ----- Return
4258
- return $v_result;
4259
- }
4260
- // --------------------------------------------------------------------------------
4261
-
4262
- // --------------------------------------------------------------------------------
4263
- // Function : privDeleteByRule()
4264
- // Description :
4265
- // Parameters :
4266
- // Return Values :
4267
- // --------------------------------------------------------------------------------
4268
- public function privDeleteByRule(&$p_result_list, &$p_options)
4269
- {
4270
- $v_result=1;
4271
- $v_list_detail = array();
4272
-
4273
- // ----- Open the zip file
4274
- if (($v_result=$this->privOpenFd('rb')) != 1) {
4275
- // ----- Return
4276
- return $v_result;
4277
- }
4278
-
4279
- // ----- Read the central directory informations
4280
- $v_central_dir = array();
4281
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
4282
- $this->privCloseFd();
4283
- return $v_result;
4284
- }
4285
-
4286
- // ----- Go to beginning of File
4287
- @rewind($this->zip_fd);
4288
-
4289
- // ----- Scan all the files
4290
- // ----- Start at beginning of Central Dir
4291
- $v_pos_entry = $v_central_dir['offset'];
4292
- @rewind($this->zip_fd);
4293
- if (@fseek($this->zip_fd, $v_pos_entry)) {
4294
- // ----- Close the zip file
4295
- $this->privCloseFd();
4296
-
4297
- // ----- Error log
4298
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
4299
-
4300
- // ----- Return
4301
- return PclZip::errorCode();
4302
- }
4303
-
4304
- // ----- Read each entry
4305
- $v_header_list = array();
4306
- $j_start = 0;
4307
- for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) {
4308
- // ----- Read the file header
4309
- $v_header_list[$v_nb_extracted] = array();
4310
- if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) {
4311
- // ----- Close the zip file
4312
- $this->privCloseFd();
4313
-
4314
- return $v_result;
4315
- }
4316
-
4317
-
4318
- // ----- Store the index
4319
- $v_header_list[$v_nb_extracted]['index'] = $i;
4320
-
4321
- // ----- Look for the specific extract rules
4322
- $v_found = false;
4323
-
4324
- // ----- Look for extract by name rule
4325
- if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
4326
- // ----- Look if the filename is in the list
4327
- for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) {
4328
- // ----- Look for a directory
4329
- if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
4330
- // ----- Look if the directory is in the filename path
4331
- if ((strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
4332
- $v_found = true;
4333
- } elseif ((($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
4334
- $v_found = true;
4335
- }
4336
- } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
4337
- // ----- Look for a filename
4338
- $v_found = true;
4339
- }
4340
- }
4341
- } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
4342
- // ----- Look for extract by preg rule
4343
- if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
4344
- $v_found = true;
4345
- }
4346
- } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
4347
- // ----- Look for extract by index rule
4348
- // ----- Look if the index is in the list
4349
- for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) {
4350
- if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
4351
- $v_found = true;
4352
- }
4353
- if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
4354
- $j_start = $j+1;
4355
- }
4356
- if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
4357
- break;
4358
- }
4359
- }
4360
- } else {
4361
- $v_found = true;
4362
- }
4363
-
4364
- // ----- Look for deletion
4365
- if ($v_found) {
4366
- unset($v_header_list[$v_nb_extracted]);
4367
- } else {
4368
- $v_nb_extracted++;
4369
- }
4370
- }
4371
-
4372
- // ----- Look if something need to be deleted
4373
- if ($v_nb_extracted > 0) {
4374
- // ----- Creates a temporay file
4375
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
4376
-
4377
- // ----- Creates a temporary zip archive
4378
- $v_temp_zip = new PclZip($v_zip_temp_name);
4379
-
4380
- // ----- Open the temporary zip file in write mode
4381
- if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
4382
- $this->privCloseFd();
4383
-
4384
- // ----- Return
4385
- return $v_result;
4386
- }
4387
-
4388
- // ----- Look which file need to be kept
4389
- for ($i=0; $i<sizeof($v_header_list); $i++) {
4390
- // ----- Calculate the position of the header
4391
- @rewind($this->zip_fd);
4392
- if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
4393
- // ----- Close the zip file
4394
- $this->privCloseFd();
4395
- $v_temp_zip->privCloseFd();
4396
- @unlink($v_zip_temp_name);
4397
-
4398
- // ----- Error log
4399
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
4400
-
4401
- // ----- Return
4402
- return PclZip::errorCode();
4403
- }
4404
-
4405
- // ----- Read the file header
4406
- $v_local_header = array();
4407
- if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
4408
- // ----- Close the zip file
4409
- $this->privCloseFd();
4410
- $v_temp_zip->privCloseFd();
4411
- @unlink($v_zip_temp_name);
4412
-
4413
- // ----- Return
4414
- return $v_result;
4415
- }
4416
-
4417
- // ----- Check that local file header is same as central file header
4418
- if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) {
4419
- // TBC
4420
- }
4421
- unset($v_local_header);
4422
-
4423
- // ----- Write the file header
4424
- if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
4425
- // ----- Close the zip file
4426
- $this->privCloseFd();
4427
- $v_temp_zip->privCloseFd();
4428
- @unlink($v_zip_temp_name);
4429
-
4430
- // ----- Return
4431
- return $v_result;
4432
- }
4433
-
4434
- // ----- Read/write the data block
4435
- if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
4436
- // ----- Close the zip file
4437
- $this->privCloseFd();
4438
- $v_temp_zip->privCloseFd();
4439
- @unlink($v_zip_temp_name);
4440
-
4441
- // ----- Return
4442
- return $v_result;
4443
- }
4444
- }
4445
-
4446
- // ----- Store the offset of the central dir
4447
- $v_offset = @ftell($v_temp_zip->zip_fd);
4448
-
4449
- // ----- Re-Create the Central Dir files header
4450
- for ($i=0; $i<sizeof($v_header_list); $i++) {
4451
- // ----- Create the file header
4452
- if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
4453
- $v_temp_zip->privCloseFd();
4454
- $this->privCloseFd();
4455
- @unlink($v_zip_temp_name);
4456
-
4457
- // ----- Return
4458
- return $v_result;
4459
- }
4460
-
4461
- // ----- Transform the header to a 'usable' info
4462
- $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
4463
- }
4464
-
4465
-
4466
- // ----- Zip file comment
4467
- $v_comment = '';
4468
- if (isset($p_options[PCLZIP_OPT_COMMENT])) {
4469
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
4470
- }
4471
-
4472
- // ----- Calculate the size of the central header
4473
- $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
4474
-
4475
- // ----- Create the central dir footer
4476
- if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
4477
- // ----- Reset the file list
4478
- unset($v_header_list);
4479
- $v_temp_zip->privCloseFd();
4480
- $this->privCloseFd();
4481
- @unlink($v_zip_temp_name);
4482
-
4483
- // ----- Return
4484
- return $v_result;
4485
- }
4486
-
4487
- // ----- Close
4488
- $v_temp_zip->privCloseFd();
4489
- $this->privCloseFd();
4490
-
4491
- // ----- Delete the zip file
4492
- // TBC : I should test the result ...
4493
- @unlink($this->zipname);
4494
-
4495
- // ----- Rename the temporary file
4496
- // TBC : I should test the result ...
4497
- //@rename($v_zip_temp_name, $this->zipname);
4498
- PclZipUtilRename($v_zip_temp_name, $this->zipname);
4499
-
4500
- // ----- Destroy the temporary archive
4501
- unset($v_temp_zip);
4502
- } elseif ($v_central_dir['entries'] != 0) {
4503
- // ----- Remove every files : reset the file
4504
- $this->privCloseFd();
4505
-
4506
- if (($v_result = $this->privOpenFd('wb')) != 1) {
4507
- return $v_result;
4508
- }
4509
-
4510
- if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
4511
- return $v_result;
4512
- }
4513
-
4514
- $this->privCloseFd();
4515
- }
4516
-
4517
- // ----- Return
4518
- return $v_result;
4519
- }
4520
- // --------------------------------------------------------------------------------
4521
-
4522
- // --------------------------------------------------------------------------------
4523
- // Function : privDirCheck()
4524
- // Description :
4525
- // Check if a directory exists, if not it creates it and all the parents directory
4526
- // which may be useful.
4527
- // Parameters :
4528
- // $p_dir : Directory path to check.
4529
- // Return Values :
4530
- // 1 : OK
4531
- // -1 : Unable to create directory
4532
- // --------------------------------------------------------------------------------
4533
- public function privDirCheck($p_dir, $p_is_dir = false)
4534
- {
4535
- $v_result = 1;
4536
-
4537
- // ----- Remove the final '/'
4538
- if (($p_is_dir) && (substr($p_dir, -1)=='/')) {
4539
- $p_dir = substr($p_dir, 0, strlen($p_dir)-1);
4540
- }
4541
-
4542
- // ----- Check the directory availability
4543
- if ((is_dir($p_dir)) || ($p_dir == "")) {
4544
- return 1;
4545
- }
4546
-
4547
- // ----- Extract parent directory
4548
- $p_parent_dir = dirname($p_dir);
4549
-
4550
- // ----- Just a check
4551
- if ($p_parent_dir != $p_dir) {
4552
- // ----- Look for parent directory
4553
- if ($p_parent_dir != "") {
4554
- if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) {
4555
- return $v_result;
4556
- }
4557
- }
4558
- }
4559
-
4560
- // ----- Create the directory
4561
- if (!@mkdir($p_dir, 0777)) {
4562
- // ----- Error log
4563
- PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
4564
-
4565
- // ----- Return
4566
- return PclZip::errorCode();
4567
- }
4568
-
4569
- // ----- Return
4570
- return $v_result;
4571
- }
4572
- // --------------------------------------------------------------------------------
4573
-
4574
- // --------------------------------------------------------------------------------
4575
- // Function : privMerge()
4576
- // Description :
4577
- // If $p_archive_to_add does not exist, the function exit with a success result.
4578
- // Parameters :
4579
- // Return Values :
4580
- // --------------------------------------------------------------------------------
4581
- public function privMerge(&$p_archive_to_add)
4582
- {
4583
- $v_result=1;
4584
-
4585
- // ----- Look if the archive_to_add exists
4586
- if (!is_file($p_archive_to_add->zipname)) {
4587
- // ----- Nothing to merge, so merge is a success
4588
- $v_result = 1;
4589
-
4590
- // ----- Return
4591
- return $v_result;
4592
- }
4593
-
4594
- // ----- Look if the archive exists
4595
- if (!is_file($this->zipname)) {
4596
- // ----- Do a duplicate
4597
- $v_result = $this->privDuplicate($p_archive_to_add->zipname);
4598
-
4599
- // ----- Return
4600
- return $v_result;
4601
- }
4602
-
4603
- // ----- Open the zip file
4604
- if (($v_result=$this->privOpenFd('rb')) != 1) {
4605
- // ----- Return
4606
- return $v_result;
4607
- }
4608
-
4609
- // ----- Read the central directory informations
4610
- $v_central_dir = array();
4611
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
4612
- $this->privCloseFd();
4613
- return $v_result;
4614
- }
4615
-
4616
- // ----- Go to beginning of File
4617
- @rewind($this->zip_fd);
4618
-
4619
- // ----- Open the archive_to_add file
4620
- if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) {
4621
- $this->privCloseFd();
4622
-
4623
- // ----- Return
4624
- return $v_result;
4625
- }
4626
-
4627
- // ----- Read the central directory informations
4628
- $v_central_dir_to_add = array();
4629
- if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) {
4630
- $this->privCloseFd();
4631
- $p_archive_to_add->privCloseFd();
4632
-
4633
- return $v_result;
4634
- }
4635
-
4636
- // ----- Go to beginning of File
4637
- @rewind($p_archive_to_add->zip_fd);
4638
-
4639
- // ----- Creates a temporay file
4640
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
4641
-
4642
- // ----- Open the temporary file in write mode
4643
- if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
4644
- $this->privCloseFd();
4645
- $p_archive_to_add->privCloseFd();
4646
-
4647
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
4648
-
4649
- // ----- Return
4650
- return PclZip::errorCode();
4651
- }
4652
-
4653
- // ----- Copy the files from the archive to the temporary file
4654
- // TBC : Here I should better append the file and go back to erase the central dir
4655
- $v_size = $v_central_dir['offset'];
4656
- while ($v_size != 0) {
4657
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
4658
- $v_buffer = fread($this->zip_fd, $v_read_size);
4659
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4660
- $v_size -= $v_read_size;
4661
- }
4662
-
4663
- // ----- Copy the files from the archive_to_add into the temporary file
4664
- $v_size = $v_central_dir_to_add['offset'];
4665
- while ($v_size != 0) {
4666
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
4667
- $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
4668
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4669
- $v_size -= $v_read_size;
4670
- }
4671
-
4672
- // ----- Store the offset of the central dir
4673
- $v_offset = @ftell($v_zip_temp_fd);
4674
-
4675
- // ----- Copy the block of file headers from the old archive
4676
- $v_size = $v_central_dir['size'];
4677
- while ($v_size != 0) {
4678
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
4679
- $v_buffer = @fread($this->zip_fd, $v_read_size);
4680
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4681
- $v_size -= $v_read_size;
4682
- }
4683
-
4684
- // ----- Copy the block of file headers from the archive_to_add
4685
- $v_size = $v_central_dir_to_add['size'];
4686
- while ($v_size != 0) {
4687
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
4688
- $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
4689
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4690
- $v_size -= $v_read_size;
4691
- }
4692
-
4693
- // ----- Merge the file comments
4694
- $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
4695
-
4696
- // ----- Calculate the size of the (new) central header
4697
- $v_size = @ftell($v_zip_temp_fd)-$v_offset;
4698
-
4699
- // ----- Swap the file descriptor
4700
- // Here is a trick : I swap the temporary fd with the zip fd, in order to use
4701
- // the following methods on the temporary fil and not the real archive fd
4702
- $v_swap = $this->zip_fd;
4703
- $this->zip_fd = $v_zip_temp_fd;
4704
- $v_zip_temp_fd = $v_swap;
4705
-
4706
- // ----- Create the central dir footer
4707
- if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) {
4708
- $this->privCloseFd();
4709
- $p_archive_to_add->privCloseFd();
4710
- @fclose($v_zip_temp_fd);
4711
- $this->zip_fd = null;
4712
-
4713
- // ----- Reset the file list
4714
- unset($v_header_list);
4715
-
4716
- // ----- Return
4717
- return $v_result;
4718
- }
4719
-
4720
- // ----- Swap back the file descriptor
4721
- $v_swap = $this->zip_fd;
4722
- $this->zip_fd = $v_zip_temp_fd;
4723
- $v_zip_temp_fd = $v_swap;
4724
-
4725
- // ----- Close
4726
- $this->privCloseFd();
4727
- $p_archive_to_add->privCloseFd();
4728
-
4729
- // ----- Close the temporary file
4730
- @fclose($v_zip_temp_fd);
4731
-
4732
- // ----- Delete the zip file
4733
- // TBC : I should test the result ...
4734
- @unlink($this->zipname);
4735
-
4736
- // ----- Rename the temporary file
4737
- // TBC : I should test the result ...
4738
- //@rename($v_zip_temp_name, $this->zipname);
4739
- PclZipUtilRename($v_zip_temp_name, $this->zipname);
4740
-
4741
- // ----- Return
4742
- return $v_result;
4743
- }
4744
- // --------------------------------------------------------------------------------
4745
-
4746
- // --------------------------------------------------------------------------------
4747
- // Function : privDuplicate()
4748
- // Description :
4749
- // Parameters :
4750
- // Return Values :
4751
- // --------------------------------------------------------------------------------
4752
- public function privDuplicate($p_archive_filename)
4753
- {
4754
- $v_result=1;
4755
-
4756
- // ----- Look if the $p_archive_filename exists
4757
- if (!is_file($p_archive_filename)) {
4758
- // ----- Nothing to duplicate, so duplicate is a success.
4759
- $v_result = 1;
4760
-
4761
- // ----- Return
4762
- return $v_result;
4763
- }
4764
-
4765
- // ----- Open the zip file
4766
- if (($v_result=$this->privOpenFd('wb')) != 1) {
4767
- // ----- Return
4768
- return $v_result;
4769
- }
4770
-
4771
- // ----- Open the temporary file in write mode
4772
- if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) {
4773
- $this->privCloseFd();
4774
-
4775
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
4776
-
4777
- // ----- Return
4778
- return PclZip::errorCode();
4779
- }
4780
-
4781
- // ----- Copy the files from the archive to the temporary file
4782
- // TBC : Here I should better append the file and go back to erase the central dir
4783
- $v_size = filesize($p_archive_filename);
4784
- while ($v_size != 0) {
4785
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
4786
- $v_buffer = fread($v_zip_temp_fd, $v_read_size);
4787
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
4788
- $v_size -= $v_read_size;
4789
- }
4790
-
4791
- // ----- Close
4792
- $this->privCloseFd();
4793
-
4794
- // ----- Close the temporary file
4795
- @fclose($v_zip_temp_fd);
4796
-
4797
- // ----- Return
4798
- return $v_result;
4799
- }
4800
- // --------------------------------------------------------------------------------
4801
-
4802
- // --------------------------------------------------------------------------------
4803
- // Function : privErrorLog()
4804
- // Description :
4805
- // Parameters :
4806
- // --------------------------------------------------------------------------------
4807
- public function privErrorLog($p_error_code = 0, $p_error_string = '')
4808
- {
4809
- if (PCLZIP_ERROR_EXTERNAL == 1) {
4810
- PclError($p_error_code, $p_error_string);
4811
- } else {
4812
- $this->error_code = $p_error_code;
4813
- $this->error_string = $p_error_string;
4814
- }
4815
- }
4816
- // --------------------------------------------------------------------------------
4817
-
4818
- // --------------------------------------------------------------------------------
4819
- // Function : privErrorReset()
4820
- // Description :
4821
- // Parameters :
4822
- // --------------------------------------------------------------------------------
4823
- public function privErrorReset()
4824
- {
4825
- if (PCLZIP_ERROR_EXTERNAL == 1) {
4826
- PclErrorReset();
4827
- } else {
4828
- $this->error_code = 0;
4829
- $this->error_string = '';
4830
- }
4831
- }
4832
- // --------------------------------------------------------------------------------
4833
-
4834
- // --------------------------------------------------------------------------------
4835
- // Function : privDisableMagicQuotes()
4836
- // Description :
4837
- // Parameters :
4838
- // Return Values :
4839
- // --------------------------------------------------------------------------------
4840
- public function privDisableMagicQuotes()
4841
- {
4842
- $v_result=1;
4843
-
4844
- // ----- Look if function exists
4845
- if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) {
4846
- return $v_result;
4847
- }
4848
-
4849
- // ----- Look if already done
4850
- if ($this->magic_quotes_status != -1) {
4851
- return $v_result;
4852
- }
4853
-
4854
- // ----- Get and memorize the magic_quote value
4855
- $this->magic_quotes_status = @get_magic_quotes_runtime();
4856
-
4857
- // ----- Disable magic_quotes
4858
- // if ($this->magic_quotes_status == 1) {
4859
- // @set_magic_quotes_runtime(0);
4860
- // }
4861
-
4862
- // ----- Return
4863
- return $v_result;
4864
- }
4865
- // --------------------------------------------------------------------------------
4866
-
4867
- // --------------------------------------------------------------------------------
4868
- // Function : privSwapBackMagicQuotes()
4869
- // Description :
4870
- // Parameters :
4871
- // Return Values :
4872
- // --------------------------------------------------------------------------------
4873
- public function privSwapBackMagicQuotes()
4874
- {
4875
- $v_result=1;
4876
-
4877
- // ----- Look if function exists
4878
- if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) {
4879
- return $v_result;
4880
- }
4881
-
4882
- // ----- Look if something to do
4883
- if ($this->magic_quotes_status != -1) {
4884
- return $v_result;
4885
- }
4886
-
4887
- // ----- Swap back magic_quotes
4888
- // if ($this->magic_quotes_status == 1) {
4889
- // @set_magic_quotes_runtime($this->magic_quotes_status);
4890
- // }
4891
-
4892
- // ----- Return
4893
- return $v_result;
4894
- }
4895
- // --------------------------------------------------------------------------------
4896
- }
4897
- // End of class
4898
- // --------------------------------------------------------------------------------
4899
-
4900
- // --------------------------------------------------------------------------------
4901
- // Function : PclZipUtilPathReduction()
4902
- // Description :
4903
- // Parameters :
4904
- // Return Values :
4905
- // --------------------------------------------------------------------------------
4906
- function PclZipUtilPathReduction($p_dir)
4907
- {
4908
- $v_result = "";
4909
-
4910
- // ----- Look for not empty path
4911
- if ($p_dir != "") {
4912
- // ----- Explode path by directory names
4913
- $v_list = explode("/", $p_dir);
4914
-
4915
- // ----- Study directories from last to first
4916
- $v_skip = 0;
4917
- for ($i=sizeof($v_list)-1; $i>=0; $i--) {
4918
- // ----- Look for current path
4919
- if ($v_list[$i] == ".") {
4920
- // ----- Ignore this directory
4921
- // Should be the first $i=0, but no check is done
4922
- } elseif ($v_list[$i] == "..") {
4923
- $v_skip++;
4924
- } elseif ($v_list[$i] == "") {
4925
- // ----- First '/' i.e. root slash
4926
- if ($i == 0) {
4927
- $v_result = "/".$v_result;
4928
- if ($v_skip > 0) {
4929
- // ----- It is an invalid path, so the path is not modified
4930
- // TBC
4931
- $v_result = $p_dir;
4932
- $v_skip = 0;
4933
- }
4934
- } elseif ($i == (sizeof($v_list)-1)) {
4935
- // ----- Last '/' i.e. indicates a directory
4936
- $v_result = $v_list[$i];
4937
- } else {
4938
- // ----- Double '/' inside the path
4939
- // ----- Ignore only the double '//' in path,
4940
- // but not the first and last '/'
4941
- }
4942
- } else {
4943
- // ----- Look for item to skip
4944
- if ($v_skip > 0) {
4945
- $v_skip--;
4946
- } else {
4947
- $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
4948
- }
4949
- }
4950
- }
4951
-
4952
- // ----- Look for skip
4953
- if ($v_skip > 0) {
4954
- while ($v_skip > 0) {
4955
- $v_result = '../'.$v_result;
4956
- $v_skip--;
4957
- }
4958
- }
4959
- }
4960
-
4961
- // ----- Return
4962
- return $v_result;
4963
- }
4964
- // --------------------------------------------------------------------------------
4965
-
4966
- // --------------------------------------------------------------------------------
4967
- // Function : PclZipUtilPathInclusion()
4968
- // Description :
4969
- // This function indicates if the path $p_path is under the $p_dir tree. Or,
4970
- // said in an other way, if the file or sub-dir $p_path is inside the dir
4971
- // $p_dir.
4972
- // The function indicates also if the path is exactly the same as the dir.
4973
- // This function supports path with duplicated '/' like '//', but does not
4974
- // support '.' or '..' statements.
4975
- // Parameters :
4976
- // Return Values :
4977
- // 0 if $p_path is not inside directory $p_dir
4978
- // 1 if $p_path is inside directory $p_dir
4979
- // 2 if $p_path is exactly the same as $p_dir
4980
- // --------------------------------------------------------------------------------
4981
- function PclZipUtilPathInclusion($p_dir, $p_path)
4982
- {
4983
- $v_result = 1;
4984
-
4985
- // ----- Look for path beginning by ./
4986
- if (($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
4987
- $p_dir = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1);
4988
- }
4989
- if (($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
4990
- $p_path = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1);
4991
- }
4992
-
4993
- // ----- Explode dir and path by directory separator
4994
- $v_list_dir = explode("/", $p_dir);
4995
- $v_list_dir_size = sizeof($v_list_dir);
4996
- $v_list_path = explode("/", $p_path);
4997
- $v_list_path_size = sizeof($v_list_path);
4998
-
4999
- // ----- Study directories paths
5000
- $i = 0;
5001
- $j = 0;
5002
- while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
5003
- // ----- Look for empty dir (path reduction)
5004
- if ($v_list_dir[$i] == '') {
5005
- $i++;
5006
- continue;
5007
- }
5008
- if ($v_list_path[$j] == '') {
5009
- $j++;
5010
- continue;
5011
- }
5012
-
5013
- // ----- Compare the items
5014
- if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) {
5015
- $v_result = 0;
5016
- }
5017
-
5018
- // ----- Next items
5019
- $i++;
5020
- $j++;
5021
- }
5022
-
5023
- // ----- Look if everything seems to be the same
5024
- if ($v_result) {
5025
- // ----- Skip all the empty items
5026
- while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) {
5027
- $j++;
5028
- }
5029
- while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) {
5030
- $i++;
5031
- }
5032
-
5033
- if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
5034
- // ----- There are exactly the same
5035
- $v_result = 2;
5036
- } elseif ($i < $v_list_dir_size) {
5037
- // ----- The path is shorter than the dir
5038
- $v_result = 0;
5039
- }
5040
- }
5041
-
5042
- // ----- Return
5043
- return $v_result;
5044
- }
5045
- // --------------------------------------------------------------------------------
5046
-
5047
- // --------------------------------------------------------------------------------
5048
- // Function : PclZipUtilCopyBlock()
5049
- // Description :
5050
- // Parameters :
5051
- // $p_mode : read/write compression mode
5052
- // 0 : src & dest normal
5053
- // 1 : src gzip, dest normal
5054
- // 2 : src normal, dest gzip
5055
- // 3 : src & dest gzip
5056
- // Return Values :
5057
- // --------------------------------------------------------------------------------
5058
- function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode = 0)
5059
- {
5060
- $v_result = 1;
5061
-
5062
- if ($p_mode==0) {
5063
- while ($p_size != 0) {
5064
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
5065
- $v_buffer = @fread($p_src, $v_read_size);
5066
- @fwrite($p_dest, $v_buffer, $v_read_size);
5067
- $p_size -= $v_read_size;
5068
- }
5069
- } elseif ($p_mode==1) {
5070
- while ($p_size != 0) {
5071
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
5072
- $v_buffer = @gzread($p_src, $v_read_size);
5073
- @fwrite($p_dest, $v_buffer, $v_read_size);
5074
- $p_size -= $v_read_size;
5075
- }
5076
- } elseif ($p_mode==2) {
5077
- while ($p_size != 0) {
5078
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
5079
- $v_buffer = @fread($p_src, $v_read_size);
5080
- @gzwrite($p_dest, $v_buffer, $v_read_size);
5081
- $p_size -= $v_read_size;
5082
- }
5083
- } elseif ($p_mode==3) {
5084
- while ($p_size != 0) {
5085
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
5086
- $v_buffer = @gzread($p_src, $v_read_size);
5087
- @gzwrite($p_dest, $v_buffer, $v_read_size);
5088
- $p_size -= $v_read_size;
5089
- }
5090
- }
5091
-
5092
- // ----- Return
5093
- return $v_result;
5094
- }
5095
- // --------------------------------------------------------------------------------
5096
-
5097
- // --------------------------------------------------------------------------------
5098
- // Function : PclZipUtilRename()
5099
- // Description :
5100
- // This function tries to do a simple rename() function. If it fails, it
5101
- // tries to copy the $p_src file in a new $p_dest file and then unlink the
5102
- // first one.
5103
- // Parameters :
5104
- // $p_src : Old filename
5105
- // $p_dest : New filename
5106
- // Return Values :
5107
- // 1 on success, 0 on failure.
5108
- // --------------------------------------------------------------------------------
5109
- function PclZipUtilRename($p_src, $p_dest)
5110
- {
5111
- $v_result = 1;
5112
-
5113
- // ----- Try to rename the files
5114
- if (!@rename($p_src, $p_dest)) {
5115
- // ----- Try to copy & unlink the src
5116
- if (!@copy($p_src, $p_dest)) {
5117
- $v_result = 0;
5118
- } elseif (!@unlink($p_src)) {
5119
- $v_result = 0;
5120
- }
5121
- }
5122
-
5123
- // ----- Return
5124
- return $v_result;
5125
- }
5126
- // --------------------------------------------------------------------------------
5127
-
5128
- // --------------------------------------------------------------------------------
5129
- // Function : PclZipUtilOptionText()
5130
- // Description :
5131
- // Translate option value in text. Mainly for debug purpose.
5132
- // Parameters :
5133
- // $p_option : the option value.
5134
- // Return Values :
5135
- // The option text value.
5136
- // --------------------------------------------------------------------------------
5137
- function PclZipUtilOptionText($p_option)
5138
- {
5139
- $v_list = get_defined_constants();
5140
- for (reset($v_list); $v_key = key($v_list); next($v_list)) {
5141
- $v_prefix = substr($v_key, 0, 10);
5142
- if ((($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) {
5143
- return $v_key;
5144
- }
5145
- }
5146
-
5147
- $v_result = 'Unknown';
5148
-
5149
- return $v_result;
5150
- }
5151
- // --------------------------------------------------------------------------------
5152
-
5153
- // --------------------------------------------------------------------------------
5154
- // Function : PclZipUtilTranslateWinPath()
5155
- // Description :
5156
- // Translate windows path by replacing '\' by '/' and optionally removing
5157
- // drive letter.
5158
- // Parameters :
5159
- // $p_path : path to translate.
5160
- // $p_remove_disk_letter : true | false
5161
- // Return Values :
5162
- // The path translated.
5163
- // --------------------------------------------------------------------------------
5164
- function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter = true)
5165
- {
5166
- if (stristr(php_uname(), 'windows')) {
5167
- // ----- Look for potential disk letter
5168
- if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
5169
- $p_path = substr($p_path, $v_position+1);
5170
- }
5171
- // ----- Change potential windows directory separator
5172
- if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) {
5173
- $p_path = strtr($p_path, '\\', '/');
5174
- }
5175
- }
5176
- return $p_path;
5177
- }
5178
- endif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugin.php CHANGED
@@ -3,7 +3,7 @@
3
  Plugin Name: WP All Import
4
  Plugin URI: http://www.wpallimport.com/wordpress-xml-csv-import/?utm_source=import-plugin-free&utm_medium=wp-plugins-page&utm_campaign=upgrade-to-pro
5
  Description: The most powerful solution for importing XML and CSV files to WordPress. Create Posts and Pages with content from any XML or CSV file. A paid upgrade to WP All Import Pro is available for support and additional features.
6
- Version: 3.6.3
7
  Author: Soflyy
8
  */
9
 
@@ -25,7 +25,7 @@ define('WP_ALL_IMPORT_ROOT_URL', rtrim(plugin_dir_url(__FILE__), '/'));
25
  */
26
  define('WP_ALL_IMPORT_PREFIX', 'pmxi_');
27
 
28
- define('PMXI_VERSION', '3.6.3');
29
 
30
  define('PMXI_EDITION', 'free');
31
 
@@ -661,7 +661,9 @@ final class PMXI_Plugin {
661
  if ('' === $page) {
662
  if ( ! is_null(self::$buffer)) {
663
  echo '<div class="wrap">';
664
- echo self::$buffer;
 
 
665
  do_action('pmxi_action_after');
666
  echo '</div>';
667
  } elseif ( ! is_null(self::$buffer_callback)) {
@@ -780,7 +782,7 @@ final class PMXI_Plugin {
780
 
781
  if (function_exists('is_multisite') && is_multisite()) {
782
  // check if it is a network activation - if so, run the activation function for each blog id
783
- if (isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
784
  $old_blog = $wpdb->blogid;
785
  // Get all blog ids
786
  $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
@@ -909,7 +911,7 @@ final class PMXI_Plugin {
909
 
910
  if (function_exists('is_multisite') && is_multisite()) {
911
  // check if it is a network activation - if so, run the activation function for each blog id
912
- if (isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
913
  $old_blog = $wpdb->blogid;
914
  // Get all blog ids
915
  $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
3
  Plugin Name: WP All Import
4
  Plugin URI: http://www.wpallimport.com/wordpress-xml-csv-import/?utm_source=import-plugin-free&utm_medium=wp-plugins-page&utm_campaign=upgrade-to-pro
5
  Description: The most powerful solution for importing XML and CSV files to WordPress. Create Posts and Pages with content from any XML or CSV file. A paid upgrade to WP All Import Pro is available for support and additional features.
6
+ Version: 3.6.4
7
  Author: Soflyy
8
  */
9
 
25
  */
26
  define('WP_ALL_IMPORT_PREFIX', 'pmxi_');
27
 
28
+ define('PMXI_VERSION', '3.6.4');
29
 
30
  define('PMXI_EDITION', 'free');
31
 
661
  if ('' === $page) {
662
  if ( ! is_null(self::$buffer)) {
663
  echo '<div class="wrap">';
664
+
665
+ echo self::$buffer;
666
+
667
  do_action('pmxi_action_after');
668
  echo '</div>';
669
  } elseif ( ! is_null(self::$buffer_callback)) {
782
 
783
  if (function_exists('is_multisite') && is_multisite()) {
784
  // check if it is a network activation - if so, run the activation function for each blog id
785
+ if (isset($_GET['networkwide']) && (intval($_GET['networkwide']) == 1)) {
786
  $old_blog = $wpdb->blogid;
787
  // Get all blog ids
788
  $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
911
 
912
  if (function_exists('is_multisite') && is_multisite()) {
913
  // check if it is a network activation - if so, run the activation function for each blog id
914
+ if (isset($_GET['networkwide']) && (intval($_GET['networkwide']) == 1)) {
915
  $old_blog = $wpdb->blogid;
916
  // Get all blog ids
917
  $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
readme.txt CHANGED
@@ -2,7 +2,7 @@
2
  Contributors: soflyy, wpallimport
3
  Requires at least: 4.1
4
  Tested up to: 5.8
5
- Stable tag: 3.6.3
6
  Tags: wordpress csv import, wordpress xml import, xml, csv, datafeed, import, migrate, import csv to wordpress, import xml to wordpress, advanced xml import, advanced csv import, bulk csv import, bulk xml import, bulk data import, xml to custom post type, csv to custom post type, woocommerce csv import, woocommerce xml import, csv import, import csv, xml import, import xml, csv importer
7
 
8
  WP All Import is an extremely powerful importer that makes it easy to import any XML or CSV file to WordPress.
@@ -105,6 +105,10 @@ Does it work with special character encoding like Hebrew, Arabic, Chinese, etc?
105
 
106
  == Changelog ==
107
 
 
 
 
 
108
  = 3.6.3 =
109
  * security fix
110
  * bug fix: images not updated for existing products when using WooCommerce Import Add-On
2
  Contributors: soflyy, wpallimport
3
  Requires at least: 4.1
4
  Tested up to: 5.8
5
+ Stable tag: 3.6.4
6
  Tags: wordpress csv import, wordpress xml import, xml, csv, datafeed, import, migrate, import csv to wordpress, import xml to wordpress, advanced xml import, advanced csv import, bulk csv import, bulk xml import, bulk data import, xml to custom post type, csv to custom post type, woocommerce csv import, woocommerce xml import, csv import, import csv, xml import, import xml, csv importer
7
 
8
  WP All Import is an extremely powerful importer that makes it easy to import any XML or CSV file to WordPress.
105
 
106
  == Changelog ==
107
 
108
+ = 3.6.4 =
109
+ * improvement: better sanitization and escaping of data in WP All Import interface
110
+ * improvement: use libraries included in WordPress Core
111
+
112
  = 3.6.3 =
113
  * security fix
114
  * bug fix: images not updated for existing products when using WooCommerce Import Add-On
static/codemirror/clike.js DELETED
@@ -1,647 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- (function(mod) {
5
- if (typeof exports == "object" && typeof module == "object") // CommonJS
6
- mod(require("../../lib/codemirror"));
7
- else if (typeof define == "function" && define.amd) // AMD
8
- define(["../../lib/codemirror"], mod);
9
- else // Plain browser env
10
- mod(CodeMirror);
11
- })(function(CodeMirror) {
12
- "use strict";
13
-
14
- CodeMirror.defineMode("clike", function(config, parserConfig) {
15
- var indentUnit = config.indentUnit,
16
- statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
17
- dontAlignCalls = parserConfig.dontAlignCalls,
18
- keywords = parserConfig.keywords || {},
19
- types = parserConfig.types || {},
20
- builtin = parserConfig.builtin || {},
21
- blockKeywords = parserConfig.blockKeywords || {},
22
- defKeywords = parserConfig.defKeywords || {},
23
- atoms = parserConfig.atoms || {},
24
- hooks = parserConfig.hooks || {},
25
- multiLineStrings = parserConfig.multiLineStrings,
26
- indentStatements = parserConfig.indentStatements !== false,
27
- indentSwitch = parserConfig.indentSwitch !== false,
28
- namespaceSeparator = parserConfig.namespaceSeparator;
29
- var isOperatorChar = /[+\-*&%=<>!?|\/]/;
30
-
31
- var curPunc, isDefKeyword;
32
-
33
- function tokenBase(stream, state) {
34
- var ch = stream.next();
35
- if (hooks[ch]) {
36
- var result = hooks[ch](stream, state);
37
- if (result !== false) return result;
38
- }
39
- if (ch == '"' || ch == "'") {
40
- state.tokenize = tokenString(ch);
41
- return state.tokenize(stream, state);
42
- }
43
- if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
44
- curPunc = ch;
45
- return null;
46
- }
47
- if (/\d/.test(ch)) {
48
- stream.eatWhile(/[\w\.]/);
49
- return "number";
50
- }
51
- if (ch == "/") {
52
- if (stream.eat("*")) {
53
- state.tokenize = tokenComment;
54
- return tokenComment(stream, state);
55
- }
56
- if (stream.eat("/")) {
57
- stream.skipToEnd();
58
- return "comment";
59
- }
60
- }
61
- if (isOperatorChar.test(ch)) {
62
- stream.eatWhile(isOperatorChar);
63
- return "operator";
64
- }
65
- stream.eatWhile(/[\w\$_\xa1-\uffff]/);
66
- if (namespaceSeparator) while (stream.match(namespaceSeparator))
67
- stream.eatWhile(/[\w\$_\xa1-\uffff]/);
68
-
69
- var cur = stream.current();
70
- if (keywords.propertyIsEnumerable(cur)) {
71
- if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
72
- if (defKeywords.propertyIsEnumerable(cur)) isDefKeyword = true;
73
- return "keyword";
74
- }
75
- if (types.propertyIsEnumerable(cur)) return "variable-3";
76
- if (builtin.propertyIsEnumerable(cur)) {
77
- if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
78
- return "builtin";
79
- }
80
- if (atoms.propertyIsEnumerable(cur)) return "atom";
81
- return "variable";
82
- }
83
-
84
- function tokenString(quote) {
85
- return function(stream, state) {
86
- var escaped = false, next, end = false;
87
- while ((next = stream.next()) != null) {
88
- if (next == quote && !escaped) {end = true; break;}
89
- escaped = !escaped && next == "\\";
90
- }
91
- if (end || !(escaped || multiLineStrings))
92
- state.tokenize = null;
93
- return "string";
94
- };
95
- }
96
-
97
- function tokenComment(stream, state) {
98
- var maybeEnd = false, ch;
99
- while (ch = stream.next()) {
100
- if (ch == "/" && maybeEnd) {
101
- state.tokenize = null;
102
- break;
103
- }
104
- maybeEnd = (ch == "*");
105
- }
106
- return "comment";
107
- }
108
-
109
- function Context(indented, column, type, align, prev) {
110
- this.indented = indented;
111
- this.column = column;
112
- this.type = type;
113
- this.align = align;
114
- this.prev = prev;
115
- }
116
- function isStatement(type) {
117
- return type == "statement" || type == "switchstatement" || type == "namespace";
118
- }
119
- function pushContext(state, col, type) {
120
- var indent = state.indented;
121
- if (state.context && isStatement(state.context.type) && !isStatement(type))
122
- indent = state.context.indented;
123
- return state.context = new Context(indent, col, type, null, state.context);
124
- }
125
- function popContext(state) {
126
- var t = state.context.type;
127
- if (t == ")" || t == "]" || t == "}")
128
- state.indented = state.context.indented;
129
- return state.context = state.context.prev;
130
- }
131
-
132
- function typeBefore(stream, state) {
133
- if (state.prevToken == "variable" || state.prevToken == "variable-3") return true;
134
- if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, stream.start))) return true;
135
- }
136
-
137
- function isTopScope(context) {
138
- for (;;) {
139
- if (!context || context.type == "top") return true;
140
- if (context.type == "}" && context.prev.type != "namespace") return false;
141
- context = context.prev;
142
- }
143
- }
144
-
145
- // Interface
146
-
147
- return {
148
- startState: function(basecolumn) {
149
- return {
150
- tokenize: null,
151
- context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
152
- indented: 0,
153
- startOfLine: true,
154
- prevToken: null
155
- };
156
- },
157
-
158
- token: function(stream, state) {
159
- var ctx = state.context;
160
- if (stream.sol()) {
161
- if (ctx.align == null) ctx.align = false;
162
- state.indented = stream.indentation();
163
- state.startOfLine = true;
164
- }
165
- if (stream.eatSpace()) return null;
166
- curPunc = isDefKeyword = null;
167
- var style = (state.tokenize || tokenBase)(stream, state);
168
- if (style == "comment" || style == "meta") return style;
169
- if (ctx.align == null) ctx.align = true;
170
-
171
- if ((curPunc == ";" || curPunc == ":" || curPunc == ","))
172
- while (isStatement(state.context.type)) popContext(state);
173
- else if (curPunc == "{") pushContext(state, stream.column(), "}");
174
- else if (curPunc == "[") pushContext(state, stream.column(), "]");
175
- else if (curPunc == "(") pushContext(state, stream.column(), ")");
176
- else if (curPunc == "}") {
177
- while (isStatement(ctx.type)) ctx = popContext(state);
178
- if (ctx.type == "}") ctx = popContext(state);
179
- while (isStatement(ctx.type)) ctx = popContext(state);
180
- }
181
- else if (curPunc == ctx.type) popContext(state);
182
- else if (indentStatements &&
183
- (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
184
- (isStatement(ctx.type) && curPunc == "newstatement"))) {
185
- var type = "statement";
186
- if (curPunc == "newstatement" && indentSwitch && stream.current() == "switch")
187
- type = "switchstatement";
188
- else if (style == "keyword" && stream.current() == "namespace")
189
- type = "namespace";
190
- pushContext(state, stream.column(), type);
191
- }
192
-
193
- if (style == "variable" &&
194
- ((state.prevToken == "def" ||
195
- (parserConfig.typeFirstDefinitions && typeBefore(stream, state) &&
196
- isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
197
- style = "def";
198
-
199
- if (hooks.token) {
200
- var result = hooks.token(stream, state, style);
201
- if (result !== undefined) style = result;
202
- }
203
-
204
- if (style == "def" && parserConfig.styleDefs === false) style = "variable";
205
-
206
- state.startOfLine = false;
207
- state.prevToken = isDefKeyword ? "def" : style || curPunc;
208
- return style;
209
- },
210
-
211
- indent: function(state, textAfter) {
212
- if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
213
- var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
214
- if (isStatement(ctx.type) && firstChar == "}") ctx = ctx.prev;
215
- var closing = firstChar == ctx.type;
216
- var switchBlock = ctx.prev && ctx.prev.type == "switchstatement";
217
- if (isStatement(ctx.type))
218
- return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
219
- if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
220
- return ctx.column + (closing ? 0 : 1);
221
- if (ctx.type == ")" && !closing)
222
- return ctx.indented + statementIndentUnit;
223
-
224
- return ctx.indented + (closing ? 0 : indentUnit) +
225
- (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
226
- },
227
-
228
- electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
229
- blockCommentStart: "/*",
230
- blockCommentEnd: "*/",
231
- lineComment: "//",
232
- fold: "brace"
233
- };
234
- });
235
-
236
- function words(str) {
237
- var obj = {}, words = str.split(" ");
238
- for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
239
- return obj;
240
- }
241
- var cKeywords = "auto if break case register continue return default do sizeof " +
242
- "static else struct switch extern typedef float union for " +
243
- "goto while enum const volatile";
244
- var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";
245
-
246
- function cppHook(stream, state) {
247
- if (!state.startOfLine) return false;
248
- for (;;) {
249
- if (stream.skipTo("\\")) {
250
- stream.next();
251
- if (stream.eol()) {
252
- state.tokenize = cppHook;
253
- break;
254
- }
255
- } else {
256
- stream.skipToEnd();
257
- state.tokenize = null;
258
- break;
259
- }
260
- }
261
- return "meta";
262
- }
263
-
264
- function pointerHook(_stream, state) {
265
- if (state.prevToken == "variable-3") return "variable-3";
266
- return false;
267
- }
268
-
269
- function cpp14Literal(stream) {
270
- stream.eatWhile(/[\w\.']/);
271
- return "number";
272
- }
273
-
274
- function cpp11StringHook(stream, state) {
275
- stream.backUp(1);
276
- // Raw strings.
277
- if (stream.match(/(R|u8R|uR|UR|LR)/)) {
278
- var match = stream.match(/"([^\s\\()]{0,16})\(/);
279
- if (!match) {
280
- return false;
281
- }
282
- state.cpp11RawStringDelim = match[1];
283
- state.tokenize = tokenRawString;
284
- return tokenRawString(stream, state);
285
- }
286
- // Unicode strings/chars.
287
- if (stream.match(/(u8|u|U|L)/)) {
288
- if (stream.match(/["']/, /* eat */ false)) {
289
- return "string";
290
- }
291
- return false;
292
- }
293
- // Ignore this hook.
294
- stream.next();
295
- return false;
296
- }
297
-
298
- function cppLooksLikeConstructor(word) {
299
- var lastTwo = /(\w+)::(\w+)$/.exec(word);
300
- return lastTwo && lastTwo[1] == lastTwo[2];
301
- }
302
-
303
- // C#-style strings where "" escapes a quote.
304
- function tokenAtString(stream, state) {
305
- var next;
306
- while ((next = stream.next()) != null) {
307
- if (next == '"' && !stream.eat('"')) {
308
- state.tokenize = null;
309
- break;
310
- }
311
- }
312
- return "string";
313
- }
314
-
315
- // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
316
- // <delim> can be a string up to 16 characters long.
317
- function tokenRawString(stream, state) {
318
- // Escape characters that have special regex meanings.
319
- var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
320
- var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
321
- if (match)
322
- state.tokenize = null;
323
- else
324
- stream.skipToEnd();
325
- return "string";
326
- }
327
-
328
- function def(mimes, mode) {
329
- if (typeof mimes == "string") mimes = [mimes];
330
- var words = [];
331
- function add(obj) {
332
- if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
333
- words.push(prop);
334
- }
335
- add(mode.keywords);
336
- add(mode.types);
337
- add(mode.builtin);
338
- add(mode.atoms);
339
- if (words.length) {
340
- mode.helperType = mimes[0];
341
- CodeMirror.registerHelper("hintWords", mimes[0], words);
342
- }
343
-
344
- for (var i = 0; i < mimes.length; ++i)
345
- CodeMirror.defineMIME(mimes[i], mode);
346
- }
347
-
348
- def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
349
- name: "clike",
350
- keywords: words(cKeywords),
351
- types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
352
- "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
353
- "uint32_t uint64_t"),
354
- blockKeywords: words("case do else for if switch while struct"),
355
- defKeywords: words("struct"),
356
- typeFirstDefinitions: true,
357
- atoms: words("null true false"),
358
- hooks: {"#": cppHook, "*": pointerHook},
359
- modeProps: {fold: ["brace", "include"]}
360
- });
361
-
362
- def(["text/x-c++src", "text/x-c++hdr"], {
363
- name: "clike",
364
- keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " +
365
- "static_cast typeid catch operator template typename class friend private " +
366
- "this using const_cast inline public throw virtual delete mutable protected " +
367
- "alignas alignof constexpr decltype nullptr noexcept thread_local final " +
368
- "static_assert override"),
369
- types: words(cTypes + " bool wchar_t"),
370
- blockKeywords: words("catch class do else finally for if struct switch try while"),
371
- defKeywords: words("class namespace struct enum union"),
372
- typeFirstDefinitions: true,
373
- atoms: words("true false null"),
374
- hooks: {
375
- "#": cppHook,
376
- "*": pointerHook,
377
- "u": cpp11StringHook,
378
- "U": cpp11StringHook,
379
- "L": cpp11StringHook,
380
- "R": cpp11StringHook,
381
- "0": cpp14Literal,
382
- "1": cpp14Literal,
383
- "2": cpp14Literal,
384
- "3": cpp14Literal,
385
- "4": cpp14Literal,
386
- "5": cpp14Literal,
387
- "6": cpp14Literal,
388
- "7": cpp14Literal,
389
- "8": cpp14Literal,
390
- "9": cpp14Literal,
391
- token: function(stream, state, style) {
392
- if (style == "variable" && stream.peek() == "(" &&
393
- (state.prevToken == ";" || state.prevToken == null ||
394
- state.prevToken == "}") &&
395
- cppLooksLikeConstructor(stream.current()))
396
- return "def";
397
- }
398
- },
399
- namespaceSeparator: "::",
400
- modeProps: {fold: ["brace", "include"]}
401
- });
402
-
403
- def("text/x-java", {
404
- name: "clike",
405
- keywords: words("abstract assert break case catch class const continue default " +
406
- "do else enum extends final finally float for goto if implements import " +
407
- "instanceof interface native new package private protected public " +
408
- "return static strictfp super switch synchronized this throw throws transient " +
409
- "try volatile while"),
410
- types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
411
- "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
412
- blockKeywords: words("catch class do else finally for if switch try while"),
413
- defKeywords: words("class interface package enum"),
414
- typeFirstDefinitions: true,
415
- atoms: words("true false null"),
416
- hooks: {
417
- "@": function(stream) {
418
- stream.eatWhile(/[\w\$_]/);
419
- return "meta";
420
- }
421
- },
422
- modeProps: {fold: ["brace", "import"]}
423
- });
424
-
425
- def("text/x-csharp", {
426
- name: "clike",
427
- keywords: words("abstract as async await base break case catch checked class const continue" +
428
- " default delegate do else enum event explicit extern finally fixed for" +
429
- " foreach goto if implicit in interface internal is lock namespace new" +
430
- " operator out override params private protected public readonly ref return sealed" +
431
- " sizeof stackalloc static struct switch this throw try typeof unchecked" +
432
- " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
433
- " global group into join let orderby partial remove select set value var yield"),
434
- types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
435
- " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
436
- " UInt64 bool byte char decimal double short int long object" +
437
- " sbyte float string ushort uint ulong"),
438
- blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
439
- defKeywords: words("class interface namespace struct var"),
440
- typeFirstDefinitions: true,
441
- atoms: words("true false null"),
442
- hooks: {
443
- "@": function(stream, state) {
444
- if (stream.eat('"')) {
445
- state.tokenize = tokenAtString;
446
- return tokenAtString(stream, state);
447
- }
448
- stream.eatWhile(/[\w\$_]/);
449
- return "meta";
450
- }
451
- }
452
- });
453
-
454
- function tokenTripleString(stream, state) {
455
- var escaped = false;
456
- while (!stream.eol()) {
457
- if (!escaped && stream.match('"""')) {
458
- state.tokenize = null;
459
- break;
460
- }
461
- escaped = stream.next() == "\\" && !escaped;
462
- }
463
- return "string";
464
- }
465
-
466
- def("text/x-scala", {
467
- name: "clike",
468
- keywords: words(
469
-
470
- /* scala */
471
- "abstract case catch class def do else extends false final finally for forSome if " +
472
- "implicit import lazy match new null object override package private protected return " +
473
- "sealed super this throw trait try type val var while with yield _ : = => <- <: " +
474
- "<% >: # @ " +
475
-
476
- /* package scala */
477
- "assert assume require print println printf readLine readBoolean readByte readShort " +
478
- "readChar readInt readLong readFloat readDouble " +
479
-
480
- ":: #:: "
481
- ),
482
- types: words(
483
- "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
484
- "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
485
- "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
486
- "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
487
- "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
488
-
489
- /* package java.lang */
490
- "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
491
- "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
492
- "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
493
- "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
494
- ),
495
- multiLineStrings: true,
496
- blockKeywords: words("catch class do else finally for forSome if match switch try while"),
497
- defKeywords: words("class def object package trait type val var"),
498
- atoms: words("true false null"),
499
- indentStatements: false,
500
- indentSwitch: false,
501
- hooks: {
502
- "@": function(stream) {
503
- stream.eatWhile(/[\w\$_]/);
504
- return "meta";
505
- },
506
- '"': function(stream, state) {
507
- if (!stream.match('""')) return false;
508
- state.tokenize = tokenTripleString;
509
- return state.tokenize(stream, state);
510
- },
511
- "'": function(stream) {
512
- stream.eatWhile(/[\w\$_\xa1-\uffff]/);
513
- return "atom";
514
- }
515
- },
516
- modeProps: {closeBrackets: {triples: '"'}}
517
- });
518
-
519
- def("text/x-kotlin", {
520
- name: "clike",
521
- keywords: words(
522
- /*keywords*/
523
- "package as typealias class interface this super val " +
524
- "var fun for is in This throw return " +
525
- "break continue object if else while do try when !in !is as?" +
526
-
527
- /*soft keywords*/
528
- "file import where by get set abstract enum open inner override private public internal " +
529
- "protected catch finally out final vararg reified dynamic companion constructor init " +
530
- "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
531
- "external annotation crossinline"
532
- ),
533
- types: words(
534
- /* package java.lang */
535
- "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
536
- "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
537
- "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
538
- "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
539
- ),
540
- multiLineStrings: true,
541
- blockKeywords: words("catch class do else finally for if where try while enum"),
542
- defKeywords: words("class val var object package interface fun"),
543
- atoms: words("true false null this"),
544
- modeProps: {closeBrackets: {triples: '"'}}
545
- });
546
-
547
- def(["x-shader/x-vertex", "x-shader/x-fragment"], {
548
- name: "clike",
549
- keywords: words("sampler1D sampler2D sampler3D samplerCube " +
550
- "sampler1DShadow sampler2DShadow " +
551
- "const attribute uniform varying " +
552
- "break continue discard return " +
553
- "for while do if else struct " +
554
- "in out inout"),
555
- types: words("float int bool void " +
556
- "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
557
- "mat2 mat3 mat4"),
558
- blockKeywords: words("for while do if else struct"),
559
- builtin: words("radians degrees sin cos tan asin acos atan " +
560
- "pow exp log exp2 sqrt inversesqrt " +
561
- "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
562
- "length distance dot cross normalize ftransform faceforward " +
563
- "reflect refract matrixCompMult " +
564
- "lessThan lessThanEqual greaterThan greaterThanEqual " +
565
- "equal notEqual any all not " +
566
- "texture1D texture1DProj texture1DLod texture1DProjLod " +
567
- "texture2D texture2DProj texture2DLod texture2DProjLod " +
568
- "texture3D texture3DProj texture3DLod texture3DProjLod " +
569
- "textureCube textureCubeLod " +
570
- "shadow1D shadow2D shadow1DProj shadow2DProj " +
571
- "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
572
- "dFdx dFdy fwidth " +
573
- "noise1 noise2 noise3 noise4"),
574
- atoms: words("true false " +
575
- "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
576
- "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
577
- "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
578
- "gl_FogCoord gl_PointCoord " +
579
- "gl_Position gl_PointSize gl_ClipVertex " +
580
- "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
581
- "gl_TexCoord gl_FogFragCoord " +
582
- "gl_FragCoord gl_FrontFacing " +
583
- "gl_FragData gl_FragDepth " +
584
- "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
585
- "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
586
- "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
587
- "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
588
- "gl_ProjectionMatrixInverseTranspose " +
589
- "gl_ModelViewProjectionMatrixInverseTranspose " +
590
- "gl_TextureMatrixInverseTranspose " +
591
- "gl_NormalScale gl_DepthRange gl_ClipPlane " +
592
- "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
593
- "gl_FrontLightModelProduct gl_BackLightModelProduct " +
594
- "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
595
- "gl_FogParameters " +
596
- "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
597
- "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
598
- "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
599
- "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
600
- "gl_MaxDrawBuffers"),
601
- indentSwitch: false,
602
- hooks: {"#": cppHook},
603
- modeProps: {fold: ["brace", "include"]}
604
- });
605
-
606
- def("text/x-nesc", {
607
- name: "clike",
608
- keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
609
- "implementation includes interface module new norace nx_struct nx_union post provides " +
610
- "signal task uses abstract extends"),
611
- types: words(cTypes),
612
- blockKeywords: words("case do else for if switch while struct"),
613
- atoms: words("null true false"),
614
- hooks: {"#": cppHook},
615
- modeProps: {fold: ["brace", "include"]}
616
- });
617
-
618
- def("text/x-objectivec", {
619
- name: "clike",
620
- keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
621
- "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
622
- types: words(cTypes),
623
- atoms: words("YES NO NULL NILL ON OFF true false"),
624
- hooks: {
625
- "@": function(stream) {
626
- stream.eatWhile(/[\w\$]/);
627
- return "keyword";
628
- },
629
- "#": cppHook
630
- },
631
- modeProps: {fold: "brace"}
632
- });
633
-
634
- def("text/x-squirrel", {
635
- name: "clike",
636
- keywords: words("base break clone continue const default delete enum extends function in class" +
637
- " foreach local resume return this throw typeof yield constructor instanceof static"),
638
- types: words(cTypes),
639
- blockKeywords: words("case catch class else for foreach if switch try while"),
640
- defKeywords: words("function local class"),
641
- typeFirstDefinitions: true,
642
- atoms: words("true false null"),
643
- hooks: {"#": cppHook},
644
- modeProps: {fold: ["brace", "include"]}
645
- });
646
-
647
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/codemirror.css DELETED
@@ -1,337 +0,0 @@
1
- /* BASICS */
2
-
3
- .CodeMirror {
4
- /* Set height, width, borders, and global font properties here */
5
- font-family: monospace;
6
- height: 200px;
7
- color: black;
8
- }
9
-
10
- /* PADDING */
11
-
12
- .CodeMirror-lines {
13
- padding: 4px 0; /* Vertical padding around content */
14
- }
15
- .CodeMirror pre {
16
- padding: 0 4px; /* Horizontal padding of content */
17
- }
18
-
19
- .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
20
- background-color: white; /* The little square between H and V scrollbars */
21
- }
22
-
23
- /* GUTTER */
24
-
25
- .CodeMirror-gutters {
26
- border-right: 1px solid #ddd;
27
- background-color: #f7f7f7;
28
- white-space: nowrap;
29
- }
30
- .CodeMirror-linenumbers {}
31
- .CodeMirror-linenumber {
32
- padding: 0 3px 0 5px;
33
- min-width: 20px;
34
- text-align: right;
35
- color: #999;
36
- white-space: nowrap;
37
- }
38
-
39
- .CodeMirror-guttermarker { color: black; }
40
- .CodeMirror-guttermarker-subtle { color: #999; }
41
-
42
- /* CURSOR */
43
-
44
- .CodeMirror-cursor {
45
- border-left: 1px solid black;
46
- border-right: none;
47
- width: 0;
48
- }
49
- /* Shown when moving in bi-directional text */
50
- .CodeMirror div.CodeMirror-secondarycursor {
51
- border-left: 1px solid silver;
52
- }
53
- .cm-fat-cursor .CodeMirror-cursor {
54
- width: auto;
55
- border: 0;
56
- background: #7e7;
57
- }
58
- .cm-fat-cursor div.CodeMirror-cursors {
59
- z-index: 1;
60
- }
61
-
62
- .cm-animate-fat-cursor {
63
- width: auto;
64
- border: 0;
65
- -webkit-animation: blink 1.06s steps(1) infinite;
66
- -moz-animation: blink 1.06s steps(1) infinite;
67
- animation: blink 1.06s steps(1) infinite;
68
- background-color: #7e7;
69
- }
70
- @-moz-keyframes blink {
71
- 0% {}
72
- 50% { background-color: transparent; }
73
- 100% {}
74
- }
75
- @-webkit-keyframes blink {
76
- 0% {}
77
- 50% { background-color: transparent; }
78
- 100% {}
79
- }
80
- @keyframes blink {
81
- 0% {}
82
- 50% { background-color: transparent; }
83
- 100% {}
84
- }
85
-
86
- /* Can style cursor different in overwrite (non-insert) mode */
87
- .CodeMirror-overwrite .CodeMirror-cursor {}
88
-
89
- .cm-tab { display: inline-block; text-decoration: inherit; }
90
-
91
- .CodeMirror-ruler {
92
- border-left: 1px solid #ccc;
93
- position: absolute;
94
- }
95
-
96
- /* DEFAULT THEME */
97
-
98
- .cm-s-default .cm-header {color: blue;}
99
- .cm-s-default .cm-quote {color: #090;}
100
- .cm-negative {color: #d44;}
101
- .cm-positive {color: #292;}
102
- .cm-header, .cm-strong {font-weight: bold;}
103
- .cm-em {font-style: italic;}
104
- .cm-link {text-decoration: underline;}
105
- .cm-strikethrough {text-decoration: line-through;}
106
-
107
- .cm-s-default .cm-keyword {color: #708;}
108
- .cm-s-default .cm-atom {color: #219;}
109
- .cm-s-default .cm-number {color: #164;}
110
- .cm-s-default .cm-def {color: #00f;}
111
- .cm-s-default .cm-variable,
112
- .cm-s-default .cm-punctuation,
113
- .cm-s-default .cm-property,
114
- .cm-s-default .cm-operator {}
115
- .cm-s-default .cm-variable-2 {color: #05a;}
116
- .cm-s-default .cm-variable-3 {color: #085;}
117
- .cm-s-default .cm-comment {color: #a50;}
118
- .cm-s-default .cm-string {color: #a11;}
119
- .cm-s-default .cm-string-2 {color: #f50;}
120
- .cm-s-default .cm-meta {color: #555;}
121
- .cm-s-default .cm-qualifier {color: #555;}
122
- .cm-s-default .cm-builtin {color: #30a;}
123
- .cm-s-default .cm-bracket {color: #997;}
124
- .cm-s-default .cm-tag {color: #170;}
125
- .cm-s-default .cm-attribute {color: #00c;}
126
- .cm-s-default .cm-hr {color: #999;}
127
- .cm-s-default .cm-link {color: #00c;}
128
-
129
- .cm-s-default .cm-error {color: #f00;}
130
- .cm-invalidchar {color: #f00;}
131
-
132
- .CodeMirror-composing { border-bottom: 2px solid; }
133
-
134
- /* Default styles for common addons */
135
-
136
- div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
137
- div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
138
- .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
139
- .CodeMirror-activeline-background {background: #e8f2ff;}
140
-
141
- /* STOP */
142
-
143
- /* The rest of this file contains styles related to the mechanics of
144
- the editor. You probably shouldn't touch them. */
145
-
146
- .CodeMirror {
147
- position: relative;
148
- overflow: hidden;
149
- background: white;
150
- }
151
-
152
- .CodeMirror-scroll {
153
- overflow: scroll !important; /* Things will break if this is overridden */
154
- /* 30px is the magic margin used to hide the element's real scrollbars */
155
- /* See overflow: hidden in .CodeMirror */
156
- margin-bottom: -30px; margin-right: -30px;
157
- padding-bottom: 30px;
158
- height: 100%;
159
- outline: none; /* Prevent dragging from highlighting the element */
160
- position: relative;
161
- }
162
- .CodeMirror-sizer {
163
- position: relative;
164
- margin-left: 30px !important;
165
- min-height: 120px !important;
166
- border-right: 30px solid transparent;
167
- }
168
-
169
- /* The fake, visible scrollbars. Used to force redraw during scrolling
170
- before actuall scrolling happens, thus preventing shaking and
171
- flickering artifacts. */
172
- .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
173
- position: absolute;
174
- z-index: 6;
175
- display: none;
176
- }
177
- .CodeMirror-vscrollbar {
178
- right: 0; top: 0;
179
- overflow-x: hidden;
180
- overflow-y: scroll;
181
- }
182
- .CodeMirror-hscrollbar {
183
- bottom: 0; left: 0;
184
- overflow-y: hidden;
185
- overflow-x: scroll;
186
- }
187
- .CodeMirror-scrollbar-filler {
188
- right: 0; bottom: 0;
189
- }
190
- .CodeMirror-gutter-filler {
191
- left: 0; bottom: 0;
192
- }
193
-
194
- .CodeMirror-gutters {
195
- position: absolute; left: 0; top: 0;
196
- z-index: 3;
197
- }
198
- .CodeMirror-gutter {
199
- white-space: normal;
200
- height: 100%;
201
- display: inline-block;
202
- margin-bottom: -30px;
203
- width: 29px !important;
204
- /* Hack to make IE7 behave */
205
- *zoom:1;
206
- *display:inline;
207
- }
208
- .CodeMirror-gutter-wrapper {
209
- position: absolute;
210
- z-index: 4;
211
- background: none !important;
212
- border: none !important;
213
- }
214
- .CodeMirror-gutter-background {
215
- position: absolute;
216
- top: 0; bottom: 0;
217
- z-index: 4;
218
- }
219
- .CodeMirror-gutter-elt {
220
- position: absolute;
221
- cursor: default;
222
- z-index: 4;
223
- }
224
- .CodeMirror-gutter-wrapper {
225
- -webkit-user-select: none;
226
- -moz-user-select: none;
227
- user-select: none;
228
- }
229
-
230
- .CodeMirror-lines {
231
- cursor: text;
232
- min-height: 1px; /* prevents collapsing before first draw */
233
- }
234
- .CodeMirror pre {
235
- /* Reset some styles that the rest of the page might have set */
236
- -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
237
- border-width: 0;
238
- background: transparent;
239
- font-family: inherit;
240
- font-size: inherit;
241
- margin: 0;
242
- white-space: pre;
243
- word-wrap: normal;
244
- line-height: inherit;
245
- color: inherit;
246
- z-index: 2;
247
- position: relative;
248
- overflow: visible;
249
- -webkit-tap-highlight-color: transparent;
250
- }
251
- .CodeMirror-wrap pre {
252
- word-wrap: break-word;
253
- white-space: pre-wrap;
254
- word-break: normal;
255
- }
256
-
257
- .CodeMirror-linebackground {
258
- position: absolute;
259
- left: 0; right: 0; top: 0; bottom: 0;
260
- z-index: 0;
261
- }
262
-
263
- .CodeMirror-linewidget {
264
- position: relative;
265
- z-index: 2;
266
- overflow: auto;
267
- }
268
-
269
- .CodeMirror-widget {}
270
-
271
- .CodeMirror-code {
272
- outline: none;
273
- }
274
-
275
- /* Force content-box sizing for the elements where we expect it */
276
- .CodeMirror-scroll,
277
- .CodeMirror-sizer,
278
- .CodeMirror-gutter,
279
- .CodeMirror-gutters,
280
- .CodeMirror-linenumber {
281
- -moz-box-sizing: content-box;
282
- box-sizing: content-box;
283
- }
284
-
285
- .CodeMirror-measure {
286
- position: absolute;
287
- width: 100%;
288
- height: 0;
289
- overflow: hidden;
290
- visibility: hidden;
291
- }
292
-
293
- .CodeMirror-cursor { position: absolute; }
294
- .CodeMirror-measure pre { position: static; }
295
-
296
- div.CodeMirror-cursors {
297
- visibility: hidden;
298
- position: relative;
299
- z-index: 3;
300
- }
301
- div.CodeMirror-dragcursors {
302
- visibility: visible;
303
- }
304
-
305
- .CodeMirror-focused div.CodeMirror-cursors {
306
- visibility: visible;
307
- }
308
-
309
- .CodeMirror-selected { background: #d9d9d9; }
310
- .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
311
- .CodeMirror-crosshair { cursor: crosshair; }
312
- .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
313
- .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
314
-
315
- .cm-searching {
316
- background: #ffa;
317
- background: rgba(255, 255, 0, .4);
318
- }
319
-
320
- /* IE7 hack to prevent it from returning funny offsetTops on the spans */
321
- .CodeMirror span { *vertical-align: text-bottom; }
322
-
323
- /* Used to force a border model for a node */
324
- .cm-force-border { padding-right: .1px; }
325
-
326
- @media print {
327
- /* Hide the cursor when printing */
328
- .CodeMirror div.CodeMirror-cursors {
329
- visibility: hidden;
330
- }
331
- }
332
-
333
- /* See issue #2901 */
334
- .cm-tab-wrap-hack:after { content: ''; }
335
-
336
- /* Help users use markselection to safely style text background */
337
- span.CodeMirror-selectedtext { background: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/codemirror.js DELETED
@@ -1,8840 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- // This is CodeMirror (http://codemirror.net), a code editor
5
- // implemented in JavaScript on top of the browser's DOM.
6
- //
7
- // You can find some technical background for some of the code below
8
- // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
-
10
- (function(mod) {
11
- if (typeof exports == "object" && typeof module == "object") // CommonJS
12
- module.exports = mod();
13
- else if (typeof define == "function" && define.amd) // AMD
14
- return define([], mod);
15
- else // Plain browser env
16
- this.CodeMirror = mod();
17
- })(function() {
18
- "use strict";
19
-
20
- // BROWSER SNIFFING
21
-
22
- // Kludges for bugs and behavior differences that can't be feature
23
- // detected are enabled based on userAgent etc sniffing.
24
-
25
- var gecko = /gecko\/\d/i.test(navigator.userAgent);
26
- var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
27
- var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
28
- var ie = ie_upto10 || ie_11up;
29
- var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
30
- var webkit = /WebKit\//.test(navigator.userAgent);
31
- var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
32
- var chrome = /Chrome\//.test(navigator.userAgent);
33
- var presto = /Opera\//.test(navigator.userAgent);
34
- var safari = /Apple Computer/.test(navigator.vendor);
35
- var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
36
- var phantom = /PhantomJS/.test(navigator.userAgent);
37
-
38
- var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
39
- // This is woefully incomplete. Suggestions for alternative methods welcome.
40
- var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
41
- var mac = ios || /Mac/.test(navigator.platform);
42
- var windows = /win/i.test(navigator.platform);
43
-
44
- var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
45
- if (presto_version) presto_version = Number(presto_version[1]);
46
- if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
47
- // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
48
- var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
49
- var captureRightClick = gecko || (ie && ie_version >= 9);
50
-
51
- // Optimize some code when these features are not used.
52
- var sawReadOnlySpans = false, sawCollapsedSpans = false;
53
-
54
- // EDITOR CONSTRUCTOR
55
-
56
- // A CodeMirror instance represents an editor. This is the object
57
- // that user code is usually dealing with.
58
-
59
- function CodeMirror(place, options) {
60
- if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
61
-
62
- this.options = options = options ? copyObj(options) : {};
63
- // Determine effective options based on given values and defaults.
64
- copyObj(defaults, options, false);
65
- setGuttersForLineNumbers(options);
66
-
67
- var doc = options.value;
68
- if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
69
- this.doc = doc;
70
-
71
- var input = new CodeMirror.inputStyles[options.inputStyle](this);
72
- var display = this.display = new Display(place, doc, input);
73
- display.wrapper.CodeMirror = this;
74
- updateGutters(this);
75
- themeChanged(this);
76
- if (options.lineWrapping)
77
- this.display.wrapper.className += " CodeMirror-wrap";
78
- if (options.autofocus && !mobile) display.input.focus();
79
- initScrollbars(this);
80
-
81
- this.state = {
82
- keyMaps: [], // stores maps added by addKeyMap
83
- overlays: [], // highlighting overlays, as added by addOverlay
84
- modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
85
- overwrite: false,
86
- delayingBlurEvent: false,
87
- focused: false,
88
- suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
89
- pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
90
- selectingText: false,
91
- draggingText: false,
92
- highlight: new Delayed(), // stores highlight worker timeout
93
- keySeq: null, // Unfinished key sequence
94
- specialChars: null
95
- };
96
-
97
- var cm = this;
98
-
99
- // Override magic textarea content restore that IE sometimes does
100
- // on our hidden textarea on reload
101
- if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
102
-
103
- registerEventHandlers(this);
104
- ensureGlobalHandlers();
105
-
106
- startOperation(this);
107
- this.curOp.forceUpdate = true;
108
- attachDoc(this, doc);
109
-
110
- if ((options.autofocus && !mobile) || cm.hasFocus())
111
- setTimeout(bind(onFocus, this), 20);
112
- else
113
- onBlur(this);
114
-
115
- for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
116
- optionHandlers[opt](this, options[opt], Init);
117
- maybeUpdateLineNumberWidth(this);
118
- if (options.finishInit) options.finishInit(this);
119
- for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
120
- endOperation(this);
121
- // Suppress optimizelegibility in Webkit, since it breaks text
122
- // measuring on line wrapping boundaries.
123
- if (webkit && options.lineWrapping &&
124
- getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
125
- display.lineDiv.style.textRendering = "auto";
126
- }
127
-
128
- // DISPLAY CONSTRUCTOR
129
-
130
- // The display handles the DOM integration, both for input reading
131
- // and content drawing. It holds references to DOM nodes and
132
- // display-related state.
133
-
134
- function Display(place, doc, input) {
135
- var d = this;
136
- this.input = input;
137
-
138
- // Covers bottom-right square when both scrollbars are present.
139
- d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
140
- d.scrollbarFiller.setAttribute("cm-not-content", "true");
141
- // Covers bottom of gutter when coverGutterNextToScrollbar is on
142
- // and h scrollbar is present.
143
- d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
144
- d.gutterFiller.setAttribute("cm-not-content", "true");
145
- // Will contain the actual code, positioned to cover the viewport.
146
- d.lineDiv = elt("div", null, "CodeMirror-code");
147
- // Elements are added to these to represent selection and cursors.
148
- d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
149
- d.cursorDiv = elt("div", null, "CodeMirror-cursors");
150
- // A visibility: hidden element used to find the size of things.
151
- d.measure = elt("div", null, "CodeMirror-measure");
152
- // When lines outside of the viewport are measured, they are drawn in this.
153
- d.lineMeasure = elt("div", null, "CodeMirror-measure");
154
- // Wraps everything that needs to exist inside the vertically-padded coordinate system
155
- d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
156
- null, "position: relative; outline: none");
157
- // Moved around its parent to cover visible view.
158
- d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
159
- // Set to the height of the document, allowing scrolling.
160
- d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
161
- d.sizerWidth = null;
162
- // Behavior of elts with overflow: auto and padding is
163
- // inconsistent across browsers. This is used to ensure the
164
- // scrollable area is big enough.
165
- d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
166
- // Will contain the gutters, if any.
167
- d.gutters = elt("div", null, "CodeMirror-gutters");
168
- d.lineGutter = null;
169
- // Actual scrollable element.
170
- d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
171
- d.scroller.setAttribute("tabIndex", "-1");
172
- // The element in which the editor lives.
173
- d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
174
-
175
- // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
176
- if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
177
- if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
178
-
179
- if (place) {
180
- if (place.appendChild) place.appendChild(d.wrapper);
181
- else place(d.wrapper);
182
- }
183
-
184
- // Current rendered range (may be bigger than the view window).
185
- d.viewFrom = d.viewTo = doc.first;
186
- d.reportedViewFrom = d.reportedViewTo = doc.first;
187
- // Information about the rendered lines.
188
- d.view = [];
189
- d.renderedView = null;
190
- // Holds info about a single rendered line when it was rendered
191
- // for measurement, while not in view.
192
- d.externalMeasured = null;
193
- // Empty space (in pixels) above the view
194
- d.viewOffset = 0;
195
- d.lastWrapHeight = d.lastWrapWidth = 0;
196
- d.updateLineNumbers = null;
197
-
198
- d.nativeBarWidth = d.barHeight = d.barWidth = 0;
199
- d.scrollbarsClipped = false;
200
-
201
- // Used to only resize the line number gutter when necessary (when
202
- // the amount of lines crosses a boundary that makes its width change)
203
- d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
204
- // Set to true when a non-horizontal-scrolling line widget is
205
- // added. As an optimization, line widget aligning is skipped when
206
- // this is false.
207
- d.alignWidgets = false;
208
-
209
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
210
-
211
- // Tracks the maximum line length so that the horizontal scrollbar
212
- // can be kept static when scrolling.
213
- d.maxLine = null;
214
- d.maxLineLength = 0;
215
- d.maxLineChanged = false;
216
-
217
- // Used for measuring wheel scrolling granularity
218
- d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
219
-
220
- // True when shift is held down.
221
- d.shift = false;
222
-
223
- // Used to track whether anything happened since the context menu
224
- // was opened.
225
- d.selForContextMenu = null;
226
-
227
- d.activeTouch = null;
228
-
229
- input.init(d);
230
- }
231
-
232
- // STATE UPDATES
233
-
234
- // Used to get the editor into a consistent state again when options change.
235
-
236
- function loadMode(cm) {
237
- cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
238
- resetModeState(cm);
239
- }
240
-
241
- function resetModeState(cm) {
242
- cm.doc.iter(function(line) {
243
- if (line.stateAfter) line.stateAfter = null;
244
- if (line.styles) line.styles = null;
245
- });
246
- cm.doc.frontier = cm.doc.first;
247
- startWorker(cm, 100);
248
- cm.state.modeGen++;
249
- if (cm.curOp) regChange(cm);
250
- }
251
-
252
- function wrappingChanged(cm) {
253
- if (cm.options.lineWrapping) {
254
- addClass(cm.display.wrapper, "CodeMirror-wrap");
255
- cm.display.sizer.style.minWidth = "";
256
- cm.display.sizerWidth = null;
257
- } else {
258
- rmClass(cm.display.wrapper, "CodeMirror-wrap");
259
- findMaxLine(cm);
260
- }
261
- estimateLineHeights(cm);
262
- regChange(cm);
263
- clearCaches(cm);
264
- setTimeout(function(){updateScrollbars(cm);}, 100);
265
- }
266
-
267
- // Returns a function that estimates the height of a line, to use as
268
- // first approximation until the line becomes visible (and is thus
269
- // properly measurable).
270
- function estimateHeight(cm) {
271
- var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
272
- var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
273
- return function(line) {
274
- if (lineIsHidden(cm.doc, line)) return 0;
275
-
276
- var widgetsHeight = 0;
277
- if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
278
- if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
279
- }
280
-
281
- if (wrapping)
282
- return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
283
- else
284
- return widgetsHeight + th;
285
- };
286
- }
287
-
288
- function estimateLineHeights(cm) {
289
- var doc = cm.doc, est = estimateHeight(cm);
290
- doc.iter(function(line) {
291
- var estHeight = est(line);
292
- if (estHeight != line.height) updateLineHeight(line, estHeight);
293
- });
294
- }
295
-
296
- function themeChanged(cm) {
297
- cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
298
- cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
299
- clearCaches(cm);
300
- }
301
-
302
- function guttersChanged(cm) {
303
- updateGutters(cm);
304
- regChange(cm);
305
- setTimeout(function(){alignHorizontally(cm);}, 20);
306
- }
307
-
308
- // Rebuild the gutter elements, ensure the margin to the left of the
309
- // code matches their width.
310
- function updateGutters(cm) {
311
- var gutters = cm.display.gutters, specs = cm.options.gutters;
312
- removeChildren(gutters);
313
- for (var i = 0; i < specs.length; ++i) {
314
- var gutterClass = specs[i];
315
- var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
316
- if (gutterClass == "CodeMirror-linenumbers") {
317
- cm.display.lineGutter = gElt;
318
- gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
319
- }
320
- }
321
- gutters.style.display = i ? "" : "none";
322
- updateGutterSpace(cm);
323
- }
324
-
325
- function updateGutterSpace(cm) {
326
- var width = cm.display.gutters.offsetWidth;
327
- cm.display.sizer.style.marginLeft = width + "px";
328
- }
329
-
330
- // Compute the character length of a line, taking into account
331
- // collapsed ranges (see markText) that might hide parts, and join
332
- // other lines onto it.
333
- function lineLength(line) {
334
- if (line.height == 0) return 0;
335
- var len = line.text.length, merged, cur = line;
336
- while (merged = collapsedSpanAtStart(cur)) {
337
- var found = merged.find(0, true);
338
- cur = found.from.line;
339
- len += found.from.ch - found.to.ch;
340
- }
341
- cur = line;
342
- while (merged = collapsedSpanAtEnd(cur)) {
343
- var found = merged.find(0, true);
344
- len -= cur.text.length - found.from.ch;
345
- cur = found.to.line;
346
- len += cur.text.length - found.to.ch;
347
- }
348
- return len;
349
- }
350
-
351
- // Find the longest line in the document.
352
- function findMaxLine(cm) {
353
- var d = cm.display, doc = cm.doc;
354
- d.maxLine = getLine(doc, doc.first);
355
- d.maxLineLength = lineLength(d.maxLine);
356
- d.maxLineChanged = true;
357
- doc.iter(function(line) {
358
- var len = lineLength(line);
359
- if (len > d.maxLineLength) {
360
- d.maxLineLength = len;
361
- d.maxLine = line;
362
- }
363
- });
364
- }
365
-
366
- // Make sure the gutters options contains the element
367
- // "CodeMirror-linenumbers" when the lineNumbers option is true.
368
- function setGuttersForLineNumbers(options) {
369
- var found = indexOf(options.gutters, "CodeMirror-linenumbers");
370
- if (found == -1 && options.lineNumbers) {
371
- options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
372
- } else if (found > -1 && !options.lineNumbers) {
373
- options.gutters = options.gutters.slice(0);
374
- options.gutters.splice(found, 1);
375
- }
376
- }
377
-
378
- // SCROLLBARS
379
-
380
- // Prepare DOM reads needed to update the scrollbars. Done in one
381
- // shot to minimize update/measure roundtrips.
382
- function measureForScrollbars(cm) {
383
- var d = cm.display, gutterW = d.gutters.offsetWidth;
384
- var docH = Math.round(cm.doc.height + paddingVert(cm.display));
385
- return {
386
- clientHeight: d.scroller.clientHeight,
387
- viewHeight: d.wrapper.clientHeight,
388
- scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
389
- viewWidth: d.wrapper.clientWidth,
390
- barLeft: cm.options.fixedGutter ? gutterW : 0,
391
- docHeight: docH,
392
- scrollHeight: docH + scrollGap(cm) + d.barHeight,
393
- nativeBarWidth: d.nativeBarWidth,
394
- gutterWidth: gutterW
395
- };
396
- }
397
-
398
- function NativeScrollbars(place, scroll, cm) {
399
- this.cm = cm;
400
- var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
401
- var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
402
- place(vert); place(horiz);
403
-
404
- on(vert, "scroll", function() {
405
- if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
406
- });
407
- on(horiz, "scroll", function() {
408
- if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
409
- });
410
-
411
- this.checkedOverlay = false;
412
- // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
413
- if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
414
- }
415
-
416
- NativeScrollbars.prototype = copyObj({
417
- update: function(measure) {
418
- var needsH = measure.scrollWidth > measure.clientWidth + 1;
419
- var needsV = measure.scrollHeight > measure.clientHeight + 1;
420
- var sWidth = measure.nativeBarWidth;
421
-
422
- if (needsV) {
423
- this.vert.style.display = "block";
424
- this.vert.style.bottom = needsH ? sWidth + "px" : "0";
425
- var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
426
- // A bug in IE8 can cause this value to be negative, so guard it.
427
- this.vert.firstChild.style.height =
428
- Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
429
- } else {
430
- this.vert.style.display = "";
431
- this.vert.firstChild.style.height = "0";
432
- }
433
-
434
- if (needsH) {
435
- this.horiz.style.display = "block";
436
- this.horiz.style.right = needsV ? sWidth + "px" : "0";
437
- this.horiz.style.left = measure.barLeft + "px";
438
- var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
439
- this.horiz.firstChild.style.width =
440
- (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
441
- } else {
442
- this.horiz.style.display = "";
443
- this.horiz.firstChild.style.width = "0";
444
- }
445
-
446
- if (!this.checkedOverlay && measure.clientHeight > 0) {
447
- if (sWidth == 0) this.overlayHack();
448
- this.checkedOverlay = true;
449
- }
450
-
451
- return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
452
- },
453
- setScrollLeft: function(pos) {
454
- if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
455
- },
456
- setScrollTop: function(pos) {
457
- if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
458
- },
459
- overlayHack: function() {
460
- var w = mac && !mac_geMountainLion ? "12px" : "18px";
461
- this.horiz.style.minHeight = this.vert.style.minWidth = w;
462
- var self = this;
463
- var barMouseDown = function(e) {
464
- if (e_target(e) != self.vert && e_target(e) != self.horiz)
465
- operation(self.cm, onMouseDown)(e);
466
- };
467
- on(this.vert, "mousedown", barMouseDown);
468
- on(this.horiz, "mousedown", barMouseDown);
469
- },
470
- clear: function() {
471
- var parent = this.horiz.parentNode;
472
- parent.removeChild(this.horiz);
473
- parent.removeChild(this.vert);
474
- }
475
- }, NativeScrollbars.prototype);
476
-
477
- function NullScrollbars() {}
478
-
479
- NullScrollbars.prototype = copyObj({
480
- update: function() { return {bottom: 0, right: 0}; },
481
- setScrollLeft: function() {},
482
- setScrollTop: function() {},
483
- clear: function() {}
484
- }, NullScrollbars.prototype);
485
-
486
- CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
487
-
488
- function initScrollbars(cm) {
489
- if (cm.display.scrollbars) {
490
- cm.display.scrollbars.clear();
491
- if (cm.display.scrollbars.addClass)
492
- rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
493
- }
494
-
495
- cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
496
- cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
497
- // Prevent clicks in the scrollbars from killing focus
498
- on(node, "mousedown", function() {
499
- if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
500
- });
501
- node.setAttribute("cm-not-content", "true");
502
- }, function(pos, axis) {
503
- if (axis == "horizontal") setScrollLeft(cm, pos);
504
- else setScrollTop(cm, pos);
505
- }, cm);
506
- if (cm.display.scrollbars.addClass)
507
- addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
508
- }
509
-
510
- function updateScrollbars(cm, measure) {
511
- if (!measure) measure = measureForScrollbars(cm);
512
- var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
513
- updateScrollbarsInner(cm, measure);
514
- for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
515
- if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
516
- updateHeightsInViewport(cm);
517
- updateScrollbarsInner(cm, measureForScrollbars(cm));
518
- startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
519
- }
520
- }
521
-
522
- // Re-synchronize the fake scrollbars with the actual size of the
523
- // content.
524
- function updateScrollbarsInner(cm, measure) {
525
- var d = cm.display;
526
- var sizes = d.scrollbars.update(measure);
527
-
528
- d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
529
- d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
530
-
531
- if (sizes.right && sizes.bottom) {
532
- d.scrollbarFiller.style.display = "block";
533
- d.scrollbarFiller.style.height = sizes.bottom + "px";
534
- d.scrollbarFiller.style.width = sizes.right + "px";
535
- } else d.scrollbarFiller.style.display = "";
536
- if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
537
- d.gutterFiller.style.display = "block";
538
- d.gutterFiller.style.height = sizes.bottom + "px";
539
- d.gutterFiller.style.width = measure.gutterWidth + "px";
540
- } else d.gutterFiller.style.display = "";
541
- }
542
-
543
- // Compute the lines that are visible in a given viewport (defaults
544
- // the the current scroll position). viewport may contain top,
545
- // height, and ensure (see op.scrollToPos) properties.
546
- function visibleLines(display, doc, viewport) {
547
- var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
548
- top = Math.floor(top - paddingTop(display));
549
- var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
550
-
551
- var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
552
- // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
553
- // forces those lines into the viewport (if possible).
554
- if (viewport && viewport.ensure) {
555
- var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
556
- if (ensureFrom < from) {
557
- from = ensureFrom;
558
- to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
559
- } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
560
- from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
561
- to = ensureTo;
562
- }
563
- }
564
- return {from: from, to: Math.max(to, from + 1)};
565
- }
566
-
567
- // LINE NUMBERS
568
-
569
- // Re-align line numbers and gutter marks to compensate for
570
- // horizontal scrolling.
571
- function alignHorizontally(cm) {
572
- var display = cm.display, view = display.view;
573
- if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
574
- var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
575
- var gutterW = display.gutters.offsetWidth, left = comp + "px";
576
- for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
577
- if (cm.options.fixedGutter && view[i].gutter)
578
- view[i].gutter.style.left = left;
579
- var align = view[i].alignable;
580
- if (align) for (var j = 0; j < align.length; j++)
581
- align[j].style.left = left;
582
- }
583
- if (cm.options.fixedGutter)
584
- display.gutters.style.left = (comp + gutterW) + "px";
585
- }
586
-
587
- // Used to ensure that the line number gutter is still the right
588
- // size for the current document size. Returns true when an update
589
- // is needed.
590
- function maybeUpdateLineNumberWidth(cm) {
591
- if (!cm.options.lineNumbers) return false;
592
- var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
593
- if (last.length != display.lineNumChars) {
594
- var test = display.measure.appendChild(elt("div", [elt("div", last)],
595
- "CodeMirror-linenumber CodeMirror-gutter-elt"));
596
- var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
597
- display.lineGutter.style.width = "";
598
- display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
599
- display.lineNumWidth = display.lineNumInnerWidth + padding;
600
- display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
601
- display.lineGutter.style.width = display.lineNumWidth + "px";
602
- updateGutterSpace(cm);
603
- return true;
604
- }
605
- return false;
606
- }
607
-
608
- function lineNumberFor(options, i) {
609
- return String(options.lineNumberFormatter(i + options.firstLineNumber));
610
- }
611
-
612
- // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
613
- // but using getBoundingClientRect to get a sub-pixel-accurate
614
- // result.
615
- function compensateForHScroll(display) {
616
- return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
617
- }
618
-
619
- // DISPLAY DRAWING
620
-
621
- function DisplayUpdate(cm, viewport, force) {
622
- var display = cm.display;
623
-
624
- this.viewport = viewport;
625
- // Store some values that we'll need later (but don't want to force a relayout for)
626
- this.visible = visibleLines(display, cm.doc, viewport);
627
- this.editorIsHidden = !display.wrapper.offsetWidth;
628
- this.wrapperHeight = display.wrapper.clientHeight;
629
- this.wrapperWidth = display.wrapper.clientWidth;
630
- this.oldDisplayWidth = displayWidth(cm);
631
- this.force = force;
632
- this.dims = getDimensions(cm);
633
- this.events = [];
634
- }
635
-
636
- DisplayUpdate.prototype.signal = function(emitter, type) {
637
- if (hasHandler(emitter, type))
638
- this.events.push(arguments);
639
- };
640
- DisplayUpdate.prototype.finish = function() {
641
- for (var i = 0; i < this.events.length; i++)
642
- signal.apply(null, this.events[i]);
643
- };
644
-
645
- function maybeClipScrollbars(cm) {
646
- var display = cm.display;
647
- if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
648
- display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
649
- display.heightForcer.style.height = scrollGap(cm) + "px";
650
- display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
651
- display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
652
- display.scrollbarsClipped = true;
653
- }
654
- }
655
-
656
- // Does the actual updating of the line display. Bails out
657
- // (returning false) when there is nothing to be done and forced is
658
- // false.
659
- function updateDisplayIfNeeded(cm, update) {
660
- var display = cm.display, doc = cm.doc;
661
-
662
- if (update.editorIsHidden) {
663
- resetView(cm);
664
- return false;
665
- }
666
-
667
- // Bail out if the visible area is already rendered and nothing changed.
668
- if (!update.force &&
669
- update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
670
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
671
- display.renderedView == display.view && countDirtyView(cm) == 0)
672
- return false;
673
-
674
- if (maybeUpdateLineNumberWidth(cm)) {
675
- resetView(cm);
676
- update.dims = getDimensions(cm);
677
- }
678
-
679
- // Compute a suitable new viewport (from & to)
680
- var end = doc.first + doc.size;
681
- var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
682
- var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
683
- if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
684
- if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
685
- if (sawCollapsedSpans) {
686
- from = visualLineNo(cm.doc, from);
687
- to = visualLineEndNo(cm.doc, to);
688
- }
689
-
690
- var different = from != display.viewFrom || to != display.viewTo ||
691
- display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
692
- adjustView(cm, from, to);
693
-
694
- display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
695
- // Position the mover div to align with the current scroll position
696
- cm.display.mover.style.top = display.viewOffset + "px";
697
-
698
- var toUpdate = countDirtyView(cm);
699
- if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
700
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
701
- return false;
702
-
703
- // For big changes, we hide the enclosing element during the
704
- // update, since that speeds up the operations on most browsers.
705
- var focused = activeElt();
706
- if (toUpdate > 4) display.lineDiv.style.display = "none";
707
- patchDisplay(cm, display.updateLineNumbers, update.dims);
708
- if (toUpdate > 4) display.lineDiv.style.display = "";
709
- display.renderedView = display.view;
710
- // There might have been a widget with a focused element that got
711
- // hidden or updated, if so re-focus it.
712
- if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
713
-
714
- // Prevent selection and cursors from interfering with the scroll
715
- // width and height.
716
- removeChildren(display.cursorDiv);
717
- removeChildren(display.selectionDiv);
718
- display.gutters.style.height = display.sizer.style.minHeight = 0;
719
-
720
- if (different) {
721
- display.lastWrapHeight = update.wrapperHeight;
722
- display.lastWrapWidth = update.wrapperWidth;
723
- startWorker(cm, 400);
724
- }
725
-
726
- display.updateLineNumbers = null;
727
-
728
- return true;
729
- }
730
-
731
- function postUpdateDisplay(cm, update) {
732
- var viewport = update.viewport;
733
- for (var first = true;; first = false) {
734
- if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
735
- // Clip forced viewport to actual scrollable area.
736
- if (viewport && viewport.top != null)
737
- viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
738
- // Updated line heights might result in the drawn area not
739
- // actually covering the viewport. Keep looping until it does.
740
- update.visible = visibleLines(cm.display, cm.doc, viewport);
741
- if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
742
- break;
743
- }
744
- if (!updateDisplayIfNeeded(cm, update)) break;
745
- updateHeightsInViewport(cm);
746
- var barMeasure = measureForScrollbars(cm);
747
- updateSelection(cm);
748
- setDocumentHeight(cm, barMeasure);
749
- updateScrollbars(cm, barMeasure);
750
- }
751
-
752
- update.signal(cm, "update", cm);
753
- if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
754
- update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
755
- cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
756
- }
757
- }
758
-
759
- function updateDisplaySimple(cm, viewport) {
760
- var update = new DisplayUpdate(cm, viewport);
761
- if (updateDisplayIfNeeded(cm, update)) {
762
- updateHeightsInViewport(cm);
763
- postUpdateDisplay(cm, update);
764
- var barMeasure = measureForScrollbars(cm);
765
- updateSelection(cm);
766
- setDocumentHeight(cm, barMeasure);
767
- updateScrollbars(cm, barMeasure);
768
- update.finish();
769
- }
770
- }
771
-
772
- function setDocumentHeight(cm, measure) {
773
- cm.display.sizer.style.minHeight = measure.docHeight + "px";
774
- var total = measure.docHeight + cm.display.barHeight;
775
- cm.display.heightForcer.style.top = total + "px";
776
- cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
777
- }
778
-
779
- // Read the actual heights of the rendered lines, and update their
780
- // stored heights to match.
781
- function updateHeightsInViewport(cm) {
782
- var display = cm.display;
783
- var prevBottom = display.lineDiv.offsetTop;
784
- for (var i = 0; i < display.view.length; i++) {
785
- var cur = display.view[i], height;
786
- if (cur.hidden) continue;
787
- if (ie && ie_version < 8) {
788
- var bot = cur.node.offsetTop + cur.node.offsetHeight;
789
- height = bot - prevBottom;
790
- prevBottom = bot;
791
- } else {
792
- var box = cur.node.getBoundingClientRect();
793
- height = box.bottom - box.top;
794
- }
795
- var diff = cur.line.height - height;
796
- if (height < 2) height = textHeight(display);
797
- if (diff > .001 || diff < -.001) {
798
- updateLineHeight(cur.line, height);
799
- updateWidgetHeight(cur.line);
800
- if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
801
- updateWidgetHeight(cur.rest[j]);
802
- }
803
- }
804
- }
805
-
806
- // Read and store the height of line widgets associated with the
807
- // given line.
808
- function updateWidgetHeight(line) {
809
- if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
810
- line.widgets[i].height = line.widgets[i].node.offsetHeight;
811
- }
812
-
813
- // Do a bulk-read of the DOM positions and sizes needed to draw the
814
- // view, so that we don't interleave reading and writing to the DOM.
815
- function getDimensions(cm) {
816
- var d = cm.display, left = {}, width = {};
817
- var gutterLeft = d.gutters.clientLeft;
818
- for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
819
- left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
820
- width[cm.options.gutters[i]] = n.clientWidth;
821
- }
822
- return {fixedPos: compensateForHScroll(d),
823
- gutterTotalWidth: d.gutters.offsetWidth,
824
- gutterLeft: left,
825
- gutterWidth: width,
826
- wrapperWidth: d.wrapper.clientWidth};
827
- }
828
-
829
- // Sync the actual display DOM structure with display.view, removing
830
- // nodes for lines that are no longer in view, and creating the ones
831
- // that are not there yet, and updating the ones that are out of
832
- // date.
833
- function patchDisplay(cm, updateNumbersFrom, dims) {
834
- var display = cm.display, lineNumbers = cm.options.lineNumbers;
835
- var container = display.lineDiv, cur = container.firstChild;
836
-
837
- function rm(node) {
838
- var next = node.nextSibling;
839
- // Works around a throw-scroll bug in OS X Webkit
840
- if (webkit && mac && cm.display.currentWheelTarget == node)
841
- node.style.display = "none";
842
- else
843
- node.parentNode.removeChild(node);
844
- return next;
845
- }
846
-
847
- var view = display.view, lineN = display.viewFrom;
848
- // Loop over the elements in the view, syncing cur (the DOM nodes
849
- // in display.lineDiv) with the view as we go.
850
- for (var i = 0; i < view.length; i++) {
851
- var lineView = view[i];
852
- if (lineView.hidden) {
853
- } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
854
- var node = buildLineElement(cm, lineView, lineN, dims);
855
- container.insertBefore(node, cur);
856
- } else { // Already drawn
857
- while (cur != lineView.node) cur = rm(cur);
858
- var updateNumber = lineNumbers && updateNumbersFrom != null &&
859
- updateNumbersFrom <= lineN && lineView.lineNumber;
860
- if (lineView.changes) {
861
- if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
862
- updateLineForChanges(cm, lineView, lineN, dims);
863
- }
864
- if (updateNumber) {
865
- removeChildren(lineView.lineNumber);
866
- lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
867
- }
868
- cur = lineView.node.nextSibling;
869
- }
870
- lineN += lineView.size;
871
- }
872
- while (cur) cur = rm(cur);
873
- }
874
-
875
- // When an aspect of a line changes, a string is added to
876
- // lineView.changes. This updates the relevant part of the line's
877
- // DOM structure.
878
- function updateLineForChanges(cm, lineView, lineN, dims) {
879
- for (var j = 0; j < lineView.changes.length; j++) {
880
- var type = lineView.changes[j];
881
- if (type == "text") updateLineText(cm, lineView);
882
- else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
883
- else if (type == "class") updateLineClasses(lineView);
884
- else if (type == "widget") updateLineWidgets(cm, lineView, dims);
885
- }
886
- lineView.changes = null;
887
- }
888
-
889
- // Lines with gutter elements, widgets or a background class need to
890
- // be wrapped, and have the extra elements added to the wrapper div
891
- function ensureLineWrapped(lineView) {
892
- if (lineView.node == lineView.text) {
893
- lineView.node = elt("div", null, null, "position: relative");
894
- if (lineView.text.parentNode)
895
- lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
896
- lineView.node.appendChild(lineView.text);
897
- if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
898
- }
899
- return lineView.node;
900
- }
901
-
902
- function updateLineBackground(lineView) {
903
- var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
904
- if (cls) cls += " CodeMirror-linebackground";
905
- if (lineView.background) {
906
- if (cls) lineView.background.className = cls;
907
- else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
908
- } else if (cls) {
909
- var wrap = ensureLineWrapped(lineView);
910
- lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
911
- }
912
- }
913
-
914
- // Wrapper around buildLineContent which will reuse the structure
915
- // in display.externalMeasured when possible.
916
- function getLineContent(cm, lineView) {
917
- var ext = cm.display.externalMeasured;
918
- if (ext && ext.line == lineView.line) {
919
- cm.display.externalMeasured = null;
920
- lineView.measure = ext.measure;
921
- return ext.built;
922
- }
923
- return buildLineContent(cm, lineView);
924
- }
925
-
926
- // Redraw the line's text. Interacts with the background and text
927
- // classes because the mode may output tokens that influence these
928
- // classes.
929
- function updateLineText(cm, lineView) {
930
- var cls = lineView.text.className;
931
- var built = getLineContent(cm, lineView);
932
- if (lineView.text == lineView.node) lineView.node = built.pre;
933
- lineView.text.parentNode.replaceChild(built.pre, lineView.text);
934
- lineView.text = built.pre;
935
- if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
936
- lineView.bgClass = built.bgClass;
937
- lineView.textClass = built.textClass;
938
- updateLineClasses(lineView);
939
- } else if (cls) {
940
- lineView.text.className = cls;
941
- }
942
- }
943
-
944
- function updateLineClasses(lineView) {
945
- updateLineBackground(lineView);
946
- if (lineView.line.wrapClass)
947
- ensureLineWrapped(lineView).className = lineView.line.wrapClass;
948
- else if (lineView.node != lineView.text)
949
- lineView.node.className = "";
950
- var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
951
- lineView.text.className = textClass || "";
952
- }
953
-
954
- function updateLineGutter(cm, lineView, lineN, dims) {
955
- if (lineView.gutter) {
956
- lineView.node.removeChild(lineView.gutter);
957
- lineView.gutter = null;
958
- }
959
- if (lineView.gutterBackground) {
960
- lineView.node.removeChild(lineView.gutterBackground);
961
- lineView.gutterBackground = null;
962
- }
963
- if (lineView.line.gutterClass) {
964
- var wrap = ensureLineWrapped(lineView);
965
- lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
966
- "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
967
- "px; width: " + dims.gutterTotalWidth + "px");
968
- wrap.insertBefore(lineView.gutterBackground, lineView.text);
969
- }
970
- var markers = lineView.line.gutterMarkers;
971
- if (cm.options.lineNumbers || markers) {
972
- var wrap = ensureLineWrapped(lineView);
973
- var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
974
- (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
975
- cm.display.input.setUneditable(gutterWrap);
976
- wrap.insertBefore(gutterWrap, lineView.text);
977
- if (lineView.line.gutterClass)
978
- gutterWrap.className += " " + lineView.line.gutterClass;
979
- if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
980
- lineView.lineNumber = gutterWrap.appendChild(
981
- elt("div", lineNumberFor(cm.options, lineN),
982
- "CodeMirror-linenumber CodeMirror-gutter-elt",
983
- "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
984
- + cm.display.lineNumInnerWidth + "px"));
985
- if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
986
- var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
987
- if (found)
988
- gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
989
- dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
990
- }
991
- }
992
- }
993
-
994
- function updateLineWidgets(cm, lineView, dims) {
995
- if (lineView.alignable) lineView.alignable = null;
996
- for (var node = lineView.node.firstChild, next; node; node = next) {
997
- var next = node.nextSibling;
998
- if (node.className == "CodeMirror-linewidget")
999
- lineView.node.removeChild(node);
1000
- }
1001
- insertLineWidgets(cm, lineView, dims);
1002
- }
1003
-
1004
- // Build a line's DOM representation from scratch
1005
- function buildLineElement(cm, lineView, lineN, dims) {
1006
- var built = getLineContent(cm, lineView);
1007
- lineView.text = lineView.node = built.pre;
1008
- if (built.bgClass) lineView.bgClass = built.bgClass;
1009
- if (built.textClass) lineView.textClass = built.textClass;
1010
-
1011
- updateLineClasses(lineView);
1012
- updateLineGutter(cm, lineView, lineN, dims);
1013
- insertLineWidgets(cm, lineView, dims);
1014
- return lineView.node;
1015
- }
1016
-
1017
- // A lineView may contain multiple logical lines (when merged by
1018
- // collapsed spans). The widgets for all of them need to be drawn.
1019
- function insertLineWidgets(cm, lineView, dims) {
1020
- insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1021
- if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1022
- insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1023
- }
1024
-
1025
- function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1026
- if (!line.widgets) return;
1027
- var wrap = ensureLineWrapped(lineView);
1028
- for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1029
- var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1030
- if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1031
- positionLineWidget(widget, node, lineView, dims);
1032
- cm.display.input.setUneditable(node);
1033
- if (allowAbove && widget.above)
1034
- wrap.insertBefore(node, lineView.gutter || lineView.text);
1035
- else
1036
- wrap.appendChild(node);
1037
- signalLater(widget, "redraw");
1038
- }
1039
- }
1040
-
1041
- function positionLineWidget(widget, node, lineView, dims) {
1042
- if (widget.noHScroll) {
1043
- (lineView.alignable || (lineView.alignable = [])).push(node);
1044
- var width = dims.wrapperWidth;
1045
- node.style.left = dims.fixedPos + "px";
1046
- if (!widget.coverGutter) {
1047
- width -= dims.gutterTotalWidth;
1048
- node.style.paddingLeft = dims.gutterTotalWidth + "px";
1049
- }
1050
- node.style.width = width + "px";
1051
- }
1052
- if (widget.coverGutter) {
1053
- node.style.zIndex = 5;
1054
- node.style.position = "relative";
1055
- if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1056
- }
1057
- }
1058
-
1059
- // POSITION OBJECT
1060
-
1061
- // A Pos instance represents a position within the text.
1062
- var Pos = CodeMirror.Pos = function(line, ch) {
1063
- if (!(this instanceof Pos)) return new Pos(line, ch);
1064
- this.line = line; this.ch = ch;
1065
- };
1066
-
1067
- // Compare two positions, return 0 if they are the same, a negative
1068
- // number when a is less, and a positive number otherwise.
1069
- var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1070
-
1071
- function copyPos(x) {return Pos(x.line, x.ch);}
1072
- function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1073
- function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1074
-
1075
- // INPUT HANDLING
1076
-
1077
- function ensureFocus(cm) {
1078
- if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1079
- }
1080
-
1081
- function isReadOnly(cm) {
1082
- return cm.options.readOnly || cm.doc.cantEdit;
1083
- }
1084
-
1085
- // This will be set to an array of strings when copying, so that,
1086
- // when pasting, we know what kind of selections the copied text
1087
- // was made out of.
1088
- var lastCopied = null;
1089
-
1090
- function applyTextInput(cm, inserted, deleted, sel, origin) {
1091
- var doc = cm.doc;
1092
- cm.display.shift = false;
1093
- if (!sel) sel = doc.sel;
1094
-
1095
- var paste = cm.state.pasteIncoming || origin == "paste";
1096
- var textLines = doc.splitLines(inserted), multiPaste = null;
1097
- // When pasing N lines into N selections, insert one line per selection
1098
- if (paste && sel.ranges.length > 1) {
1099
- if (lastCopied && lastCopied.join("\n") == inserted) {
1100
- if (sel.ranges.length % lastCopied.length == 0) {
1101
- multiPaste = [];
1102
- for (var i = 0; i < lastCopied.length; i++)
1103
- multiPaste.push(doc.splitLines(lastCopied[i]));
1104
- }
1105
- } else if (textLines.length == sel.ranges.length) {
1106
- multiPaste = map(textLines, function(l) { return [l]; });
1107
- }
1108
- }
1109
-
1110
- // Normal behavior is to insert the new text into every selection
1111
- for (var i = sel.ranges.length - 1; i >= 0; i--) {
1112
- var range = sel.ranges[i];
1113
- var from = range.from(), to = range.to();
1114
- if (range.empty()) {
1115
- if (deleted && deleted > 0) // Handle deletion
1116
- from = Pos(from.line, from.ch - deleted);
1117
- else if (cm.state.overwrite && !paste) // Handle overwrite
1118
- to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1119
- }
1120
- var updateInput = cm.curOp.updateInput;
1121
- var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1122
- origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1123
- makeChange(cm.doc, changeEvent);
1124
- signalLater(cm, "inputRead", cm, changeEvent);
1125
- }
1126
- if (inserted && !paste)
1127
- triggerElectric(cm, inserted);
1128
-
1129
- ensureCursorVisible(cm);
1130
- cm.curOp.updateInput = updateInput;
1131
- cm.curOp.typing = true;
1132
- cm.state.pasteIncoming = cm.state.cutIncoming = false;
1133
- }
1134
-
1135
- function handlePaste(e, cm) {
1136
- var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1137
- if (pasted) {
1138
- e.preventDefault();
1139
- if (!isReadOnly(cm) && !cm.options.disableInput)
1140
- runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1141
- return true;
1142
- }
1143
- }
1144
-
1145
- function triggerElectric(cm, inserted) {
1146
- // When an 'electric' character is inserted, immediately trigger a reindent
1147
- if (!cm.options.electricChars || !cm.options.smartIndent) return;
1148
- var sel = cm.doc.sel;
1149
-
1150
- for (var i = sel.ranges.length - 1; i >= 0; i--) {
1151
- var range = sel.ranges[i];
1152
- if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1153
- var mode = cm.getModeAt(range.head);
1154
- var indented = false;
1155
- if (mode.electricChars) {
1156
- for (var j = 0; j < mode.electricChars.length; j++)
1157
- if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1158
- indented = indentLine(cm, range.head.line, "smart");
1159
- break;
1160
- }
1161
- } else if (mode.electricInput) {
1162
- if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1163
- indented = indentLine(cm, range.head.line, "smart");
1164
- }
1165
- if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1166
- }
1167
- }
1168
-
1169
- function copyableRanges(cm) {
1170
- var text = [], ranges = [];
1171
- for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1172
- var line = cm.doc.sel.ranges[i].head.line;
1173
- var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1174
- ranges.push(lineRange);
1175
- text.push(cm.getRange(lineRange.anchor, lineRange.head));
1176
- }
1177
- return {text: text, ranges: ranges};
1178
- }
1179
-
1180
- function disableBrowserMagic(field) {
1181
- field.setAttribute("autocorrect", "off");
1182
- field.setAttribute("autocapitalize", "off");
1183
- field.setAttribute("spellcheck", "false");
1184
- }
1185
-
1186
- // TEXTAREA INPUT STYLE
1187
-
1188
- function TextareaInput(cm) {
1189
- this.cm = cm;
1190
- // See input.poll and input.reset
1191
- this.prevInput = "";
1192
-
1193
- // Flag that indicates whether we expect input to appear real soon
1194
- // now (after some event like 'keypress' or 'input') and are
1195
- // polling intensively.
1196
- this.pollingFast = false;
1197
- // Self-resetting timeout for the poller
1198
- this.polling = new Delayed();
1199
- // Tracks when input.reset has punted to just putting a short
1200
- // string into the textarea instead of the full selection.
1201
- this.inaccurateSelection = false;
1202
- // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1203
- this.hasSelection = false;
1204
- this.composing = null;
1205
- };
1206
-
1207
- function hiddenTextarea() {
1208
- var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1209
- var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1210
- // The textarea is kept positioned near the cursor to prevent the
1211
- // fact that it'll be scrolled into view on input from scrolling
1212
- // our fake cursor out of view. On webkit, when wrap=off, paste is
1213
- // very slow. So make the area wide instead.
1214
- if (webkit) te.style.width = "1000px";
1215
- else te.setAttribute("wrap", "off");
1216
- // If border: 0; -- iOS fails to open keyboard (issue #1287)
1217
- if (ios) te.style.border = "1px solid black";
1218
- disableBrowserMagic(te);
1219
- return div;
1220
- }
1221
-
1222
- TextareaInput.prototype = copyObj({
1223
- init: function(display) {
1224
- var input = this, cm = this.cm;
1225
-
1226
- // Wraps and hides input textarea
1227
- var div = this.wrapper = hiddenTextarea();
1228
- // The semihidden textarea that is focused when the editor is
1229
- // focused, and receives input.
1230
- var te = this.textarea = div.firstChild;
1231
- display.wrapper.insertBefore(div, display.wrapper.firstChild);
1232
-
1233
- // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1234
- if (ios) te.style.width = "0px";
1235
-
1236
- on(te, "input", function() {
1237
- if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1238
- input.poll();
1239
- });
1240
-
1241
- on(te, "paste", function(e) {
1242
- if (handlePaste(e, cm)) return true;
1243
-
1244
- cm.state.pasteIncoming = true;
1245
- input.fastPoll();
1246
- });
1247
-
1248
- function prepareCopyCut(e) {
1249
- if (cm.somethingSelected()) {
1250
- lastCopied = cm.getSelections();
1251
- if (input.inaccurateSelection) {
1252
- input.prevInput = "";
1253
- input.inaccurateSelection = false;
1254
- te.value = lastCopied.join("\n");
1255
- selectInput(te);
1256
- }
1257
- } else if (!cm.options.lineWiseCopyCut) {
1258
- return;
1259
- } else {
1260
- var ranges = copyableRanges(cm);
1261
- lastCopied = ranges.text;
1262
- if (e.type == "cut") {
1263
- cm.setSelections(ranges.ranges, null, sel_dontScroll);
1264
- } else {
1265
- input.prevInput = "";
1266
- te.value = ranges.text.join("\n");
1267
- selectInput(te);
1268
- }
1269
- }
1270
- if (e.type == "cut") cm.state.cutIncoming = true;
1271
- }
1272
- on(te, "cut", prepareCopyCut);
1273
- on(te, "copy", prepareCopyCut);
1274
-
1275
- on(display.scroller, "paste", function(e) {
1276
- if (eventInWidget(display, e)) return;
1277
- cm.state.pasteIncoming = true;
1278
- input.focus();
1279
- });
1280
-
1281
- // Prevent normal selection in the editor (we handle our own)
1282
- on(display.lineSpace, "selectstart", function(e) {
1283
- if (!eventInWidget(display, e)) e_preventDefault(e);
1284
- });
1285
-
1286
- on(te, "compositionstart", function() {
1287
- var start = cm.getCursor("from");
1288
- if (input.composing) input.composing.range.clear()
1289
- input.composing = {
1290
- start: start,
1291
- range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1292
- };
1293
- });
1294
- on(te, "compositionend", function() {
1295
- if (input.composing) {
1296
- input.poll();
1297
- input.composing.range.clear();
1298
- input.composing = null;
1299
- }
1300
- });
1301
- },
1302
-
1303
- prepareSelection: function() {
1304
- // Redraw the selection and/or cursor
1305
- var cm = this.cm, display = cm.display, doc = cm.doc;
1306
- var result = prepareSelection(cm);
1307
-
1308
- // Move the hidden textarea near the cursor to prevent scrolling artifacts
1309
- if (cm.options.moveInputWithCursor) {
1310
- var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1311
- var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1312
- result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1313
- headPos.top + lineOff.top - wrapOff.top));
1314
- result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1315
- headPos.left + lineOff.left - wrapOff.left));
1316
- }
1317
-
1318
- return result;
1319
- },
1320
-
1321
- showSelection: function(drawn) {
1322
- var cm = this.cm, display = cm.display;
1323
- removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1324
- removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1325
- if (drawn.teTop != null) {
1326
- this.wrapper.style.top = drawn.teTop + "px";
1327
- this.wrapper.style.left = drawn.teLeft + "px";
1328
- }
1329
- },
1330
-
1331
- // Reset the input to correspond to the selection (or to be empty,
1332
- // when not typing and nothing is selected)
1333
- reset: function(typing) {
1334
- if (this.contextMenuPending) return;
1335
- var minimal, selected, cm = this.cm, doc = cm.doc;
1336
- if (cm.somethingSelected()) {
1337
- this.prevInput = "";
1338
- var range = doc.sel.primary();
1339
- minimal = hasCopyEvent &&
1340
- (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1341
- var content = minimal ? "-" : selected || cm.getSelection();
1342
- this.textarea.value = content;
1343
- if (cm.state.focused) selectInput(this.textarea);
1344
- if (ie && ie_version >= 9) this.hasSelection = content;
1345
- } else if (!typing) {
1346
- this.prevInput = this.textarea.value = "";
1347
- if (ie && ie_version >= 9) this.hasSelection = null;
1348
- }
1349
- this.inaccurateSelection = minimal;
1350
- },
1351
-
1352
- getField: function() { return this.textarea; },
1353
-
1354
- supportsTouch: function() { return false; },
1355
-
1356
- focus: function() {
1357
- if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1358
- try { this.textarea.focus(); }
1359
- catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1360
- }
1361
- },
1362
-
1363
- blur: function() { this.textarea.blur(); },
1364
-
1365
- resetPosition: function() {
1366
- this.wrapper.style.top = this.wrapper.style.left = 0;
1367
- },
1368
-
1369
- receivedFocus: function() { this.slowPoll(); },
1370
-
1371
- // Poll for input changes, using the normal rate of polling. This
1372
- // runs as long as the editor is focused.
1373
- slowPoll: function() {
1374
- var input = this;
1375
- if (input.pollingFast) return;
1376
- input.polling.set(this.cm.options.pollInterval, function() {
1377
- input.poll();
1378
- if (input.cm.state.focused) input.slowPoll();
1379
- });
1380
- },
1381
-
1382
- // When an event has just come in that is likely to add or change
1383
- // something in the input textarea, we poll faster, to ensure that
1384
- // the change appears on the screen quickly.
1385
- fastPoll: function() {
1386
- var missed = false, input = this;
1387
- input.pollingFast = true;
1388
- function p() {
1389
- var changed = input.poll();
1390
- if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1391
- else {input.pollingFast = false; input.slowPoll();}
1392
- }
1393
- input.polling.set(20, p);
1394
- },
1395
-
1396
- // Read input from the textarea, and update the document to match.
1397
- // When something is selected, it is present in the textarea, and
1398
- // selected (unless it is huge, in which case a placeholder is
1399
- // used). When nothing is selected, the cursor sits after previously
1400
- // seen text (can be empty), which is stored in prevInput (we must
1401
- // not reset the textarea when typing, because that breaks IME).
1402
- poll: function() {
1403
- var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1404
- // Since this is called a *lot*, try to bail out as cheaply as
1405
- // possible when it is clear that nothing happened. hasSelection
1406
- // will be the case when there is a lot of text in the textarea,
1407
- // in which case reading its value would be expensive.
1408
- if (this.contextMenuPending || !cm.state.focused ||
1409
- (hasSelection(input) && !prevInput && !this.composing) ||
1410
- isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
1411
- return false;
1412
-
1413
- var text = input.value;
1414
- // If nothing changed, bail.
1415
- if (text == prevInput && !cm.somethingSelected()) return false;
1416
- // Work around nonsensical selection resetting in IE9/10, and
1417
- // inexplicable appearance of private area unicode characters on
1418
- // some key combos in Mac (#2689).
1419
- if (ie && ie_version >= 9 && this.hasSelection === text ||
1420
- mac && /[\uf700-\uf7ff]/.test(text)) {
1421
- cm.display.input.reset();
1422
- return false;
1423
- }
1424
-
1425
- if (cm.doc.sel == cm.display.selForContextMenu) {
1426
- var first = text.charCodeAt(0);
1427
- if (first == 0x200b && !prevInput) prevInput = "\u200b";
1428
- if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1429
- }
1430
- // Find the part of the input that is actually new
1431
- var same = 0, l = Math.min(prevInput.length, text.length);
1432
- while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1433
-
1434
- var self = this;
1435
- runInOp(cm, function() {
1436
- applyTextInput(cm, text.slice(same), prevInput.length - same,
1437
- null, self.composing ? "*compose" : null);
1438
-
1439
- // Don't leave long text in the textarea, since it makes further polling slow
1440
- if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1441
- else self.prevInput = text;
1442
-
1443
- if (self.composing) {
1444
- self.composing.range.clear();
1445
- self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1446
- {className: "CodeMirror-composing"});
1447
- }
1448
- });
1449
- return true;
1450
- },
1451
-
1452
- ensurePolled: function() {
1453
- if (this.pollingFast && this.poll()) this.pollingFast = false;
1454
- },
1455
-
1456
- onKeyPress: function() {
1457
- if (ie && ie_version >= 9) this.hasSelection = null;
1458
- this.fastPoll();
1459
- },
1460
-
1461
- onContextMenu: function(e) {
1462
- var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1463
- var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1464
- if (!pos || presto) return; // Opera is difficult.
1465
-
1466
- // Reset the current text selection only if the click is done outside of the selection
1467
- // and 'resetSelectionOnContextMenu' option is true.
1468
- var reset = cm.options.resetSelectionOnContextMenu;
1469
- if (reset && cm.doc.sel.contains(pos) == -1)
1470
- operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1471
-
1472
- var oldCSS = te.style.cssText;
1473
- input.wrapper.style.position = "absolute";
1474
- te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1475
- "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1476
- (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1477
- "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1478
- if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1479
- display.input.focus();
1480
- if (webkit) window.scrollTo(null, oldScrollY);
1481
- display.input.reset();
1482
- // Adds "Select all" to context menu in FF
1483
- if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1484
- input.contextMenuPending = true;
1485
- display.selForContextMenu = cm.doc.sel;
1486
- clearTimeout(display.detectingSelectAll);
1487
-
1488
- // Select-all will be greyed out if there's nothing to select, so
1489
- // this adds a zero-width space so that we can later check whether
1490
- // it got selected.
1491
- function prepareSelectAllHack() {
1492
- if (te.selectionStart != null) {
1493
- var selected = cm.somethingSelected();
1494
- var extval = "\u200b" + (selected ? te.value : "");
1495
- te.value = "\u21da"; // Used to catch context-menu undo
1496
- te.value = extval;
1497
- input.prevInput = selected ? "" : "\u200b";
1498
- te.selectionStart = 1; te.selectionEnd = extval.length;
1499
- // Re-set this, in case some other handler touched the
1500
- // selection in the meantime.
1501
- display.selForContextMenu = cm.doc.sel;
1502
- }
1503
- }
1504
- function rehide() {
1505
- input.contextMenuPending = false;
1506
- input.wrapper.style.position = "relative";
1507
- te.style.cssText = oldCSS;
1508
- if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1509
-
1510
- // Try to detect the user choosing select-all
1511
- if (te.selectionStart != null) {
1512
- if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1513
- var i = 0, poll = function() {
1514
- if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1515
- te.selectionEnd > 0 && input.prevInput == "\u200b")
1516
- operation(cm, commands.selectAll)(cm);
1517
- else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1518
- else display.input.reset();
1519
- };
1520
- display.detectingSelectAll = setTimeout(poll, 200);
1521
- }
1522
- }
1523
-
1524
- if (ie && ie_version >= 9) prepareSelectAllHack();
1525
- if (captureRightClick) {
1526
- e_stop(e);
1527
- var mouseup = function() {
1528
- off(window, "mouseup", mouseup);
1529
- setTimeout(rehide, 20);
1530
- };
1531
- on(window, "mouseup", mouseup);
1532
- } else {
1533
- setTimeout(rehide, 50);
1534
- }
1535
- },
1536
-
1537
- readOnlyChanged: function(val) {
1538
- if (!val) this.reset();
1539
- },
1540
-
1541
- setUneditable: nothing,
1542
-
1543
- needsContentAttribute: false
1544
- }, TextareaInput.prototype);
1545
-
1546
- // CONTENTEDITABLE INPUT STYLE
1547
-
1548
- function ContentEditableInput(cm) {
1549
- this.cm = cm;
1550
- this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1551
- this.polling = new Delayed();
1552
- this.gracePeriod = false;
1553
- }
1554
-
1555
- ContentEditableInput.prototype = copyObj({
1556
- init: function(display) {
1557
- var input = this, cm = input.cm;
1558
- var div = input.div = display.lineDiv;
1559
- disableBrowserMagic(div);
1560
-
1561
- on(div, "paste", function(e) { handlePaste(e, cm); })
1562
-
1563
- on(div, "compositionstart", function(e) {
1564
- var data = e.data;
1565
- input.composing = {sel: cm.doc.sel, data: data, startData: data};
1566
- if (!data) return;
1567
- var prim = cm.doc.sel.primary();
1568
- var line = cm.getLine(prim.head.line);
1569
- var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1570
- if (found > -1 && found <= prim.head.ch)
1571
- input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1572
- Pos(prim.head.line, found + data.length));
1573
- });
1574
- on(div, "compositionupdate", function(e) {
1575
- input.composing.data = e.data;
1576
- });
1577
- on(div, "compositionend", function(e) {
1578
- var ours = input.composing;
1579
- if (!ours) return;
1580
- if (e.data != ours.startData && !/\u200b/.test(e.data))
1581
- ours.data = e.data;
1582
- // Need a small delay to prevent other code (input event,
1583
- // selection polling) from doing damage when fired right after
1584
- // compositionend.
1585
- setTimeout(function() {
1586
- if (!ours.handled)
1587
- input.applyComposition(ours);
1588
- if (input.composing == ours)
1589
- input.composing = null;
1590
- }, 50);
1591
- });
1592
-
1593
- on(div, "touchstart", function() {
1594
- input.forceCompositionEnd();
1595
- });
1596
-
1597
- on(div, "input", function() {
1598
- if (input.composing) return;
1599
- if (isReadOnly(cm) || !input.pollContent())
1600
- runInOp(input.cm, function() {regChange(cm);});
1601
- });
1602
-
1603
- function onCopyCut(e) {
1604
- if (cm.somethingSelected()) {
1605
- lastCopied = cm.getSelections();
1606
- if (e.type == "cut") cm.replaceSelection("", null, "cut");
1607
- } else if (!cm.options.lineWiseCopyCut) {
1608
- return;
1609
- } else {
1610
- var ranges = copyableRanges(cm);
1611
- lastCopied = ranges.text;
1612
- if (e.type == "cut") {
1613
- cm.operation(function() {
1614
- cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1615
- cm.replaceSelection("", null, "cut");
1616
- });
1617
- }
1618
- }
1619
- // iOS exposes the clipboard API, but seems to discard content inserted into it
1620
- if (e.clipboardData && !ios) {
1621
- e.preventDefault();
1622
- e.clipboardData.clearData();
1623
- e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1624
- } else {
1625
- // Old-fashioned briefly-focus-a-textarea hack
1626
- var kludge = hiddenTextarea(), te = kludge.firstChild;
1627
- cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1628
- te.value = lastCopied.join("\n");
1629
- var hadFocus = document.activeElement;
1630
- selectInput(te);
1631
- setTimeout(function() {
1632
- cm.display.lineSpace.removeChild(kludge);
1633
- hadFocus.focus();
1634
- }, 50);
1635
- }
1636
- }
1637
- on(div, "copy", onCopyCut);
1638
- on(div, "cut", onCopyCut);
1639
- },
1640
-
1641
- prepareSelection: function() {
1642
- var result = prepareSelection(this.cm, false);
1643
- result.focus = this.cm.state.focused;
1644
- return result;
1645
- },
1646
-
1647
- showSelection: function(info) {
1648
- if (!info || !this.cm.display.view.length) return;
1649
- if (info.focus) this.showPrimarySelection();
1650
- this.showMultipleSelections(info);
1651
- },
1652
-
1653
- showPrimarySelection: function() {
1654
- var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1655
- var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1656
- var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1657
- if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1658
- cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1659
- cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1660
- return;
1661
-
1662
- var start = posToDOM(this.cm, prim.from());
1663
- var end = posToDOM(this.cm, prim.to());
1664
- if (!start && !end) return;
1665
-
1666
- var view = this.cm.display.view;
1667
- var old = sel.rangeCount && sel.getRangeAt(0);
1668
- if (!start) {
1669
- start = {node: view[0].measure.map[2], offset: 0};
1670
- } else if (!end) { // FIXME dangerously hacky
1671
- var measure = view[view.length - 1].measure;
1672
- var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1673
- end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1674
- }
1675
-
1676
- try { var rng = range(start.node, start.offset, end.offset, end.node); }
1677
- catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1678
- if (rng) {
1679
- sel.removeAllRanges();
1680
- sel.addRange(rng);
1681
- if (old && sel.anchorNode == null) sel.addRange(old);
1682
- else if (gecko) this.startGracePeriod();
1683
- }
1684
- this.rememberSelection();
1685
- },
1686
-
1687
- startGracePeriod: function() {
1688
- var input = this;
1689
- clearTimeout(this.gracePeriod);
1690
- this.gracePeriod = setTimeout(function() {
1691
- input.gracePeriod = false;
1692
- if (input.selectionChanged())
1693
- input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1694
- }, 20);
1695
- },
1696
-
1697
- showMultipleSelections: function(info) {
1698
- removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1699
- removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1700
- },
1701
-
1702
- rememberSelection: function() {
1703
- var sel = window.getSelection();
1704
- this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1705
- this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1706
- },
1707
-
1708
- selectionInEditor: function() {
1709
- var sel = window.getSelection();
1710
- if (!sel.rangeCount) return false;
1711
- var node = sel.getRangeAt(0).commonAncestorContainer;
1712
- return contains(this.div, node);
1713
- },
1714
-
1715
- focus: function() {
1716
- if (this.cm.options.readOnly != "nocursor") this.div.focus();
1717
- },
1718
- blur: function() { this.div.blur(); },
1719
- getField: function() { return this.div; },
1720
-
1721
- supportsTouch: function() { return true; },
1722
-
1723
- receivedFocus: function() {
1724
- var input = this;
1725
- if (this.selectionInEditor())
1726
- this.pollSelection();
1727
- else
1728
- runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1729
-
1730
- function poll() {
1731
- if (input.cm.state.focused) {
1732
- input.pollSelection();
1733
- input.polling.set(input.cm.options.pollInterval, poll);
1734
- }
1735
- }
1736
- this.polling.set(this.cm.options.pollInterval, poll);
1737
- },
1738
-
1739
- selectionChanged: function() {
1740
- var sel = window.getSelection();
1741
- return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1742
- sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1743
- },
1744
-
1745
- pollSelection: function() {
1746
- if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1747
- var sel = window.getSelection(), cm = this.cm;
1748
- this.rememberSelection();
1749
- var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1750
- var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1751
- if (anchor && head) runInOp(cm, function() {
1752
- setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1753
- if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1754
- });
1755
- }
1756
- },
1757
-
1758
- pollContent: function() {
1759
- var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1760
- var from = sel.from(), to = sel.to();
1761
- if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1762
-
1763
- var fromIndex;
1764
- if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1765
- var fromLine = lineNo(display.view[0].line);
1766
- var fromNode = display.view[0].node;
1767
- } else {
1768
- var fromLine = lineNo(display.view[fromIndex].line);
1769
- var fromNode = display.view[fromIndex - 1].node.nextSibling;
1770
- }
1771
- var toIndex = findViewIndex(cm, to.line);
1772
- if (toIndex == display.view.length - 1) {
1773
- var toLine = display.viewTo - 1;
1774
- var toNode = display.lineDiv.lastChild;
1775
- } else {
1776
- var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1777
- var toNode = display.view[toIndex + 1].node.previousSibling;
1778
- }
1779
-
1780
- var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1781
- var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1782
- while (newText.length > 1 && oldText.length > 1) {
1783
- if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1784
- else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1785
- else break;
1786
- }
1787
-
1788
- var cutFront = 0, cutEnd = 0;
1789
- var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1790
- while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1791
- ++cutFront;
1792
- var newBot = lst(newText), oldBot = lst(oldText);
1793
- var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1794
- oldBot.length - (oldText.length == 1 ? cutFront : 0));
1795
- while (cutEnd < maxCutEnd &&
1796
- newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1797
- ++cutEnd;
1798
-
1799
- newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1800
- newText[0] = newText[0].slice(cutFront);
1801
-
1802
- var chFrom = Pos(fromLine, cutFront);
1803
- var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1804
- if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1805
- replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1806
- return true;
1807
- }
1808
- },
1809
-
1810
- ensurePolled: function() {
1811
- this.forceCompositionEnd();
1812
- },
1813
- reset: function() {
1814
- this.forceCompositionEnd();
1815
- },
1816
- forceCompositionEnd: function() {
1817
- if (!this.composing || this.composing.handled) return;
1818
- this.applyComposition(this.composing);
1819
- this.composing.handled = true;
1820
- this.div.blur();
1821
- this.div.focus();
1822
- },
1823
- applyComposition: function(composing) {
1824
- if (isReadOnly(this.cm))
1825
- operation(this.cm, regChange)(this.cm)
1826
- else if (composing.data && composing.data != composing.startData)
1827
- operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1828
- },
1829
-
1830
- setUneditable: function(node) {
1831
- node.contentEditable = "false"
1832
- },
1833
-
1834
- onKeyPress: function(e) {
1835
- e.preventDefault();
1836
- if (!isReadOnly(this.cm))
1837
- operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1838
- },
1839
-
1840
- readOnlyChanged: function(val) {
1841
- this.div.contentEditable = String(val != "nocursor")
1842
- },
1843
-
1844
- onContextMenu: nothing,
1845
- resetPosition: nothing,
1846
-
1847
- needsContentAttribute: true
1848
- }, ContentEditableInput.prototype);
1849
-
1850
- function posToDOM(cm, pos) {
1851
- var view = findViewForLine(cm, pos.line);
1852
- if (!view || view.hidden) return null;
1853
- var line = getLine(cm.doc, pos.line);
1854
- var info = mapFromLineView(view, line, pos.line);
1855
-
1856
- var order = getOrder(line), side = "left";
1857
- if (order) {
1858
- var partPos = getBidiPartAt(order, pos.ch);
1859
- side = partPos % 2 ? "right" : "left";
1860
- }
1861
- var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1862
- result.offset = result.collapse == "right" ? result.end : result.start;
1863
- return result;
1864
- }
1865
-
1866
- function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1867
-
1868
- function domToPos(cm, node, offset) {
1869
- var lineNode;
1870
- if (node == cm.display.lineDiv) {
1871
- lineNode = cm.display.lineDiv.childNodes[offset];
1872
- if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1873
- node = null; offset = 0;
1874
- } else {
1875
- for (lineNode = node;; lineNode = lineNode.parentNode) {
1876
- if (!lineNode || lineNode == cm.display.lineDiv) return null;
1877
- if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1878
- }
1879
- }
1880
- for (var i = 0; i < cm.display.view.length; i++) {
1881
- var lineView = cm.display.view[i];
1882
- if (lineView.node == lineNode)
1883
- return locateNodeInLineView(lineView, node, offset);
1884
- }
1885
- }
1886
-
1887
- function locateNodeInLineView(lineView, node, offset) {
1888
- var wrapper = lineView.text.firstChild, bad = false;
1889
- if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1890
- if (node == wrapper) {
1891
- bad = true;
1892
- node = wrapper.childNodes[offset];
1893
- offset = 0;
1894
- if (!node) {
1895
- var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1896
- return badPos(Pos(lineNo(line), line.text.length), bad);
1897
- }
1898
- }
1899
-
1900
- var textNode = node.nodeType == 3 ? node : null, topNode = node;
1901
- if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1902
- textNode = node.firstChild;
1903
- if (offset) offset = textNode.nodeValue.length;
1904
- }
1905
- while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1906
- var measure = lineView.measure, maps = measure.maps;
1907
-
1908
- function find(textNode, topNode, offset) {
1909
- for (var i = -1; i < (maps ? maps.length : 0); i++) {
1910
- var map = i < 0 ? measure.map : maps[i];
1911
- for (var j = 0; j < map.length; j += 3) {
1912
- var curNode = map[j + 2];
1913
- if (curNode == textNode || curNode == topNode) {
1914
- var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1915
- var ch = map[j] + offset;
1916
- if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1917
- return Pos(line, ch);
1918
- }
1919
- }
1920
- }
1921
- }
1922
- var found = find(textNode, topNode, offset);
1923
- if (found) return badPos(found, bad);
1924
-
1925
- // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1926
- for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1927
- found = find(after, after.firstChild, 0);
1928
- if (found)
1929
- return badPos(Pos(found.line, found.ch - dist), bad);
1930
- else
1931
- dist += after.textContent.length;
1932
- }
1933
- for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1934
- found = find(before, before.firstChild, -1);
1935
- if (found)
1936
- return badPos(Pos(found.line, found.ch + dist), bad);
1937
- else
1938
- dist += after.textContent.length;
1939
- }
1940
- }
1941
-
1942
- function domTextBetween(cm, from, to, fromLine, toLine) {
1943
- var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1944
- function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1945
- function walk(node) {
1946
- if (node.nodeType == 1) {
1947
- var cmText = node.getAttribute("cm-text");
1948
- if (cmText != null) {
1949
- if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1950
- text += cmText;
1951
- return;
1952
- }
1953
- var markerID = node.getAttribute("cm-marker"), range;
1954
- if (markerID) {
1955
- var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1956
- if (found.length && (range = found[0].find()))
1957
- text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1958
- return;
1959
- }
1960
- if (node.getAttribute("contenteditable") == "false") return;
1961
- for (var i = 0; i < node.childNodes.length; i++)
1962
- walk(node.childNodes[i]);
1963
- if (/^(pre|div|p)$/i.test(node.nodeName))
1964
- closing = true;
1965
- } else if (node.nodeType == 3) {
1966
- var val = node.nodeValue;
1967
- if (!val) return;
1968
- if (closing) {
1969
- text += lineSep;
1970
- closing = false;
1971
- }
1972
- text += val;
1973
- }
1974
- }
1975
- for (;;) {
1976
- walk(from);
1977
- if (from == to) break;
1978
- from = from.nextSibling;
1979
- }
1980
- return text;
1981
- }
1982
-
1983
- CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
1984
-
1985
- // SELECTION / CURSOR
1986
-
1987
- // Selection objects are immutable. A new one is created every time
1988
- // the selection changes. A selection is one or more non-overlapping
1989
- // (and non-touching) ranges, sorted, and an integer that indicates
1990
- // which one is the primary selection (the one that's scrolled into
1991
- // view, that getCursor returns, etc).
1992
- function Selection(ranges, primIndex) {
1993
- this.ranges = ranges;
1994
- this.primIndex = primIndex;
1995
- }
1996
-
1997
- Selection.prototype = {
1998
- primary: function() { return this.ranges[this.primIndex]; },
1999
- equals: function(other) {
2000
- if (other == this) return true;
2001
- if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2002
- for (var i = 0; i < this.ranges.length; i++) {
2003
- var here = this.ranges[i], there = other.ranges[i];
2004
- if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2005
- }
2006
- return true;
2007
- },
2008
- deepCopy: function() {
2009
- for (var out = [], i = 0; i < this.ranges.length; i++)
2010
- out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2011
- return new Selection(out, this.primIndex);
2012
- },
2013
- somethingSelected: function() {
2014
- for (var i = 0; i < this.ranges.length; i++)
2015
- if (!this.ranges[i].empty()) return true;
2016
- return false;
2017
- },
2018
- contains: function(pos, end) {
2019
- if (!end) end = pos;
2020
- for (var i = 0; i < this.ranges.length; i++) {
2021
- var range = this.ranges[i];
2022
- if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2023
- return i;
2024
- }
2025
- return -1;
2026
- }
2027
- };
2028
-
2029
- function Range(anchor, head) {
2030
- this.anchor = anchor; this.head = head;
2031
- }
2032
-
2033
- Range.prototype = {
2034
- from: function() { return minPos(this.anchor, this.head); },
2035
- to: function() { return maxPos(this.anchor, this.head); },
2036
- empty: function() {
2037
- return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2038
- }
2039
- };
2040
-
2041
- // Take an unsorted, potentially overlapping set of ranges, and
2042
- // build a selection out of it. 'Consumes' ranges array (modifying
2043
- // it).
2044
- function normalizeSelection(ranges, primIndex) {
2045
- var prim = ranges[primIndex];
2046
- ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2047
- primIndex = indexOf(ranges, prim);
2048
- for (var i = 1; i < ranges.length; i++) {
2049
- var cur = ranges[i], prev = ranges[i - 1];
2050
- if (cmp(prev.to(), cur.from()) >= 0) {
2051
- var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2052
- var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2053
- if (i <= primIndex) --primIndex;
2054
- ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2055
- }
2056
- }
2057
- return new Selection(ranges, primIndex);
2058
- }
2059
-
2060
- function simpleSelection(anchor, head) {
2061
- return new Selection([new Range(anchor, head || anchor)], 0);
2062
- }
2063
-
2064
- // Most of the external API clips given positions to make sure they
2065
- // actually exist within the document.
2066
- function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2067
- function clipPos(doc, pos) {
2068
- if (pos.line < doc.first) return Pos(doc.first, 0);
2069
- var last = doc.first + doc.size - 1;
2070
- if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2071
- return clipToLen(pos, getLine(doc, pos.line).text.length);
2072
- }
2073
- function clipToLen(pos, linelen) {
2074
- var ch = pos.ch;
2075
- if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2076
- else if (ch < 0) return Pos(pos.line, 0);
2077
- else return pos;
2078
- }
2079
- function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2080
- function clipPosArray(doc, array) {
2081
- for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2082
- return out;
2083
- }
2084
-
2085
- // SELECTION UPDATES
2086
-
2087
- // The 'scroll' parameter given to many of these indicated whether
2088
- // the new cursor position should be scrolled into view after
2089
- // modifying the selection.
2090
-
2091
- // If shift is held or the extend flag is set, extends a range to
2092
- // include a given position (and optionally a second position).
2093
- // Otherwise, simply returns the range between the given positions.
2094
- // Used for cursor motion and such.
2095
- function extendRange(doc, range, head, other) {
2096
- if (doc.cm && doc.cm.display.shift || doc.extend) {
2097
- var anchor = range.anchor;
2098
- if (other) {
2099
- var posBefore = cmp(head, anchor) < 0;
2100
- if (posBefore != (cmp(other, anchor) < 0)) {
2101
- anchor = head;
2102
- head = other;
2103
- } else if (posBefore != (cmp(head, other) < 0)) {
2104
- head = other;
2105
- }
2106
- }
2107
- return new Range(anchor, head);
2108
- } else {
2109
- return new Range(other || head, head);
2110
- }
2111
- }
2112
-
2113
- // Extend the primary selection range, discard the rest.
2114
- function extendSelection(doc, head, other, options) {
2115
- setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2116
- }
2117
-
2118
- // Extend all selections (pos is an array of selections with length
2119
- // equal the number of selections)
2120
- function extendSelections(doc, heads, options) {
2121
- for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2122
- out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2123
- var newSel = normalizeSelection(out, doc.sel.primIndex);
2124
- setSelection(doc, newSel, options);
2125
- }
2126
-
2127
- // Updates a single range in the selection.
2128
- function replaceOneSelection(doc, i, range, options) {
2129
- var ranges = doc.sel.ranges.slice(0);
2130
- ranges[i] = range;
2131
- setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2132
- }
2133
-
2134
- // Reset the selection to a single range.
2135
- function setSimpleSelection(doc, anchor, head, options) {
2136
- setSelection(doc, simpleSelection(anchor, head), options);
2137
- }
2138
-
2139
- // Give beforeSelectionChange handlers a change to influence a
2140
- // selection update.
2141
- function filterSelectionChange(doc, sel) {
2142
- var obj = {
2143
- ranges: sel.ranges,
2144
- update: function(ranges) {
2145
- this.ranges = [];
2146
- for (var i = 0; i < ranges.length; i++)
2147
- this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2148
- clipPos(doc, ranges[i].head));
2149
- }
2150
- };
2151
- signal(doc, "beforeSelectionChange", doc, obj);
2152
- if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2153
- if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2154
- else return sel;
2155
- }
2156
-
2157
- function setSelectionReplaceHistory(doc, sel, options) {
2158
- var done = doc.history.done, last = lst(done);
2159
- if (last && last.ranges) {
2160
- done[done.length - 1] = sel;
2161
- setSelectionNoUndo(doc, sel, options);
2162
- } else {
2163
- setSelection(doc, sel, options);
2164
- }
2165
- }
2166
-
2167
- // Set a new selection.
2168
- function setSelection(doc, sel, options) {
2169
- setSelectionNoUndo(doc, sel, options);
2170
- addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2171
- }
2172
-
2173
- function setSelectionNoUndo(doc, sel, options) {
2174
- if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2175
- sel = filterSelectionChange(doc, sel);
2176
-
2177
- var bias = options && options.bias ||
2178
- (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2179
- setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2180
-
2181
- if (!(options && options.scroll === false) && doc.cm)
2182
- ensureCursorVisible(doc.cm);
2183
- }
2184
-
2185
- function setSelectionInner(doc, sel) {
2186
- if (sel.equals(doc.sel)) return;
2187
-
2188
- doc.sel = sel;
2189
-
2190
- if (doc.cm) {
2191
- doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2192
- signalCursorActivity(doc.cm);
2193
- }
2194
- signalLater(doc, "cursorActivity", doc);
2195
- }
2196
-
2197
- // Verify that the selection does not partially select any atomic
2198
- // marked ranges.
2199
- function reCheckSelection(doc) {
2200
- setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2201
- }
2202
-
2203
- // Return a selection that does not partially select any atomic
2204
- // ranges.
2205
- function skipAtomicInSelection(doc, sel, bias, mayClear) {
2206
- var out;
2207
- for (var i = 0; i < sel.ranges.length; i++) {
2208
- var range = sel.ranges[i];
2209
- var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
2210
- var newHead = skipAtomic(doc, range.head, bias, mayClear);
2211
- if (out || newAnchor != range.anchor || newHead != range.head) {
2212
- if (!out) out = sel.ranges.slice(0, i);
2213
- out[i] = new Range(newAnchor, newHead);
2214
- }
2215
- }
2216
- return out ? normalizeSelection(out, sel.primIndex) : sel;
2217
- }
2218
-
2219
- // Ensure a given position is not inside an atomic range.
2220
- function skipAtomic(doc, pos, bias, mayClear) {
2221
- var flipped = false, curPos = pos;
2222
- var dir = bias || 1;
2223
- doc.cantEdit = false;
2224
- search: for (;;) {
2225
- var line = getLine(doc, curPos.line);
2226
- if (line.markedSpans) {
2227
- for (var i = 0; i < line.markedSpans.length; ++i) {
2228
- var sp = line.markedSpans[i], m = sp.marker;
2229
- if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2230
- (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2231
- if (mayClear) {
2232
- signal(m, "beforeCursorEnter");
2233
- if (m.explicitlyCleared) {
2234
- if (!line.markedSpans) break;
2235
- else {--i; continue;}
2236
- }
2237
- }
2238
- if (!m.atomic) continue;
2239
- var newPos = m.find(dir < 0 ? -1 : 1);
2240
- if (cmp(newPos, curPos) == 0) {
2241
- newPos.ch += dir;
2242
- if (newPos.ch < 0) {
2243
- if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2244
- else newPos = null;
2245
- } else if (newPos.ch > line.text.length) {
2246
- if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2247
- else newPos = null;
2248
- }
2249
- if (!newPos) {
2250
- if (flipped) {
2251
- // Driven in a corner -- no valid cursor position found at all
2252
- // -- try again *with* clearing, if we didn't already
2253
- if (!mayClear) return skipAtomic(doc, pos, bias, true);
2254
- // Otherwise, turn off editing until further notice, and return the start of the doc
2255
- doc.cantEdit = true;
2256
- return Pos(doc.first, 0);
2257
- }
2258
- flipped = true; newPos = pos; dir = -dir;
2259
- }
2260
- }
2261
- curPos = newPos;
2262
- continue search;
2263
- }
2264
- }
2265
- }
2266
- return curPos;
2267
- }
2268
- }
2269
-
2270
- // SELECTION DRAWING
2271
-
2272
- function updateSelection(cm) {
2273
- cm.display.input.showSelection(cm.display.input.prepareSelection());
2274
- }
2275
-
2276
- function prepareSelection(cm, primary) {
2277
- var doc = cm.doc, result = {};
2278
- var curFragment = result.cursors = document.createDocumentFragment();
2279
- var selFragment = result.selection = document.createDocumentFragment();
2280
-
2281
- for (var i = 0; i < doc.sel.ranges.length; i++) {
2282
- if (primary === false && i == doc.sel.primIndex) continue;
2283
- var range = doc.sel.ranges[i];
2284
- var collapsed = range.empty();
2285
- if (collapsed || cm.options.showCursorWhenSelecting)
2286
- drawSelectionCursor(cm, range.head, curFragment);
2287
- if (!collapsed)
2288
- drawSelectionRange(cm, range, selFragment);
2289
- }
2290
- return result;
2291
- }
2292
-
2293
- // Draws a cursor for the given range
2294
- function drawSelectionCursor(cm, head, output) {
2295
- var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2296
-
2297
- var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2298
- cursor.style.left = pos.left + "px";
2299
- cursor.style.top = pos.top + "px";
2300
- cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2301
-
2302
- if (pos.other) {
2303
- // Secondary cursor, shown when on a 'jump' in bi-directional text
2304
- var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2305
- otherCursor.style.display = "";
2306
- otherCursor.style.left = pos.other.left + "px";
2307
- otherCursor.style.top = pos.other.top + "px";
2308
- otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2309
- }
2310
- }
2311
-
2312
- // Draws the given range as a highlighted selection
2313
- function drawSelectionRange(cm, range, output) {
2314
- var display = cm.display, doc = cm.doc;
2315
- var fragment = document.createDocumentFragment();
2316
- var padding = paddingH(cm.display), leftSide = padding.left;
2317
- var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2318
-
2319
- function add(left, top, width, bottom) {
2320
- if (top < 0) top = 0;
2321
- top = Math.round(top);
2322
- bottom = Math.round(bottom);
2323
- fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2324
- "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2325
- "px; height: " + (bottom - top) + "px"));
2326
- }
2327
-
2328
- function drawForLine(line, fromArg, toArg) {
2329
- var lineObj = getLine(doc, line);
2330
- var lineLen = lineObj.text.length;
2331
- var start, end;
2332
- function coords(ch, bias) {
2333
- return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2334
- }
2335
-
2336
- iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2337
- var leftPos = coords(from, "left"), rightPos, left, right;
2338
- if (from == to) {
2339
- rightPos = leftPos;
2340
- left = right = leftPos.left;
2341
- } else {
2342
- rightPos = coords(to - 1, "right");
2343
- if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2344
- left = leftPos.left;
2345
- right = rightPos.right;
2346
- }
2347
- if (fromArg == null && from == 0) left = leftSide;
2348
- if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2349
- add(left, leftPos.top, null, leftPos.bottom);
2350
- left = leftSide;
2351
- if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2352
- }
2353
- if (toArg == null && to == lineLen) right = rightSide;
2354
- if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2355
- start = leftPos;
2356
- if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2357
- end = rightPos;
2358
- if (left < leftSide + 1) left = leftSide;
2359
- add(left, rightPos.top, right - left, rightPos.bottom);
2360
- });
2361
- return {start: start, end: end};
2362
- }
2363
-
2364
- var sFrom = range.from(), sTo = range.to();
2365
- if (sFrom.line == sTo.line) {
2366
- drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2367
- } else {
2368
- var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2369
- var singleVLine = visualLine(fromLine) == visualLine(toLine);
2370
- var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2371
- var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2372
- if (singleVLine) {
2373
- if (leftEnd.top < rightStart.top - 2) {
2374
- add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2375
- add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2376
- } else {
2377
- add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2378
- }
2379
- }
2380
- if (leftEnd.bottom < rightStart.top)
2381
- add(leftSide, leftEnd.bottom, null, rightStart.top);
2382
- }
2383
-
2384
- output.appendChild(fragment);
2385
- }
2386
-
2387
- // Cursor-blinking
2388
- function restartBlink(cm) {
2389
- if (!cm.state.focused) return;
2390
- var display = cm.display;
2391
- clearInterval(display.blinker);
2392
- var on = true;
2393
- display.cursorDiv.style.visibility = "";
2394
- if (cm.options.cursorBlinkRate > 0)
2395
- display.blinker = setInterval(function() {
2396
- display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2397
- }, cm.options.cursorBlinkRate);
2398
- else if (cm.options.cursorBlinkRate < 0)
2399
- display.cursorDiv.style.visibility = "hidden";
2400
- }
2401
-
2402
- // HIGHLIGHT WORKER
2403
-
2404
- function startWorker(cm, time) {
2405
- if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2406
- cm.state.highlight.set(time, bind(highlightWorker, cm));
2407
- }
2408
-
2409
- function highlightWorker(cm) {
2410
- var doc = cm.doc;
2411
- if (doc.frontier < doc.first) doc.frontier = doc.first;
2412
- if (doc.frontier >= cm.display.viewTo) return;
2413
- var end = +new Date + cm.options.workTime;
2414
- var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2415
- var changedLines = [];
2416
-
2417
- doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2418
- if (doc.frontier >= cm.display.viewFrom) { // Visible
2419
- var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2420
- var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2421
- line.styles = highlighted.styles;
2422
- var oldCls = line.styleClasses, newCls = highlighted.classes;
2423
- if (newCls) line.styleClasses = newCls;
2424
- else if (oldCls) line.styleClasses = null;
2425
- var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2426
- oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2427
- for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2428
- if (ischange) changedLines.push(doc.frontier);
2429
- line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2430
- } else {
2431
- if (line.text.length <= cm.options.maxHighlightLength)
2432
- processLine(cm, line.text, state);
2433
- line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2434
- }
2435
- ++doc.frontier;
2436
- if (+new Date > end) {
2437
- startWorker(cm, cm.options.workDelay);
2438
- return true;
2439
- }
2440
- });
2441
- if (changedLines.length) runInOp(cm, function() {
2442
- for (var i = 0; i < changedLines.length; i++)
2443
- regLineChange(cm, changedLines[i], "text");
2444
- });
2445
- }
2446
-
2447
- // Finds the line to start with when starting a parse. Tries to
2448
- // find a line with a stateAfter, so that it can start with a
2449
- // valid state. If that fails, it returns the line with the
2450
- // smallest indentation, which tends to need the least context to
2451
- // parse correctly.
2452
- function findStartLine(cm, n, precise) {
2453
- var minindent, minline, doc = cm.doc;
2454
- var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2455
- for (var search = n; search > lim; --search) {
2456
- if (search <= doc.first) return doc.first;
2457
- var line = getLine(doc, search - 1);
2458
- if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2459
- var indented = countColumn(line.text, null, cm.options.tabSize);
2460
- if (minline == null || minindent > indented) {
2461
- minline = search - 1;
2462
- minindent = indented;
2463
- }
2464
- }
2465
- return minline;
2466
- }
2467
-
2468
- function getStateBefore(cm, n, precise) {
2469
- var doc = cm.doc, display = cm.display;
2470
- if (!doc.mode.startState) return true;
2471
- var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2472
- if (!state) state = startState(doc.mode);
2473
- else state = copyState(doc.mode, state);
2474
- doc.iter(pos, n, function(line) {
2475
- processLine(cm, line.text, state);
2476
- var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2477
- line.stateAfter = save ? copyState(doc.mode, state) : null;
2478
- ++pos;
2479
- });
2480
- if (precise) doc.frontier = pos;
2481
- return state;
2482
- }
2483
-
2484
- // POSITION MEASUREMENT
2485
-
2486
- function paddingTop(display) {return display.lineSpace.offsetTop;}
2487
- function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2488
- function paddingH(display) {
2489
- if (display.cachedPaddingH) return display.cachedPaddingH;
2490
- var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2491
- var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2492
- var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2493
- if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2494
- return data;
2495
- }
2496
-
2497
- function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2498
- function displayWidth(cm) {
2499
- return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2500
- }
2501
- function displayHeight(cm) {
2502
- return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2503
- }
2504
-
2505
- // Ensure the lineView.wrapping.heights array is populated. This is
2506
- // an array of bottom offsets for the lines that make up a drawn
2507
- // line. When lineWrapping is on, there might be more than one
2508
- // height.
2509
- function ensureLineHeights(cm, lineView, rect) {
2510
- var wrapping = cm.options.lineWrapping;
2511
- var curWidth = wrapping && displayWidth(cm);
2512
- if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2513
- var heights = lineView.measure.heights = [];
2514
- if (wrapping) {
2515
- lineView.measure.width = curWidth;
2516
- var rects = lineView.text.firstChild.getClientRects();
2517
- for (var i = 0; i < rects.length - 1; i++) {
2518
- var cur = rects[i], next = rects[i + 1];
2519
- if (Math.abs(cur.bottom - next.bottom) > 2)
2520
- heights.push((cur.bottom + next.top) / 2 - rect.top);
2521
- }
2522
- }
2523
- heights.push(rect.bottom - rect.top);
2524
- }
2525
- }
2526
-
2527
- // Find a line map (mapping character offsets to text nodes) and a
2528
- // measurement cache for the given line number. (A line view might
2529
- // contain multiple lines when collapsed ranges are present.)
2530
- function mapFromLineView(lineView, line, lineN) {
2531
- if (lineView.line == line)
2532
- return {map: lineView.measure.map, cache: lineView.measure.cache};
2533
- for (var i = 0; i < lineView.rest.length; i++)
2534
- if (lineView.rest[i] == line)
2535
- return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2536
- for (var i = 0; i < lineView.rest.length; i++)
2537
- if (lineNo(lineView.rest[i]) > lineN)
2538
- return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2539
- }
2540
-
2541
- // Render a line into the hidden node display.externalMeasured. Used
2542
- // when measurement is needed for a line that's not in the viewport.
2543
- function updateExternalMeasurement(cm, line) {
2544
- line = visualLine(line);
2545
- var lineN = lineNo(line);
2546
- var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2547
- view.lineN = lineN;
2548
- var built = view.built = buildLineContent(cm, view);
2549
- view.text = built.pre;
2550
- removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2551
- return view;
2552
- }
2553
-
2554
- // Get a {top, bottom, left, right} box (in line-local coordinates)
2555
- // for a given character.
2556
- function measureChar(cm, line, ch, bias) {
2557
- return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2558
- }
2559
-
2560
- // Find a line view that corresponds to the given line number.
2561
- function findViewForLine(cm, lineN) {
2562
- if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2563
- return cm.display.view[findViewIndex(cm, lineN)];
2564
- var ext = cm.display.externalMeasured;
2565
- if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2566
- return ext;
2567
- }
2568
-
2569
- // Measurement can be split in two steps, the set-up work that
2570
- // applies to the whole line, and the measurement of the actual
2571
- // character. Functions like coordsChar, that need to do a lot of
2572
- // measurements in a row, can thus ensure that the set-up work is
2573
- // only done once.
2574
- function prepareMeasureForLine(cm, line) {
2575
- var lineN = lineNo(line);
2576
- var view = findViewForLine(cm, lineN);
2577
- if (view && !view.text) {
2578
- view = null;
2579
- } else if (view && view.changes) {
2580
- updateLineForChanges(cm, view, lineN, getDimensions(cm));
2581
- cm.curOp.forceUpdate = true;
2582
- }
2583
- if (!view)
2584
- view = updateExternalMeasurement(cm, line);
2585
-
2586
- var info = mapFromLineView(view, line, lineN);
2587
- return {
2588
- line: line, view: view, rect: null,
2589
- map: info.map, cache: info.cache, before: info.before,
2590
- hasHeights: false
2591
- };
2592
- }
2593
-
2594
- // Given a prepared measurement object, measures the position of an
2595
- // actual character (or fetches it from the cache).
2596
- function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2597
- if (prepared.before) ch = -1;
2598
- var key = ch + (bias || ""), found;
2599
- if (prepared.cache.hasOwnProperty(key)) {
2600
- found = prepared.cache[key];
2601
- } else {
2602
- if (!prepared.rect)
2603
- prepared.rect = prepared.view.text.getBoundingClientRect();
2604
- if (!prepared.hasHeights) {
2605
- ensureLineHeights(cm, prepared.view, prepared.rect);
2606
- prepared.hasHeights = true;
2607
- }
2608
- found = measureCharInner(cm, prepared, ch, bias);
2609
- if (!found.bogus) prepared.cache[key] = found;
2610
- }
2611
- return {left: found.left, right: found.right,
2612
- top: varHeight ? found.rtop : found.top,
2613
- bottom: varHeight ? found.rbottom : found.bottom};
2614
- }
2615
-
2616
- var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2617
-
2618
- function nodeAndOffsetInLineMap(map, ch, bias) {
2619
- var node, start, end, collapse;
2620
- // First, search the line map for the text node corresponding to,
2621
- // or closest to, the target character.
2622
- for (var i = 0; i < map.length; i += 3) {
2623
- var mStart = map[i], mEnd = map[i + 1];
2624
- if (ch < mStart) {
2625
- start = 0; end = 1;
2626
- collapse = "left";
2627
- } else if (ch < mEnd) {
2628
- start = ch - mStart;
2629
- end = start + 1;
2630
- } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2631
- end = mEnd - mStart;
2632
- start = end - 1;
2633
- if (ch >= mEnd) collapse = "right";
2634
- }
2635
- if (start != null) {
2636
- node = map[i + 2];
2637
- if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2638
- collapse = bias;
2639
- if (bias == "left" && start == 0)
2640
- while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2641
- node = map[(i -= 3) + 2];
2642
- collapse = "left";
2643
- }
2644
- if (bias == "right" && start == mEnd - mStart)
2645
- while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2646
- node = map[(i += 3) + 2];
2647
- collapse = "right";
2648
- }
2649
- break;
2650
- }
2651
- }
2652
- return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2653
- }
2654
-
2655
- function measureCharInner(cm, prepared, ch, bias) {
2656
- var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2657
- var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2658
-
2659
- var rect;
2660
- if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2661
- for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2662
- while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2663
- while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2664
- if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2665
- rect = node.parentNode.getBoundingClientRect();
2666
- } else if (ie && cm.options.lineWrapping) {
2667
- var rects = range(node, start, end).getClientRects();
2668
- if (rects.length)
2669
- rect = rects[bias == "right" ? rects.length - 1 : 0];
2670
- else
2671
- rect = nullRect;
2672
- } else {
2673
- rect = range(node, start, end).getBoundingClientRect() || nullRect;
2674
- }
2675
- if (rect.left || rect.right || start == 0) break;
2676
- end = start;
2677
- start = start - 1;
2678
- collapse = "right";
2679
- }
2680
- if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2681
- } else { // If it is a widget, simply get the box for the whole widget.
2682
- if (start > 0) collapse = bias = "right";
2683
- var rects;
2684
- if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2685
- rect = rects[bias == "right" ? rects.length - 1 : 0];
2686
- else
2687
- rect = node.getBoundingClientRect();
2688
- }
2689
- if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2690
- var rSpan = node.parentNode.getClientRects()[0];
2691
- if (rSpan)
2692
- rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2693
- else
2694
- rect = nullRect;
2695
- }
2696
-
2697
- var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2698
- var mid = (rtop + rbot) / 2;
2699
- var heights = prepared.view.measure.heights;
2700
- for (var i = 0; i < heights.length - 1; i++)
2701
- if (mid < heights[i]) break;
2702
- var top = i ? heights[i - 1] : 0, bot = heights[i];
2703
- var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2704
- right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2705
- top: top, bottom: bot};
2706
- if (!rect.left && !rect.right) result.bogus = true;
2707
- if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2708
-
2709
- return result;
2710
- }
2711
-
2712
- // Work around problem with bounding client rects on ranges being
2713
- // returned incorrectly when zoomed on IE10 and below.
2714
- function maybeUpdateRectForZooming(measure, rect) {
2715
- if (!window.screen || screen.logicalXDPI == null ||
2716
- screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2717
- return rect;
2718
- var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2719
- var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2720
- return {left: rect.left * scaleX, right: rect.right * scaleX,
2721
- top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2722
- }
2723
-
2724
- function clearLineMeasurementCacheFor(lineView) {
2725
- if (lineView.measure) {
2726
- lineView.measure.cache = {};
2727
- lineView.measure.heights = null;
2728
- if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2729
- lineView.measure.caches[i] = {};
2730
- }
2731
- }
2732
-
2733
- function clearLineMeasurementCache(cm) {
2734
- cm.display.externalMeasure = null;
2735
- removeChildren(cm.display.lineMeasure);
2736
- for (var i = 0; i < cm.display.view.length; i++)
2737
- clearLineMeasurementCacheFor(cm.display.view[i]);
2738
- }
2739
-
2740
- function clearCaches(cm) {
2741
- clearLineMeasurementCache(cm);
2742
- cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2743
- if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2744
- cm.display.lineNumChars = null;
2745
- }
2746
-
2747
- function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2748
- function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2749
-
2750
- // Converts a {top, bottom, left, right} box from line-local
2751
- // coordinates into another coordinate system. Context may be one of
2752
- // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2753
- // or "page".
2754
- function intoCoordSystem(cm, lineObj, rect, context) {
2755
- if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2756
- var size = widgetHeight(lineObj.widgets[i]);
2757
- rect.top += size; rect.bottom += size;
2758
- }
2759
- if (context == "line") return rect;
2760
- if (!context) context = "local";
2761
- var yOff = heightAtLine(lineObj);
2762
- if (context == "local") yOff += paddingTop(cm.display);
2763
- else yOff -= cm.display.viewOffset;
2764
- if (context == "page" || context == "window") {
2765
- var lOff = cm.display.lineSpace.getBoundingClientRect();
2766
- yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2767
- var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2768
- rect.left += xOff; rect.right += xOff;
2769
- }
2770
- rect.top += yOff; rect.bottom += yOff;
2771
- return rect;
2772
- }
2773
-
2774
- // Coverts a box from "div" coords to another coordinate system.
2775
- // Context may be "window", "page", "div", or "local"/null.
2776
- function fromCoordSystem(cm, coords, context) {
2777
- if (context == "div") return coords;
2778
- var left = coords.left, top = coords.top;
2779
- // First move into "page" coordinate system
2780
- if (context == "page") {
2781
- left -= pageScrollX();
2782
- top -= pageScrollY();
2783
- } else if (context == "local" || !context) {
2784
- var localBox = cm.display.sizer.getBoundingClientRect();
2785
- left += localBox.left;
2786
- top += localBox.top;
2787
- }
2788
-
2789
- var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2790
- return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2791
- }
2792
-
2793
- function charCoords(cm, pos, context, lineObj, bias) {
2794
- if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2795
- return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2796
- }
2797
-
2798
- // Returns a box for a given cursor position, which may have an
2799
- // 'other' property containing the position of the secondary cursor
2800
- // on a bidi boundary.
2801
- function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2802
- lineObj = lineObj || getLine(cm.doc, pos.line);
2803
- if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2804
- function get(ch, right) {
2805
- var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2806
- if (right) m.left = m.right; else m.right = m.left;
2807
- return intoCoordSystem(cm, lineObj, m, context);
2808
- }
2809
- function getBidi(ch, partPos) {
2810
- var part = order[partPos], right = part.level % 2;
2811
- if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2812
- part = order[--partPos];
2813
- ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2814
- right = true;
2815
- } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2816
- part = order[++partPos];
2817
- ch = bidiLeft(part) - part.level % 2;
2818
- right = false;
2819
- }
2820
- if (right && ch == part.to && ch > part.from) return get(ch - 1);
2821
- return get(ch, right);
2822
- }
2823
- var order = getOrder(lineObj), ch = pos.ch;
2824
- if (!order) return get(ch);
2825
- var partPos = getBidiPartAt(order, ch);
2826
- var val = getBidi(ch, partPos);
2827
- if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2828
- return val;
2829
- }
2830
-
2831
- // Used to cheaply estimate the coordinates for a position. Used for
2832
- // intermediate scroll updates.
2833
- function estimateCoords(cm, pos) {
2834
- var left = 0, pos = clipPos(cm.doc, pos);
2835
- if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2836
- var lineObj = getLine(cm.doc, pos.line);
2837
- var top = heightAtLine(lineObj) + paddingTop(cm.display);
2838
- return {left: left, right: left, top: top, bottom: top + lineObj.height};
2839
- }
2840
-
2841
- // Positions returned by coordsChar contain some extra information.
2842
- // xRel is the relative x position of the input coordinates compared
2843
- // to the found position (so xRel > 0 means the coordinates are to
2844
- // the right of the character position, for example). When outside
2845
- // is true, that means the coordinates lie outside the line's
2846
- // vertical range.
2847
- function PosWithInfo(line, ch, outside, xRel) {
2848
- var pos = Pos(line, ch);
2849
- pos.xRel = xRel;
2850
- if (outside) pos.outside = true;
2851
- return pos;
2852
- }
2853
-
2854
- // Compute the character position closest to the given coordinates.
2855
- // Input must be lineSpace-local ("div" coordinate system).
2856
- function coordsChar(cm, x, y) {
2857
- var doc = cm.doc;
2858
- y += cm.display.viewOffset;
2859
- if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2860
- var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2861
- if (lineN > last)
2862
- return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2863
- if (x < 0) x = 0;
2864
-
2865
- var lineObj = getLine(doc, lineN);
2866
- for (;;) {
2867
- var found = coordsCharInner(cm, lineObj, lineN, x, y);
2868
- var merged = collapsedSpanAtEnd(lineObj);
2869
- var mergedPos = merged && merged.find(0, true);
2870
- if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2871
- lineN = lineNo(lineObj = mergedPos.to.line);
2872
- else
2873
- return found;
2874
- }
2875
- }
2876
-
2877
- function coordsCharInner(cm, lineObj, lineNo, x, y) {
2878
- var innerOff = y - heightAtLine(lineObj);
2879
- var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2880
- var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2881
-
2882
- function getX(ch) {
2883
- var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2884
- wrongLine = true;
2885
- if (innerOff > sp.bottom) return sp.left - adjust;
2886
- else if (innerOff < sp.top) return sp.left + adjust;
2887
- else wrongLine = false;
2888
- return sp.left;
2889
- }
2890
-
2891
- var bidi = getOrder(lineObj), dist = lineObj.text.length;
2892
- var from = lineLeft(lineObj), to = lineRight(lineObj);
2893
- var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2894
-
2895
- if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2896
- // Do a binary search between these bounds.
2897
- for (;;) {
2898
- if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2899
- var ch = x < fromX || x - fromX <= toX - x ? from : to;
2900
- var xDiff = x - (ch == from ? fromX : toX);
2901
- while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2902
- var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2903
- xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2904
- return pos;
2905
- }
2906
- var step = Math.ceil(dist / 2), middle = from + step;
2907
- if (bidi) {
2908
- middle = from;
2909
- for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2910
- }
2911
- var middleX = getX(middle);
2912
- if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2913
- else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2914
- }
2915
- }
2916
-
2917
- var measureText;
2918
- // Compute the default text height.
2919
- function textHeight(display) {
2920
- if (display.cachedTextHeight != null) return display.cachedTextHeight;
2921
- if (measureText == null) {
2922
- measureText = elt("pre");
2923
- // Measure a bunch of lines, for browsers that compute
2924
- // fractional heights.
2925
- for (var i = 0; i < 49; ++i) {
2926
- measureText.appendChild(document.createTextNode("x"));
2927
- measureText.appendChild(elt("br"));
2928
- }
2929
- measureText.appendChild(document.createTextNode("x"));
2930
- }
2931
- removeChildrenAndAdd(display.measure, measureText);
2932
- var height = measureText.offsetHeight / 50;
2933
- if (height > 3) display.cachedTextHeight = height;
2934
- removeChildren(display.measure);
2935
- return height || 1;
2936
- }
2937
-
2938
- // Compute the default character width.
2939
- function charWidth(display) {
2940
- if (display.cachedCharWidth != null) return display.cachedCharWidth;
2941
- var anchor = elt("span", "xxxxxxxxxx");
2942
- var pre = elt("pre", [anchor]);
2943
- removeChildrenAndAdd(display.measure, pre);
2944
- var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2945
- if (width > 2) display.cachedCharWidth = width;
2946
- return width || 10;
2947
- }
2948
-
2949
- // OPERATIONS
2950
-
2951
- // Operations are used to wrap a series of changes to the editor
2952
- // state in such a way that each change won't have to update the
2953
- // cursor and display (which would be awkward, slow, and
2954
- // error-prone). Instead, display updates are batched and then all
2955
- // combined and executed at once.
2956
-
2957
- var operationGroup = null;
2958
-
2959
- var nextOpId = 0;
2960
- // Start a new operation.
2961
- function startOperation(cm) {
2962
- cm.curOp = {
2963
- cm: cm,
2964
- viewChanged: false, // Flag that indicates that lines might need to be redrawn
2965
- startHeight: cm.doc.height, // Used to detect need to update scrollbar
2966
- forceUpdate: false, // Used to force a redraw
2967
- updateInput: null, // Whether to reset the input textarea
2968
- typing: false, // Whether this reset should be careful to leave existing text (for compositing)
2969
- changeObjs: null, // Accumulated changes, for firing change events
2970
- cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2971
- cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2972
- selectionChanged: false, // Whether the selection needs to be redrawn
2973
- updateMaxLine: false, // Set when the widest line needs to be determined anew
2974
- scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2975
- scrollToPos: null, // Used to scroll to a specific position
2976
- focus: false,
2977
- id: ++nextOpId // Unique ID
2978
- };
2979
- if (operationGroup) {
2980
- operationGroup.ops.push(cm.curOp);
2981
- } else {
2982
- cm.curOp.ownsGroup = operationGroup = {
2983
- ops: [cm.curOp],
2984
- delayedCallbacks: []
2985
- };
2986
- }
2987
- }
2988
-
2989
- function fireCallbacksForOps(group) {
2990
- // Calls delayed callbacks and cursorActivity handlers until no
2991
- // new ones appear
2992
- var callbacks = group.delayedCallbacks, i = 0;
2993
- do {
2994
- for (; i < callbacks.length; i++)
2995
- callbacks[i].call(null);
2996
- for (var j = 0; j < group.ops.length; j++) {
2997
- var op = group.ops[j];
2998
- if (op.cursorActivityHandlers)
2999
- while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3000
- op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3001
- }
3002
- } while (i < callbacks.length);
3003
- }
3004
-
3005
- // Finish an operation, updating the display and signalling delayed events
3006
- function endOperation(cm) {
3007
- var op = cm.curOp, group = op.ownsGroup;
3008
- if (!group) return;
3009
-
3010
- try { fireCallbacksForOps(group); }
3011
- finally {
3012
- operationGroup = null;
3013
- for (var i = 0; i < group.ops.length; i++)
3014
- group.ops[i].cm.curOp = null;
3015
- endOperations(group);
3016
- }
3017
- }
3018
-
3019
- // The DOM updates done when an operation finishes are batched so
3020
- // that the minimum number of relayouts are required.
3021
- function endOperations(group) {
3022
- var ops = group.ops;
3023
- for (var i = 0; i < ops.length; i++) // Read DOM
3024
- endOperation_R1(ops[i]);
3025
- for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3026
- endOperation_W1(ops[i]);
3027
- for (var i = 0; i < ops.length; i++) // Read DOM
3028
- endOperation_R2(ops[i]);
3029
- for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3030
- endOperation_W2(ops[i]);
3031
- for (var i = 0; i < ops.length; i++) // Read DOM
3032
- endOperation_finish(ops[i]);
3033
- }
3034
-
3035
- function endOperation_R1(op) {
3036
- var cm = op.cm, display = cm.display;
3037
- maybeClipScrollbars(cm);
3038
- if (op.updateMaxLine) findMaxLine(cm);
3039
-
3040
- op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3041
- op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3042
- op.scrollToPos.to.line >= display.viewTo) ||
3043
- display.maxLineChanged && cm.options.lineWrapping;
3044
- op.update = op.mustUpdate &&
3045
- new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3046
- }
3047
-
3048
- function endOperation_W1(op) {
3049
- op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3050
- }
3051
-
3052
- function endOperation_R2(op) {
3053
- var cm = op.cm, display = cm.display;
3054
- if (op.updatedDisplay) updateHeightsInViewport(cm);
3055
-
3056
- op.barMeasure = measureForScrollbars(cm);
3057
-
3058
- // If the max line changed since it was last measured, measure it,
3059
- // and ensure the document's width matches it.
3060
- // updateDisplay_W2 will use these properties to do the actual resizing
3061
- if (display.maxLineChanged && !cm.options.lineWrapping) {
3062
- op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3063
- cm.display.sizerWidth = op.adjustWidthTo;
3064
- op.barMeasure.scrollWidth =
3065
- Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3066
- op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3067
- }
3068
-
3069
- if (op.updatedDisplay || op.selectionChanged)
3070
- op.preparedSelection = display.input.prepareSelection();
3071
- }
3072
-
3073
- function endOperation_W2(op) {
3074
- var cm = op.cm;
3075
-
3076
- if (op.adjustWidthTo != null) {
3077
- cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3078
- if (op.maxScrollLeft < cm.doc.scrollLeft)
3079
- setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3080
- cm.display.maxLineChanged = false;
3081
- }
3082
-
3083
- if (op.preparedSelection)
3084
- cm.display.input.showSelection(op.preparedSelection);
3085
- if (op.updatedDisplay)
3086
- setDocumentHeight(cm, op.barMeasure);
3087
- if (op.updatedDisplay || op.startHeight != cm.doc.height)
3088
- updateScrollbars(cm, op.barMeasure);
3089
-
3090
- if (op.selectionChanged) restartBlink(cm);
3091
-
3092
- if (cm.state.focused && op.updateInput)
3093
- cm.display.input.reset(op.typing);
3094
- if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
3095
- }
3096
-
3097
- function endOperation_finish(op) {
3098
- var cm = op.cm, display = cm.display, doc = cm.doc;
3099
-
3100
- if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3101
-
3102
- // Abort mouse wheel delta measurement, when scrolling explicitly
3103
- if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3104
- display.wheelStartX = display.wheelStartY = null;
3105
-
3106
- // Propagate the scroll position to the actual DOM scroller
3107
- if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3108
- doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3109
- display.scrollbars.setScrollTop(doc.scrollTop);
3110
- display.scroller.scrollTop = doc.scrollTop;
3111
- }
3112
- if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3113
- doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3114
- display.scrollbars.setScrollLeft(doc.scrollLeft);
3115
- display.scroller.scrollLeft = doc.scrollLeft;
3116
- alignHorizontally(cm);
3117
- }
3118
- // If we need to scroll a specific position into view, do so.
3119
- if (op.scrollToPos) {
3120
- var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3121
- clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3122
- if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3123
- }
3124
-
3125
- // Fire events for markers that are hidden/unidden by editing or
3126
- // undoing
3127
- var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3128
- if (hidden) for (var i = 0; i < hidden.length; ++i)
3129
- if (!hidden[i].lines.length) signal(hidden[i], "hide");
3130
- if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3131
- if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3132
-
3133
- if (display.wrapper.offsetHeight)
3134
- doc.scrollTop = cm.display.scroller.scrollTop;
3135
-
3136
- // Fire change events, and delayed event handlers
3137
- if (op.changeObjs)
3138
- signal(cm, "changes", cm, op.changeObjs);
3139
- if (op.update)
3140
- op.update.finish();
3141
- }
3142
-
3143
- // Run the given function in an operation
3144
- function runInOp(cm, f) {
3145
- if (cm.curOp) return f();
3146
- startOperation(cm);
3147
- try { return f(); }
3148
- finally { endOperation(cm); }
3149
- }
3150
- // Wraps a function in an operation. Returns the wrapped function.
3151
- function operation(cm, f) {
3152
- return function() {
3153
- if (cm.curOp) return f.apply(cm, arguments);
3154
- startOperation(cm);
3155
- try { return f.apply(cm, arguments); }
3156
- finally { endOperation(cm); }
3157
- };
3158
- }
3159
- // Used to add methods to editor and doc instances, wrapping them in
3160
- // operations.
3161
- function methodOp(f) {
3162
- return function() {
3163
- if (this.curOp) return f.apply(this, arguments);
3164
- startOperation(this);
3165
- try { return f.apply(this, arguments); }
3166
- finally { endOperation(this); }
3167
- };
3168
- }
3169
- function docMethodOp(f) {
3170
- return function() {
3171
- var cm = this.cm;
3172
- if (!cm || cm.curOp) return f.apply(this, arguments);
3173
- startOperation(cm);
3174
- try { return f.apply(this, arguments); }
3175
- finally { endOperation(cm); }
3176
- };
3177
- }
3178
-
3179
- // VIEW TRACKING
3180
-
3181
- // These objects are used to represent the visible (currently drawn)
3182
- // part of the document. A LineView may correspond to multiple
3183
- // logical lines, if those are connected by collapsed ranges.
3184
- function LineView(doc, line, lineN) {
3185
- // The starting line
3186
- this.line = line;
3187
- // Continuing lines, if any
3188
- this.rest = visualLineContinued(line);
3189
- // Number of logical lines in this visual line
3190
- this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3191
- this.node = this.text = null;
3192
- this.hidden = lineIsHidden(doc, line);
3193
- }
3194
-
3195
- // Create a range of LineView objects for the given lines.
3196
- function buildViewArray(cm, from, to) {
3197
- var array = [], nextPos;
3198
- for (var pos = from; pos < to; pos = nextPos) {
3199
- var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3200
- nextPos = pos + view.size;
3201
- array.push(view);
3202
- }
3203
- return array;
3204
- }
3205
-
3206
- // Updates the display.view data structure for a given change to the
3207
- // document. From and to are in pre-change coordinates. Lendiff is
3208
- // the amount of lines added or subtracted by the change. This is
3209
- // used for changes that span multiple lines, or change the way
3210
- // lines are divided into visual lines. regLineChange (below)
3211
- // registers single-line changes.
3212
- function regChange(cm, from, to, lendiff) {
3213
- if (from == null) from = cm.doc.first;
3214
- if (to == null) to = cm.doc.first + cm.doc.size;
3215
- if (!lendiff) lendiff = 0;
3216
-
3217
- var display = cm.display;
3218
- if (lendiff && to < display.viewTo &&
3219
- (display.updateLineNumbers == null || display.updateLineNumbers > from))
3220
- display.updateLineNumbers = from;
3221
-
3222
- cm.curOp.viewChanged = true;
3223
-
3224
- if (from >= display.viewTo) { // Change after
3225
- if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3226
- resetView(cm);
3227
- } else if (to <= display.viewFrom) { // Change before
3228
- if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3229
- resetView(cm);
3230
- } else {
3231
- display.viewFrom += lendiff;
3232
- display.viewTo += lendiff;
3233
- }
3234
- } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3235
- resetView(cm);
3236
- } else if (from <= display.viewFrom) { // Top overlap
3237
- var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3238
- if (cut) {
3239
- display.view = display.view.slice(cut.index);
3240
- display.viewFrom = cut.lineN;
3241
- display.viewTo += lendiff;
3242
- } else {
3243
- resetView(cm);
3244
- }
3245
- } else if (to >= display.viewTo) { // Bottom overlap
3246
- var cut = viewCuttingPoint(cm, from, from, -1);
3247
- if (cut) {
3248
- display.view = display.view.slice(0, cut.index);
3249
- display.viewTo = cut.lineN;
3250
- } else {
3251
- resetView(cm);
3252
- }
3253
- } else { // Gap in the middle
3254
- var cutTop = viewCuttingPoint(cm, from, from, -1);
3255
- var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3256
- if (cutTop && cutBot) {
3257
- display.view = display.view.slice(0, cutTop.index)
3258
- .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3259
- .concat(display.view.slice(cutBot.index));
3260
- display.viewTo += lendiff;
3261
- } else {
3262
- resetView(cm);
3263
- }
3264
- }
3265
-
3266
- var ext = display.externalMeasured;
3267
- if (ext) {
3268
- if (to < ext.lineN)
3269
- ext.lineN += lendiff;
3270
- else if (from < ext.lineN + ext.size)
3271
- display.externalMeasured = null;
3272
- }
3273
- }
3274
-
3275
- // Register a change to a single line. Type must be one of "text",
3276
- // "gutter", "class", "widget"
3277
- function regLineChange(cm, line, type) {
3278
- cm.curOp.viewChanged = true;
3279
- var display = cm.display, ext = cm.display.externalMeasured;
3280
- if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3281
- display.externalMeasured = null;
3282
-
3283
- if (line < display.viewFrom || line >= display.viewTo) return;
3284
- var lineView = display.view[findViewIndex(cm, line)];
3285
- if (lineView.node == null) return;
3286
- var arr = lineView.changes || (lineView.changes = []);
3287
- if (indexOf(arr, type) == -1) arr.push(type);
3288
- }
3289
-
3290
- // Clear the view.
3291
- function resetView(cm) {
3292
- cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3293
- cm.display.view = [];
3294
- cm.display.viewOffset = 0;
3295
- }
3296
-
3297
- // Find the view element corresponding to a given line. Return null
3298
- // when the line isn't visible.
3299
- function findViewIndex(cm, n) {
3300
- if (n >= cm.display.viewTo) return null;
3301
- n -= cm.display.viewFrom;
3302
- if (n < 0) return null;
3303
- var view = cm.display.view;
3304
- for (var i = 0; i < view.length; i++) {
3305
- n -= view[i].size;
3306
- if (n < 0) return i;
3307
- }
3308
- }
3309
-
3310
- function viewCuttingPoint(cm, oldN, newN, dir) {
3311
- var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3312
- if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3313
- return {index: index, lineN: newN};
3314
- for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3315
- n += view[i].size;
3316
- if (n != oldN) {
3317
- if (dir > 0) {
3318
- if (index == view.length - 1) return null;
3319
- diff = (n + view[index].size) - oldN;
3320
- index++;
3321
- } else {
3322
- diff = n - oldN;
3323
- }
3324
- oldN += diff; newN += diff;
3325
- }
3326
- while (visualLineNo(cm.doc, newN) != newN) {
3327
- if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3328
- newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3329
- index += dir;
3330
- }
3331
- return {index: index, lineN: newN};
3332
- }
3333
-
3334
- // Force the view to cover a given range, adding empty view element
3335
- // or clipping off existing ones as needed.
3336
- function adjustView(cm, from, to) {
3337
- var display = cm.display, view = display.view;
3338
- if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3339
- display.view = buildViewArray(cm, from, to);
3340
- display.viewFrom = from;
3341
- } else {
3342
- if (display.viewFrom > from)
3343
- display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3344
- else if (display.viewFrom < from)
3345
- display.view = display.view.slice(findViewIndex(cm, from));
3346
- display.viewFrom = from;
3347
- if (display.viewTo < to)
3348
- display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3349
- else if (display.viewTo > to)
3350
- display.view = display.view.slice(0, findViewIndex(cm, to));
3351
- }
3352
- display.viewTo = to;
3353
- }
3354
-
3355
- // Count the number of lines in the view whose DOM representation is
3356
- // out of date (or nonexistent).
3357
- function countDirtyView(cm) {
3358
- var view = cm.display.view, dirty = 0;
3359
- for (var i = 0; i < view.length; i++) {
3360
- var lineView = view[i];
3361
- if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3362
- }
3363
- return dirty;
3364
- }
3365
-
3366
- // EVENT HANDLERS
3367
-
3368
- // Attach the necessary event handlers when initializing the editor
3369
- function registerEventHandlers(cm) {
3370
- var d = cm.display;
3371
- on(d.scroller, "mousedown", operation(cm, onMouseDown));
3372
- // Older IE's will not fire a second mousedown for a double click
3373
- if (ie && ie_version < 11)
3374
- on(d.scroller, "dblclick", operation(cm, function(e) {
3375
- if (signalDOMEvent(cm, e)) return;
3376
- var pos = posFromMouse(cm, e);
3377
- if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3378
- e_preventDefault(e);
3379
- var word = cm.findWordAt(pos);
3380
- extendSelection(cm.doc, word.anchor, word.head);
3381
- }));
3382
- else
3383
- on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3384
- // Some browsers fire contextmenu *after* opening the menu, at
3385
- // which point we can't mess with it anymore. Context menu is
3386
- // handled in onMouseDown for these browsers.
3387
- if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3388
-
3389
- // Used to suppress mouse event handling when a touch happens
3390
- var touchFinished, prevTouch = {end: 0};
3391
- function finishTouch() {
3392
- if (d.activeTouch) {
3393
- touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3394
- prevTouch = d.activeTouch;
3395
- prevTouch.end = +new Date;
3396
- }
3397
- };
3398
- function isMouseLikeTouchEvent(e) {
3399
- if (e.touches.length != 1) return false;
3400
- var touch = e.touches[0];
3401
- return touch.radiusX <= 1 && touch.radiusY <= 1;
3402
- }
3403
- function farAway(touch, other) {
3404
- if (other.left == null) return true;
3405
- var dx = other.left - touch.left, dy = other.top - touch.top;
3406
- return dx * dx + dy * dy > 20 * 20;
3407
- }
3408
- on(d.scroller, "touchstart", function(e) {
3409
- if (!isMouseLikeTouchEvent(e)) {
3410
- clearTimeout(touchFinished);
3411
- var now = +new Date;
3412
- d.activeTouch = {start: now, moved: false,
3413
- prev: now - prevTouch.end <= 300 ? prevTouch : null};
3414
- if (e.touches.length == 1) {
3415
- d.activeTouch.left = e.touches[0].pageX;
3416
- d.activeTouch.top = e.touches[0].pageY;
3417
- }
3418
- }
3419
- });
3420
- on(d.scroller, "touchmove", function() {
3421
- if (d.activeTouch) d.activeTouch.moved = true;
3422
- });
3423
- on(d.scroller, "touchend", function(e) {
3424
- var touch = d.activeTouch;
3425
- if (touch && !eventInWidget(d, e) && touch.left != null &&
3426
- !touch.moved && new Date - touch.start < 300) {
3427
- var pos = cm.coordsChar(d.activeTouch, "page"), range;
3428
- if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3429
- range = new Range(pos, pos);
3430
- else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3431
- range = cm.findWordAt(pos);
3432
- else // Triple tap
3433
- range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3434
- cm.setSelection(range.anchor, range.head);
3435
- cm.focus();
3436
- e_preventDefault(e);
3437
- }
3438
- finishTouch();
3439
- });
3440
- on(d.scroller, "touchcancel", finishTouch);
3441
-
3442
- // Sync scrolling between fake scrollbars and real scrollable
3443
- // area, ensure viewport is updated when scrolling.
3444
- on(d.scroller, "scroll", function() {
3445
- if (d.scroller.clientHeight) {
3446
- setScrollTop(cm, d.scroller.scrollTop);
3447
- setScrollLeft(cm, d.scroller.scrollLeft, true);
3448
- signal(cm, "scroll", cm);
3449
- }
3450
- });
3451
-
3452
- // Listen to wheel events in order to try and update the viewport on time.
3453
- on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3454
- on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3455
-
3456
- // Prevent wrapper from ever scrolling
3457
- on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3458
-
3459
- d.dragFunctions = {
3460
- enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3461
- over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3462
- start: function(e){onDragStart(cm, e);},
3463
- drop: operation(cm, onDrop),
3464
- leave: function() {clearDragCursor(cm);}
3465
- };
3466
-
3467
- var inp = d.input.getField();
3468
- on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3469
- on(inp, "keydown", operation(cm, onKeyDown));
3470
- on(inp, "keypress", operation(cm, onKeyPress));
3471
- on(inp, "focus", bind(onFocus, cm));
3472
- on(inp, "blur", bind(onBlur, cm));
3473
- }
3474
-
3475
- function dragDropChanged(cm, value, old) {
3476
- var wasOn = old && old != CodeMirror.Init;
3477
- if (!value != !wasOn) {
3478
- var funcs = cm.display.dragFunctions;
3479
- var toggle = value ? on : off;
3480
- toggle(cm.display.scroller, "dragstart", funcs.start);
3481
- toggle(cm.display.scroller, "dragenter", funcs.enter);
3482
- toggle(cm.display.scroller, "dragover", funcs.over);
3483
- toggle(cm.display.scroller, "dragleave", funcs.leave);
3484
- toggle(cm.display.scroller, "drop", funcs.drop);
3485
- }
3486
- }
3487
-
3488
- // Called when the window resizes
3489
- function onResize(cm) {
3490
- var d = cm.display;
3491
- if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3492
- return;
3493
- // Might be a text scaling operation, clear size caches.
3494
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3495
- d.scrollbarsClipped = false;
3496
- cm.setSize();
3497
- }
3498
-
3499
- // MOUSE EVENTS
3500
-
3501
- // Return true when the given mouse event happened in a widget
3502
- function eventInWidget(display, e) {
3503
- for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3504
- if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3505
- (n.parentNode == display.sizer && n != display.mover))
3506
- return true;
3507
- }
3508
- }
3509
-
3510
- // Given a mouse event, find the corresponding position. If liberal
3511
- // is false, it checks whether a gutter or scrollbar was clicked,
3512
- // and returns null if it was. forRect is used by rectangular
3513
- // selections, and tries to estimate a character position even for
3514
- // coordinates beyond the right of the text.
3515
- function posFromMouse(cm, e, liberal, forRect) {
3516
- var display = cm.display;
3517
- if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3518
-
3519
- var x, y, space = display.lineSpace.getBoundingClientRect();
3520
- // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3521
- try { x = e.clientX - space.left; y = e.clientY - space.top; }
3522
- catch (e) { return null; }
3523
- var coords = coordsChar(cm, x, y), line;
3524
- if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3525
- var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3526
- coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3527
- }
3528
- return coords;
3529
- }
3530
-
3531
- // A mouse down can be a single click, double click, triple click,
3532
- // start of selection drag, start of text drag, new cursor
3533
- // (ctrl-click), rectangle drag (alt-drag), or xwin
3534
- // middle-click-paste. Or it might be a click on something we should
3535
- // not interfere with, such as a scrollbar or widget.
3536
- function onMouseDown(e) {
3537
- var cm = this, display = cm.display;
3538
- if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3539
- display.shift = e.shiftKey;
3540
-
3541
- if (eventInWidget(display, e)) {
3542
- if (!webkit) {
3543
- // Briefly turn off draggability, to allow widgets to do
3544
- // normal dragging things.
3545
- display.scroller.draggable = false;
3546
- setTimeout(function(){display.scroller.draggable = true;}, 100);
3547
- }
3548
- return;
3549
- }
3550
- if (clickInGutter(cm, e)) return;
3551
- var start = posFromMouse(cm, e);
3552
- window.focus();
3553
-
3554
- switch (e_button(e)) {
3555
- case 1:
3556
- // #3261: make sure, that we're not starting a second selection
3557
- if (cm.state.selectingText)
3558
- cm.state.selectingText(e);
3559
- else if (start)
3560
- leftButtonDown(cm, e, start);
3561
- else if (e_target(e) == display.scroller)
3562
- e_preventDefault(e);
3563
- break;
3564
- case 2:
3565
- if (webkit) cm.state.lastMiddleDown = +new Date;
3566
- if (start) extendSelection(cm.doc, start);
3567
- setTimeout(function() {display.input.focus();}, 20);
3568
- e_preventDefault(e);
3569
- break;
3570
- case 3:
3571
- if (captureRightClick) onContextMenu(cm, e);
3572
- else delayBlurEvent(cm);
3573
- break;
3574
- }
3575
- }
3576
-
3577
- var lastClick, lastDoubleClick;
3578
- function leftButtonDown(cm, e, start) {
3579
- if (ie) setTimeout(bind(ensureFocus, cm), 0);
3580
- else cm.curOp.focus = activeElt();
3581
-
3582
- var now = +new Date, type;
3583
- if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3584
- type = "triple";
3585
- } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3586
- type = "double";
3587
- lastDoubleClick = {time: now, pos: start};
3588
- } else {
3589
- type = "single";
3590
- lastClick = {time: now, pos: start};
3591
- }
3592
-
3593
- var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3594
- if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
3595
- type == "single" && (contained = sel.contains(start)) > -1 &&
3596
- (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3597
- (cmp(contained.to(), start) > 0 || start.xRel < 0))
3598
- leftButtonStartDrag(cm, e, start, modifier);
3599
- else
3600
- leftButtonSelect(cm, e, start, type, modifier);
3601
- }
3602
-
3603
- // Start a text drag. When it ends, see if any dragging actually
3604
- // happen, and treat as a click if it didn't.
3605
- function leftButtonStartDrag(cm, e, start, modifier) {
3606
- var display = cm.display, startTime = +new Date;
3607
- var dragEnd = operation(cm, function(e2) {
3608
- if (webkit) display.scroller.draggable = false;
3609
- cm.state.draggingText = false;
3610
- off(document, "mouseup", dragEnd);
3611
- off(display.scroller, "drop", dragEnd);
3612
- if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3613
- e_preventDefault(e2);
3614
- if (!modifier && +new Date - 200 < startTime)
3615
- extendSelection(cm.doc, start);
3616
- // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3617
- if (webkit || ie && ie_version == 9)
3618
- setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3619
- else
3620
- display.input.focus();
3621
- }
3622
- });
3623
- // Let the drag handler handle this.
3624
- if (webkit) display.scroller.draggable = true;
3625
- cm.state.draggingText = dragEnd;
3626
- // IE's approach to draggable
3627
- if (display.scroller.dragDrop) display.scroller.dragDrop();
3628
- on(document, "mouseup", dragEnd);
3629
- on(display.scroller, "drop", dragEnd);
3630
- }
3631
-
3632
- // Normal selection, as opposed to text dragging.
3633
- function leftButtonSelect(cm, e, start, type, addNew) {
3634
- var display = cm.display, doc = cm.doc;
3635
- e_preventDefault(e);
3636
-
3637
- var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3638
- if (addNew && !e.shiftKey) {
3639
- ourIndex = doc.sel.contains(start);
3640
- if (ourIndex > -1)
3641
- ourRange = ranges[ourIndex];
3642
- else
3643
- ourRange = new Range(start, start);
3644
- } else {
3645
- ourRange = doc.sel.primary();
3646
- ourIndex = doc.sel.primIndex;
3647
- }
3648
-
3649
- if (e.altKey) {
3650
- type = "rect";
3651
- if (!addNew) ourRange = new Range(start, start);
3652
- start = posFromMouse(cm, e, true, true);
3653
- ourIndex = -1;
3654
- } else if (type == "double") {
3655
- var word = cm.findWordAt(start);
3656
- if (cm.display.shift || doc.extend)
3657
- ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3658
- else
3659
- ourRange = word;
3660
- } else if (type == "triple") {
3661
- var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3662
- if (cm.display.shift || doc.extend)
3663
- ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3664
- else
3665
- ourRange = line;
3666
- } else {
3667
- ourRange = extendRange(doc, ourRange, start);
3668
- }
3669
-
3670
- if (!addNew) {
3671
- ourIndex = 0;
3672
- setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3673
- startSel = doc.sel;
3674
- } else if (ourIndex == -1) {
3675
- ourIndex = ranges.length;
3676
- setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3677
- {scroll: false, origin: "*mouse"});
3678
- } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3679
- setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3680
- {scroll: false, origin: "*mouse"});
3681
- startSel = doc.sel;
3682
- } else {
3683
- replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3684
- }
3685
-
3686
- var lastPos = start;
3687
- function extendTo(pos) {
3688
- if (cmp(lastPos, pos) == 0) return;
3689
- lastPos = pos;
3690
-
3691
- if (type == "rect") {
3692
- var ranges = [], tabSize = cm.options.tabSize;
3693
- var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3694
- var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3695
- var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3696
- for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3697
- line <= end; line++) {
3698
- var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3699
- if (left == right)
3700
- ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3701
- else if (text.length > leftPos)
3702
- ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3703
- }
3704
- if (!ranges.length) ranges.push(new Range(start, start));
3705
- setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3706
- {origin: "*mouse", scroll: false});
3707
- cm.scrollIntoView(pos);
3708
- } else {
3709
- var oldRange = ourRange;
3710
- var anchor = oldRange.anchor, head = pos;
3711
- if (type != "single") {
3712
- if (type == "double")
3713
- var range = cm.findWordAt(pos);
3714
- else
3715
- var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3716
- if (cmp(range.anchor, anchor) > 0) {
3717
- head = range.head;
3718
- anchor = minPos(oldRange.from(), range.anchor);
3719
- } else {
3720
- head = range.anchor;
3721
- anchor = maxPos(oldRange.to(), range.head);
3722
- }
3723
- }
3724
- var ranges = startSel.ranges.slice(0);
3725
- ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3726
- setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3727
- }
3728
- }
3729
-
3730
- var editorSize = display.wrapper.getBoundingClientRect();
3731
- // Used to ensure timeout re-tries don't fire when another extend
3732
- // happened in the meantime (clearTimeout isn't reliable -- at
3733
- // least on Chrome, the timeouts still happen even when cleared,
3734
- // if the clear happens after their scheduled firing time).
3735
- var counter = 0;
3736
-
3737
- function extend(e) {
3738
- var curCount = ++counter;
3739
- var cur = posFromMouse(cm, e, true, type == "rect");
3740
- if (!cur) return;
3741
- if (cmp(cur, lastPos) != 0) {
3742
- cm.curOp.focus = activeElt();
3743
- extendTo(cur);
3744
- var visible = visibleLines(display, doc);
3745
- if (cur.line >= visible.to || cur.line < visible.from)
3746
- setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3747
- } else {
3748
- var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3749
- if (outside) setTimeout(operation(cm, function() {
3750
- if (counter != curCount) return;
3751
- display.scroller.scrollTop += outside;
3752
- extend(e);
3753
- }), 50);
3754
- }
3755
- }
3756
-
3757
- function done(e) {
3758
- cm.state.selectingText = false;
3759
- counter = Infinity;
3760
- e_preventDefault(e);
3761
- display.input.focus();
3762
- off(document, "mousemove", move);
3763
- off(document, "mouseup", up);
3764
- doc.history.lastSelOrigin = null;
3765
- }
3766
-
3767
- var move = operation(cm, function(e) {
3768
- if (!e_button(e)) done(e);
3769
- else extend(e);
3770
- });
3771
- var up = operation(cm, done);
3772
- cm.state.selectingText = up;
3773
- on(document, "mousemove", move);
3774
- on(document, "mouseup", up);
3775
- }
3776
-
3777
- // Determines whether an event happened in the gutter, and fires the
3778
- // handlers for the corresponding event.
3779
- function gutterEvent(cm, e, type, prevent, signalfn) {
3780
- try { var mX = e.clientX, mY = e.clientY; }
3781
- catch(e) { return false; }
3782
- if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3783
- if (prevent) e_preventDefault(e);
3784
-
3785
- var display = cm.display;
3786
- var lineBox = display.lineDiv.getBoundingClientRect();
3787
-
3788
- if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3789
- mY -= lineBox.top - display.viewOffset;
3790
-
3791
- for (var i = 0; i < cm.options.gutters.length; ++i) {
3792
- var g = display.gutters.childNodes[i];
3793
- if (g && g.getBoundingClientRect().right >= mX) {
3794
- var line = lineAtHeight(cm.doc, mY);
3795
- var gutter = cm.options.gutters[i];
3796
- signalfn(cm, type, cm, line, gutter, e);
3797
- return e_defaultPrevented(e);
3798
- }
3799
- }
3800
- }
3801
-
3802
- function clickInGutter(cm, e) {
3803
- return gutterEvent(cm, e, "gutterClick", true, signalLater);
3804
- }
3805
-
3806
- // Kludge to work around strange IE behavior where it'll sometimes
3807
- // re-fire a series of drag-related events right after the drop (#1551)
3808
- var lastDrop = 0;
3809
-
3810
- function onDrop(e) {
3811
- var cm = this;
3812
- clearDragCursor(cm);
3813
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3814
- return;
3815
- e_preventDefault(e);
3816
- if (ie) lastDrop = +new Date;
3817
- var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3818
- if (!pos || isReadOnly(cm)) return;
3819
- // Might be a file drop, in which case we simply extract the text
3820
- // and insert it.
3821
- if (files && files.length && window.FileReader && window.File) {
3822
- var n = files.length, text = Array(n), read = 0;
3823
- var loadFile = function(file, i) {
3824
- var reader = new FileReader;
3825
- reader.onload = operation(cm, function() {
3826
- text[i] = reader.result;
3827
- if (++read == n) {
3828
- pos = clipPos(cm.doc, pos);
3829
- var change = {from: pos, to: pos,
3830
- text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3831
- origin: "paste"};
3832
- makeChange(cm.doc, change);
3833
- setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3834
- }
3835
- });
3836
- reader.readAsText(file);
3837
- };
3838
- for (var i = 0; i < n; ++i) loadFile(files[i], i);
3839
- } else { // Normal drop
3840
- // Don't do a replace if the drop happened inside of the selected text.
3841
- if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3842
- cm.state.draggingText(e);
3843
- // Ensure the editor is re-focused
3844
- setTimeout(function() {cm.display.input.focus();}, 20);
3845
- return;
3846
- }
3847
- try {
3848
- var text = e.dataTransfer.getData("Text");
3849
- if (text) {
3850
- if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3851
- var selected = cm.listSelections();
3852
- setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3853
- if (selected) for (var i = 0; i < selected.length; ++i)
3854
- replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3855
- cm.replaceSelection(text, "around", "paste");
3856
- cm.display.input.focus();
3857
- }
3858
- }
3859
- catch(e){}
3860
- }
3861
- }
3862
-
3863
- function onDragStart(cm, e) {
3864
- if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3865
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3866
-
3867
- e.dataTransfer.setData("Text", cm.getSelection());
3868
-
3869
- // Use dummy image instead of default browsers image.
3870
- // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3871
- if (e.dataTransfer.setDragImage && !safari) {
3872
- var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3873
- img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3874
- if (presto) {
3875
- img.width = img.height = 1;
3876
- cm.display.wrapper.appendChild(img);
3877
- // Force a relayout, or Opera won't use our image for some obscure reason
3878
- img._top = img.offsetTop;
3879
- }
3880
- e.dataTransfer.setDragImage(img, 0, 0);
3881
- if (presto) img.parentNode.removeChild(img);
3882
- }
3883
- }
3884
-
3885
- function onDragOver(cm, e) {
3886
- var pos = posFromMouse(cm, e);
3887
- if (!pos) return;
3888
- var frag = document.createDocumentFragment();
3889
- drawSelectionCursor(cm, pos, frag);
3890
- if (!cm.display.dragCursor) {
3891
- cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3892
- cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3893
- }
3894
- removeChildrenAndAdd(cm.display.dragCursor, frag);
3895
- }
3896
-
3897
- function clearDragCursor(cm) {
3898
- if (cm.display.dragCursor) {
3899
- cm.display.lineSpace.removeChild(cm.display.dragCursor);
3900
- cm.display.dragCursor = null;
3901
- }
3902
- }
3903
-
3904
- // SCROLL EVENTS
3905
-
3906
- // Sync the scrollable area and scrollbars, ensure the viewport
3907
- // covers the visible area.
3908
- function setScrollTop(cm, val) {
3909
- if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3910
- cm.doc.scrollTop = val;
3911
- if (!gecko) updateDisplaySimple(cm, {top: val});
3912
- if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3913
- cm.display.scrollbars.setScrollTop(val);
3914
- if (gecko) updateDisplaySimple(cm);
3915
- startWorker(cm, 100);
3916
- }
3917
- // Sync scroller and scrollbar, ensure the gutter elements are
3918
- // aligned.
3919
- function setScrollLeft(cm, val, isScroller) {
3920
- if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3921
- val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3922
- cm.doc.scrollLeft = val;
3923
- alignHorizontally(cm);
3924
- if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3925
- cm.display.scrollbars.setScrollLeft(val);
3926
- }
3927
-
3928
- // Since the delta values reported on mouse wheel events are
3929
- // unstandardized between browsers and even browser versions, and
3930
- // generally horribly unpredictable, this code starts by measuring
3931
- // the scroll effect that the first few mouse wheel events have,
3932
- // and, from that, detects the way it can convert deltas to pixel
3933
- // offsets afterwards.
3934
- //
3935
- // The reason we want to know the amount a wheel event will scroll
3936
- // is that it gives us a chance to update the display before the
3937
- // actual scrolling happens, reducing flickering.
3938
-
3939
- var wheelSamples = 0, wheelPixelsPerUnit = null;
3940
- // Fill in a browser-detected starting value on browsers where we
3941
- // know one. These don't have to be accurate -- the result of them
3942
- // being wrong would just be a slight flicker on the first wheel
3943
- // scroll (if it is large enough).
3944
- if (ie) wheelPixelsPerUnit = -.53;
3945
- else if (gecko) wheelPixelsPerUnit = 15;
3946
- else if (chrome) wheelPixelsPerUnit = -.7;
3947
- else if (safari) wheelPixelsPerUnit = -1/3;
3948
-
3949
- var wheelEventDelta = function(e) {
3950
- var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3951
- if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3952
- if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3953
- else if (dy == null) dy = e.wheelDelta;
3954
- return {x: dx, y: dy};
3955
- };
3956
- CodeMirror.wheelEventPixels = function(e) {
3957
- var delta = wheelEventDelta(e);
3958
- delta.x *= wheelPixelsPerUnit;
3959
- delta.y *= wheelPixelsPerUnit;
3960
- return delta;
3961
- };
3962
-
3963
- function onScrollWheel(cm, e) {
3964
- var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3965
-
3966
- var display = cm.display, scroll = display.scroller;
3967
- // Quit if there's nothing to scroll here
3968
- if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
3969
- dy && scroll.scrollHeight > scroll.clientHeight)) return;
3970
-
3971
- // Webkit browsers on OS X abort momentum scrolls when the target
3972
- // of the scroll event is removed from the scrollable element.
3973
- // This hack (see related code in patchDisplay) makes sure the
3974
- // element is kept around.
3975
- if (dy && mac && webkit) {
3976
- outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
3977
- for (var i = 0; i < view.length; i++) {
3978
- if (view[i].node == cur) {
3979
- cm.display.currentWheelTarget = cur;
3980
- break outer;
3981
- }
3982
- }
3983
- }
3984
- }
3985
-
3986
- // On some browsers, horizontal scrolling will cause redraws to
3987
- // happen before the gutter has been realigned, causing it to
3988
- // wriggle around in a most unseemly way. When we have an
3989
- // estimated pixels/delta value, we just handle horizontal
3990
- // scrolling entirely here. It'll be slightly off from native, but
3991
- // better than glitching out.
3992
- if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
3993
- if (dy)
3994
- setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
3995
- setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
3996
- e_preventDefault(e);
3997
- display.wheelStartX = null; // Abort measurement, if in progress
3998
- return;
3999
- }
4000
-
4001
- // 'Project' the visible viewport to cover the area that is being
4002
- // scrolled into view (if we know enough to estimate it).
4003
- if (dy && wheelPixelsPerUnit != null) {
4004
- var pixels = dy * wheelPixelsPerUnit;
4005
- var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4006
- if (pixels < 0) top = Math.max(0, top + pixels - 50);
4007
- else bot = Math.min(cm.doc.height, bot + pixels + 50);
4008
- updateDisplaySimple(cm, {top: top, bottom: bot});
4009
- }
4010
-
4011
- if (wheelSamples < 20) {
4012
- if (display.wheelStartX == null) {
4013
- display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4014
- display.wheelDX = dx; display.wheelDY = dy;
4015
- setTimeout(function() {
4016
- if (display.wheelStartX == null) return;
4017
- var movedX = scroll.scrollLeft - display.wheelStartX;
4018
- var movedY = scroll.scrollTop - display.wheelStartY;
4019
- var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4020
- (movedX && display.wheelDX && movedX / display.wheelDX);
4021
- display.wheelStartX = display.wheelStartY = null;
4022
- if (!sample) return;
4023
- wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4024
- ++wheelSamples;
4025
- }, 200);
4026
- } else {
4027
- display.wheelDX += dx; display.wheelDY += dy;
4028
- }
4029
- }
4030
- }
4031
-
4032
- // KEY EVENTS
4033
-
4034
- // Run a handler that was bound to a key.
4035
- function doHandleBinding(cm, bound, dropShift) {
4036
- if (typeof bound == "string") {
4037
- bound = commands[bound];
4038
- if (!bound) return false;
4039
- }
4040
- // Ensure previous input has been read, so that the handler sees a
4041
- // consistent view of the document
4042
- cm.display.input.ensurePolled();
4043
- var prevShift = cm.display.shift, done = false;
4044
- try {
4045
- if (isReadOnly(cm)) cm.state.suppressEdits = true;
4046
- if (dropShift) cm.display.shift = false;
4047
- done = bound(cm) != Pass;
4048
- } finally {
4049
- cm.display.shift = prevShift;
4050
- cm.state.suppressEdits = false;
4051
- }
4052
- return done;
4053
- }
4054
-
4055
- function lookupKeyForEditor(cm, name, handle) {
4056
- for (var i = 0; i < cm.state.keyMaps.length; i++) {
4057
- var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4058
- if (result) return result;
4059
- }
4060
- return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4061
- || lookupKey(name, cm.options.keyMap, handle, cm);
4062
- }
4063
-
4064
- var stopSeq = new Delayed;
4065
- function dispatchKey(cm, name, e, handle) {
4066
- var seq = cm.state.keySeq;
4067
- if (seq) {
4068
- if (isModifierKey(name)) return "handled";
4069
- stopSeq.set(50, function() {
4070
- if (cm.state.keySeq == seq) {
4071
- cm.state.keySeq = null;
4072
- cm.display.input.reset();
4073
- }
4074
- });
4075
- name = seq + " " + name;
4076
- }
4077
- var result = lookupKeyForEditor(cm, name, handle);
4078
-
4079
- if (result == "multi")
4080
- cm.state.keySeq = name;
4081
- if (result == "handled")
4082
- signalLater(cm, "keyHandled", cm, name, e);
4083
-
4084
- if (result == "handled" || result == "multi") {
4085
- e_preventDefault(e);
4086
- restartBlink(cm);
4087
- }
4088
-
4089
- if (seq && !result && /\'$/.test(name)) {
4090
- e_preventDefault(e);
4091
- return true;
4092
- }
4093
- return !!result;
4094
- }
4095
-
4096
- // Handle a key from the keydown event.
4097
- function handleKeyBinding(cm, e) {
4098
- var name = keyName(e, true);
4099
- if (!name) return false;
4100
-
4101
- if (e.shiftKey && !cm.state.keySeq) {
4102
- // First try to resolve full name (including 'Shift-'). Failing
4103
- // that, see if there is a cursor-motion command (starting with
4104
- // 'go') bound to the keyname without 'Shift-'.
4105
- return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4106
- || dispatchKey(cm, name, e, function(b) {
4107
- if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4108
- return doHandleBinding(cm, b);
4109
- });
4110
- } else {
4111
- return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4112
- }
4113
- }
4114
-
4115
- // Handle a key from the keypress event
4116
- function handleCharBinding(cm, e, ch) {
4117
- return dispatchKey(cm, "'" + ch + "'", e,
4118
- function(b) { return doHandleBinding(cm, b, true); });
4119
- }
4120
-
4121
- var lastStoppedKey = null;
4122
- function onKeyDown(e) {
4123
- var cm = this;
4124
- cm.curOp.focus = activeElt();
4125
- if (signalDOMEvent(cm, e)) return;
4126
- // IE does strange things with escape.
4127
- if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4128
- var code = e.keyCode;
4129
- cm.display.shift = code == 16 || e.shiftKey;
4130
- var handled = handleKeyBinding(cm, e);
4131
- if (presto) {
4132
- lastStoppedKey = handled ? code : null;
4133
- // Opera has no cut event... we try to at least catch the key combo
4134
- if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4135
- cm.replaceSelection("", null, "cut");
4136
- }
4137
-
4138
- // Turn mouse into crosshair when Alt is held on Mac.
4139
- if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4140
- showCrossHair(cm);
4141
- }
4142
-
4143
- function showCrossHair(cm) {
4144
- var lineDiv = cm.display.lineDiv;
4145
- addClass(lineDiv, "CodeMirror-crosshair");
4146
-
4147
- function up(e) {
4148
- if (e.keyCode == 18 || !e.altKey) {
4149
- rmClass(lineDiv, "CodeMirror-crosshair");
4150
- off(document, "keyup", up);
4151
- off(document, "mouseover", up);
4152
- }
4153
- }
4154
- on(document, "keyup", up);
4155
- on(document, "mouseover", up);
4156
- }
4157
-
4158
- function onKeyUp(e) {
4159
- if (e.keyCode == 16) this.doc.sel.shift = false;
4160
- signalDOMEvent(this, e);
4161
- }
4162
-
4163
- function onKeyPress(e) {
4164
- var cm = this;
4165
- if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4166
- var keyCode = e.keyCode, charCode = e.charCode;
4167
- if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4168
- if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4169
- var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4170
- if (handleCharBinding(cm, e, ch)) return;
4171
- cm.display.input.onKeyPress(e);
4172
- }
4173
-
4174
- // FOCUS/BLUR EVENTS
4175
-
4176
- function delayBlurEvent(cm) {
4177
- cm.state.delayingBlurEvent = true;
4178
- setTimeout(function() {
4179
- if (cm.state.delayingBlurEvent) {
4180
- cm.state.delayingBlurEvent = false;
4181
- onBlur(cm);
4182
- }
4183
- }, 100);
4184
- }
4185
-
4186
- function onFocus(cm) {
4187
- if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4188
-
4189
- if (cm.options.readOnly == "nocursor") return;
4190
- if (!cm.state.focused) {
4191
- signal(cm, "focus", cm);
4192
- cm.state.focused = true;
4193
- addClass(cm.display.wrapper, "CodeMirror-focused");
4194
- // This test prevents this from firing when a context
4195
- // menu is closed (since the input reset would kill the
4196
- // select-all detection hack)
4197
- if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4198
- cm.display.input.reset();
4199
- if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4200
- }
4201
- cm.display.input.receivedFocus();
4202
- }
4203
- restartBlink(cm);
4204
- }
4205
- function onBlur(cm) {
4206
- if (cm.state.delayingBlurEvent) return;
4207
-
4208
- if (cm.state.focused) {
4209
- signal(cm, "blur", cm);
4210
- cm.state.focused = false;
4211
- rmClass(cm.display.wrapper, "CodeMirror-focused");
4212
- }
4213
- clearInterval(cm.display.blinker);
4214
- setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4215
- }
4216
-
4217
- // CONTEXT MENU HANDLING
4218
-
4219
- // To make the context menu work, we need to briefly unhide the
4220
- // textarea (making it as unobtrusive as possible) to let the
4221
- // right-click take effect on it.
4222
- function onContextMenu(cm, e) {
4223
- if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4224
- cm.display.input.onContextMenu(e);
4225
- }
4226
-
4227
- function contextMenuInGutter(cm, e) {
4228
- if (!hasHandler(cm, "gutterContextMenu")) return false;
4229
- return gutterEvent(cm, e, "gutterContextMenu", false, signal);
4230
- }
4231
-
4232
- // UPDATING
4233
-
4234
- // Compute the position of the end of a change (its 'to' property
4235
- // refers to the pre-change end).
4236
- var changeEnd = CodeMirror.changeEnd = function(change) {
4237
- if (!change.text) return change.to;
4238
- return Pos(change.from.line + change.text.length - 1,
4239
- lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4240
- };
4241
-
4242
- // Adjust a position to refer to the post-change position of the
4243
- // same text, or the end of the change if the change covers it.
4244
- function adjustForChange(pos, change) {
4245
- if (cmp(pos, change.from) < 0) return pos;
4246
- if (cmp(pos, change.to) <= 0) return changeEnd(change);
4247
-
4248
- var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4249
- if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4250
- return Pos(line, ch);
4251
- }
4252
-
4253
- function computeSelAfterChange(doc, change) {
4254
- var out = [];
4255
- for (var i = 0; i < doc.sel.ranges.length; i++) {
4256
- var range = doc.sel.ranges[i];
4257
- out.push(new Range(adjustForChange(range.anchor, change),
4258
- adjustForChange(range.head, change)));
4259
- }
4260
- return normalizeSelection(out, doc.sel.primIndex);
4261
- }
4262
-
4263
- function offsetPos(pos, old, nw) {
4264
- if (pos.line == old.line)
4265
- return Pos(nw.line, pos.ch - old.ch + nw.ch);
4266
- else
4267
- return Pos(nw.line + (pos.line - old.line), pos.ch);
4268
- }
4269
-
4270
- // Used by replaceSelections to allow moving the selection to the
4271
- // start or around the replaced test. Hint may be "start" or "around".
4272
- function computeReplacedSel(doc, changes, hint) {
4273
- var out = [];
4274
- var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4275
- for (var i = 0; i < changes.length; i++) {
4276
- var change = changes[i];
4277
- var from = offsetPos(change.from, oldPrev, newPrev);
4278
- var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4279
- oldPrev = change.to;
4280
- newPrev = to;
4281
- if (hint == "around") {
4282
- var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4283
- out[i] = new Range(inv ? to : from, inv ? from : to);
4284
- } else {
4285
- out[i] = new Range(from, from);
4286
- }
4287
- }
4288
- return new Selection(out, doc.sel.primIndex);
4289
- }
4290
-
4291
- // Allow "beforeChange" event handlers to influence a change
4292
- function filterChange(doc, change, update) {
4293
- var obj = {
4294
- canceled: false,
4295
- from: change.from,
4296
- to: change.to,
4297
- text: change.text,
4298
- origin: change.origin,
4299
- cancel: function() { this.canceled = true; }
4300
- };
4301
- if (update) obj.update = function(from, to, text, origin) {
4302
- if (from) this.from = clipPos(doc, from);
4303
- if (to) this.to = clipPos(doc, to);
4304
- if (text) this.text = text;
4305
- if (origin !== undefined) this.origin = origin;
4306
- };
4307
- signal(doc, "beforeChange", doc, obj);
4308
- if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4309
-
4310
- if (obj.canceled) return null;
4311
- return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4312
- }
4313
-
4314
- // Apply a change to a document, and add it to the document's
4315
- // history, and propagating it to all linked documents.
4316
- function makeChange(doc, change, ignoreReadOnly) {
4317
- if (doc.cm) {
4318
- if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4319
- if (doc.cm.state.suppressEdits) return;
4320
- }
4321
-
4322
- if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4323
- change = filterChange(doc, change, true);
4324
- if (!change) return;
4325
- }
4326
-
4327
- // Possibly split or suppress the update based on the presence
4328
- // of read-only spans in its range.
4329
- var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4330
- if (split) {
4331
- for (var i = split.length - 1; i >= 0; --i)
4332
- makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4333
- } else {
4334
- makeChangeInner(doc, change);
4335
- }
4336
- }
4337
-
4338
- function makeChangeInner(doc, change) {
4339
- if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4340
- var selAfter = computeSelAfterChange(doc, change);
4341
- addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4342
-
4343
- makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4344
- var rebased = [];
4345
-
4346
- linkedDocs(doc, function(doc, sharedHist) {
4347
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4348
- rebaseHist(doc.history, change);
4349
- rebased.push(doc.history);
4350
- }
4351
- makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4352
- });
4353
- }
4354
-
4355
- // Revert a change stored in a document's history.
4356
- function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4357
- if (doc.cm && doc.cm.state.suppressEdits) return;
4358
-
4359
- var hist = doc.history, event, selAfter = doc.sel;
4360
- var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4361
-
4362
- // Verify that there is a useable event (so that ctrl-z won't
4363
- // needlessly clear selection events)
4364
- for (var i = 0; i < source.length; i++) {
4365
- event = source[i];
4366
- if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4367
- break;
4368
- }
4369
- if (i == source.length) return;
4370
- hist.lastOrigin = hist.lastSelOrigin = null;
4371
-
4372
- for (;;) {
4373
- event = source.pop();
4374
- if (event.ranges) {
4375
- pushSelectionToHistory(event, dest);
4376
- if (allowSelectionOnly && !event.equals(doc.sel)) {
4377
- setSelection(doc, event, {clearRedo: false});
4378
- return;
4379
- }
4380
- selAfter = event;
4381
- }
4382
- else break;
4383
- }
4384
-
4385
- // Build up a reverse change object to add to the opposite history
4386
- // stack (redo when undoing, and vice versa).
4387
- var antiChanges = [];
4388
- pushSelectionToHistory(selAfter, dest);
4389
- dest.push({changes: antiChanges, generation: hist.generation});
4390
- hist.generation = event.generation || ++hist.maxGeneration;
4391
-
4392
- var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4393
-
4394
- for (var i = event.changes.length - 1; i >= 0; --i) {
4395
- var change = event.changes[i];
4396
- change.origin = type;
4397
- if (filter && !filterChange(doc, change, false)) {
4398
- source.length = 0;
4399
- return;
4400
- }
4401
-
4402
- antiChanges.push(historyChangeFromChange(doc, change));
4403
-
4404
- var after = i ? computeSelAfterChange(doc, change) : lst(source);
4405
- makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4406
- if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4407
- var rebased = [];
4408
-
4409
- // Propagate to the linked documents
4410
- linkedDocs(doc, function(doc, sharedHist) {
4411
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4412
- rebaseHist(doc.history, change);
4413
- rebased.push(doc.history);
4414
- }
4415
- makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4416
- });
4417
- }
4418
- }
4419
-
4420
- // Sub-views need their line numbers shifted when text is added
4421
- // above or below them in the parent document.
4422
- function shiftDoc(doc, distance) {
4423
- if (distance == 0) return;
4424
- doc.first += distance;
4425
- doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4426
- return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4427
- Pos(range.head.line + distance, range.head.ch));
4428
- }), doc.sel.primIndex);
4429
- if (doc.cm) {
4430
- regChange(doc.cm, doc.first, doc.first - distance, distance);
4431
- for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4432
- regLineChange(doc.cm, l, "gutter");
4433
- }
4434
- }
4435
-
4436
- // More lower-level change function, handling only a single document
4437
- // (not linked ones).
4438
- function makeChangeSingleDoc(doc, change, selAfter, spans) {
4439
- if (doc.cm && !doc.cm.curOp)
4440
- return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4441
-
4442
- if (change.to.line < doc.first) {
4443
- shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4444
- return;
4445
- }
4446
- if (change.from.line > doc.lastLine()) return;
4447
-
4448
- // Clip the change to the size of this doc
4449
- if (change.from.line < doc.first) {
4450
- var shift = change.text.length - 1 - (doc.first - change.from.line);
4451
- shiftDoc(doc, shift);
4452
- change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4453
- text: [lst(change.text)], origin: change.origin};
4454
- }
4455
- var last = doc.lastLine();
4456
- if (change.to.line > last) {
4457
- change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4458
- text: [change.text[0]], origin: change.origin};
4459
- }
4460
-
4461
- change.removed = getBetween(doc, change.from, change.to);
4462
-
4463
- if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4464
- if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4465
- else updateDoc(doc, change, spans);
4466
- setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4467
- }
4468
-
4469
- // Handle the interaction of a change to a document with the editor
4470
- // that this document is part of.
4471
- function makeChangeSingleDocInEditor(cm, change, spans) {
4472
- var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4473
-
4474
- var recomputeMaxLength = false, checkWidthStart = from.line;
4475
- if (!cm.options.lineWrapping) {
4476
- checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4477
- doc.iter(checkWidthStart, to.line + 1, function(line) {
4478
- if (line == display.maxLine) {
4479
- recomputeMaxLength = true;
4480
- return true;
4481
- }
4482
- });
4483
- }
4484
-
4485
- if (doc.sel.contains(change.from, change.to) > -1)
4486
- signalCursorActivity(cm);
4487
-
4488
- updateDoc(doc, change, spans, estimateHeight(cm));
4489
-
4490
- if (!cm.options.lineWrapping) {
4491
- doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4492
- var len = lineLength(line);
4493
- if (len > display.maxLineLength) {
4494
- display.maxLine = line;
4495
- display.maxLineLength = len;
4496
- display.maxLineChanged = true;
4497
- recomputeMaxLength = false;
4498
- }
4499
- });
4500
- if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4501
- }
4502
-
4503
- // Adjust frontier, schedule worker
4504
- doc.frontier = Math.min(doc.frontier, from.line);
4505
- startWorker(cm, 400);
4506
-
4507
- var lendiff = change.text.length - (to.line - from.line) - 1;
4508
- // Remember that these lines changed, for updating the display
4509
- if (change.full)
4510
- regChange(cm);
4511
- else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4512
- regLineChange(cm, from.line, "text");
4513
- else
4514
- regChange(cm, from.line, to.line + 1, lendiff);
4515
-
4516
- var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4517
- if (changeHandler || changesHandler) {
4518
- var obj = {
4519
- from: from, to: to,
4520
- text: change.text,
4521
- removed: change.removed,
4522
- origin: change.origin
4523
- };
4524
- if (changeHandler) signalLater(cm, "change", cm, obj);
4525
- if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4526
- }
4527
- cm.display.selForContextMenu = null;
4528
- }
4529
-
4530
- function replaceRange(doc, code, from, to, origin) {
4531
- if (!to) to = from;
4532
- if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4533
- if (typeof code == "string") code = doc.splitLines(code);
4534
- makeChange(doc, {from: from, to: to, text: code, origin: origin});
4535
- }
4536
-
4537
- // SCROLLING THINGS INTO VIEW
4538
-
4539
- // If an editor sits on the top or bottom of the window, partially
4540
- // scrolled out of view, this ensures that the cursor is visible.
4541
- function maybeScrollWindow(cm, coords) {
4542
- if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4543
-
4544
- var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4545
- if (coords.top + box.top < 0) doScroll = true;
4546
- else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4547
- if (doScroll != null && !phantom) {
4548
- var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4549
- (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4550
- (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4551
- coords.left + "px; width: 2px;");
4552
- cm.display.lineSpace.appendChild(scrollNode);
4553
- scrollNode.scrollIntoView(doScroll);
4554
- cm.display.lineSpace.removeChild(scrollNode);
4555
- }
4556
- }
4557
-
4558
- // Scroll a given position into view (immediately), verifying that
4559
- // it actually became visible (as line heights are accurately
4560
- // measured, the position of something may 'drift' during drawing).
4561
- function scrollPosIntoView(cm, pos, end, margin) {
4562
- if (margin == null) margin = 0;
4563
- for (var limit = 0; limit < 5; limit++) {
4564
- var changed = false, coords = cursorCoords(cm, pos);
4565
- var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4566
- var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4567
- Math.min(coords.top, endCoords.top) - margin,
4568
- Math.max(coords.left, endCoords.left),
4569
- Math.max(coords.bottom, endCoords.bottom) + margin);
4570
- var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4571
- if (scrollPos.scrollTop != null) {
4572
- setScrollTop(cm, scrollPos.scrollTop);
4573
- if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4574
- }
4575
- if (scrollPos.scrollLeft != null) {
4576
- setScrollLeft(cm, scrollPos.scrollLeft);
4577
- if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4578
- }
4579
- if (!changed) break;
4580
- }
4581
- return coords;
4582
- }
4583
-
4584
- // Scroll a given set of coordinates into view (immediately).
4585
- function scrollIntoView(cm, x1, y1, x2, y2) {
4586
- var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4587
- if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4588
- if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4589
- }
4590
-
4591
- // Calculate a new scroll position needed to scroll the given
4592
- // rectangle into view. Returns an object with scrollTop and
4593
- // scrollLeft properties. When these are undefined, the
4594
- // vertical/horizontal position does not need to be adjusted.
4595
- function calculateScrollPos(cm, x1, y1, x2, y2) {
4596
- var display = cm.display, snapMargin = textHeight(cm.display);
4597
- if (y1 < 0) y1 = 0;
4598
- var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4599
- var screen = displayHeight(cm), result = {};
4600
- if (y2 - y1 > screen) y2 = y1 + screen;
4601
- var docBottom = cm.doc.height + paddingVert(display);
4602
- var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4603
- if (y1 < screentop) {
4604
- result.scrollTop = atTop ? 0 : y1;
4605
- } else if (y2 > screentop + screen) {
4606
- var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4607
- if (newTop != screentop) result.scrollTop = newTop;
4608
- }
4609
-
4610
- var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4611
- var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4612
- var tooWide = x2 - x1 > screenw;
4613
- if (tooWide) x2 = x1 + screenw;
4614
- if (x1 < 10)
4615
- result.scrollLeft = 0;
4616
- else if (x1 < screenleft)
4617
- result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4618
- else if (x2 > screenw + screenleft - 3)
4619
- result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4620
- return result;
4621
- }
4622
-
4623
- // Store a relative adjustment to the scroll position in the current
4624
- // operation (to be applied when the operation finishes).
4625
- function addToScrollPos(cm, left, top) {
4626
- if (left != null || top != null) resolveScrollToPos(cm);
4627
- if (left != null)
4628
- cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4629
- if (top != null)
4630
- cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4631
- }
4632
-
4633
- // Make sure that at the end of the operation the current cursor is
4634
- // shown.
4635
- function ensureCursorVisible(cm) {
4636
- resolveScrollToPos(cm);
4637
- var cur = cm.getCursor(), from = cur, to = cur;
4638
- if (!cm.options.lineWrapping) {
4639
- from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4640
- to = Pos(cur.line, cur.ch + 1);
4641
- }
4642
- cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4643
- }
4644
-
4645
- // When an operation has its scrollToPos property set, and another
4646
- // scroll action is applied before the end of the operation, this
4647
- // 'simulates' scrolling that position into view in a cheap way, so
4648
- // that the effect of intermediate scroll commands is not ignored.
4649
- function resolveScrollToPos(cm) {
4650
- var range = cm.curOp.scrollToPos;
4651
- if (range) {
4652
- cm.curOp.scrollToPos = null;
4653
- var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4654
- var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4655
- Math.min(from.top, to.top) - range.margin,
4656
- Math.max(from.right, to.right),
4657
- Math.max(from.bottom, to.bottom) + range.margin);
4658
- cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4659
- }
4660
- }
4661
-
4662
- // API UTILITIES
4663
-
4664
- // Indent the given line. The how parameter can be "smart",
4665
- // "add"/null, "subtract", or "prev". When aggressive is false
4666
- // (typically set to true for forced single-line indents), empty
4667
- // lines are not indented, and places where the mode returns Pass
4668
- // are left alone.
4669
- function indentLine(cm, n, how, aggressive) {
4670
- var doc = cm.doc, state;
4671
- if (how == null) how = "add";
4672
- if (how == "smart") {
4673
- // Fall back to "prev" when the mode doesn't have an indentation
4674
- // method.
4675
- if (!doc.mode.indent) how = "prev";
4676
- else state = getStateBefore(cm, n);
4677
- }
4678
-
4679
- var tabSize = cm.options.tabSize;
4680
- var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4681
- if (line.stateAfter) line.stateAfter = null;
4682
- var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4683
- if (!aggressive && !/\S/.test(line.text)) {
4684
- indentation = 0;
4685
- how = "not";
4686
- } else if (how == "smart") {
4687
- indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4688
- if (indentation == Pass || indentation > 150) {
4689
- if (!aggressive) return;
4690
- how = "prev";
4691
- }
4692
- }
4693
- if (how == "prev") {
4694
- if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4695
- else indentation = 0;
4696
- } else if (how == "add") {
4697
- indentation = curSpace + cm.options.indentUnit;
4698
- } else if (how == "subtract") {
4699
- indentation = curSpace - cm.options.indentUnit;
4700
- } else if (typeof how == "number") {
4701
- indentation = curSpace + how;
4702
- }
4703
- indentation = Math.max(0, indentation);
4704
-
4705
- var indentString = "", pos = 0;
4706
- if (cm.options.indentWithTabs)
4707
- for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4708
- if (pos < indentation) indentString += spaceStr(indentation - pos);
4709
-
4710
- if (indentString != curSpaceString) {
4711
- replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4712
- line.stateAfter = null;
4713
- return true;
4714
- } else {
4715
- // Ensure that, if the cursor was in the whitespace at the start
4716
- // of the line, it is moved to the end of that space.
4717
- for (var i = 0; i < doc.sel.ranges.length; i++) {
4718
- var range = doc.sel.ranges[i];
4719
- if (range.head.line == n && range.head.ch < curSpaceString.length) {
4720
- var pos = Pos(n, curSpaceString.length);
4721
- replaceOneSelection(doc, i, new Range(pos, pos));
4722
- break;
4723
- }
4724
- }
4725
- }
4726
- }
4727
-
4728
- // Utility for applying a change to a line by handle or number,
4729
- // returning the number and optionally registering the line as
4730
- // changed.
4731
- function changeLine(doc, handle, changeType, op) {
4732
- var no = handle, line = handle;
4733
- if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4734
- else no = lineNo(handle);
4735
- if (no == null) return null;
4736
- if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4737
- return line;
4738
- }
4739
-
4740
- // Helper for deleting text near the selection(s), used to implement
4741
- // backspace, delete, and similar functionality.
4742
- function deleteNearSelection(cm, compute) {
4743
- var ranges = cm.doc.sel.ranges, kill = [];
4744
- // Build up a set of ranges to kill first, merging overlapping
4745
- // ranges.
4746
- for (var i = 0; i < ranges.length; i++) {
4747
- var toKill = compute(ranges[i]);
4748
- while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4749
- var replaced = kill.pop();
4750
- if (cmp(replaced.from, toKill.from) < 0) {
4751
- toKill.from = replaced.from;
4752
- break;
4753
- }
4754
- }
4755
- kill.push(toKill);
4756
- }
4757
- // Next, remove those actual ranges.
4758
- runInOp(cm, function() {
4759
- for (var i = kill.length - 1; i >= 0; i--)
4760
- replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4761
- ensureCursorVisible(cm);
4762
- });
4763
- }
4764
-
4765
- // Used for horizontal relative motion. Dir is -1 or 1 (left or
4766
- // right), unit can be "char", "column" (like char, but doesn't
4767
- // cross line boundaries), "word" (across next word), or "group" (to
4768
- // the start of next group of word or non-word-non-whitespace
4769
- // chars). The visually param controls whether, in right-to-left
4770
- // text, direction 1 means to move towards the next index in the
4771
- // string, or towards the character to the right of the current
4772
- // position. The resulting position will have a hitSide=true
4773
- // property if it reached the end of the document.
4774
- function findPosH(doc, pos, dir, unit, visually) {
4775
- var line = pos.line, ch = pos.ch, origDir = dir;
4776
- var lineObj = getLine(doc, line);
4777
- var possible = true;
4778
- function findNextLine() {
4779
- var l = line + dir;
4780
- if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4781
- line = l;
4782
- return lineObj = getLine(doc, l);
4783
- }
4784
- function moveOnce(boundToLine) {
4785
- var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4786
- if (next == null) {
4787
- if (!boundToLine && findNextLine()) {
4788
- if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4789
- else ch = dir < 0 ? lineObj.text.length : 0;
4790
- } else return (possible = false);
4791
- } else ch = next;
4792
- return true;
4793
- }
4794
-
4795
- if (unit == "char") moveOnce();
4796
- else if (unit == "column") moveOnce(true);
4797
- else if (unit == "word" || unit == "group") {
4798
- var sawType = null, group = unit == "group";
4799
- var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4800
- for (var first = true;; first = false) {
4801
- if (dir < 0 && !moveOnce(!first)) break;
4802
- var cur = lineObj.text.charAt(ch) || "\n";
4803
- var type = isWordChar(cur, helper) ? "w"
4804
- : group && cur == "\n" ? "n"
4805
- : !group || /\s/.test(cur) ? null
4806
- : "p";
4807
- if (group && !first && !type) type = "s";
4808
- if (sawType && sawType != type) {
4809
- if (dir < 0) {dir = 1; moveOnce();}
4810
- break;
4811
- }
4812
-
4813
- if (type) sawType = type;
4814
- if (dir > 0 && !moveOnce(!first)) break;
4815
- }
4816
- }
4817
- var result = skipAtomic(doc, Pos(line, ch), origDir, true);
4818
- if (!possible) result.hitSide = true;
4819
- return result;
4820
- }
4821
-
4822
- // For relative vertical movement. Dir may be -1 or 1. Unit can be
4823
- // "page" or "line". The resulting position will have a hitSide=true
4824
- // property if it reached the end of the document.
4825
- function findPosV(cm, pos, dir, unit) {
4826
- var doc = cm.doc, x = pos.left, y;
4827
- if (unit == "page") {
4828
- var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4829
- y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4830
- } else if (unit == "line") {
4831
- y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4832
- }
4833
- for (;;) {
4834
- var target = coordsChar(cm, x, y);
4835
- if (!target.outside) break;
4836
- if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4837
- y += dir * 5;
4838
- }
4839
- return target;
4840
- }
4841
-
4842
- // EDITOR METHODS
4843
-
4844
- // The publicly visible API. Note that methodOp(f) means
4845
- // 'wrap f in an operation, performed on its `this` parameter'.
4846
-
4847
- // This is not the complete set of editor methods. Most of the
4848
- // methods defined on the Doc type are also injected into
4849
- // CodeMirror.prototype, for backwards compatibility and
4850
- // convenience.
4851
-
4852
- CodeMirror.prototype = {
4853
- constructor: CodeMirror,
4854
- focus: function(){window.focus(); this.display.input.focus();},
4855
-
4856
- setOption: function(option, value) {
4857
- var options = this.options, old = options[option];
4858
- if (options[option] == value && option != "mode") return;
4859
- options[option] = value;
4860
- if (optionHandlers.hasOwnProperty(option))
4861
- operation(this, optionHandlers[option])(this, value, old);
4862
- },
4863
-
4864
- getOption: function(option) {return this.options[option];},
4865
- getDoc: function() {return this.doc;},
4866
-
4867
- addKeyMap: function(map, bottom) {
4868
- this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4869
- },
4870
- removeKeyMap: function(map) {
4871
- var maps = this.state.keyMaps;
4872
- for (var i = 0; i < maps.length; ++i)
4873
- if (maps[i] == map || maps[i].name == map) {
4874
- maps.splice(i, 1);
4875
- return true;
4876
- }
4877
- },
4878
-
4879
- addOverlay: methodOp(function(spec, options) {
4880
- var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4881
- if (mode.startState) throw new Error("Overlays may not be stateful.");
4882
- this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4883
- this.state.modeGen++;
4884
- regChange(this);
4885
- }),
4886
- removeOverlay: methodOp(function(spec) {
4887
- var overlays = this.state.overlays;
4888
- for (var i = 0; i < overlays.length; ++i) {
4889
- var cur = overlays[i].modeSpec;
4890
- if (cur == spec || typeof spec == "string" && cur.name == spec) {
4891
- overlays.splice(i, 1);
4892
- this.state.modeGen++;
4893
- regChange(this);
4894
- return;
4895
- }
4896
- }
4897
- }),
4898
-
4899
- indentLine: methodOp(function(n, dir, aggressive) {
4900
- if (typeof dir != "string" && typeof dir != "number") {
4901
- if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4902
- else dir = dir ? "add" : "subtract";
4903
- }
4904
- if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4905
- }),
4906
- indentSelection: methodOp(function(how) {
4907
- var ranges = this.doc.sel.ranges, end = -1;
4908
- for (var i = 0; i < ranges.length; i++) {
4909
- var range = ranges[i];
4910
- if (!range.empty()) {
4911
- var from = range.from(), to = range.to();
4912
- var start = Math.max(end, from.line);
4913
- end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4914
- for (var j = start; j < end; ++j)
4915
- indentLine(this, j, how);
4916
- var newRanges = this.doc.sel.ranges;
4917
- if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4918
- replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4919
- } else if (range.head.line > end) {
4920
- indentLine(this, range.head.line, how, true);
4921
- end = range.head.line;
4922
- if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4923
- }
4924
- }
4925
- }),
4926
-
4927
- // Fetch the parser token for a given character. Useful for hacks
4928
- // that want to inspect the mode state (say, for completion).
4929
- getTokenAt: function(pos, precise) {
4930
- return takeToken(this, pos, precise);
4931
- },
4932
-
4933
- getLineTokens: function(line, precise) {
4934
- return takeToken(this, Pos(line), precise, true);
4935
- },
4936
-
4937
- getTokenTypeAt: function(pos) {
4938
- pos = clipPos(this.doc, pos);
4939
- var styles = getLineStyles(this, getLine(this.doc, pos.line));
4940
- var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4941
- var type;
4942
- if (ch == 0) type = styles[2];
4943
- else for (;;) {
4944
- var mid = (before + after) >> 1;
4945
- if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4946
- else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4947
- else { type = styles[mid * 2 + 2]; break; }
4948
- }
4949
- var cut = type ? type.indexOf("cm-overlay ") : -1;
4950
- return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4951
- },
4952
-
4953
- getModeAt: function(pos) {
4954
- var mode = this.doc.mode;
4955
- if (!mode.innerMode) return mode;
4956
- return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4957
- },
4958
-
4959
- getHelper: function(pos, type) {
4960
- return this.getHelpers(pos, type)[0];
4961
- },
4962
-
4963
- getHelpers: function(pos, type) {
4964
- var found = [];
4965
- if (!helpers.hasOwnProperty(type)) return found;
4966
- var help = helpers[type], mode = this.getModeAt(pos);
4967
- if (typeof mode[type] == "string") {
4968
- if (help[mode[type]]) found.push(help[mode[type]]);
4969
- } else if (mode[type]) {
4970
- for (var i = 0; i < mode[type].length; i++) {
4971
- var val = help[mode[type][i]];
4972
- if (val) found.push(val);
4973
- }
4974
- } else if (mode.helperType && help[mode.helperType]) {
4975
- found.push(help[mode.helperType]);
4976
- } else if (help[mode.name]) {
4977
- found.push(help[mode.name]);
4978
- }
4979
- for (var i = 0; i < help._global.length; i++) {
4980
- var cur = help._global[i];
4981
- if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
4982
- found.push(cur.val);
4983
- }
4984
- return found;
4985
- },
4986
-
4987
- getStateAfter: function(line, precise) {
4988
- var doc = this.doc;
4989
- line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
4990
- return getStateBefore(this, line + 1, precise);
4991
- },
4992
-
4993
- cursorCoords: function(start, mode) {
4994
- var pos, range = this.doc.sel.primary();
4995
- if (start == null) pos = range.head;
4996
- else if (typeof start == "object") pos = clipPos(this.doc, start);
4997
- else pos = start ? range.from() : range.to();
4998
- return cursorCoords(this, pos, mode || "page");
4999
- },
5000
-
5001
- charCoords: function(pos, mode) {
5002
- return charCoords(this, clipPos(this.doc, pos), mode || "page");
5003
- },
5004
-
5005
- coordsChar: function(coords, mode) {
5006
- coords = fromCoordSystem(this, coords, mode || "page");
5007
- return coordsChar(this, coords.left, coords.top);
5008
- },
5009
-
5010
- lineAtHeight: function(height, mode) {
5011
- height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5012
- return lineAtHeight(this.doc, height + this.display.viewOffset);
5013
- },
5014
- heightAtLine: function(line, mode) {
5015
- var end = false, lineObj;
5016
- if (typeof line == "number") {
5017
- var last = this.doc.first + this.doc.size - 1;
5018
- if (line < this.doc.first) line = this.doc.first;
5019
- else if (line > last) { line = last; end = true; }
5020
- lineObj = getLine(this.doc, line);
5021
- } else {
5022
- lineObj = line;
5023
- }
5024
- return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5025
- (end ? this.doc.height - heightAtLine(lineObj) : 0);
5026
- },
5027
-
5028
- defaultTextHeight: function() { return textHeight(this.display); },
5029
- defaultCharWidth: function() { return charWidth(this.display); },
5030
-
5031
- setGutterMarker: methodOp(function(line, gutterID, value) {
5032
- return changeLine(this.doc, line, "gutter", function(line) {
5033
- var markers = line.gutterMarkers || (line.gutterMarkers = {});
5034
- markers[gutterID] = value;
5035
- if (!value && isEmpty(markers)) line.gutterMarkers = null;
5036
- return true;
5037
- });
5038
- }),
5039
-
5040
- clearGutter: methodOp(function(gutterID) {
5041
- var cm = this, doc = cm.doc, i = doc.first;
5042
- doc.iter(function(line) {
5043
- if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5044
- line.gutterMarkers[gutterID] = null;
5045
- regLineChange(cm, i, "gutter");
5046
- if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5047
- }
5048
- ++i;
5049
- });
5050
- }),
5051
-
5052
- lineInfo: function(line) {
5053
- if (typeof line == "number") {
5054
- if (!isLine(this.doc, line)) return null;
5055
- var n = line;
5056
- line = getLine(this.doc, line);
5057
- if (!line) return null;
5058
- } else {
5059
- var n = lineNo(line);
5060
- if (n == null) return null;
5061
- }
5062
- return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5063
- textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5064
- widgets: line.widgets};
5065
- },
5066
-
5067
- getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5068
-
5069
- addWidget: function(pos, node, scroll, vert, horiz) {
5070
- var display = this.display;
5071
- pos = cursorCoords(this, clipPos(this.doc, pos));
5072
- var top = pos.bottom, left = pos.left;
5073
- node.style.position = "absolute";
5074
- node.setAttribute("cm-ignore-events", "true");
5075
- this.display.input.setUneditable(node);
5076
- display.sizer.appendChild(node);
5077
- if (vert == "over") {
5078
- top = pos.top;
5079
- } else if (vert == "above" || vert == "near") {
5080
- var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5081
- hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5082
- // Default to positioning above (if specified and possible); otherwise default to positioning below
5083
- if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5084
- top = pos.top - node.offsetHeight;
5085
- else if (pos.bottom + node.offsetHeight <= vspace)
5086
- top = pos.bottom;
5087
- if (left + node.offsetWidth > hspace)
5088
- left = hspace - node.offsetWidth;
5089
- }
5090
- node.style.top = top + "px";
5091
- node.style.left = node.style.right = "";
5092
- if (horiz == "right") {
5093
- left = display.sizer.clientWidth - node.offsetWidth;
5094
- node.style.right = "0px";
5095
- } else {
5096
- if (horiz == "left") left = 0;
5097
- else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5098
- node.style.left = left + "px";
5099
- }
5100
- if (scroll)
5101
- scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5102
- },
5103
-
5104
- triggerOnKeyDown: methodOp(onKeyDown),
5105
- triggerOnKeyPress: methodOp(onKeyPress),
5106
- triggerOnKeyUp: onKeyUp,
5107
-
5108
- execCommand: function(cmd) {
5109
- if (commands.hasOwnProperty(cmd))
5110
- return commands[cmd].call(null, this);
5111
- },
5112
-
5113
- triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5114
-
5115
- findPosH: function(from, amount, unit, visually) {
5116
- var dir = 1;
5117
- if (amount < 0) { dir = -1; amount = -amount; }
5118
- for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5119
- cur = findPosH(this.doc, cur, dir, unit, visually);
5120
- if (cur.hitSide) break;
5121
- }
5122
- return cur;
5123
- },
5124
-
5125
- moveH: methodOp(function(dir, unit) {
5126
- var cm = this;
5127
- cm.extendSelectionsBy(function(range) {
5128
- if (cm.display.shift || cm.doc.extend || range.empty())
5129
- return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5130
- else
5131
- return dir < 0 ? range.from() : range.to();
5132
- }, sel_move);
5133
- }),
5134
-
5135
- deleteH: methodOp(function(dir, unit) {
5136
- var sel = this.doc.sel, doc = this.doc;
5137
- if (sel.somethingSelected())
5138
- doc.replaceSelection("", null, "+delete");
5139
- else
5140
- deleteNearSelection(this, function(range) {
5141
- var other = findPosH(doc, range.head, dir, unit, false);
5142
- return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5143
- });
5144
- }),
5145
-
5146
- findPosV: function(from, amount, unit, goalColumn) {
5147
- var dir = 1, x = goalColumn;
5148
- if (amount < 0) { dir = -1; amount = -amount; }
5149
- for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5150
- var coords = cursorCoords(this, cur, "div");
5151
- if (x == null) x = coords.left;
5152
- else coords.left = x;
5153
- cur = findPosV(this, coords, dir, unit);
5154
- if (cur.hitSide) break;
5155
- }
5156
- return cur;
5157
- },
5158
-
5159
- moveV: methodOp(function(dir, unit) {
5160
- var cm = this, doc = this.doc, goals = [];
5161
- var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5162
- doc.extendSelectionsBy(function(range) {
5163
- if (collapse)
5164
- return dir < 0 ? range.from() : range.to();
5165
- var headPos = cursorCoords(cm, range.head, "div");
5166
- if (range.goalColumn != null) headPos.left = range.goalColumn;
5167
- goals.push(headPos.left);
5168
- var pos = findPosV(cm, headPos, dir, unit);
5169
- if (unit == "page" && range == doc.sel.primary())
5170
- addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5171
- return pos;
5172
- }, sel_move);
5173
- if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5174
- doc.sel.ranges[i].goalColumn = goals[i];
5175
- }),
5176
-
5177
- // Find the word at the given position (as returned by coordsChar).
5178
- findWordAt: function(pos) {
5179
- var doc = this.doc, line = getLine(doc, pos.line).text;
5180
- var start = pos.ch, end = pos.ch;
5181
- if (line) {
5182
- var helper = this.getHelper(pos, "wordChars");
5183
- if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5184
- var startChar = line.charAt(start);
5185
- var check = isWordChar(startChar, helper)
5186
- ? function(ch) { return isWordChar(ch, helper); }
5187
- : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5188
- : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5189
- while (start > 0 && check(line.charAt(start - 1))) --start;
5190
- while (end < line.length && check(line.charAt(end))) ++end;
5191
- }
5192
- return new Range(Pos(pos.line, start), Pos(pos.line, end));
5193
- },
5194
-
5195
- toggleOverwrite: function(value) {
5196
- if (value != null && value == this.state.overwrite) return;
5197
- if (this.state.overwrite = !this.state.overwrite)
5198
- addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5199
- else
5200
- rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5201
-
5202
- signal(this, "overwriteToggle", this, this.state.overwrite);
5203
- },
5204
- hasFocus: function() { return this.display.input.getField() == activeElt(); },
5205
-
5206
- scrollTo: methodOp(function(x, y) {
5207
- if (x != null || y != null) resolveScrollToPos(this);
5208
- if (x != null) this.curOp.scrollLeft = x;
5209
- if (y != null) this.curOp.scrollTop = y;
5210
- }),
5211
- getScrollInfo: function() {
5212
- var scroller = this.display.scroller;
5213
- return {left: scroller.scrollLeft, top: scroller.scrollTop,
5214
- height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5215
- width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5216
- clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5217
- },
5218
-
5219
- scrollIntoView: methodOp(function(range, margin) {
5220
- if (range == null) {
5221
- range = {from: this.doc.sel.primary().head, to: null};
5222
- if (margin == null) margin = this.options.cursorScrollMargin;
5223
- } else if (typeof range == "number") {
5224
- range = {from: Pos(range, 0), to: null};
5225
- } else if (range.from == null) {
5226
- range = {from: range, to: null};
5227
- }
5228
- if (!range.to) range.to = range.from;
5229
- range.margin = margin || 0;
5230
-
5231
- if (range.from.line != null) {
5232
- resolveScrollToPos(this);
5233
- this.curOp.scrollToPos = range;
5234
- } else {
5235
- var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5236
- Math.min(range.from.top, range.to.top) - range.margin,
5237
- Math.max(range.from.right, range.to.right),
5238
- Math.max(range.from.bottom, range.to.bottom) + range.margin);
5239
- this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5240
- }
5241
- }),
5242
-
5243
- setSize: methodOp(function(width, height) {
5244
- var cm = this;
5245
- function interpret(val) {
5246
- return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5247
- }
5248
- if (width != null) cm.display.wrapper.style.width = interpret(width);
5249
- if (height != null) cm.display.wrapper.style.height = interpret(height);
5250
- if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5251
- var lineNo = cm.display.viewFrom;
5252
- cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5253
- if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5254
- if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5255
- ++lineNo;
5256
- });
5257
- cm.curOp.forceUpdate = true;
5258
- signal(cm, "refresh", this);
5259
- }),
5260
-
5261
- operation: function(f){return runInOp(this, f);},
5262
-
5263
- refresh: methodOp(function() {
5264
- var oldHeight = this.display.cachedTextHeight;
5265
- regChange(this);
5266
- this.curOp.forceUpdate = true;
5267
- clearCaches(this);
5268
- this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5269
- updateGutterSpace(this);
5270
- if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5271
- estimateLineHeights(this);
5272
- signal(this, "refresh", this);
5273
- }),
5274
-
5275
- swapDoc: methodOp(function(doc) {
5276
- var old = this.doc;
5277
- old.cm = null;
5278
- attachDoc(this, doc);
5279
- clearCaches(this);
5280
- this.display.input.reset();
5281
- this.scrollTo(doc.scrollLeft, doc.scrollTop);
5282
- this.curOp.forceScroll = true;
5283
- signalLater(this, "swapDoc", this, old);
5284
- return old;
5285
- }),
5286
-
5287
- getInputField: function(){return this.display.input.getField();},
5288
- getWrapperElement: function(){return this.display.wrapper;},
5289
- getScrollerElement: function(){return this.display.scroller;},
5290
- getGutterElement: function(){return this.display.gutters;}
5291
- };
5292
- eventMixin(CodeMirror);
5293
-
5294
- // OPTION DEFAULTS
5295
-
5296
- // The default configuration options.
5297
- var defaults = CodeMirror.defaults = {};
5298
- // Functions to run when options are changed.
5299
- var optionHandlers = CodeMirror.optionHandlers = {};
5300
-
5301
- function option(name, deflt, handle, notOnInit) {
5302
- CodeMirror.defaults[name] = deflt;
5303
- if (handle) optionHandlers[name] =
5304
- notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5305
- }
5306
-
5307
- // Passed to option handlers when there is no old value.
5308
- var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5309
-
5310
- // These two are, on init, called from the constructor because they
5311
- // have to be initialized before the editor can start at all.
5312
- option("value", "", function(cm, val) {
5313
- cm.setValue(val);
5314
- }, true);
5315
- option("mode", null, function(cm, val) {
5316
- cm.doc.modeOption = val;
5317
- loadMode(cm);
5318
- }, true);
5319
-
5320
- option("indentUnit", 2, loadMode, true);
5321
- option("indentWithTabs", false);
5322
- option("smartIndent", true);
5323
- option("tabSize", 4, function(cm) {
5324
- resetModeState(cm);
5325
- clearCaches(cm);
5326
- regChange(cm);
5327
- }, true);
5328
- option("lineSeparator", null, function(cm, val) {
5329
- cm.doc.lineSep = val;
5330
- if (!val) return;
5331
- var newBreaks = [], lineNo = cm.doc.first;
5332
- cm.doc.iter(function(line) {
5333
- for (var pos = 0;;) {
5334
- var found = line.text.indexOf(val, pos);
5335
- if (found == -1) break;
5336
- pos = found + val.length;
5337
- newBreaks.push(Pos(lineNo, found));
5338
- }
5339
- lineNo++;
5340
- });
5341
- for (var i = newBreaks.length - 1; i >= 0; i--)
5342
- replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5343
- });
5344
- option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5345
- cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5346
- if (old != CodeMirror.Init) cm.refresh();
5347
- });
5348
- option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5349
- option("electricChars", true);
5350
- option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5351
- throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5352
- }, true);
5353
- option("rtlMoveVisually", !windows);
5354
- option("wholeLineUpdateBefore", true);
5355
-
5356
- option("theme", "default", function(cm) {
5357
- themeChanged(cm);
5358
- guttersChanged(cm);
5359
- }, true);
5360
- option("keyMap", "default", function(cm, val, old) {
5361
- var next = getKeyMap(val);
5362
- var prev = old != CodeMirror.Init && getKeyMap(old);
5363
- if (prev && prev.detach) prev.detach(cm, next);
5364
- if (next.attach) next.attach(cm, prev || null);
5365
- });
5366
- option("extraKeys", null);
5367
-
5368
- option("lineWrapping", false, wrappingChanged, true);
5369
- option("gutters", [], function(cm) {
5370
- setGuttersForLineNumbers(cm.options);
5371
- guttersChanged(cm);
5372
- }, true);
5373
- option("fixedGutter", true, function(cm, val) {
5374
- cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5375
- cm.refresh();
5376
- }, true);
5377
- option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5378
- option("scrollbarStyle", "native", function(cm) {
5379
- initScrollbars(cm);
5380
- updateScrollbars(cm);
5381
- cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5382
- cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5383
- }, true);
5384
- option("lineNumbers", false, function(cm) {
5385
- setGuttersForLineNumbers(cm.options);
5386
- guttersChanged(cm);
5387
- }, true);
5388
- option("firstLineNumber", 1, guttersChanged, true);
5389
- option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5390
- option("showCursorWhenSelecting", false, updateSelection, true);
5391
-
5392
- option("resetSelectionOnContextMenu", true);
5393
- option("lineWiseCopyCut", true);
5394
-
5395
- option("readOnly", false, function(cm, val) {
5396
- if (val == "nocursor") {
5397
- onBlur(cm);
5398
- cm.display.input.blur();
5399
- cm.display.disabled = true;
5400
- } else {
5401
- cm.display.disabled = false;
5402
- }
5403
- cm.display.input.readOnlyChanged(val)
5404
- });
5405
- option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5406
- option("dragDrop", true, dragDropChanged);
5407
-
5408
- option("cursorBlinkRate", 530);
5409
- option("cursorScrollMargin", 0);
5410
- option("cursorHeight", 1, updateSelection, true);
5411
- option("singleCursorHeightPerLine", true, updateSelection, true);
5412
- option("workTime", 100);
5413
- option("workDelay", 100);
5414
- option("flattenSpans", true, resetModeState, true);
5415
- option("addModeClass", false, resetModeState, true);
5416
- option("pollInterval", 100);
5417
- option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5418
- option("historyEventDelay", 1250);
5419
- option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5420
- option("maxHighlightLength", 10000, resetModeState, true);
5421
- option("moveInputWithCursor", true, function(cm, val) {
5422
- if (!val) cm.display.input.resetPosition();
5423
- });
5424
-
5425
- option("tabindex", null, function(cm, val) {
5426
- cm.display.input.getField().tabIndex = val || "";
5427
- });
5428
- option("autofocus", null);
5429
-
5430
- // MODE DEFINITION AND QUERYING
5431
-
5432
- // Known modes, by name and by MIME
5433
- var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5434
-
5435
- // Extra arguments are stored as the mode's dependencies, which is
5436
- // used by (legacy) mechanisms like loadmode.js to automatically
5437
- // load a mode. (Preferred mechanism is the require/define calls.)
5438
- CodeMirror.defineMode = function(name, mode) {
5439
- if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5440
- if (arguments.length > 2)
5441
- mode.dependencies = Array.prototype.slice.call(arguments, 2);
5442
- modes[name] = mode;
5443
- };
5444
-
5445
- CodeMirror.defineMIME = function(mime, spec) {
5446
- mimeModes[mime] = spec;
5447
- };
5448
-
5449
- // Given a MIME type, a {name, ...options} config object, or a name
5450
- // string, return a mode config object.
5451
- CodeMirror.resolveMode = function(spec) {
5452
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5453
- spec = mimeModes[spec];
5454
- } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5455
- var found = mimeModes[spec.name];
5456
- if (typeof found == "string") found = {name: found};
5457
- spec = createObj(found, spec);
5458
- spec.name = found.name;
5459
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5460
- return CodeMirror.resolveMode("application/xml");
5461
- }
5462
- if (typeof spec == "string") return {name: spec};
5463
- else return spec || {name: "null"};
5464
- };
5465
-
5466
- // Given a mode spec (anything that resolveMode accepts), find and
5467
- // initialize an actual mode object.
5468
- CodeMirror.getMode = function(options, spec) {
5469
- var spec = CodeMirror.resolveMode(spec);
5470
- var mfactory = modes[spec.name];
5471
- if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5472
- var modeObj = mfactory(options, spec);
5473
- if (modeExtensions.hasOwnProperty(spec.name)) {
5474
- var exts = modeExtensions[spec.name];
5475
- for (var prop in exts) {
5476
- if (!exts.hasOwnProperty(prop)) continue;
5477
- if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5478
- modeObj[prop] = exts[prop];
5479
- }
5480
- }
5481
- modeObj.name = spec.name;
5482
- if (spec.helperType) modeObj.helperType = spec.helperType;
5483
- if (spec.modeProps) for (var prop in spec.modeProps)
5484
- modeObj[prop] = spec.modeProps[prop];
5485
-
5486
- return modeObj;
5487
- };
5488
-
5489
- // Minimal default mode.
5490
- CodeMirror.defineMode("null", function() {
5491
- return {token: function(stream) {stream.skipToEnd();}};
5492
- });
5493
- CodeMirror.defineMIME("text/plain", "null");
5494
-
5495
- // This can be used to attach properties to mode objects from
5496
- // outside the actual mode definition.
5497
- var modeExtensions = CodeMirror.modeExtensions = {};
5498
- CodeMirror.extendMode = function(mode, properties) {
5499
- var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5500
- copyObj(properties, exts);
5501
- };
5502
-
5503
- // EXTENSIONS
5504
-
5505
- CodeMirror.defineExtension = function(name, func) {
5506
- CodeMirror.prototype[name] = func;
5507
- };
5508
- CodeMirror.defineDocExtension = function(name, func) {
5509
- Doc.prototype[name] = func;
5510
- };
5511
- CodeMirror.defineOption = option;
5512
-
5513
- var initHooks = [];
5514
- CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5515
-
5516
- var helpers = CodeMirror.helpers = {};
5517
- CodeMirror.registerHelper = function(type, name, value) {
5518
- if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5519
- helpers[type][name] = value;
5520
- };
5521
- CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5522
- CodeMirror.registerHelper(type, name, value);
5523
- helpers[type]._global.push({pred: predicate, val: value});
5524
- };
5525
-
5526
- // MODE STATE HANDLING
5527
-
5528
- // Utility functions for working with state. Exported because nested
5529
- // modes need to do this for their inner modes.
5530
-
5531
- var copyState = CodeMirror.copyState = function(mode, state) {
5532
- if (state === true) return state;
5533
- if (mode.copyState) return mode.copyState(state);
5534
- var nstate = {};
5535
- for (var n in state) {
5536
- var val = state[n];
5537
- if (val instanceof Array) val = val.concat([]);
5538
- nstate[n] = val;
5539
- }
5540
- return nstate;
5541
- };
5542
-
5543
- var startState = CodeMirror.startState = function(mode, a1, a2) {
5544
- return mode.startState ? mode.startState(a1, a2) : true;
5545
- };
5546
-
5547
- // Given a mode and a state (for that mode), find the inner mode and
5548
- // state at the position that the state refers to.
5549
- CodeMirror.innerMode = function(mode, state) {
5550
- while (mode.innerMode) {
5551
- var info = mode.innerMode(state);
5552
- if (!info || info.mode == mode) break;
5553
- state = info.state;
5554
- mode = info.mode;
5555
- }
5556
- return info || {mode: mode, state: state};
5557
- };
5558
-
5559
- // STANDARD COMMANDS
5560
-
5561
- // Commands are parameter-less actions that can be performed on an
5562
- // editor, mostly used for keybindings.
5563
- var commands = CodeMirror.commands = {
5564
- selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5565
- singleSelection: function(cm) {
5566
- cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5567
- },
5568
- killLine: function(cm) {
5569
- deleteNearSelection(cm, function(range) {
5570
- if (range.empty()) {
5571
- var len = getLine(cm.doc, range.head.line).text.length;
5572
- if (range.head.ch == len && range.head.line < cm.lastLine())
5573
- return {from: range.head, to: Pos(range.head.line + 1, 0)};
5574
- else
5575
- return {from: range.head, to: Pos(range.head.line, len)};
5576
- } else {
5577
- return {from: range.from(), to: range.to()};
5578
- }
5579
- });
5580
- },
5581
- deleteLine: function(cm) {
5582
- deleteNearSelection(cm, function(range) {
5583
- return {from: Pos(range.from().line, 0),
5584
- to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5585
- });
5586
- },
5587
- delLineLeft: function(cm) {
5588
- deleteNearSelection(cm, function(range) {
5589
- return {from: Pos(range.from().line, 0), to: range.from()};
5590
- });
5591
- },
5592
- delWrappedLineLeft: function(cm) {
5593
- deleteNearSelection(cm, function(range) {
5594
- var top = cm.charCoords(range.head, "div").top + 5;
5595
- var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5596
- return {from: leftPos, to: range.from()};
5597
- });
5598
- },
5599
- delWrappedLineRight: function(cm) {
5600
- deleteNearSelection(cm, function(range) {
5601
- var top = cm.charCoords(range.head, "div").top + 5;
5602
- var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5603
- return {from: range.from(), to: rightPos };
5604
- });
5605
- },
5606
- undo: function(cm) {cm.undo();},
5607
- redo: function(cm) {cm.redo();},
5608
- undoSelection: function(cm) {cm.undoSelection();},
5609
- redoSelection: function(cm) {cm.redoSelection();},
5610
- goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5611
- goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5612
- goLineStart: function(cm) {
5613
- cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5614
- {origin: "+move", bias: 1});
5615
- },
5616
- goLineStartSmart: function(cm) {
5617
- cm.extendSelectionsBy(function(range) {
5618
- return lineStartSmart(cm, range.head);
5619
- }, {origin: "+move", bias: 1});
5620
- },
5621
- goLineEnd: function(cm) {
5622
- cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5623
- {origin: "+move", bias: -1});
5624
- },
5625
- goLineRight: function(cm) {
5626
- cm.extendSelectionsBy(function(range) {
5627
- var top = cm.charCoords(range.head, "div").top + 5;
5628
- return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5629
- }, sel_move);
5630
- },
5631
- goLineLeft: function(cm) {
5632
- cm.extendSelectionsBy(function(range) {
5633
- var top = cm.charCoords(range.head, "div").top + 5;
5634
- return cm.coordsChar({left: 0, top: top}, "div");
5635
- }, sel_move);
5636
- },
5637
- goLineLeftSmart: function(cm) {
5638
- cm.extendSelectionsBy(function(range) {
5639
- var top = cm.charCoords(range.head, "div").top + 5;
5640
- var pos = cm.coordsChar({left: 0, top: top}, "div");
5641
- if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5642
- return pos;
5643
- }, sel_move);
5644
- },
5645
- goLineUp: function(cm) {cm.moveV(-1, "line");},
5646
- goLineDown: function(cm) {cm.moveV(1, "line");},
5647
- goPageUp: function(cm) {cm.moveV(-1, "page");},
5648
- goPageDown: function(cm) {cm.moveV(1, "page");},
5649
- goCharLeft: function(cm) {cm.moveH(-1, "char");},
5650
- goCharRight: function(cm) {cm.moveH(1, "char");},
5651
- goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5652
- goColumnRight: function(cm) {cm.moveH(1, "column");},
5653
- goWordLeft: function(cm) {cm.moveH(-1, "word");},
5654
- goGroupRight: function(cm) {cm.moveH(1, "group");},
5655
- goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5656
- goWordRight: function(cm) {cm.moveH(1, "word");},
5657
- delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5658
- delCharAfter: function(cm) {cm.deleteH(1, "char");},
5659
- delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5660
- delWordAfter: function(cm) {cm.deleteH(1, "word");},
5661
- delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5662
- delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5663
- indentAuto: function(cm) {cm.indentSelection("smart");},
5664
- indentMore: function(cm) {cm.indentSelection("add");},
5665
- indentLess: function(cm) {cm.indentSelection("subtract");},
5666
- insertTab: function(cm) {cm.replaceSelection("\t");},
5667
- insertSoftTab: function(cm) {
5668
- var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5669
- for (var i = 0; i < ranges.length; i++) {
5670
- var pos = ranges[i].from();
5671
- var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5672
- spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5673
- }
5674
- cm.replaceSelections(spaces);
5675
- },
5676
- defaultTab: function(cm) {
5677
- if (cm.somethingSelected()) cm.indentSelection("add");
5678
- else cm.execCommand("insertTab");
5679
- },
5680
- transposeChars: function(cm) {
5681
- runInOp(cm, function() {
5682
- var ranges = cm.listSelections(), newSel = [];
5683
- for (var i = 0; i < ranges.length; i++) {
5684
- var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5685
- if (line) {
5686
- if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5687
- if (cur.ch > 0) {
5688
- cur = new Pos(cur.line, cur.ch + 1);
5689
- cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5690
- Pos(cur.line, cur.ch - 2), cur, "+transpose");
5691
- } else if (cur.line > cm.doc.first) {
5692
- var prev = getLine(cm.doc, cur.line - 1).text;
5693
- if (prev)
5694
- cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5695
- prev.charAt(prev.length - 1),
5696
- Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5697
- }
5698
- }
5699
- newSel.push(new Range(cur, cur));
5700
- }
5701
- cm.setSelections(newSel);
5702
- });
5703
- },
5704
- newlineAndIndent: function(cm) {
5705
- runInOp(cm, function() {
5706
- var len = cm.listSelections().length;
5707
- for (var i = 0; i < len; i++) {
5708
- var range = cm.listSelections()[i];
5709
- cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5710
- cm.indentLine(range.from().line + 1, null, true);
5711
- ensureCursorVisible(cm);
5712
- }
5713
- });
5714
- },
5715
- toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5716
- };
5717
-
5718
-
5719
- // STANDARD KEYMAPS
5720
-
5721
- var keyMap = CodeMirror.keyMap = {};
5722
-
5723
- keyMap.basic = {
5724
- "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5725
- "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5726
- "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5727
- "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5728
- "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5729
- "Esc": "singleSelection"
5730
- };
5731
- // Note that the save and find-related commands aren't defined by
5732
- // default. User code or addons can define them. Unknown commands
5733
- // are simply ignored.
5734
- keyMap.pcDefault = {
5735
- "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5736
- "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5737
- "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5738
- "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5739
- "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5740
- "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5741
- "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5742
- fallthrough: "basic"
5743
- };
5744
- // Very basic readline/emacs-style bindings, which are standard on Mac.
5745
- keyMap.emacsy = {
5746
- "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5747
- "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5748
- "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5749
- "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5750
- };
5751
- keyMap.macDefault = {
5752
- "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5753
- "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5754
- "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5755
- "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5756
- "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5757
- "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5758
- "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5759
- fallthrough: ["basic", "emacsy"]
5760
- };
5761
- keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5762
-
5763
- // KEYMAP DISPATCH
5764
-
5765
- function normalizeKeyName(name) {
5766
- var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5767
- var alt, ctrl, shift, cmd;
5768
- for (var i = 0; i < parts.length - 1; i++) {
5769
- var mod = parts[i];
5770
- if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5771
- else if (/^a(lt)?$/i.test(mod)) alt = true;
5772
- else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5773
- else if (/^s(hift)$/i.test(mod)) shift = true;
5774
- else throw new Error("Unrecognized modifier name: " + mod);
5775
- }
5776
- if (alt) name = "Alt-" + name;
5777
- if (ctrl) name = "Ctrl-" + name;
5778
- if (cmd) name = "Cmd-" + name;
5779
- if (shift) name = "Shift-" + name;
5780
- return name;
5781
- }
5782
-
5783
- // This is a kludge to keep keymaps mostly working as raw objects
5784
- // (backwards compatibility) while at the same time support features
5785
- // like normalization and multi-stroke key bindings. It compiles a
5786
- // new normalized keymap, and then updates the old object to reflect
5787
- // this.
5788
- CodeMirror.normalizeKeyMap = function(keymap) {
5789
- var copy = {};
5790
- for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5791
- var value = keymap[keyname];
5792
- if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5793
- if (value == "...") { delete keymap[keyname]; continue; }
5794
-
5795
- var keys = map(keyname.split(" "), normalizeKeyName);
5796
- for (var i = 0; i < keys.length; i++) {
5797
- var val, name;
5798
- if (i == keys.length - 1) {
5799
- name = keys.join(" ");
5800
- val = value;
5801
- } else {
5802
- name = keys.slice(0, i + 1).join(" ");
5803
- val = "...";
5804
- }
5805
- var prev = copy[name];
5806
- if (!prev) copy[name] = val;
5807
- else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5808
- }
5809
- delete keymap[keyname];
5810
- }
5811
- for (var prop in copy) keymap[prop] = copy[prop];
5812
- return keymap;
5813
- };
5814
-
5815
- var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5816
- map = getKeyMap(map);
5817
- var found = map.call ? map.call(key, context) : map[key];
5818
- if (found === false) return "nothing";
5819
- if (found === "...") return "multi";
5820
- if (found != null && handle(found)) return "handled";
5821
-
5822
- if (map.fallthrough) {
5823
- if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5824
- return lookupKey(key, map.fallthrough, handle, context);
5825
- for (var i = 0; i < map.fallthrough.length; i++) {
5826
- var result = lookupKey(key, map.fallthrough[i], handle, context);
5827
- if (result) return result;
5828
- }
5829
- }
5830
- };
5831
-
5832
- // Modifier key presses don't count as 'real' key presses for the
5833
- // purpose of keymap fallthrough.
5834
- var isModifierKey = CodeMirror.isModifierKey = function(value) {
5835
- var name = typeof value == "string" ? value : keyNames[value.keyCode];
5836
- return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5837
- };
5838
-
5839
- // Look up the name of a key as indicated by an event object.
5840
- var keyName = CodeMirror.keyName = function(event, noShift) {
5841
- if (presto && event.keyCode == 34 && event["char"]) return false;
5842
- var base = keyNames[event.keyCode], name = base;
5843
- if (name == null || event.altGraphKey) return false;
5844
- if (event.altKey && base != "Alt") name = "Alt-" + name;
5845
- if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5846
- if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5847
- if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5848
- return name;
5849
- };
5850
-
5851
- function getKeyMap(val) {
5852
- return typeof val == "string" ? keyMap[val] : val;
5853
- }
5854
-
5855
- // FROMTEXTAREA
5856
-
5857
- CodeMirror.fromTextArea = function(textarea, options) {
5858
- options = options ? copyObj(options) : {};
5859
- options.value = textarea.value;
5860
- if (!options.tabindex && textarea.tabIndex)
5861
- options.tabindex = textarea.tabIndex;
5862
- if (!options.placeholder && textarea.placeholder)
5863
- options.placeholder = textarea.placeholder;
5864
- // Set autofocus to true if this textarea is focused, or if it has
5865
- // autofocus and no other element is focused.
5866
- if (options.autofocus == null) {
5867
- var hasFocus = activeElt();
5868
- options.autofocus = hasFocus == textarea ||
5869
- textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5870
- }
5871
-
5872
- function save() {textarea.value = cm.getValue();}
5873
- if (textarea.form) {
5874
- on(textarea.form, "submit", save);
5875
- // Deplorable hack to make the submit method do the right thing.
5876
- if (!options.leaveSubmitMethodAlone) {
5877
- var form = textarea.form, realSubmit = form.submit;
5878
- try {
5879
- var wrappedSubmit = form.submit = function() {
5880
- save();
5881
- form.submit = realSubmit;
5882
- form.submit();
5883
- form.submit = wrappedSubmit;
5884
- };
5885
- } catch(e) {}
5886
- }
5887
- }
5888
-
5889
- options.finishInit = function(cm) {
5890
- cm.save = save;
5891
- cm.getTextArea = function() { return textarea; };
5892
- cm.toTextArea = function() {
5893
- cm.toTextArea = isNaN; // Prevent this from being ran twice
5894
- save();
5895
- textarea.parentNode.removeChild(cm.getWrapperElement());
5896
- textarea.style.display = "";
5897
- if (textarea.form) {
5898
- off(textarea.form, "submit", save);
5899
- if (typeof textarea.form.submit == "function")
5900
- textarea.form.submit = realSubmit;
5901
- }
5902
- };
5903
- };
5904
-
5905
- textarea.style.display = "none";
5906
- var cm = CodeMirror(function(node) {
5907
- textarea.parentNode.insertBefore(node, textarea.nextSibling);
5908
- }, options);
5909
- return cm;
5910
- };
5911
-
5912
- // STRING STREAM
5913
-
5914
- // Fed to the mode parsers, provides helper functions to make
5915
- // parsers more succinct.
5916
-
5917
- var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5918
- this.pos = this.start = 0;
5919
- this.string = string;
5920
- this.tabSize = tabSize || 8;
5921
- this.lastColumnPos = this.lastColumnValue = 0;
5922
- this.lineStart = 0;
5923
- };
5924
-
5925
- StringStream.prototype = {
5926
- eol: function() {return this.pos >= this.string.length;},
5927
- sol: function() {return this.pos == this.lineStart;},
5928
- peek: function() {return this.string.charAt(this.pos) || undefined;},
5929
- next: function() {
5930
- if (this.pos < this.string.length)
5931
- return this.string.charAt(this.pos++);
5932
- },
5933
- eat: function(match) {
5934
- var ch = this.string.charAt(this.pos);
5935
- if (typeof match == "string") var ok = ch == match;
5936
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
5937
- if (ok) {++this.pos; return ch;}
5938
- },
5939
- eatWhile: function(match) {
5940
- var start = this.pos;
5941
- while (this.eat(match)){}
5942
- return this.pos > start;
5943
- },
5944
- eatSpace: function() {
5945
- var start = this.pos;
5946
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5947
- return this.pos > start;
5948
- },
5949
- skipToEnd: function() {this.pos = this.string.length;},
5950
- skipTo: function(ch) {
5951
- var found = this.string.indexOf(ch, this.pos);
5952
- if (found > -1) {this.pos = found; return true;}
5953
- },
5954
- backUp: function(n) {this.pos -= n;},
5955
- column: function() {
5956
- if (this.lastColumnPos < this.start) {
5957
- this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5958
- this.lastColumnPos = this.start;
5959
- }
5960
- return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5961
- },
5962
- indentation: function() {
5963
- return countColumn(this.string, null, this.tabSize) -
5964
- (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5965
- },
5966
- match: function(pattern, consume, caseInsensitive) {
5967
- if (typeof pattern == "string") {
5968
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
5969
- var substr = this.string.substr(this.pos, pattern.length);
5970
- if (cased(substr) == cased(pattern)) {
5971
- if (consume !== false) this.pos += pattern.length;
5972
- return true;
5973
- }
5974
- } else {
5975
- var match = this.string.slice(this.pos).match(pattern);
5976
- if (match && match.index > 0) return null;
5977
- if (match && consume !== false) this.pos += match[0].length;
5978
- return match;
5979
- }
5980
- },
5981
- current: function(){return this.string.slice(this.start, this.pos);},
5982
- hideFirstChars: function(n, inner) {
5983
- this.lineStart += n;
5984
- try { return inner(); }
5985
- finally { this.lineStart -= n; }
5986
- }
5987
- };
5988
-
5989
- // TEXTMARKERS
5990
-
5991
- // Created with markText and setBookmark methods. A TextMarker is a
5992
- // handle that can be used to clear or find a marked position in the
5993
- // document. Line objects hold arrays (markedSpans) containing
5994
- // {from, to, marker} object pointing to such marker objects, and
5995
- // indicating that such a marker is present on that line. Multiple
5996
- // lines may point to the same marker when it spans across lines.
5997
- // The spans will have null for their from/to properties when the
5998
- // marker continues beyond the start/end of the line. Markers have
5999
- // links back to the lines they currently touch.
6000
-
6001
- var nextMarkerId = 0;
6002
-
6003
- var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6004
- this.lines = [];
6005
- this.type = type;
6006
- this.doc = doc;
6007
- this.id = ++nextMarkerId;
6008
- };
6009
- eventMixin(TextMarker);
6010
-
6011
- // Clear the marker.
6012
- TextMarker.prototype.clear = function() {
6013
- if (this.explicitlyCleared) return;
6014
- var cm = this.doc.cm, withOp = cm && !cm.curOp;
6015
- if (withOp) startOperation(cm);
6016
- if (hasHandler(this, "clear")) {
6017
- var found = this.find();
6018
- if (found) signalLater(this, "clear", found.from, found.to);
6019
- }
6020
- var min = null, max = null;
6021
- for (var i = 0; i < this.lines.length; ++i) {
6022
- var line = this.lines[i];
6023
- var span = getMarkedSpanFor(line.markedSpans, this);
6024
- if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6025
- else if (cm) {
6026
- if (span.to != null) max = lineNo(line);
6027
- if (span.from != null) min = lineNo(line);
6028
- }
6029
- line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6030
- if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6031
- updateLineHeight(line, textHeight(cm.display));
6032
- }
6033
- if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6034
- var visual = visualLine(this.lines[i]), len = lineLength(visual);
6035
- if (len > cm.display.maxLineLength) {
6036
- cm.display.maxLine = visual;
6037
- cm.display.maxLineLength = len;
6038
- cm.display.maxLineChanged = true;
6039
- }
6040
- }
6041
-
6042
- if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6043
- this.lines.length = 0;
6044
- this.explicitlyCleared = true;
6045
- if (this.atomic && this.doc.cantEdit) {
6046
- this.doc.cantEdit = false;
6047
- if (cm) reCheckSelection(cm.doc);
6048
- }
6049
- if (cm) signalLater(cm, "markerCleared", cm, this);
6050
- if (withOp) endOperation(cm);
6051
- if (this.parent) this.parent.clear();
6052
- };
6053
-
6054
- // Find the position of the marker in the document. Returns a {from,
6055
- // to} object by default. Side can be passed to get a specific side
6056
- // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6057
- // Pos objects returned contain a line object, rather than a line
6058
- // number (used to prevent looking up the same line twice).
6059
- TextMarker.prototype.find = function(side, lineObj) {
6060
- if (side == null && this.type == "bookmark") side = 1;
6061
- var from, to;
6062
- for (var i = 0; i < this.lines.length; ++i) {
6063
- var line = this.lines[i];
6064
- var span = getMarkedSpanFor(line.markedSpans, this);
6065
- if (span.from != null) {
6066
- from = Pos(lineObj ? line : lineNo(line), span.from);
6067
- if (side == -1) return from;
6068
- }
6069
- if (span.to != null) {
6070
- to = Pos(lineObj ? line : lineNo(line), span.to);
6071
- if (side == 1) return to;
6072
- }
6073
- }
6074
- return from && {from: from, to: to};
6075
- };
6076
-
6077
- // Signals that the marker's widget changed, and surrounding layout
6078
- // should be recomputed.
6079
- TextMarker.prototype.changed = function() {
6080
- var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6081
- if (!pos || !cm) return;
6082
- runInOp(cm, function() {
6083
- var line = pos.line, lineN = lineNo(pos.line);
6084
- var view = findViewForLine(cm, lineN);
6085
- if (view) {
6086
- clearLineMeasurementCacheFor(view);
6087
- cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6088
- }
6089
- cm.curOp.updateMaxLine = true;
6090
- if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6091
- var oldHeight = widget.height;
6092
- widget.height = null;
6093
- var dHeight = widgetHeight(widget) - oldHeight;
6094
- if (dHeight)
6095
- updateLineHeight(line, line.height + dHeight);
6096
- }
6097
- });
6098
- };
6099
-
6100
- TextMarker.prototype.attachLine = function(line) {
6101
- if (!this.lines.length && this.doc.cm) {
6102
- var op = this.doc.cm.curOp;
6103
- if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6104
- (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6105
- }
6106
- this.lines.push(line);
6107
- };
6108
- TextMarker.prototype.detachLine = function(line) {
6109
- this.lines.splice(indexOf(this.lines, line), 1);
6110
- if (!this.lines.length && this.doc.cm) {
6111
- var op = this.doc.cm.curOp;
6112
- (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6113
- }
6114
- };
6115
-
6116
- // Collapsed markers have unique ids, in order to be able to order
6117
- // them, which is needed for uniquely determining an outer marker
6118
- // when they overlap (they may nest, but not partially overlap).
6119
- var nextMarkerId = 0;
6120
-
6121
- // Create a marker, wire it up to the right lines, and
6122
- function markText(doc, from, to, options, type) {
6123
- // Shared markers (across linked documents) are handled separately
6124
- // (markTextShared will call out to this again, once per
6125
- // document).
6126
- if (options && options.shared) return markTextShared(doc, from, to, options, type);
6127
- // Ensure we are in an operation.
6128
- if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6129
-
6130
- var marker = new TextMarker(doc, type), diff = cmp(from, to);
6131
- if (options) copyObj(options, marker, false);
6132
- // Don't connect empty markers unless clearWhenEmpty is false
6133
- if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6134
- return marker;
6135
- if (marker.replacedWith) {
6136
- // Showing up as a widget implies collapsed (widget replaces text)
6137
- marker.collapsed = true;
6138
- marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6139
- if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6140
- if (options.insertLeft) marker.widgetNode.insertLeft = true;
6141
- }
6142
- if (marker.collapsed) {
6143
- if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6144
- from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6145
- throw new Error("Inserting collapsed marker partially overlapping an existing one");
6146
- sawCollapsedSpans = true;
6147
- }
6148
-
6149
- if (marker.addToHistory)
6150
- addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6151
-
6152
- var curLine = from.line, cm = doc.cm, updateMaxLine;
6153
- doc.iter(curLine, to.line + 1, function(line) {
6154
- if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6155
- updateMaxLine = true;
6156
- if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6157
- addMarkedSpan(line, new MarkedSpan(marker,
6158
- curLine == from.line ? from.ch : null,
6159
- curLine == to.line ? to.ch : null));
6160
- ++curLine;
6161
- });
6162
- // lineIsHidden depends on the presence of the spans, so needs a second pass
6163
- if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6164
- if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6165
- });
6166
-
6167
- if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6168
-
6169
- if (marker.readOnly) {
6170
- sawReadOnlySpans = true;
6171
- if (doc.history.done.length || doc.history.undone.length)
6172
- doc.clearHistory();
6173
- }
6174
- if (marker.collapsed) {
6175
- marker.id = ++nextMarkerId;
6176
- marker.atomic = true;
6177
- }
6178
- if (cm) {
6179
- // Sync editor state
6180
- if (updateMaxLine) cm.curOp.updateMaxLine = true;
6181
- if (marker.collapsed)
6182
- regChange(cm, from.line, to.line + 1);
6183
- else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6184
- for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6185
- if (marker.atomic) reCheckSelection(cm.doc);
6186
- signalLater(cm, "markerAdded", cm, marker);
6187
- }
6188
- return marker;
6189
- }
6190
-
6191
- // SHARED TEXTMARKERS
6192
-
6193
- // A shared marker spans multiple linked documents. It is
6194
- // implemented as a meta-marker-object controlling multiple normal
6195
- // markers.
6196
- var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6197
- this.markers = markers;
6198
- this.primary = primary;
6199
- for (var i = 0; i < markers.length; ++i)
6200
- markers[i].parent = this;
6201
- };
6202
- eventMixin(SharedTextMarker);
6203
-
6204
- SharedTextMarker.prototype.clear = function() {
6205
- if (this.explicitlyCleared) return;
6206
- this.explicitlyCleared = true;
6207
- for (var i = 0; i < this.markers.length; ++i)
6208
- this.markers[i].clear();
6209
- signalLater(this, "clear");
6210
- };
6211
- SharedTextMarker.prototype.find = function(side, lineObj) {
6212
- return this.primary.find(side, lineObj);
6213
- };
6214
-
6215
- function markTextShared(doc, from, to, options, type) {
6216
- options = copyObj(options);
6217
- options.shared = false;
6218
- var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6219
- var widget = options.widgetNode;
6220
- linkedDocs(doc, function(doc) {
6221
- if (widget) options.widgetNode = widget.cloneNode(true);
6222
- markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6223
- for (var i = 0; i < doc.linked.length; ++i)
6224
- if (doc.linked[i].isParent) return;
6225
- primary = lst(markers);
6226
- });
6227
- return new SharedTextMarker(markers, primary);
6228
- }
6229
-
6230
- function findSharedMarkers(doc) {
6231
- return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6232
- function(m) { return m.parent; });
6233
- }
6234
-
6235
- function copySharedMarkers(doc, markers) {
6236
- for (var i = 0; i < markers.length; i++) {
6237
- var marker = markers[i], pos = marker.find();
6238
- var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6239
- if (cmp(mFrom, mTo)) {
6240
- var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6241
- marker.markers.push(subMark);
6242
- subMark.parent = marker;
6243
- }
6244
- }
6245
- }
6246
-
6247
- function detachSharedMarkers(markers) {
6248
- for (var i = 0; i < markers.length; i++) {
6249
- var marker = markers[i], linked = [marker.primary.doc];;
6250
- linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6251
- for (var j = 0; j < marker.markers.length; j++) {
6252
- var subMarker = marker.markers[j];
6253
- if (indexOf(linked, subMarker.doc) == -1) {
6254
- subMarker.parent = null;
6255
- marker.markers.splice(j--, 1);
6256
- }
6257
- }
6258
- }
6259
- }
6260
-
6261
- // TEXTMARKER SPANS
6262
-
6263
- function MarkedSpan(marker, from, to) {
6264
- this.marker = marker;
6265
- this.from = from; this.to = to;
6266
- }
6267
-
6268
- // Search an array of spans for a span matching the given marker.
6269
- function getMarkedSpanFor(spans, marker) {
6270
- if (spans) for (var i = 0; i < spans.length; ++i) {
6271
- var span = spans[i];
6272
- if (span.marker == marker) return span;
6273
- }
6274
- }
6275
- // Remove a span from an array, returning undefined if no spans are
6276
- // left (we don't store arrays for lines without spans).
6277
- function removeMarkedSpan(spans, span) {
6278
- for (var r, i = 0; i < spans.length; ++i)
6279
- if (spans[i] != span) (r || (r = [])).push(spans[i]);
6280
- return r;
6281
- }
6282
- // Add a span to a line.
6283
- function addMarkedSpan(line, span) {
6284
- line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6285
- span.marker.attachLine(line);
6286
- }
6287
-
6288
- // Used for the algorithm that adjusts markers for a change in the
6289
- // document. These functions cut an array of spans at a given
6290
- // character position, returning an array of remaining chunks (or
6291
- // undefined if nothing remains).
6292
- function markedSpansBefore(old, startCh, isInsert) {
6293
- if (old) for (var i = 0, nw; i < old.length; ++i) {
6294
- var span = old[i], marker = span.marker;
6295
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6296
- if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6297
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6298
- (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6299
- }
6300
- }
6301
- return nw;
6302
- }
6303
- function markedSpansAfter(old, endCh, isInsert) {
6304
- if (old) for (var i = 0, nw; i < old.length; ++i) {
6305
- var span = old[i], marker = span.marker;
6306
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6307
- if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6308
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6309
- (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6310
- span.to == null ? null : span.to - endCh));
6311
- }
6312
- }
6313
- return nw;
6314
- }
6315
-
6316
- // Given a change object, compute the new set of marker spans that
6317
- // cover the line in which the change took place. Removes spans
6318
- // entirely within the change, reconnects spans belonging to the
6319
- // same marker that appear on both sides of the change, and cuts off
6320
- // spans partially within the change. Returns an array of span
6321
- // arrays with one element for each line in (after) the change.
6322
- function stretchSpansOverChange(doc, change) {
6323
- if (change.full) return null;
6324
- var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6325
- var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6326
- if (!oldFirst && !oldLast) return null;
6327
-
6328
- var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6329
- // Get the spans that 'stick out' on both sides
6330
- var first = markedSpansBefore(oldFirst, startCh, isInsert);
6331
- var last = markedSpansAfter(oldLast, endCh, isInsert);
6332
-
6333
- // Next, merge those two ends
6334
- var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6335
- if (first) {
6336
- // Fix up .to properties of first
6337
- for (var i = 0; i < first.length; ++i) {
6338
- var span = first[i];
6339
- if (span.to == null) {
6340
- var found = getMarkedSpanFor(last, span.marker);
6341
- if (!found) span.to = startCh;
6342
- else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6343
- }
6344
- }
6345
- }
6346
- if (last) {
6347
- // Fix up .from in last (or move them into first in case of sameLine)
6348
- for (var i = 0; i < last.length; ++i) {
6349
- var span = last[i];
6350
- if (span.to != null) span.to += offset;
6351
- if (span.from == null) {
6352
- var found = getMarkedSpanFor(first, span.marker);
6353
- if (!found) {
6354
- span.from = offset;
6355
- if (sameLine) (first || (first = [])).push(span);
6356
- }
6357
- } else {
6358
- span.from += offset;
6359
- if (sameLine) (first || (first = [])).push(span);
6360
- }
6361
- }
6362
- }
6363
- // Make sure we didn't create any zero-length spans
6364
- if (first) first = clearEmptySpans(first);
6365
- if (last && last != first) last = clearEmptySpans(last);
6366
-
6367
- var newMarkers = [first];
6368
- if (!sameLine) {
6369
- // Fill gap with whole-line-spans
6370
- var gap = change.text.length - 2, gapMarkers;
6371
- if (gap > 0 && first)
6372
- for (var i = 0; i < first.length; ++i)
6373
- if (first[i].to == null)
6374
- (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6375
- for (var i = 0; i < gap; ++i)
6376
- newMarkers.push(gapMarkers);
6377
- newMarkers.push(last);
6378
- }
6379
- return newMarkers;
6380
- }
6381
-
6382
- // Remove spans that are empty and don't have a clearWhenEmpty
6383
- // option of false.
6384
- function clearEmptySpans(spans) {
6385
- for (var i = 0; i < spans.length; ++i) {
6386
- var span = spans[i];
6387
- if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6388
- spans.splice(i--, 1);
6389
- }
6390
- if (!spans.length) return null;
6391
- return spans;
6392
- }
6393
-
6394
- // Used for un/re-doing changes from the history. Combines the
6395
- // result of computing the existing spans with the set of spans that
6396
- // existed in the history (so that deleting around a span and then
6397
- // undoing brings back the span).
6398
- function mergeOldSpans(doc, change) {
6399
- var old = getOldSpans(doc, change);
6400
- var stretched = stretchSpansOverChange(doc, change);
6401
- if (!old) return stretched;
6402
- if (!stretched) return old;
6403
-
6404
- for (var i = 0; i < old.length; ++i) {
6405
- var oldCur = old[i], stretchCur = stretched[i];
6406
- if (oldCur && stretchCur) {
6407
- spans: for (var j = 0; j < stretchCur.length; ++j) {
6408
- var span = stretchCur[j];
6409
- for (var k = 0; k < oldCur.length; ++k)
6410
- if (oldCur[k].marker == span.marker) continue spans;
6411
- oldCur.push(span);
6412
- }
6413
- } else if (stretchCur) {
6414
- old[i] = stretchCur;
6415
- }
6416
- }
6417
- return old;
6418
- }
6419
-
6420
- // Used to 'clip' out readOnly ranges when making a change.
6421
- function removeReadOnlyRanges(doc, from, to) {
6422
- var markers = null;
6423
- doc.iter(from.line, to.line + 1, function(line) {
6424
- if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6425
- var mark = line.markedSpans[i].marker;
6426
- if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6427
- (markers || (markers = [])).push(mark);
6428
- }
6429
- });
6430
- if (!markers) return null;
6431
- var parts = [{from: from, to: to}];
6432
- for (var i = 0; i < markers.length; ++i) {
6433
- var mk = markers[i], m = mk.find(0);
6434
- for (var j = 0; j < parts.length; ++j) {
6435
- var p = parts[j];
6436
- if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6437
- var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6438
- if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6439
- newParts.push({from: p.from, to: m.from});
6440
- if (dto > 0 || !mk.inclusiveRight && !dto)
6441
- newParts.push({from: m.to, to: p.to});
6442
- parts.splice.apply(parts, newParts);
6443
- j += newParts.length - 1;
6444
- }
6445
- }
6446
- return parts;
6447
- }
6448
-
6449
- // Connect or disconnect spans from a line.
6450
- function detachMarkedSpans(line) {
6451
- var spans = line.markedSpans;
6452
- if (!spans) return;
6453
- for (var i = 0; i < spans.length; ++i)
6454
- spans[i].marker.detachLine(line);
6455
- line.markedSpans = null;
6456
- }
6457
- function attachMarkedSpans(line, spans) {
6458
- if (!spans) return;
6459
- for (var i = 0; i < spans.length; ++i)
6460
- spans[i].marker.attachLine(line);
6461
- line.markedSpans = spans;
6462
- }
6463
-
6464
- // Helpers used when computing which overlapping collapsed span
6465
- // counts as the larger one.
6466
- function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6467
- function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6468
-
6469
- // Returns a number indicating which of two overlapping collapsed
6470
- // spans is larger (and thus includes the other). Falls back to
6471
- // comparing ids when the spans cover exactly the same range.
6472
- function compareCollapsedMarkers(a, b) {
6473
- var lenDiff = a.lines.length - b.lines.length;
6474
- if (lenDiff != 0) return lenDiff;
6475
- var aPos = a.find(), bPos = b.find();
6476
- var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6477
- if (fromCmp) return -fromCmp;
6478
- var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6479
- if (toCmp) return toCmp;
6480
- return b.id - a.id;
6481
- }
6482
-
6483
- // Find out whether a line ends or starts in a collapsed span. If
6484
- // so, return the marker for that span.
6485
- function collapsedSpanAtSide(line, start) {
6486
- var sps = sawCollapsedSpans && line.markedSpans, found;
6487
- if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6488
- sp = sps[i];
6489
- if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6490
- (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6491
- found = sp.marker;
6492
- }
6493
- return found;
6494
- }
6495
- function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6496
- function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6497
-
6498
- // Test whether there exists a collapsed span that partially
6499
- // overlaps (covers the start or end, but not both) of a new span.
6500
- // Such overlap is not allowed.
6501
- function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6502
- var line = getLine(doc, lineNo);
6503
- var sps = sawCollapsedSpans && line.markedSpans;
6504
- if (sps) for (var i = 0; i < sps.length; ++i) {
6505
- var sp = sps[i];
6506
- if (!sp.marker.collapsed) continue;
6507
- var found = sp.marker.find(0);
6508
- var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6509
- var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6510
- if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6511
- if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6512
- fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6513
- return true;
6514
- }
6515
- }
6516
-
6517
- // A visual line is a line as drawn on the screen. Folding, for
6518
- // example, can cause multiple logical lines to appear on the same
6519
- // visual line. This finds the start of the visual line that the
6520
- // given line is part of (usually that is the line itself).
6521
- function visualLine(line) {
6522
- var merged;
6523
- while (merged = collapsedSpanAtStart(line))
6524
- line = merged.find(-1, true).line;
6525
- return line;
6526
- }
6527
-
6528
- // Returns an array of logical lines that continue the visual line
6529
- // started by the argument, or undefined if there are no such lines.
6530
- function visualLineContinued(line) {
6531
- var merged, lines;
6532
- while (merged = collapsedSpanAtEnd(line)) {
6533
- line = merged.find(1, true).line;
6534
- (lines || (lines = [])).push(line);
6535
- }
6536
- return lines;
6537
- }
6538
-
6539
- // Get the line number of the start of the visual line that the
6540
- // given line number is part of.
6541
- function visualLineNo(doc, lineN) {
6542
- var line = getLine(doc, lineN), vis = visualLine(line);
6543
- if (line == vis) return lineN;
6544
- return lineNo(vis);
6545
- }
6546
- // Get the line number of the start of the next visual line after
6547
- // the given line.
6548
- function visualLineEndNo(doc, lineN) {
6549
- if (lineN > doc.lastLine()) return lineN;
6550
- var line = getLine(doc, lineN), merged;
6551
- if (!lineIsHidden(doc, line)) return lineN;
6552
- while (merged = collapsedSpanAtEnd(line))
6553
- line = merged.find(1, true).line;
6554
- return lineNo(line) + 1;
6555
- }
6556
-
6557
- // Compute whether a line is hidden. Lines count as hidden when they
6558
- // are part of a visual line that starts with another line, or when
6559
- // they are entirely covered by collapsed, non-widget span.
6560
- function lineIsHidden(doc, line) {
6561
- var sps = sawCollapsedSpans && line.markedSpans;
6562
- if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6563
- sp = sps[i];
6564
- if (!sp.marker.collapsed) continue;
6565
- if (sp.from == null) return true;
6566
- if (sp.marker.widgetNode) continue;
6567
- if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6568
- return true;
6569
- }
6570
- }
6571
- function lineIsHiddenInner(doc, line, span) {
6572
- if (span.to == null) {
6573
- var end = span.marker.find(1, true);
6574
- return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6575
- }
6576
- if (span.marker.inclusiveRight && span.to == line.text.length)
6577
- return true;
6578
- for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6579
- sp = line.markedSpans[i];
6580
- if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6581
- (sp.to == null || sp.to != span.from) &&
6582
- (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6583
- lineIsHiddenInner(doc, line, sp)) return true;
6584
- }
6585
- }
6586
-
6587
- // LINE WIDGETS
6588
-
6589
- // Line widgets are block elements displayed above or below a line.
6590
-
6591
- var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6592
- if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6593
- this[opt] = options[opt];
6594
- this.doc = doc;
6595
- this.node = node;
6596
- };
6597
- eventMixin(LineWidget);
6598
-
6599
- function adjustScrollWhenAboveVisible(cm, line, diff) {
6600
- if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6601
- addToScrollPos(cm, null, diff);
6602
- }
6603
-
6604
- LineWidget.prototype.clear = function() {
6605
- var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6606
- if (no == null || !ws) return;
6607
- for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6608
- if (!ws.length) line.widgets = null;
6609
- var height = widgetHeight(this);
6610
- updateLineHeight(line, Math.max(0, line.height - height));
6611
- if (cm) runInOp(cm, function() {
6612
- adjustScrollWhenAboveVisible(cm, line, -height);
6613
- regLineChange(cm, no, "widget");
6614
- });
6615
- };
6616
- LineWidget.prototype.changed = function() {
6617
- var oldH = this.height, cm = this.doc.cm, line = this.line;
6618
- this.height = null;
6619
- var diff = widgetHeight(this) - oldH;
6620
- if (!diff) return;
6621
- updateLineHeight(line, line.height + diff);
6622
- if (cm) runInOp(cm, function() {
6623
- cm.curOp.forceUpdate = true;
6624
- adjustScrollWhenAboveVisible(cm, line, diff);
6625
- });
6626
- };
6627
-
6628
- function widgetHeight(widget) {
6629
- if (widget.height != null) return widget.height;
6630
- var cm = widget.doc.cm;
6631
- if (!cm) return 0;
6632
- if (!contains(document.body, widget.node)) {
6633
- var parentStyle = "position: relative;";
6634
- if (widget.coverGutter)
6635
- parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6636
- if (widget.noHScroll)
6637
- parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6638
- removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6639
- }
6640
- return widget.height = widget.node.offsetHeight;
6641
- }
6642
-
6643
- function addLineWidget(doc, handle, node, options) {
6644
- var widget = new LineWidget(doc, node, options);
6645
- var cm = doc.cm;
6646
- if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6647
- changeLine(doc, handle, "widget", function(line) {
6648
- var widgets = line.widgets || (line.widgets = []);
6649
- if (widget.insertAt == null) widgets.push(widget);
6650
- else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6651
- widget.line = line;
6652
- if (cm && !lineIsHidden(doc, line)) {
6653
- var aboveVisible = heightAtLine(line) < doc.scrollTop;
6654
- updateLineHeight(line, line.height + widgetHeight(widget));
6655
- if (aboveVisible) addToScrollPos(cm, null, widget.height);
6656
- cm.curOp.forceUpdate = true;
6657
- }
6658
- return true;
6659
- });
6660
- return widget;
6661
- }
6662
-
6663
- // LINE DATA STRUCTURE
6664
-
6665
- // Line objects. These hold state related to a line, including
6666
- // highlighting info (the styles array).
6667
- var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6668
- this.text = text;
6669
- attachMarkedSpans(this, markedSpans);
6670
- this.height = estimateHeight ? estimateHeight(this) : 1;
6671
- };
6672
- eventMixin(Line);
6673
- Line.prototype.lineNo = function() { return lineNo(this); };
6674
-
6675
- // Change the content (text, markers) of a line. Automatically
6676
- // invalidates cached information and tries to re-estimate the
6677
- // line's height.
6678
- function updateLine(line, text, markedSpans, estimateHeight) {
6679
- line.text = text;
6680
- if (line.stateAfter) line.stateAfter = null;
6681
- if (line.styles) line.styles = null;
6682
- if (line.order != null) line.order = null;
6683
- detachMarkedSpans(line);
6684
- attachMarkedSpans(line, markedSpans);
6685
- var estHeight = estimateHeight ? estimateHeight(line) : 1;
6686
- if (estHeight != line.height) updateLineHeight(line, estHeight);
6687
- }
6688
-
6689
- // Detach a line from the document tree and its markers.
6690
- function cleanUpLine(line) {
6691
- line.parent = null;
6692
- detachMarkedSpans(line);
6693
- }
6694
-
6695
- function extractLineClasses(type, output) {
6696
- if (type) for (;;) {
6697
- var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6698
- if (!lineClass) break;
6699
- type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6700
- var prop = lineClass[1] ? "bgClass" : "textClass";
6701
- if (output[prop] == null)
6702
- output[prop] = lineClass[2];
6703
- else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6704
- output[prop] += " " + lineClass[2];
6705
- }
6706
- return type;
6707
- }
6708
-
6709
- function callBlankLine(mode, state) {
6710
- if (mode.blankLine) return mode.blankLine(state);
6711
- if (!mode.innerMode) return;
6712
- var inner = CodeMirror.innerMode(mode, state);
6713
- if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6714
- }
6715
-
6716
- function readToken(mode, stream, state, inner) {
6717
- for (var i = 0; i < 10; i++) {
6718
- if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6719
- var style = mode.token(stream, state);
6720
- if (stream.pos > stream.start) return style;
6721
- }
6722
- throw new Error("Mode " + mode.name + " failed to advance stream.");
6723
- }
6724
-
6725
- // Utility for getTokenAt and getLineTokens
6726
- function takeToken(cm, pos, precise, asArray) {
6727
- function getObj(copy) {
6728
- return {start: stream.start, end: stream.pos,
6729
- string: stream.current(),
6730
- type: style || null,
6731
- state: copy ? copyState(doc.mode, state) : state};
6732
- }
6733
-
6734
- var doc = cm.doc, mode = doc.mode, style;
6735
- pos = clipPos(doc, pos);
6736
- var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6737
- var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6738
- if (asArray) tokens = [];
6739
- while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6740
- stream.start = stream.pos;
6741
- style = readToken(mode, stream, state);
6742
- if (asArray) tokens.push(getObj(true));
6743
- }
6744
- return asArray ? tokens : getObj();
6745
- }
6746
-
6747
- // Run the given mode's parser over a line, calling f for each token.
6748
- function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6749
- var flattenSpans = mode.flattenSpans;
6750
- if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6751
- var curStart = 0, curStyle = null;
6752
- var stream = new StringStream(text, cm.options.tabSize), style;
6753
- var inner = cm.options.addModeClass && [null];
6754
- if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6755
- while (!stream.eol()) {
6756
- if (stream.pos > cm.options.maxHighlightLength) {
6757
- flattenSpans = false;
6758
- if (forceToEnd) processLine(cm, text, state, stream.pos);
6759
- stream.pos = text.length;
6760
- style = null;
6761
- } else {
6762
- style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6763
- }
6764
- if (inner) {
6765
- var mName = inner[0].name;
6766
- if (mName) style = "m-" + (style ? mName + " " + style : mName);
6767
- }
6768
- if (!flattenSpans || curStyle != style) {
6769
- while (curStart < stream.start) {
6770
- curStart = Math.min(stream.start, curStart + 50000);
6771
- f(curStart, curStyle);
6772
- }
6773
- curStyle = style;
6774
- }
6775
- stream.start = stream.pos;
6776
- }
6777
- while (curStart < stream.pos) {
6778
- // Webkit seems to refuse to render text nodes longer than 57444 characters
6779
- var pos = Math.min(stream.pos, curStart + 50000);
6780
- f(pos, curStyle);
6781
- curStart = pos;
6782
- }
6783
- }
6784
-
6785
- // Compute a style array (an array starting with a mode generation
6786
- // -- for invalidation -- followed by pairs of end positions and
6787
- // style strings), which is used to highlight the tokens on the
6788
- // line.
6789
- function highlightLine(cm, line, state, forceToEnd) {
6790
- // A styles array always starts with a number identifying the
6791
- // mode/overlays that it is based on (for easy invalidation).
6792
- var st = [cm.state.modeGen], lineClasses = {};
6793
- // Compute the base array of styles
6794
- runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6795
- st.push(end, style);
6796
- }, lineClasses, forceToEnd);
6797
-
6798
- // Run overlays, adjust style array.
6799
- for (var o = 0; o < cm.state.overlays.length; ++o) {
6800
- var overlay = cm.state.overlays[o], i = 1, at = 0;
6801
- runMode(cm, line.text, overlay.mode, true, function(end, style) {
6802
- var start = i;
6803
- // Ensure there's a token end at the current position, and that i points at it
6804
- while (at < end) {
6805
- var i_end = st[i];
6806
- if (i_end > end)
6807
- st.splice(i, 1, end, st[i+1], i_end);
6808
- i += 2;
6809
- at = Math.min(end, i_end);
6810
- }
6811
- if (!style) return;
6812
- if (overlay.opaque) {
6813
- st.splice(start, i - start, end, "cm-overlay " + style);
6814
- i = start + 2;
6815
- } else {
6816
- for (; start < i; start += 2) {
6817
- var cur = st[start+1];
6818
- st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6819
- }
6820
- }
6821
- }, lineClasses);
6822
- }
6823
-
6824
- return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6825
- }
6826
-
6827
- function getLineStyles(cm, line, updateFrontier) {
6828
- if (!line.styles || line.styles[0] != cm.state.modeGen) {
6829
- var state = getStateBefore(cm, lineNo(line));
6830
- var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6831
- line.stateAfter = state;
6832
- line.styles = result.styles;
6833
- if (result.classes) line.styleClasses = result.classes;
6834
- else if (line.styleClasses) line.styleClasses = null;
6835
- if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6836
- }
6837
- return line.styles;
6838
- }
6839
-
6840
- // Lightweight form of highlight -- proceed over this line and
6841
- // update state, but don't save a style array. Used for lines that
6842
- // aren't currently visible.
6843
- function processLine(cm, text, state, startAt) {
6844
- var mode = cm.doc.mode;
6845
- var stream = new StringStream(text, cm.options.tabSize);
6846
- stream.start = stream.pos = startAt || 0;
6847
- if (text == "") callBlankLine(mode, state);
6848
- while (!stream.eol()) {
6849
- readToken(mode, stream, state);
6850
- stream.start = stream.pos;
6851
- }
6852
- }
6853
-
6854
- // Convert a style as returned by a mode (either null, or a string
6855
- // containing one or more styles) to a CSS style. This is cached,
6856
- // and also looks for line-wide styles.
6857
- var styleToClassCache = {}, styleToClassCacheWithMode = {};
6858
- function interpretTokenStyle(style, options) {
6859
- if (!style || /^\s*$/.test(style)) return null;
6860
- var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6861
- return cache[style] ||
6862
- (cache[style] = style.replace(/\S+/g, "cm-$&"));
6863
- }
6864
-
6865
- // Render the DOM representation of the text of a line. Also builds
6866
- // up a 'line map', which points at the DOM nodes that represent
6867
- // specific stretches of text, and is used by the measuring code.
6868
- // The returned object contains the DOM node, this map, and
6869
- // information about line-wide styles that were set by the mode.
6870
- function buildLineContent(cm, lineView) {
6871
- // The padding-right forces the element to have a 'border', which
6872
- // is needed on Webkit to be able to get line-level bounding
6873
- // rectangles for it (in measureChar).
6874
- var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6875
- var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6876
- col: 0, pos: 0, cm: cm,
6877
- splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6878
- lineView.measure = {};
6879
-
6880
- // Iterate over the logical lines that make up this visual line.
6881
- for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6882
- var line = i ? lineView.rest[i - 1] : lineView.line, order;
6883
- builder.pos = 0;
6884
- builder.addToken = buildToken;
6885
- // Optionally wire in some hacks into the token-rendering
6886
- // algorithm, to deal with browser quirks.
6887
- if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6888
- builder.addToken = buildTokenBadBidi(builder.addToken, order);
6889
- builder.map = [];
6890
- var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6891
- insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6892
- if (line.styleClasses) {
6893
- if (line.styleClasses.bgClass)
6894
- builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6895
- if (line.styleClasses.textClass)
6896
- builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6897
- }
6898
-
6899
- // Ensure at least a single node is present, for measuring.
6900
- if (builder.map.length == 0)
6901
- builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6902
-
6903
- // Store the map and a cache object for the current logical line
6904
- if (i == 0) {
6905
- lineView.measure.map = builder.map;
6906
- lineView.measure.cache = {};
6907
- } else {
6908
- (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6909
- (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6910
- }
6911
- }
6912
-
6913
- // See issue #2901
6914
- if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6915
- builder.content.className = "cm-tab-wrap-hack";
6916
-
6917
- signal(cm, "renderLine", cm, lineView.line, builder.pre);
6918
- if (builder.pre.className)
6919
- builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6920
-
6921
- return builder;
6922
- }
6923
-
6924
- function defaultSpecialCharPlaceholder(ch) {
6925
- var token = elt("span", "\u2022", "cm-invalidchar");
6926
- token.title = "\\u" + ch.charCodeAt(0).toString(16);
6927
- token.setAttribute("aria-label", token.title);
6928
- return token;
6929
- }
6930
-
6931
- // Build up the DOM representation for a single token, and add it to
6932
- // the line map. Takes care to render special characters separately.
6933
- function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6934
- if (!text) return;
6935
- var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6936
- var special = builder.cm.state.specialChars, mustWrap = false;
6937
- if (!special.test(text)) {
6938
- builder.col += text.length;
6939
- var content = document.createTextNode(displayText);
6940
- builder.map.push(builder.pos, builder.pos + text.length, content);
6941
- if (ie && ie_version < 9) mustWrap = true;
6942
- builder.pos += text.length;
6943
- } else {
6944
- var content = document.createDocumentFragment(), pos = 0;
6945
- while (true) {
6946
- special.lastIndex = pos;
6947
- var m = special.exec(text);
6948
- var skipped = m ? m.index - pos : text.length - pos;
6949
- if (skipped) {
6950
- var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6951
- if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6952
- else content.appendChild(txt);
6953
- builder.map.push(builder.pos, builder.pos + skipped, txt);
6954
- builder.col += skipped;
6955
- builder.pos += skipped;
6956
- }
6957
- if (!m) break;
6958
- pos += skipped + 1;
6959
- if (m[0] == "\t") {
6960
- var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
6961
- var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
6962
- txt.setAttribute("role", "presentation");
6963
- txt.setAttribute("cm-text", "\t");
6964
- builder.col += tabWidth;
6965
- } else if (m[0] == "\r" || m[0] == "\n") {
6966
- var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
6967
- txt.setAttribute("cm-text", m[0]);
6968
- builder.col += 1;
6969
- } else {
6970
- var txt = builder.cm.options.specialCharPlaceholder(m[0]);
6971
- txt.setAttribute("cm-text", m[0]);
6972
- if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6973
- else content.appendChild(txt);
6974
- builder.col += 1;
6975
- }
6976
- builder.map.push(builder.pos, builder.pos + 1, txt);
6977
- builder.pos++;
6978
- }
6979
- }
6980
- if (style || startStyle || endStyle || mustWrap || css) {
6981
- var fullStyle = style || "";
6982
- if (startStyle) fullStyle += startStyle;
6983
- if (endStyle) fullStyle += endStyle;
6984
- var token = elt("span", [content], fullStyle, css);
6985
- if (title) token.title = title;
6986
- return builder.content.appendChild(token);
6987
- }
6988
- builder.content.appendChild(content);
6989
- }
6990
-
6991
- function splitSpaces(old) {
6992
- var out = " ";
6993
- for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
6994
- out += " ";
6995
- return out;
6996
- }
6997
-
6998
- // Work around nonsense dimensions being reported for stretches of
6999
- // right-to-left text.
7000
- function buildTokenBadBidi(inner, order) {
7001
- return function(builder, text, style, startStyle, endStyle, title, css) {
7002
- style = style ? style + " cm-force-border" : "cm-force-border";
7003
- var start = builder.pos, end = start + text.length;
7004
- for (;;) {
7005
- // Find the part that overlaps with the start of this text
7006
- for (var i = 0; i < order.length; i++) {
7007
- var part = order[i];
7008
- if (part.to > start && part.from <= start) break;
7009
- }
7010
- if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7011
- inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7012
- startStyle = null;
7013
- text = text.slice(part.to - start);
7014
- start = part.to;
7015
- }
7016
- };
7017
- }
7018
-
7019
- function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7020
- var widget = !ignoreWidget && marker.widgetNode;
7021
- if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7022
- if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7023
- if (!widget)
7024
- widget = builder.content.appendChild(document.createElement("span"));
7025
- widget.setAttribute("cm-marker", marker.id);
7026
- }
7027
- if (widget) {
7028
- builder.cm.display.input.setUneditable(widget);
7029
- builder.content.appendChild(widget);
7030
- }
7031
- builder.pos += size;
7032
- }
7033
-
7034
- // Outputs a number of spans to make up a line, taking highlighting
7035
- // and marked text into account.
7036
- function insertLineContent(line, builder, styles) {
7037
- var spans = line.markedSpans, allText = line.text, at = 0;
7038
- if (!spans) {
7039
- for (var i = 1; i < styles.length; i+=2)
7040
- builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7041
- return;
7042
- }
7043
-
7044
- var len = allText.length, pos = 0, i = 1, text = "", style, css;
7045
- var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7046
- for (;;) {
7047
- if (nextChange == pos) { // Update current marker set
7048
- spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7049
- collapsed = null; nextChange = Infinity;
7050
- var foundBookmarks = [];
7051
- for (var j = 0; j < spans.length; ++j) {
7052
- var sp = spans[j], m = sp.marker;
7053
- if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7054
- foundBookmarks.push(m);
7055
- } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7056
- if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7057
- nextChange = sp.to;
7058
- spanEndStyle = "";
7059
- }
7060
- if (m.className) spanStyle += " " + m.className;
7061
- if (m.css) css = m.css;
7062
- if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7063
- if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
7064
- if (m.title && !title) title = m.title;
7065
- if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7066
- collapsed = sp;
7067
- } else if (sp.from > pos && nextChange > sp.from) {
7068
- nextChange = sp.from;
7069
- }
7070
- }
7071
- if (collapsed && (collapsed.from || 0) == pos) {
7072
- buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7073
- collapsed.marker, collapsed.from == null);
7074
- if (collapsed.to == null) return;
7075
- if (collapsed.to == pos) collapsed = false;
7076
- }
7077
- if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7078
- buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7079
- }
7080
- if (pos >= len) break;
7081
-
7082
- var upto = Math.min(len, nextChange);
7083
- while (true) {
7084
- if (text) {
7085
- var end = pos + text.length;
7086
- if (!collapsed) {
7087
- var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7088
- builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7089
- spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7090
- }
7091
- if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7092
- pos = end;
7093
- spanStartStyle = "";
7094
- }
7095
- text = allText.slice(at, at = styles[i++]);
7096
- style = interpretTokenStyle(styles[i++], builder.cm.options);
7097
- }
7098
- }
7099
- }
7100
-
7101
- // DOCUMENT DATA STRUCTURE
7102
-
7103
- // By default, updates that start and end at the beginning of a line
7104
- // are treated specially, in order to make the association of line
7105
- // widgets and marker elements with the text behave more intuitive.
7106
- function isWholeLineUpdate(doc, change) {
7107
- return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7108
- (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7109
- }
7110
-
7111
- // Perform a change on the document data structure.
7112
- function updateDoc(doc, change, markedSpans, estimateHeight) {
7113
- function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7114
- function update(line, text, spans) {
7115
- updateLine(line, text, spans, estimateHeight);
7116
- signalLater(line, "change", line, change);
7117
- }
7118
- function linesFor(start, end) {
7119
- for (var i = start, result = []; i < end; ++i)
7120
- result.push(new Line(text[i], spansFor(i), estimateHeight));
7121
- return result;
7122
- }
7123
-
7124
- var from = change.from, to = change.to, text = change.text;
7125
- var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7126
- var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7127
-
7128
- // Adjust the line structure
7129
- if (change.full) {
7130
- doc.insert(0, linesFor(0, text.length));
7131
- doc.remove(text.length, doc.size - text.length);
7132
- } else if (isWholeLineUpdate(doc, change)) {
7133
- // This is a whole-line replace. Treated specially to make
7134
- // sure line objects move the way they are supposed to.
7135
- var added = linesFor(0, text.length - 1);
7136
- update(lastLine, lastLine.text, lastSpans);
7137
- if (nlines) doc.remove(from.line, nlines);
7138
- if (added.length) doc.insert(from.line, added);
7139
- } else if (firstLine == lastLine) {
7140
- if (text.length == 1) {
7141
- update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7142
- } else {
7143
- var added = linesFor(1, text.length - 1);
7144
- added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7145
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7146
- doc.insert(from.line + 1, added);
7147
- }
7148
- } else if (text.length == 1) {
7149
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7150
- doc.remove(from.line + 1, nlines);
7151
- } else {
7152
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7153
- update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7154
- var added = linesFor(1, text.length - 1);
7155
- if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7156
- doc.insert(from.line + 1, added);
7157
- }
7158
-
7159
- signalLater(doc, "change", doc, change);
7160
- }
7161
-
7162
- // The document is represented as a BTree consisting of leaves, with
7163
- // chunk of lines in them, and branches, with up to ten leaves or
7164
- // other branch nodes below them. The top node is always a branch
7165
- // node, and is the document object itself (meaning it has
7166
- // additional methods and properties).
7167
- //
7168
- // All nodes have parent links. The tree is used both to go from
7169
- // line numbers to line objects, and to go from objects to numbers.
7170
- // It also indexes by height, and is used to convert between height
7171
- // and line object, and to find the total height of the document.
7172
- //
7173
- // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7174
-
7175
- function LeafChunk(lines) {
7176
- this.lines = lines;
7177
- this.parent = null;
7178
- for (var i = 0, height = 0; i < lines.length; ++i) {
7179
- lines[i].parent = this;
7180
- height += lines[i].height;
7181
- }
7182
- this.height = height;
7183
- }
7184
-
7185
- LeafChunk.prototype = {
7186
- chunkSize: function() { return this.lines.length; },
7187
- // Remove the n lines at offset 'at'.
7188
- removeInner: function(at, n) {
7189
- for (var i = at, e = at + n; i < e; ++i) {
7190
- var line = this.lines[i];
7191
- this.height -= line.height;
7192
- cleanUpLine(line);
7193
- signalLater(line, "delete");
7194
- }
7195
- this.lines.splice(at, n);
7196
- },
7197
- // Helper used to collapse a small branch into a single leaf.
7198
- collapse: function(lines) {
7199
- lines.push.apply(lines, this.lines);
7200
- },
7201
- // Insert the given array of lines at offset 'at', count them as
7202
- // having the given height.
7203
- insertInner: function(at, lines, height) {
7204
- this.height += height;
7205
- this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7206
- for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7207
- },
7208
- // Used to iterate over a part of the tree.
7209
- iterN: function(at, n, op) {
7210
- for (var e = at + n; at < e; ++at)
7211
- if (op(this.lines[at])) return true;
7212
- }
7213
- };
7214
-
7215
- function BranchChunk(children) {
7216
- this.children = children;
7217
- var size = 0, height = 0;
7218
- for (var i = 0; i < children.length; ++i) {
7219
- var ch = children[i];
7220
- size += ch.chunkSize(); height += ch.height;
7221
- ch.parent = this;
7222
- }
7223
- this.size = size;
7224
- this.height = height;
7225
- this.parent = null;
7226
- }
7227
-
7228
- BranchChunk.prototype = {
7229
- chunkSize: function() { return this.size; },
7230
- removeInner: function(at, n) {
7231
- this.size -= n;
7232
- for (var i = 0; i < this.children.length; ++i) {
7233
- var child = this.children[i], sz = child.chunkSize();
7234
- if (at < sz) {
7235
- var rm = Math.min(n, sz - at), oldHeight = child.height;
7236
- child.removeInner(at, rm);
7237
- this.height -= oldHeight - child.height;
7238
- if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7239
- if ((n -= rm) == 0) break;
7240
- at = 0;
7241
- } else at -= sz;
7242
- }
7243
- // If the result is smaller than 25 lines, ensure that it is a
7244
- // single leaf node.
7245
- if (this.size - n < 25 &&
7246
- (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7247
- var lines = [];
7248
- this.collapse(lines);
7249
- this.children = [new LeafChunk(lines)];
7250
- this.children[0].parent = this;
7251
- }
7252
- },
7253
- collapse: function(lines) {
7254
- for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7255
- },
7256
- insertInner: function(at, lines, height) {
7257
- this.size += lines.length;
7258
- this.height += height;
7259
- for (var i = 0; i < this.children.length; ++i) {
7260
- var child = this.children[i], sz = child.chunkSize();
7261
- if (at <= sz) {
7262
- child.insertInner(at, lines, height);
7263
- if (child.lines && child.lines.length > 50) {
7264
- while (child.lines.length > 50) {
7265
- var spilled = child.lines.splice(child.lines.length - 25, 25);
7266
- var newleaf = new LeafChunk(spilled);
7267
- child.height -= newleaf.height;
7268
- this.children.splice(i + 1, 0, newleaf);
7269
- newleaf.parent = this;
7270
- }
7271
- this.maybeSpill();
7272
- }
7273
- break;
7274
- }
7275
- at -= sz;
7276
- }
7277
- },
7278
- // When a node has grown, check whether it should be split.
7279
- maybeSpill: function() {
7280
- if (this.children.length <= 10) return;
7281
- var me = this;
7282
- do {
7283
- var spilled = me.children.splice(me.children.length - 5, 5);
7284
- var sibling = new BranchChunk(spilled);
7285
- if (!me.parent) { // Become the parent node
7286
- var copy = new BranchChunk(me.children);
7287
- copy.parent = me;
7288
- me.children = [copy, sibling];
7289
- me = copy;
7290
- } else {
7291
- me.size -= sibling.size;
7292
- me.height -= sibling.height;
7293
- var myIndex = indexOf(me.parent.children, me);
7294
- me.parent.children.splice(myIndex + 1, 0, sibling);
7295
- }
7296
- sibling.parent = me.parent;
7297
- } while (me.children.length > 10);
7298
- me.parent.maybeSpill();
7299
- },
7300
- iterN: function(at, n, op) {
7301
- for (var i = 0; i < this.children.length; ++i) {
7302
- var child = this.children[i], sz = child.chunkSize();
7303
- if (at < sz) {
7304
- var used = Math.min(n, sz - at);
7305
- if (child.iterN(at, used, op)) return true;
7306
- if ((n -= used) == 0) break;
7307
- at = 0;
7308
- } else at -= sz;
7309
- }
7310
- }
7311
- };
7312
-
7313
- var nextDocId = 0;
7314
- var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7315
- if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7316
- if (firstLine == null) firstLine = 0;
7317
-
7318
- BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7319
- this.first = firstLine;
7320
- this.scrollTop = this.scrollLeft = 0;
7321
- this.cantEdit = false;
7322
- this.cleanGeneration = 1;
7323
- this.frontier = firstLine;
7324
- var start = Pos(firstLine, 0);
7325
- this.sel = simpleSelection(start);
7326
- this.history = new History(null);
7327
- this.id = ++nextDocId;
7328
- this.modeOption = mode;
7329
- this.lineSep = lineSep;
7330
-
7331
- if (typeof text == "string") text = this.splitLines(text);
7332
- updateDoc(this, {from: start, to: start, text: text});
7333
- setSelection(this, simpleSelection(start), sel_dontScroll);
7334
- };
7335
-
7336
- Doc.prototype = createObj(BranchChunk.prototype, {
7337
- constructor: Doc,
7338
- // Iterate over the document. Supports two forms -- with only one
7339
- // argument, it calls that for each line in the document. With
7340
- // three, it iterates over the range given by the first two (with
7341
- // the second being non-inclusive).
7342
- iter: function(from, to, op) {
7343
- if (op) this.iterN(from - this.first, to - from, op);
7344
- else this.iterN(this.first, this.first + this.size, from);
7345
- },
7346
-
7347
- // Non-public interface for adding and removing lines.
7348
- insert: function(at, lines) {
7349
- var height = 0;
7350
- for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7351
- this.insertInner(at - this.first, lines, height);
7352
- },
7353
- remove: function(at, n) { this.removeInner(at - this.first, n); },
7354
-
7355
- // From here, the methods are part of the public interface. Most
7356
- // are also available from CodeMirror (editor) instances.
7357
-
7358
- getValue: function(lineSep) {
7359
- var lines = getLines(this, this.first, this.first + this.size);
7360
- if (lineSep === false) return lines;
7361
- return lines.join(lineSep || this.lineSeparator());
7362
- },
7363
- setValue: docMethodOp(function(code) {
7364
- var top = Pos(this.first, 0), last = this.first + this.size - 1;
7365
- makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7366
- text: this.splitLines(code), origin: "setValue", full: true}, true);
7367
- setSelection(this, simpleSelection(top));
7368
- }),
7369
- replaceRange: function(code, from, to, origin) {
7370
- from = clipPos(this, from);
7371
- to = to ? clipPos(this, to) : from;
7372
- replaceRange(this, code, from, to, origin);
7373
- },
7374
- getRange: function(from, to, lineSep) {
7375
- var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7376
- if (lineSep === false) return lines;
7377
- return lines.join(lineSep || this.lineSeparator());
7378
- },
7379
-
7380
- getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7381
-
7382
- getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7383
- getLineNumber: function(line) {return lineNo(line);},
7384
-
7385
- getLineHandleVisualStart: function(line) {
7386
- if (typeof line == "number") line = getLine(this, line);
7387
- return visualLine(line);
7388
- },
7389
-
7390
- lineCount: function() {return this.size;},
7391
- firstLine: function() {return this.first;},
7392
- lastLine: function() {return this.first + this.size - 1;},
7393
-
7394
- clipPos: function(pos) {return clipPos(this, pos);},
7395
-
7396
- getCursor: function(start) {
7397
- var range = this.sel.primary(), pos;
7398
- if (start == null || start == "head") pos = range.head;
7399
- else if (start == "anchor") pos = range.anchor;
7400
- else if (start == "end" || start == "to" || start === false) pos = range.to();
7401
- else pos = range.from();
7402
- return pos;
7403
- },
7404
- listSelections: function() { return this.sel.ranges; },
7405
- somethingSelected: function() {return this.sel.somethingSelected();},
7406
-
7407
- setCursor: docMethodOp(function(line, ch, options) {
7408
- setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7409
- }),
7410
- setSelection: docMethodOp(function(anchor, head, options) {
7411
- setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7412
- }),
7413
- extendSelection: docMethodOp(function(head, other, options) {
7414
- extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7415
- }),
7416
- extendSelections: docMethodOp(function(heads, options) {
7417
- extendSelections(this, clipPosArray(this, heads, options));
7418
- }),
7419
- extendSelectionsBy: docMethodOp(function(f, options) {
7420
- extendSelections(this, map(this.sel.ranges, f), options);
7421
- }),
7422
- setSelections: docMethodOp(function(ranges, primary, options) {
7423
- if (!ranges.length) return;
7424
- for (var i = 0, out = []; i < ranges.length; i++)
7425
- out[i] = new Range(clipPos(this, ranges[i].anchor),
7426
- clipPos(this, ranges[i].head));
7427
- if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7428
- setSelection(this, normalizeSelection(out, primary), options);
7429
- }),
7430
- addSelection: docMethodOp(function(anchor, head, options) {
7431
- var ranges = this.sel.ranges.slice(0);
7432
- ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7433
- setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7434
- }),
7435
-
7436
- getSelection: function(lineSep) {
7437
- var ranges = this.sel.ranges, lines;
7438
- for (var i = 0; i < ranges.length; i++) {
7439
- var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7440
- lines = lines ? lines.concat(sel) : sel;
7441
- }
7442
- if (lineSep === false) return lines;
7443
- else return lines.join(lineSep || this.lineSeparator());
7444
- },
7445
- getSelections: function(lineSep) {
7446
- var parts = [], ranges = this.sel.ranges;
7447
- for (var i = 0; i < ranges.length; i++) {
7448
- var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7449
- if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7450
- parts[i] = sel;
7451
- }
7452
- return parts;
7453
- },
7454
- replaceSelection: function(code, collapse, origin) {
7455
- var dup = [];
7456
- for (var i = 0; i < this.sel.ranges.length; i++)
7457
- dup[i] = code;
7458
- this.replaceSelections(dup, collapse, origin || "+input");
7459
- },
7460
- replaceSelections: docMethodOp(function(code, collapse, origin) {
7461
- var changes = [], sel = this.sel;
7462
- for (var i = 0; i < sel.ranges.length; i++) {
7463
- var range = sel.ranges[i];
7464
- changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7465
- }
7466
- var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7467
- for (var i = changes.length - 1; i >= 0; i--)
7468
- makeChange(this, changes[i]);
7469
- if (newSel) setSelectionReplaceHistory(this, newSel);
7470
- else if (this.cm) ensureCursorVisible(this.cm);
7471
- }),
7472
- undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7473
- redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7474
- undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7475
- redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7476
-
7477
- setExtending: function(val) {this.extend = val;},
7478
- getExtending: function() {return this.extend;},
7479
-
7480
- historySize: function() {
7481
- var hist = this.history, done = 0, undone = 0;
7482
- for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7483
- for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7484
- return {undo: done, redo: undone};
7485
- },
7486
- clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7487
-
7488
- markClean: function() {
7489
- this.cleanGeneration = this.changeGeneration(true);
7490
- },
7491
- changeGeneration: function(forceSplit) {
7492
- if (forceSplit)
7493
- this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7494
- return this.history.generation;
7495
- },
7496
- isClean: function (gen) {
7497
- return this.history.generation == (gen || this.cleanGeneration);
7498
- },
7499
-
7500
- getHistory: function() {
7501
- return {done: copyHistoryArray(this.history.done),
7502
- undone: copyHistoryArray(this.history.undone)};
7503
- },
7504
- setHistory: function(histData) {
7505
- var hist = this.history = new History(this.history.maxGeneration);
7506
- hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7507
- hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7508
- },
7509
-
7510
- addLineClass: docMethodOp(function(handle, where, cls) {
7511
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7512
- var prop = where == "text" ? "textClass"
7513
- : where == "background" ? "bgClass"
7514
- : where == "gutter" ? "gutterClass" : "wrapClass";
7515
- if (!line[prop]) line[prop] = cls;
7516
- else if (classTest(cls).test(line[prop])) return false;
7517
- else line[prop] += " " + cls;
7518
- return true;
7519
- });
7520
- }),
7521
- removeLineClass: docMethodOp(function(handle, where, cls) {
7522
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7523
- var prop = where == "text" ? "textClass"
7524
- : where == "background" ? "bgClass"
7525
- : where == "gutter" ? "gutterClass" : "wrapClass";
7526
- var cur = line[prop];
7527
- if (!cur) return false;
7528
- else if (cls == null) line[prop] = null;
7529
- else {
7530
- var found = cur.match(classTest(cls));
7531
- if (!found) return false;
7532
- var end = found.index + found[0].length;
7533
- line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7534
- }
7535
- return true;
7536
- });
7537
- }),
7538
-
7539
- addLineWidget: docMethodOp(function(handle, node, options) {
7540
- return addLineWidget(this, handle, node, options);
7541
- }),
7542
- removeLineWidget: function(widget) { widget.clear(); },
7543
-
7544
- markText: function(from, to, options) {
7545
- return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
7546
- },
7547
- setBookmark: function(pos, options) {
7548
- var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7549
- insertLeft: options && options.insertLeft,
7550
- clearWhenEmpty: false, shared: options && options.shared,
7551
- handleMouseEvents: options && options.handleMouseEvents};
7552
- pos = clipPos(this, pos);
7553
- return markText(this, pos, pos, realOpts, "bookmark");
7554
- },
7555
- findMarksAt: function(pos) {
7556
- pos = clipPos(this, pos);
7557
- var markers = [], spans = getLine(this, pos.line).markedSpans;
7558
- if (spans) for (var i = 0; i < spans.length; ++i) {
7559
- var span = spans[i];
7560
- if ((span.from == null || span.from <= pos.ch) &&
7561
- (span.to == null || span.to >= pos.ch))
7562
- markers.push(span.marker.parent || span.marker);
7563
- }
7564
- return markers;
7565
- },
7566
- findMarks: function(from, to, filter) {
7567
- from = clipPos(this, from); to = clipPos(this, to);
7568
- var found = [], lineNo = from.line;
7569
- this.iter(from.line, to.line + 1, function(line) {
7570
- var spans = line.markedSpans;
7571
- if (spans) for (var i = 0; i < spans.length; i++) {
7572
- var span = spans[i];
7573
- if (!(lineNo == from.line && from.ch > span.to ||
7574
- span.from == null && lineNo != from.line||
7575
- lineNo == to.line && span.from > to.ch) &&
7576
- (!filter || filter(span.marker)))
7577
- found.push(span.marker.parent || span.marker);
7578
- }
7579
- ++lineNo;
7580
- });
7581
- return found;
7582
- },
7583
- getAllMarks: function() {
7584
- var markers = [];
7585
- this.iter(function(line) {
7586
- var sps = line.markedSpans;
7587
- if (sps) for (var i = 0; i < sps.length; ++i)
7588
- if (sps[i].from != null) markers.push(sps[i].marker);
7589
- });
7590
- return markers;
7591
- },
7592
-
7593
- posFromIndex: function(off) {
7594
- var ch, lineNo = this.first;
7595
- this.iter(function(line) {
7596
- var sz = line.text.length + 1;
7597
- if (sz > off) { ch = off; return true; }
7598
- off -= sz;
7599
- ++lineNo;
7600
- });
7601
- return clipPos(this, Pos(lineNo, ch));
7602
- },
7603
- indexFromPos: function (coords) {
7604
- coords = clipPos(this, coords);
7605
- var index = coords.ch;
7606
- if (coords.line < this.first || coords.ch < 0) return 0;
7607
- this.iter(this.first, coords.line, function (line) {
7608
- index += line.text.length + 1;
7609
- });
7610
- return index;
7611
- },
7612
-
7613
- copy: function(copyHistory) {
7614
- var doc = new Doc(getLines(this, this.first, this.first + this.size),
7615
- this.modeOption, this.first, this.lineSep);
7616
- doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7617
- doc.sel = this.sel;
7618
- doc.extend = false;
7619
- if (copyHistory) {
7620
- doc.history.undoDepth = this.history.undoDepth;
7621
- doc.setHistory(this.getHistory());
7622
- }
7623
- return doc;
7624
- },
7625
-
7626
- linkedDoc: function(options) {
7627
- if (!options) options = {};
7628
- var from = this.first, to = this.first + this.size;
7629
- if (options.from != null && options.from > from) from = options.from;
7630
- if (options.to != null && options.to < to) to = options.to;
7631
- var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7632
- if (options.sharedHist) copy.history = this.history;
7633
- (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7634
- copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7635
- copySharedMarkers(copy, findSharedMarkers(this));
7636
- return copy;
7637
- },
7638
- unlinkDoc: function(other) {
7639
- if (other instanceof CodeMirror) other = other.doc;
7640
- if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7641
- var link = this.linked[i];
7642
- if (link.doc != other) continue;
7643
- this.linked.splice(i, 1);
7644
- other.unlinkDoc(this);
7645
- detachSharedMarkers(findSharedMarkers(this));
7646
- break;
7647
- }
7648
- // If the histories were shared, split them again
7649
- if (other.history == this.history) {
7650
- var splitIds = [other.id];
7651
- linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7652
- other.history = new History(null);
7653
- other.history.done = copyHistoryArray(this.history.done, splitIds);
7654
- other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7655
- }
7656
- },
7657
- iterLinkedDocs: function(f) {linkedDocs(this, f);},
7658
-
7659
- getMode: function() {return this.mode;},
7660
- getEditor: function() {return this.cm;},
7661
-
7662
- splitLines: function(str) {
7663
- if (this.lineSep) return str.split(this.lineSep);
7664
- return splitLinesAuto(str);
7665
- },
7666
- lineSeparator: function() { return this.lineSep || "\n"; }
7667
- });
7668
-
7669
- // Public alias.
7670
- Doc.prototype.eachLine = Doc.prototype.iter;
7671
-
7672
- // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7673
- var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7674
- for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7675
- CodeMirror.prototype[prop] = (function(method) {
7676
- return function() {return method.apply(this.doc, arguments);};
7677
- })(Doc.prototype[prop]);
7678
-
7679
- eventMixin(Doc);
7680
-
7681
- // Call f for all linked documents.
7682
- function linkedDocs(doc, f, sharedHistOnly) {
7683
- function propagate(doc, skip, sharedHist) {
7684
- if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7685
- var rel = doc.linked[i];
7686
- if (rel.doc == skip) continue;
7687
- var shared = sharedHist && rel.sharedHist;
7688
- if (sharedHistOnly && !shared) continue;
7689
- f(rel.doc, shared);
7690
- propagate(rel.doc, doc, shared);
7691
- }
7692
- }
7693
- propagate(doc, null, true);
7694
- }
7695
-
7696
- // Attach a document to an editor.
7697
- function attachDoc(cm, doc) {
7698
- if (doc.cm) throw new Error("This document is already in use.");
7699
- cm.doc = doc;
7700
- doc.cm = cm;
7701
- estimateLineHeights(cm);
7702
- loadMode(cm);
7703
- if (!cm.options.lineWrapping) findMaxLine(cm);
7704
- cm.options.mode = doc.modeOption;
7705
- regChange(cm);
7706
- }
7707
-
7708
- // LINE UTILITIES
7709
-
7710
- // Find the line object corresponding to the given line number.
7711
- function getLine(doc, n) {
7712
- n -= doc.first;
7713
- if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7714
- for (var chunk = doc; !chunk.lines;) {
7715
- for (var i = 0;; ++i) {
7716
- var child = chunk.children[i], sz = child.chunkSize();
7717
- if (n < sz) { chunk = child; break; }
7718
- n -= sz;
7719
- }
7720
- }
7721
- return chunk.lines[n];
7722
- }
7723
-
7724
- // Get the part of a document between two positions, as an array of
7725
- // strings.
7726
- function getBetween(doc, start, end) {
7727
- var out = [], n = start.line;
7728
- doc.iter(start.line, end.line + 1, function(line) {
7729
- var text = line.text;
7730
- if (n == end.line) text = text.slice(0, end.ch);
7731
- if (n == start.line) text = text.slice(start.ch);
7732
- out.push(text);
7733
- ++n;
7734
- });
7735
- return out;
7736
- }
7737
- // Get the lines between from and to, as array of strings.
7738
- function getLines(doc, from, to) {
7739
- var out = [];
7740
- doc.iter(from, to, function(line) { out.push(line.text); });
7741
- return out;
7742
- }
7743
-
7744
- // Update the height of a line, propagating the height change
7745
- // upwards to parent nodes.
7746
- function updateLineHeight(line, height) {
7747
- var diff = height - line.height;
7748
- if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7749
- }
7750
-
7751
- // Given a line object, find its line number by walking up through
7752
- // its parent links.
7753
- function lineNo(line) {
7754
- if (line.parent == null) return null;
7755
- var cur = line.parent, no = indexOf(cur.lines, line);
7756
- for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7757
- for (var i = 0;; ++i) {
7758
- if (chunk.children[i] == cur) break;
7759
- no += chunk.children[i].chunkSize();
7760
- }
7761
- }
7762
- return no + cur.first;
7763
- }
7764
-
7765
- // Find the line at the given vertical position, using the height
7766
- // information in the document tree.
7767
- function lineAtHeight(chunk, h) {
7768
- var n = chunk.first;
7769
- outer: do {
7770
- for (var i = 0; i < chunk.children.length; ++i) {
7771
- var child = chunk.children[i], ch = child.height;
7772
- if (h < ch) { chunk = child; continue outer; }
7773
- h -= ch;
7774
- n += child.chunkSize();
7775
- }
7776
- return n;
7777
- } while (!chunk.lines);
7778
- for (var i = 0; i < chunk.lines.length; ++i) {
7779
- var line = chunk.lines[i], lh = line.height;
7780
- if (h < lh) break;
7781
- h -= lh;
7782
- }
7783
- return n + i;
7784
- }
7785
-
7786
-
7787
- // Find the height above the given line.
7788
- function heightAtLine(lineObj) {
7789
- lineObj = visualLine(lineObj);
7790
-
7791
- var h = 0, chunk = lineObj.parent;
7792
- for (var i = 0; i < chunk.lines.length; ++i) {
7793
- var line = chunk.lines[i];
7794
- if (line == lineObj) break;
7795
- else h += line.height;
7796
- }
7797
- for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7798
- for (var i = 0; i < p.children.length; ++i) {
7799
- var cur = p.children[i];
7800
- if (cur == chunk) break;
7801
- else h += cur.height;
7802
- }
7803
- }
7804
- return h;
7805
- }
7806
-
7807
- // Get the bidi ordering for the given line (and cache it). Returns
7808
- // false for lines that are fully left-to-right, and an array of
7809
- // BidiSpan objects otherwise.
7810
- function getOrder(line) {
7811
- var order = line.order;
7812
- if (order == null) order = line.order = bidiOrdering(line.text);
7813
- return order;
7814
- }
7815
-
7816
- // HISTORY
7817
-
7818
- function History(startGen) {
7819
- // Arrays of change events and selections. Doing something adds an
7820
- // event to done and clears undo. Undoing moves events from done
7821
- // to undone, redoing moves them in the other direction.
7822
- this.done = []; this.undone = [];
7823
- this.undoDepth = Infinity;
7824
- // Used to track when changes can be merged into a single undo
7825
- // event
7826
- this.lastModTime = this.lastSelTime = 0;
7827
- this.lastOp = this.lastSelOp = null;
7828
- this.lastOrigin = this.lastSelOrigin = null;
7829
- // Used by the isClean() method
7830
- this.generation = this.maxGeneration = startGen || 1;
7831
- }
7832
-
7833
- // Create a history change event from an updateDoc-style change
7834
- // object.
7835
- function historyChangeFromChange(doc, change) {
7836
- var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7837
- attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7838
- linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7839
- return histChange;
7840
- }
7841
-
7842
- // Pop all selection events off the end of a history array. Stop at
7843
- // a change event.
7844
- function clearSelectionEvents(array) {
7845
- while (array.length) {
7846
- var last = lst(array);
7847
- if (last.ranges) array.pop();
7848
- else break;
7849
- }
7850
- }
7851
-
7852
- // Find the top change event in the history. Pop off selection
7853
- // events that are in the way.
7854
- function lastChangeEvent(hist, force) {
7855
- if (force) {
7856
- clearSelectionEvents(hist.done);
7857
- return lst(hist.done);
7858
- } else if (hist.done.length && !lst(hist.done).ranges) {
7859
- return lst(hist.done);
7860
- } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7861
- hist.done.pop();
7862
- return lst(hist.done);
7863
- }
7864
- }
7865
-
7866
- // Register a change in the history. Merges changes that are within
7867
- // a single operation, ore are close together with an origin that
7868
- // allows merging (starting with "+") into a single event.
7869
- function addChangeToHistory(doc, change, selAfter, opId) {
7870
- var hist = doc.history;
7871
- hist.undone.length = 0;
7872
- var time = +new Date, cur;
7873
-
7874
- if ((hist.lastOp == opId ||
7875
- hist.lastOrigin == change.origin && change.origin &&
7876
- ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7877
- change.origin.charAt(0) == "*")) &&
7878
- (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7879
- // Merge this change into the last event
7880
- var last = lst(cur.changes);
7881
- if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7882
- // Optimized case for simple insertion -- don't want to add
7883
- // new changesets for every character typed
7884
- last.to = changeEnd(change);
7885
- } else {
7886
- // Add new sub-event
7887
- cur.changes.push(historyChangeFromChange(doc, change));
7888
- }
7889
- } else {
7890
- // Can not be merged, start a new event.
7891
- var before = lst(hist.done);
7892
- if (!before || !before.ranges)
7893
- pushSelectionToHistory(doc.sel, hist.done);
7894
- cur = {changes: [historyChangeFromChange(doc, change)],
7895
- generation: hist.generation};
7896
- hist.done.push(cur);
7897
- while (hist.done.length > hist.undoDepth) {
7898
- hist.done.shift();
7899
- if (!hist.done[0].ranges) hist.done.shift();
7900
- }
7901
- }
7902
- hist.done.push(selAfter);
7903
- hist.generation = ++hist.maxGeneration;
7904
- hist.lastModTime = hist.lastSelTime = time;
7905
- hist.lastOp = hist.lastSelOp = opId;
7906
- hist.lastOrigin = hist.lastSelOrigin = change.origin;
7907
-
7908
- if (!last) signal(doc, "historyAdded");
7909
- }
7910
-
7911
- function selectionEventCanBeMerged(doc, origin, prev, sel) {
7912
- var ch = origin.charAt(0);
7913
- return ch == "*" ||
7914
- ch == "+" &&
7915
- prev.ranges.length == sel.ranges.length &&
7916
- prev.somethingSelected() == sel.somethingSelected() &&
7917
- new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7918
- }
7919
-
7920
- // Called whenever the selection changes, sets the new selection as
7921
- // the pending selection in the history, and pushes the old pending
7922
- // selection into the 'done' array when it was significantly
7923
- // different (in number of selected ranges, emptiness, or time).
7924
- function addSelectionToHistory(doc, sel, opId, options) {
7925
- var hist = doc.history, origin = options && options.origin;
7926
-
7927
- // A new event is started when the previous origin does not match
7928
- // the current, or the origins don't allow matching. Origins
7929
- // starting with * are always merged, those starting with + are
7930
- // merged when similar and close together in time.
7931
- if (opId == hist.lastSelOp ||
7932
- (origin && hist.lastSelOrigin == origin &&
7933
- (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7934
- selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7935
- hist.done[hist.done.length - 1] = sel;
7936
- else
7937
- pushSelectionToHistory(sel, hist.done);
7938
-
7939
- hist.lastSelTime = +new Date;
7940
- hist.lastSelOrigin = origin;
7941
- hist.lastSelOp = opId;
7942
- if (options && options.clearRedo !== false)
7943
- clearSelectionEvents(hist.undone);
7944
- }
7945
-
7946
- function pushSelectionToHistory(sel, dest) {
7947
- var top = lst(dest);
7948
- if (!(top && top.ranges && top.equals(sel)))
7949
- dest.push(sel);
7950
- }
7951
-
7952
- // Used to store marked span information in the history.
7953
- function attachLocalSpans(doc, change, from, to) {
7954
- var existing = change["spans_" + doc.id], n = 0;
7955
- doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7956
- if (line.markedSpans)
7957
- (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7958
- ++n;
7959
- });
7960
- }
7961
-
7962
- // When un/re-doing restores text containing marked spans, those
7963
- // that have been explicitly cleared should not be restored.
7964
- function removeClearedSpans(spans) {
7965
- if (!spans) return null;
7966
- for (var i = 0, out; i < spans.length; ++i) {
7967
- if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
7968
- else if (out) out.push(spans[i]);
7969
- }
7970
- return !out ? spans : out.length ? out : null;
7971
- }
7972
-
7973
- // Retrieve and filter the old marked spans stored in a change event.
7974
- function getOldSpans(doc, change) {
7975
- var found = change["spans_" + doc.id];
7976
- if (!found) return null;
7977
- for (var i = 0, nw = []; i < change.text.length; ++i)
7978
- nw.push(removeClearedSpans(found[i]));
7979
- return nw;
7980
- }
7981
-
7982
- // Used both to provide a JSON-safe object in .getHistory, and, when
7983
- // detaching a document, to split the history in two
7984
- function copyHistoryArray(events, newGroup, instantiateSel) {
7985
- for (var i = 0, copy = []; i < events.length; ++i) {
7986
- var event = events[i];
7987
- if (event.ranges) {
7988
- copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
7989
- continue;
7990
- }
7991
- var changes = event.changes, newChanges = [];
7992
- copy.push({changes: newChanges});
7993
- for (var j = 0; j < changes.length; ++j) {
7994
- var change = changes[j], m;
7995
- newChanges.push({from: change.from, to: change.to, text: change.text});
7996
- if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
7997
- if (indexOf(newGroup, Number(m[1])) > -1) {
7998
- lst(newChanges)[prop] = change[prop];
7999
- delete change[prop];
8000
- }
8001
- }
8002
- }
8003
- }
8004
- return copy;
8005
- }
8006
-
8007
- // Rebasing/resetting history to deal with externally-sourced changes
8008
-
8009
- function rebaseHistSelSingle(pos, from, to, diff) {
8010
- if (to < pos.line) {
8011
- pos.line += diff;
8012
- } else if (from < pos.line) {
8013
- pos.line = from;
8014
- pos.ch = 0;
8015
- }
8016
- }
8017
-
8018
- // Tries to rebase an array of history events given a change in the
8019
- // document. If the change touches the same lines as the event, the
8020
- // event, and everything 'behind' it, is discarded. If the change is
8021
- // before the event, the event's positions are updated. Uses a
8022
- // copy-on-write scheme for the positions, to avoid having to
8023
- // reallocate them all on every rebase, but also avoid problems with
8024
- // shared position objects being unsafely updated.
8025
- function rebaseHistArray(array, from, to, diff) {
8026
- for (var i = 0; i < array.length; ++i) {
8027
- var sub = array[i], ok = true;
8028
- if (sub.ranges) {
8029
- if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8030
- for (var j = 0; j < sub.ranges.length; j++) {
8031
- rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8032
- rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8033
- }
8034
- continue;
8035
- }
8036
- for (var j = 0; j < sub.changes.length; ++j) {
8037
- var cur = sub.changes[j];
8038
- if (to < cur.from.line) {
8039
- cur.from = Pos(cur.from.line + diff, cur.from.ch);
8040
- cur.to = Pos(cur.to.line + diff, cur.to.ch);
8041
- } else if (from <= cur.to.line) {
8042
- ok = false;
8043
- break;
8044
- }
8045
- }
8046
- if (!ok) {
8047
- array.splice(0, i + 1);
8048
- i = 0;
8049
- }
8050
- }
8051
- }
8052
-
8053
- function rebaseHist(hist, change) {
8054
- var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8055
- rebaseHistArray(hist.done, from, to, diff);
8056
- rebaseHistArray(hist.undone, from, to, diff);
8057
- }
8058
-
8059
- // EVENT UTILITIES
8060
-
8061
- // Due to the fact that we still support jurassic IE versions, some
8062
- // compatibility wrappers are needed.
8063
-
8064
- var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8065
- if (e.preventDefault) e.preventDefault();
8066
- else e.returnValue = false;
8067
- };
8068
- var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8069
- if (e.stopPropagation) e.stopPropagation();
8070
- else e.cancelBubble = true;
8071
- };
8072
- function e_defaultPrevented(e) {
8073
- return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8074
- }
8075
- var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8076
-
8077
- function e_target(e) {return e.target || e.srcElement;}
8078
- function e_button(e) {
8079
- var b = e.which;
8080
- if (b == null) {
8081
- if (e.button & 1) b = 1;
8082
- else if (e.button & 2) b = 3;
8083
- else if (e.button & 4) b = 2;
8084
- }
8085
- if (mac && e.ctrlKey && b == 1) b = 3;
8086
- return b;
8087
- }
8088
-
8089
- // EVENT HANDLING
8090
-
8091
- // Lightweight event framework. on/off also work on DOM nodes,
8092
- // registering native DOM handlers.
8093
-
8094
- var on = CodeMirror.on = function(emitter, type, f) {
8095
- if (emitter.addEventListener)
8096
- emitter.addEventListener(type, f, false);
8097
- else if (emitter.attachEvent)
8098
- emitter.attachEvent("on" + type, f);
8099
- else {
8100
- var map = emitter._handlers || (emitter._handlers = {});
8101
- var arr = map[type] || (map[type] = []);
8102
- arr.push(f);
8103
- }
8104
- };
8105
-
8106
- var noHandlers = []
8107
- function getHandlers(emitter, type, copy) {
8108
- var arr = emitter._handlers && emitter._handlers[type]
8109
- if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8110
- else return arr || noHandlers
8111
- }
8112
-
8113
- var off = CodeMirror.off = function(emitter, type, f) {
8114
- if (emitter.removeEventListener)
8115
- emitter.removeEventListener(type, f, false);
8116
- else if (emitter.detachEvent)
8117
- emitter.detachEvent("on" + type, f);
8118
- else {
8119
- var handlers = getHandlers(emitter, type, false)
8120
- for (var i = 0; i < handlers.length; ++i)
8121
- if (handlers[i] == f) { handlers.splice(i, 1); break; }
8122
- }
8123
- };
8124
-
8125
- var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8126
- var handlers = getHandlers(emitter, type, true)
8127
- if (!handlers.length) return;
8128
- var args = Array.prototype.slice.call(arguments, 2);
8129
- for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8130
- };
8131
-
8132
- var orphanDelayedCallbacks = null;
8133
-
8134
- // Often, we want to signal events at a point where we are in the
8135
- // middle of some work, but don't want the handler to start calling
8136
- // other methods on the editor, which might be in an inconsistent
8137
- // state or simply not expect any other events to happen.
8138
- // signalLater looks whether there are any handlers, and schedules
8139
- // them to be executed when the last operation ends, or, if no
8140
- // operation is active, when a timeout fires.
8141
- function signalLater(emitter, type /*, values...*/) {
8142
- var arr = getHandlers(emitter, type, false)
8143
- if (!arr.length) return;
8144
- var args = Array.prototype.slice.call(arguments, 2), list;
8145
- if (operationGroup) {
8146
- list = operationGroup.delayedCallbacks;
8147
- } else if (orphanDelayedCallbacks) {
8148
- list = orphanDelayedCallbacks;
8149
- } else {
8150
- list = orphanDelayedCallbacks = [];
8151
- setTimeout(fireOrphanDelayed, 0);
8152
- }
8153
- function bnd(f) {return function(){f.apply(null, args);};};
8154
- for (var i = 0; i < arr.length; ++i)
8155
- list.push(bnd(arr[i]));
8156
- }
8157
-
8158
- function fireOrphanDelayed() {
8159
- var delayed = orphanDelayedCallbacks;
8160
- orphanDelayedCallbacks = null;
8161
- for (var i = 0; i < delayed.length; ++i) delayed[i]();
8162
- }
8163
-
8164
- // The DOM events that CodeMirror handles can be overridden by
8165
- // registering a (non-DOM) handler on the editor for the event name,
8166
- // and preventDefault-ing the event in that handler.
8167
- function signalDOMEvent(cm, e, override) {
8168
- if (typeof e == "string")
8169
- e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8170
- signal(cm, override || e.type, cm, e);
8171
- return e_defaultPrevented(e) || e.codemirrorIgnore;
8172
- }
8173
-
8174
- function signalCursorActivity(cm) {
8175
- var arr = cm._handlers && cm._handlers.cursorActivity;
8176
- if (!arr) return;
8177
- var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8178
- for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8179
- set.push(arr[i]);
8180
- }
8181
-
8182
- function hasHandler(emitter, type) {
8183
- return getHandlers(emitter, type).length > 0
8184
- }
8185
-
8186
- // Add on and off methods to a constructor's prototype, to make
8187
- // registering events on such objects more convenient.
8188
- function eventMixin(ctor) {
8189
- ctor.prototype.on = function(type, f) {on(this, type, f);};
8190
- ctor.prototype.off = function(type, f) {off(this, type, f);};
8191
- }
8192
-
8193
- // MISC UTILITIES
8194
-
8195
- // Number of pixels added to scroller and sizer to hide scrollbar
8196
- var scrollerGap = 30;
8197
-
8198
- // Returned or thrown by various protocols to signal 'I'm not
8199
- // handling this'.
8200
- var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8201
-
8202
- // Reused option objects for setSelection & friends
8203
- var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8204
-
8205
- function Delayed() {this.id = null;}
8206
- Delayed.prototype.set = function(ms, f) {
8207
- clearTimeout(this.id);
8208
- this.id = setTimeout(f, ms);
8209
- };
8210
-
8211
- // Counts the column offset in a string, taking tabs into account.
8212
- // Used mostly to find indentation.
8213
- var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8214
- if (end == null) {
8215
- end = string.search(/[^\s\u00a0]/);
8216
- if (end == -1) end = string.length;
8217
- }
8218
- for (var i = startIndex || 0, n = startValue || 0;;) {
8219
- var nextTab = string.indexOf("\t", i);
8220
- if (nextTab < 0 || nextTab >= end)
8221
- return n + (end - i);
8222
- n += nextTab - i;
8223
- n += tabSize - (n % tabSize);
8224
- i = nextTab + 1;
8225
- }
8226
- };
8227
-
8228
- // The inverse of countColumn -- find the offset that corresponds to
8229
- // a particular column.
8230
- var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8231
- for (var pos = 0, col = 0;;) {
8232
- var nextTab = string.indexOf("\t", pos);
8233
- if (nextTab == -1) nextTab = string.length;
8234
- var skipped = nextTab - pos;
8235
- if (nextTab == string.length || col + skipped >= goal)
8236
- return pos + Math.min(skipped, goal - col);
8237
- col += nextTab - pos;
8238
- col += tabSize - (col % tabSize);
8239
- pos = nextTab + 1;
8240
- if (col >= goal) return pos;
8241
- }
8242
- }
8243
-
8244
- var spaceStrs = [""];
8245
- function spaceStr(n) {
8246
- while (spaceStrs.length <= n)
8247
- spaceStrs.push(lst(spaceStrs) + " ");
8248
- return spaceStrs[n];
8249
- }
8250
-
8251
- function lst(arr) { return arr[arr.length-1]; }
8252
-
8253
- var selectInput = function(node) { node.select(); };
8254
- if (ios) // Mobile Safari apparently has a bug where select() is broken.
8255
- selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8256
- else if (ie) // Suppress mysterious IE10 errors
8257
- selectInput = function(node) { try { node.select(); } catch(_e) {} };
8258
-
8259
- function indexOf(array, elt) {
8260
- for (var i = 0; i < array.length; ++i)
8261
- if (array[i] == elt) return i;
8262
- return -1;
8263
- }
8264
- function map(array, f) {
8265
- var out = [];
8266
- for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8267
- return out;
8268
- }
8269
-
8270
- function nothing() {}
8271
-
8272
- function createObj(base, props) {
8273
- var inst;
8274
- if (Object.create) {
8275
- inst = Object.create(base);
8276
- } else {
8277
- nothing.prototype = base;
8278
- inst = new nothing();
8279
- }
8280
- if (props) copyObj(props, inst);
8281
- return inst;
8282
- };
8283
-
8284
- function copyObj(obj, target, overwrite) {
8285
- if (!target) target = {};
8286
- for (var prop in obj)
8287
- if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8288
- target[prop] = obj[prop];
8289
- return target;
8290
- }
8291
-
8292
- function bind(f) {
8293
- var args = Array.prototype.slice.call(arguments, 1);
8294
- return function(){return f.apply(null, args);};
8295
- }
8296
-
8297
- var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8298
- var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8299
- return /\w/.test(ch) || ch > "\x80" &&
8300
- (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8301
- };
8302
- function isWordChar(ch, helper) {
8303
- if (!helper) return isWordCharBasic(ch);
8304
- if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8305
- return helper.test(ch);
8306
- }
8307
-
8308
- function isEmpty(obj) {
8309
- for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8310
- return true;
8311
- }
8312
-
8313
- // Extending unicode characters. A series of a non-extending char +
8314
- // any number of extending chars is treated as a single unit as far
8315
- // as editing and measuring is concerned. This is not fully correct,
8316
- // since some scripts/fonts/browsers also treat other configurations
8317
- // of code points as a group.
8318
- var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
8319
- function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8320
-
8321
- // DOM UTILITIES
8322
-
8323
- function elt(tag, content, className, style) {
8324
- var e = document.createElement(tag);
8325
- if (className) e.className = className;
8326
- if (style) e.style.cssText = style;
8327
- if (typeof content == "string") e.appendChild(document.createTextNode(content));
8328
- else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8329
- return e;
8330
- }
8331
-
8332
- var range;
8333
- if (document.createRange) range = function(node, start, end, endNode) {
8334
- var r = document.createRange();
8335
- r.setEnd(endNode || node, end);
8336
- r.setStart(node, start);
8337
- return r;
8338
- };
8339
- else range = function(node, start, end) {
8340
- var r = document.body.createTextRange();
8341
- try { r.moveToElementText(node.parentNode); }
8342
- catch(e) { return r; }
8343
- r.collapse(true);
8344
- r.moveEnd("character", end);
8345
- r.moveStart("character", start);
8346
- return r;
8347
- };
8348
-
8349
- function removeChildren(e) {
8350
- for (var count = e.childNodes.length; count > 0; --count)
8351
- e.removeChild(e.firstChild);
8352
- return e;
8353
- }
8354
-
8355
- function removeChildrenAndAdd(parent, e) {
8356
- return removeChildren(parent).appendChild(e);
8357
- }
8358
-
8359
- var contains = CodeMirror.contains = function(parent, child) {
8360
- if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8361
- child = child.parentNode;
8362
- if (parent.contains)
8363
- return parent.contains(child);
8364
- do {
8365
- if (child.nodeType == 11) child = child.host;
8366
- if (child == parent) return true;
8367
- } while (child = child.parentNode);
8368
- };
8369
-
8370
- function activeElt() {
8371
- var activeElement = document.activeElement;
8372
- while (activeElement && activeElement.root && activeElement.root.activeElement)
8373
- activeElement = activeElement.root.activeElement;
8374
- return activeElement;
8375
- }
8376
- // Older versions of IE throws unspecified error when touching
8377
- // document.activeElement in some cases (during loading, in iframe)
8378
- if (ie && ie_version < 11) activeElt = function() {
8379
- try { return document.activeElement; }
8380
- catch(e) { return document.body; }
8381
- };
8382
-
8383
- function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8384
- var rmClass = CodeMirror.rmClass = function(node, cls) {
8385
- var current = node.className;
8386
- var match = classTest(cls).exec(current);
8387
- if (match) {
8388
- var after = current.slice(match.index + match[0].length);
8389
- node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8390
- }
8391
- };
8392
- var addClass = CodeMirror.addClass = function(node, cls) {
8393
- var current = node.className;
8394
- if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8395
- };
8396
- function joinClasses(a, b) {
8397
- var as = a.split(" ");
8398
- for (var i = 0; i < as.length; i++)
8399
- if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8400
- return b;
8401
- }
8402
-
8403
- // WINDOW-WIDE EVENTS
8404
-
8405
- // These must be handled carefully, because naively registering a
8406
- // handler for each editor will cause the editors to never be
8407
- // garbage collected.
8408
-
8409
- function forEachCodeMirror(f) {
8410
- if (!document.body.getElementsByClassName) return;
8411
- var byClass = document.body.getElementsByClassName("CodeMirror");
8412
- for (var i = 0; i < byClass.length; i++) {
8413
- var cm = byClass[i].CodeMirror;
8414
- if (cm) f(cm);
8415
- }
8416
- }
8417
-
8418
- var globalsRegistered = false;
8419
- function ensureGlobalHandlers() {
8420
- if (globalsRegistered) return;
8421
- registerGlobalHandlers();
8422
- globalsRegistered = true;
8423
- }
8424
- function registerGlobalHandlers() {
8425
- // When the window resizes, we need to refresh active editors.
8426
- var resizeTimer;
8427
- on(window, "resize", function() {
8428
- if (resizeTimer == null) resizeTimer = setTimeout(function() {
8429
- resizeTimer = null;
8430
- forEachCodeMirror(onResize);
8431
- }, 100);
8432
- });
8433
- // When the window loses focus, we want to show the editor as blurred
8434
- on(window, "blur", function() {
8435
- forEachCodeMirror(onBlur);
8436
- });
8437
- }
8438
-
8439
- // FEATURE DETECTION
8440
-
8441
- // Detect drag-and-drop
8442
- var dragAndDrop = function() {
8443
- // There is *some* kind of drag-and-drop support in IE6-8, but I
8444
- // couldn't get it to work yet.
8445
- if (ie && ie_version < 9) return false;
8446
- var div = elt('div');
8447
- return "draggable" in div || "dragDrop" in div;
8448
- }();
8449
-
8450
- var zwspSupported;
8451
- function zeroWidthElement(measure) {
8452
- if (zwspSupported == null) {
8453
- var test = elt("span", "\u200b");
8454
- removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8455
- if (measure.firstChild.offsetHeight != 0)
8456
- zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8457
- }
8458
- var node = zwspSupported ? elt("span", "\u200b") :
8459
- elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8460
- node.setAttribute("cm-text", "");
8461
- return node;
8462
- }
8463
-
8464
- // Feature-detect IE's crummy client rect reporting for bidi text
8465
- var badBidiRects;
8466
- function hasBadBidiRects(measure) {
8467
- if (badBidiRects != null) return badBidiRects;
8468
- var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8469
- var r0 = range(txt, 0, 1).getBoundingClientRect();
8470
- if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8471
- var r1 = range(txt, 1, 2).getBoundingClientRect();
8472
- return badBidiRects = (r1.right - r0.right < 3);
8473
- }
8474
-
8475
- // See if "".split is the broken IE version, if so, provide an
8476
- // alternative way to split lines.
8477
- var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8478
- var pos = 0, result = [], l = string.length;
8479
- while (pos <= l) {
8480
- var nl = string.indexOf("\n", pos);
8481
- if (nl == -1) nl = string.length;
8482
- var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8483
- var rt = line.indexOf("\r");
8484
- if (rt != -1) {
8485
- result.push(line.slice(0, rt));
8486
- pos += rt + 1;
8487
- } else {
8488
- result.push(line);
8489
- pos = nl + 1;
8490
- }
8491
- }
8492
- return result;
8493
- } : function(string){return string.split(/\r\n?|\n/);};
8494
-
8495
- var hasSelection = window.getSelection ? function(te) {
8496
- try { return te.selectionStart != te.selectionEnd; }
8497
- catch(e) { return false; }
8498
- } : function(te) {
8499
- try {var range = te.ownerDocument.selection.createRange();}
8500
- catch(e) {}
8501
- if (!range || range.parentElement() != te) return false;
8502
- return range.compareEndPoints("StartToEnd", range) != 0;
8503
- };
8504
-
8505
- var hasCopyEvent = (function() {
8506
- var e = elt("div");
8507
- if ("oncopy" in e) return true;
8508
- e.setAttribute("oncopy", "return;");
8509
- return typeof e.oncopy == "function";
8510
- })();
8511
-
8512
- var badZoomedRects = null;
8513
- function hasBadZoomedRects(measure) {
8514
- if (badZoomedRects != null) return badZoomedRects;
8515
- var node = removeChildrenAndAdd(measure, elt("span", "x"));
8516
- var normal = node.getBoundingClientRect();
8517
- var fromRange = range(node, 0, 1).getBoundingClientRect();
8518
- return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8519
- }
8520
-
8521
- // KEY NAMES
8522
-
8523
- var keyNames = CodeMirror.keyNames = {
8524
- 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8525
- 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8526
- 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8527
- 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8528
- 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8529
- 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8530
- 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8531
- 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8532
- };
8533
- (function() {
8534
- // Number keys
8535
- for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8536
- // Alphabetic keys
8537
- for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8538
- // Function keys
8539
- for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8540
- })();
8541
-
8542
- // BIDI HELPERS
8543
-
8544
- function iterateBidiSections(order, from, to, f) {
8545
- if (!order) return f(from, to, "ltr");
8546
- var found = false;
8547
- for (var i = 0; i < order.length; ++i) {
8548
- var part = order[i];
8549
- if (part.from < to && part.to > from || from == to && part.to == from) {
8550
- f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8551
- found = true;
8552
- }
8553
- }
8554
- if (!found) f(from, to, "ltr");
8555
- }
8556
-
8557
- function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8558
- function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8559
-
8560
- function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8561
- function lineRight(line) {
8562
- var order = getOrder(line);
8563
- if (!order) return line.text.length;
8564
- return bidiRight(lst(order));
8565
- }
8566
-
8567
- function lineStart(cm, lineN) {
8568
- var line = getLine(cm.doc, lineN);
8569
- var visual = visualLine(line);
8570
- if (visual != line) lineN = lineNo(visual);
8571
- var order = getOrder(visual);
8572
- var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8573
- return Pos(lineN, ch);
8574
- }
8575
- function lineEnd(cm, lineN) {
8576
- var merged, line = getLine(cm.doc, lineN);
8577
- while (merged = collapsedSpanAtEnd(line)) {
8578
- line = merged.find(1, true).line;
8579
- lineN = null;
8580
- }
8581
- var order = getOrder(line);
8582
- var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8583
- return Pos(lineN == null ? lineNo(line) : lineN, ch);
8584
- }
8585
- function lineStartSmart(cm, pos) {
8586
- var start = lineStart(cm, pos.line);
8587
- var line = getLine(cm.doc, start.line);
8588
- var order = getOrder(line);
8589
- if (!order || order[0].level == 0) {
8590
- var firstNonWS = Math.max(0, line.text.search(/\S/));
8591
- var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8592
- return Pos(start.line, inWS ? 0 : firstNonWS);
8593
- }
8594
- return start;
8595
- }
8596
-
8597
- function compareBidiLevel(order, a, b) {
8598
- var linedir = order[0].level;
8599
- if (a == linedir) return true;
8600
- if (b == linedir) return false;
8601
- return a < b;
8602
- }
8603
- var bidiOther;
8604
- function getBidiPartAt(order, pos) {
8605
- bidiOther = null;
8606
- for (var i = 0, found; i < order.length; ++i) {
8607
- var cur = order[i];
8608
- if (cur.from < pos && cur.to > pos) return i;
8609
- if ((cur.from == pos || cur.to == pos)) {
8610
- if (found == null) {
8611
- found = i;
8612
- } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8613
- if (cur.from != cur.to) bidiOther = found;
8614
- return i;
8615
- } else {
8616
- if (cur.from != cur.to) bidiOther = i;
8617
- return found;
8618
- }
8619
- }
8620
- }
8621
- return found;
8622
- }
8623
-
8624
- function moveInLine(line, pos, dir, byUnit) {
8625
- if (!byUnit) return pos + dir;
8626
- do pos += dir;
8627
- while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8628
- return pos;
8629
- }
8630
-
8631
- // This is needed in order to move 'visually' through bi-directional
8632
- // text -- i.e., pressing left should make the cursor go left, even
8633
- // when in RTL text. The tricky part is the 'jumps', where RTL and
8634
- // LTR text touch each other. This often requires the cursor offset
8635
- // to move more than one unit, in order to visually move one unit.
8636
- function moveVisually(line, start, dir, byUnit) {
8637
- var bidi = getOrder(line);
8638
- if (!bidi) return moveLogically(line, start, dir, byUnit);
8639
- var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8640
- var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8641
-
8642
- for (;;) {
8643
- if (target > part.from && target < part.to) return target;
8644
- if (target == part.from || target == part.to) {
8645
- if (getBidiPartAt(bidi, target) == pos) return target;
8646
- part = bidi[pos += dir];
8647
- return (dir > 0) == part.level % 2 ? part.to : part.from;
8648
- } else {
8649
- part = bidi[pos += dir];
8650
- if (!part) return null;
8651
- if ((dir > 0) == part.level % 2)
8652
- target = moveInLine(line, part.to, -1, byUnit);
8653
- else
8654
- target = moveInLine(line, part.from, 1, byUnit);
8655
- }
8656
- }
8657
- }
8658
-
8659
- function moveLogically(line, start, dir, byUnit) {
8660
- var target = start + dir;
8661
- if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8662
- return target < 0 || target > line.text.length ? null : target;
8663
- }
8664
-
8665
- // Bidirectional ordering algorithm
8666
- // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8667
- // that this (partially) implements.
8668
-
8669
- // One-char codes used for character types:
8670
- // L (L): Left-to-Right
8671
- // R (R): Right-to-Left
8672
- // r (AL): Right-to-Left Arabic
8673
- // 1 (EN): European Number
8674
- // + (ES): European Number Separator
8675
- // % (ET): European Number Terminator
8676
- // n (AN): Arabic Number
8677
- // , (CS): Common Number Separator
8678
- // m (NSM): Non-Spacing Mark
8679
- // b (BN): Boundary Neutral
8680
- // s (B): Paragraph Separator
8681
- // t (S): Segment Separator
8682
- // w (WS): Whitespace
8683
- // N (ON): Other Neutrals
8684
-
8685
- // Returns null if characters are ordered as they appear
8686
- // (left-to-right), or an array of sections ({from, to, level}
8687
- // objects) in the order in which they occur visually.
8688
- var bidiOrdering = (function() {
8689
- // Character types for codepoints 0 to 0xff
8690
- var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8691
- // Character types for codepoints 0x600 to 0x6ff
8692
- var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8693
- function charType(code) {
8694
- if (code <= 0xf7) return lowTypes.charAt(code);
8695
- else if (0x590 <= code && code <= 0x5f4) return "R";
8696
- else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8697
- else if (0x6ee <= code && code <= 0x8ac) return "r";
8698
- else if (0x2000 <= code && code <= 0x200b) return "w";
8699
- else if (code == 0x200c) return "b";
8700
- else return "L";
8701
- }
8702
-
8703
- var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8704
- var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8705
- // Browsers seem to always treat the boundaries of block elements as being L.
8706
- var outerType = "L";
8707
-
8708
- function BidiSpan(level, from, to) {
8709
- this.level = level;
8710
- this.from = from; this.to = to;
8711
- }
8712
-
8713
- return function(str) {
8714
- if (!bidiRE.test(str)) return false;
8715
- var len = str.length, types = [];
8716
- for (var i = 0, type; i < len; ++i)
8717
- types.push(type = charType(str.charCodeAt(i)));
8718
-
8719
- // W1. Examine each non-spacing mark (NSM) in the level run, and
8720
- // change the type of the NSM to the type of the previous
8721
- // character. If the NSM is at the start of the level run, it will
8722
- // get the type of sor.
8723
- for (var i = 0, prev = outerType; i < len; ++i) {
8724
- var type = types[i];
8725
- if (type == "m") types[i] = prev;
8726
- else prev = type;
8727
- }
8728
-
8729
- // W2. Search backwards from each instance of a European number
8730
- // until the first strong type (R, L, AL, or sor) is found. If an
8731
- // AL is found, change the type of the European number to Arabic
8732
- // number.
8733
- // W3. Change all ALs to R.
8734
- for (var i = 0, cur = outerType; i < len; ++i) {
8735
- var type = types[i];
8736
- if (type == "1" && cur == "r") types[i] = "n";
8737
- else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8738
- }
8739
-
8740
- // W4. A single European separator between two European numbers
8741
- // changes to a European number. A single common separator between
8742
- // two numbers of the same type changes to that type.
8743
- for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8744
- var type = types[i];
8745
- if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8746
- else if (type == "," && prev == types[i+1] &&
8747
- (prev == "1" || prev == "n")) types[i] = prev;
8748
- prev = type;
8749
- }
8750
-
8751
- // W5. A sequence of European terminators adjacent to European
8752
- // numbers changes to all European numbers.
8753
- // W6. Otherwise, separators and terminators change to Other
8754
- // Neutral.
8755
- for (var i = 0; i < len; ++i) {
8756
- var type = types[i];
8757
- if (type == ",") types[i] = "N";
8758
- else if (type == "%") {
8759
- for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8760
- var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8761
- for (var j = i; j < end; ++j) types[j] = replace;
8762
- i = end - 1;
8763
- }
8764
- }
8765
-
8766
- // W7. Search backwards from each instance of a European number
8767
- // until the first strong type (R, L, or sor) is found. If an L is
8768
- // found, then change the type of the European number to L.
8769
- for (var i = 0, cur = outerType; i < len; ++i) {
8770
- var type = types[i];
8771
- if (cur == "L" && type == "1") types[i] = "L";
8772
- else if (isStrong.test(type)) cur = type;
8773
- }
8774
-
8775
- // N1. A sequence of neutrals takes the direction of the
8776
- // surrounding strong text if the text on both sides has the same
8777
- // direction. European and Arabic numbers act as if they were R in
8778
- // terms of their influence on neutrals. Start-of-level-run (sor)
8779
- // and end-of-level-run (eor) are used at level run boundaries.
8780
- // N2. Any remaining neutrals take the embedding direction.
8781
- for (var i = 0; i < len; ++i) {
8782
- if (isNeutral.test(types[i])) {
8783
- for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8784
- var before = (i ? types[i-1] : outerType) == "L";
8785
- var after = (end < len ? types[end] : outerType) == "L";
8786
- var replace = before || after ? "L" : "R";
8787
- for (var j = i; j < end; ++j) types[j] = replace;
8788
- i = end - 1;
8789
- }
8790
- }
8791
-
8792
- // Here we depart from the documented algorithm, in order to avoid
8793
- // building up an actual levels array. Since there are only three
8794
- // levels (0, 1, 2) in an implementation that doesn't take
8795
- // explicit embedding into account, we can build up the order on
8796
- // the fly, without following the level-based algorithm.
8797
- var order = [], m;
8798
- for (var i = 0; i < len;) {
8799
- if (countsAsLeft.test(types[i])) {
8800
- var start = i;
8801
- for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8802
- order.push(new BidiSpan(0, start, i));
8803
- } else {
8804
- var pos = i, at = order.length;
8805
- for (++i; i < len && types[i] != "L"; ++i) {}
8806
- for (var j = pos; j < i;) {
8807
- if (countsAsNum.test(types[j])) {
8808
- if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8809
- var nstart = j;
8810
- for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8811
- order.splice(at, 0, new BidiSpan(2, nstart, j));
8812
- pos = j;
8813
- } else ++j;
8814
- }
8815
- if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8816
- }
8817
- }
8818
- if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8819
- order[0].from = m[0].length;
8820
- order.unshift(new BidiSpan(0, 0, m[0].length));
8821
- }
8822
- if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8823
- lst(order).to -= m[0].length;
8824
- order.push(new BidiSpan(0, len - m[0].length, len));
8825
- }
8826
- if (order[0].level == 2)
8827
- order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8828
- if (order[0].level != lst(order).level)
8829
- order.push(new BidiSpan(order[0].level, len, len));
8830
-
8831
- return order;
8832
- };
8833
- })();
8834
-
8835
- // THE END
8836
-
8837
- CodeMirror.version = "5.7.1";
8838
-
8839
- return CodeMirror;
8840
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/htmlmixed.js DELETED
@@ -1,150 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- (function(mod) {
5
- if (typeof exports == "object" && typeof module == "object") // CommonJS
6
- mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
7
- else if (typeof define == "function" && define.amd) // AMD
8
- define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
9
- else // Plain browser env
10
- mod(CodeMirror);
11
- })(function(CodeMirror) {
12
- "use strict";
13
-
14
- var defaultTags = {
15
- script: [
16
- ["lang", /(javascript|babel)/i, "javascript"],
17
- ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"],
18
- ["type", /./, "text/plain"],
19
- [null, null, "javascript"]
20
- ],
21
- style: [
22
- ["lang", /^css$/i, "css"],
23
- ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
24
- ["type", /./, "text/plain"],
25
- [null, null, "css"]
26
- ]
27
- };
28
-
29
- function maybeBackup(stream, pat, style) {
30
- var cur = stream.current(), close = cur.search(pat);
31
- if (close > -1) {
32
- stream.backUp(cur.length - close);
33
- } else if (cur.match(/<\/?$/)) {
34
- stream.backUp(cur.length);
35
- if (!stream.match(pat, false)) stream.match(cur);
36
- }
37
- return style;
38
- }
39
-
40
- var attrRegexpCache = {};
41
- function getAttrRegexp(attr) {
42
- var regexp = attrRegexpCache[attr];
43
- if (regexp) return regexp;
44
- return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
45
- }
46
-
47
- function getAttrValue(stream, attr) {
48
- var pos = stream.pos, match;
49
- while (pos >= 0 && stream.string.charAt(pos) !== "<") pos--;
50
- if (pos < 0) return pos;
51
- if (match = stream.string.slice(pos, stream.pos).match(getAttrRegexp(attr)))
52
- return match[2];
53
- return "";
54
- }
55
-
56
- function getTagRegexp(tagName, anchored) {
57
- return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
58
- }
59
-
60
- function addTags(from, to) {
61
- for (var tag in from) {
62
- var dest = to[tag] || (to[tag] = []);
63
- var source = from[tag];
64
- for (var i = source.length - 1; i >= 0; i--)
65
- dest.unshift(source[i])
66
- }
67
- }
68
-
69
- function findMatchingMode(tagInfo, stream) {
70
- for (var i = 0; i < tagInfo.length; i++) {
71
- var spec = tagInfo[i];
72
- if (!spec[0] || spec[1].test(getAttrValue(stream, spec[0]))) return spec[2];
73
- }
74
- }
75
-
76
- CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
77
- var htmlMode = CodeMirror.getMode(config, {
78
- name: "xml",
79
- htmlMode: true,
80
- multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
81
- multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
82
- });
83
-
84
- var tags = {};
85
- var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
86
- addTags(defaultTags, tags);
87
- if (configTags) addTags(configTags, tags);
88
- if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
89
- tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
90
-
91
- function html(stream, state) {
92
- var tagName = state.htmlState.tagName;
93
- var tagInfo = tagName && tags[tagName.toLowerCase()];
94
-
95
- var style = htmlMode.token(stream, state.htmlState), modeSpec;
96
-
97
- if (tagInfo && /\btag\b/.test(style) && stream.current() === ">" &&
98
- (modeSpec = findMatchingMode(tagInfo, stream))) {
99
- var mode = CodeMirror.getMode(config, modeSpec);
100
- var endTagA = getTagRegexp(tagName, true), endTag = getTagRegexp(tagName, false);
101
- state.token = function (stream, state) {
102
- if (stream.match(endTagA, false)) {
103
- state.token = html;
104
- state.localState = state.localMode = null;
105
- return null;
106
- }
107
- return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
108
- };
109
- state.localMode = mode;
110
- state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, ""));
111
- }
112
- return style;
113
- };
114
-
115
- return {
116
- startState: function () {
117
- var state = htmlMode.startState();
118
- return {token: html, localMode: null, localState: null, htmlState: state};
119
- },
120
-
121
- copyState: function (state) {
122
- var local;
123
- if (state.localState) {
124
- local = CodeMirror.copyState(state.localMode, state.localState);
125
- }
126
- return {token: state.token, localMode: state.localMode, localState: local,
127
- htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
128
- },
129
-
130
- token: function (stream, state) {
131
- return state.token(stream, state);
132
- },
133
-
134
- indent: function (state, textAfter) {
135
- if (!state.localMode || /^\s*<\//.test(textAfter))
136
- return htmlMode.indent(state.htmlState, textAfter);
137
- else if (state.localMode.indent)
138
- return state.localMode.indent(state.localState, textAfter);
139
- else
140
- return CodeMirror.Pass;
141
- },
142
-
143
- innerMode: function (state) {
144
- return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
145
- }
146
- };
147
- }, "xml", "javascript", "css");
148
-
149
- CodeMirror.defineMIME("text/html", "htmlmixed");
150
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/javascript.js DELETED
@@ -1,710 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- // TODO actually recognize syntax of TypeScript constructs
5
-
6
- (function(mod) {
7
- if (typeof exports == "object" && typeof module == "object") // CommonJS
8
- mod(require("../../lib/codemirror"));
9
- else if (typeof define == "function" && define.amd) // AMD
10
- define(["../../lib/codemirror"], mod);
11
- else // Plain browser env
12
- mod(CodeMirror);
13
- })(function(CodeMirror) {
14
- "use strict";
15
-
16
- CodeMirror.defineMode("javascript", function(config, parserConfig) {
17
- var indentUnit = config.indentUnit;
18
- var statementIndent = parserConfig.statementIndent;
19
- var jsonldMode = parserConfig.jsonld;
20
- var jsonMode = parserConfig.json || jsonldMode;
21
- var isTS = parserConfig.typescript;
22
- var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
23
-
24
- // Tokenizer
25
-
26
- var keywords = function(){
27
- function kw(type) {return {type: type, style: "keyword"};}
28
- var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
29
- var operator = kw("operator"), atom = {type: "atom", style: "atom"};
30
-
31
- var jsKeywords = {
32
- "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
33
- "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C,
34
- "var": kw("var"), "const": kw("var"), "let": kw("var"),
35
- "async": kw("async"), "function": kw("function"), "catch": kw("catch"),
36
- "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
37
- "in": operator, "typeof": operator, "instanceof": operator,
38
- "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
39
- "this": kw("this"), "class": kw("class"), "super": kw("atom"),
40
- "await": C, "yield": C, "export": kw("export"), "import": kw("import"), "extends": C
41
- };
42
-
43
- // Extend the 'normal' keywords with the TypeScript language extensions
44
- if (isTS) {
45
- var type = {type: "variable", style: "variable-3"};
46
- var tsKeywords = {
47
- // object-like things
48
- "interface": kw("interface"),
49
- "extends": kw("extends"),
50
- "constructor": kw("constructor"),
51
-
52
- // scope modifiers
53
- "public": kw("public"),
54
- "private": kw("private"),
55
- "protected": kw("protected"),
56
- "static": kw("static"),
57
-
58
- // types
59
- "string": type, "number": type, "bool": type, "any": type
60
- };
61
-
62
- for (var attr in tsKeywords) {
63
- jsKeywords[attr] = tsKeywords[attr];
64
- }
65
- }
66
-
67
- return jsKeywords;
68
- }();
69
-
70
- var isOperatorChar = /[+\-*&%=<>!?|~^]/;
71
- var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
72
-
73
- function readRegexp(stream) {
74
- var escaped = false, next, inSet = false;
75
- while ((next = stream.next()) != null) {
76
- if (!escaped) {
77
- if (next == "/" && !inSet) return;
78
- if (next == "[") inSet = true;
79
- else if (inSet && next == "]") inSet = false;
80
- }
81
- escaped = !escaped && next == "\\";
82
- }
83
- }
84
-
85
- // Used as scratch variables to communicate multiple values without
86
- // consing up tons of objects.
87
- var type, content;
88
- function ret(tp, style, cont) {
89
- type = tp; content = cont;
90
- return style;
91
- }
92
- function tokenBase(stream, state) {
93
- var ch = stream.next();
94
- if (ch == '"' || ch == "'") {
95
- state.tokenize = tokenString(ch);
96
- return state.tokenize(stream, state);
97
- } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
98
- return ret("number", "number");
99
- } else if (ch == "." && stream.match("..")) {
100
- return ret("spread", "meta");
101
- } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
102
- return ret(ch);
103
- } else if (ch == "=" && stream.eat(">")) {
104
- return ret("=>", "operator");
105
- } else if (ch == "0" && stream.eat(/x/i)) {
106
- stream.eatWhile(/[\da-f]/i);
107
- return ret("number", "number");
108
- } else if (ch == "0" && stream.eat(/o/i)) {
109
- stream.eatWhile(/[0-7]/i);
110
- return ret("number", "number");
111
- } else if (ch == "0" && stream.eat(/b/i)) {
112
- stream.eatWhile(/[01]/i);
113
- return ret("number", "number");
114
- } else if (/\d/.test(ch)) {
115
- stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
116
- return ret("number", "number");
117
- } else if (ch == "/") {
118
- if (stream.eat("*")) {
119
- state.tokenize = tokenComment;
120
- return tokenComment(stream, state);
121
- } else if (stream.eat("/")) {
122
- stream.skipToEnd();
123
- return ret("comment", "comment");
124
- } else if (state.lastType == "operator" || state.lastType == "keyword c" ||
125
- state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) {
126
- readRegexp(stream);
127
- stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
128
- return ret("regexp", "string-2");
129
- } else {
130
- stream.eatWhile(isOperatorChar);
131
- return ret("operator", "operator", stream.current());
132
- }
133
- } else if (ch == "`") {
134
- state.tokenize = tokenQuasi;
135
- return tokenQuasi(stream, state);
136
- } else if (ch == "#") {
137
- stream.skipToEnd();
138
- return ret("error", "error");
139
- } else if (isOperatorChar.test(ch)) {
140
- stream.eatWhile(isOperatorChar);
141
- return ret("operator", "operator", stream.current());
142
- } else if (wordRE.test(ch)) {
143
- stream.eatWhile(wordRE);
144
- var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
145
- return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
146
- ret("variable", "variable", word);
147
- }
148
- }
149
-
150
- function tokenString(quote) {
151
- return function(stream, state) {
152
- var escaped = false, next;
153
- if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
154
- state.tokenize = tokenBase;
155
- return ret("jsonld-keyword", "meta");
156
- }
157
- while ((next = stream.next()) != null) {
158
- if (next == quote && !escaped) break;
159
- escaped = !escaped && next == "\\";
160
- }
161
- if (!escaped) state.tokenize = tokenBase;
162
- return ret("string", "string");
163
- };
164
- }
165
-
166
- function tokenComment(stream, state) {
167
- var maybeEnd = false, ch;
168
- while (ch = stream.next()) {
169
- if (ch == "/" && maybeEnd) {
170
- state.tokenize = tokenBase;
171
- break;
172
- }
173
- maybeEnd = (ch == "*");
174
- }
175
- return ret("comment", "comment");
176
- }
177
-
178
- function tokenQuasi(stream, state) {
179
- var escaped = false, next;
180
- while ((next = stream.next()) != null) {
181
- if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
182
- state.tokenize = tokenBase;
183
- break;
184
- }
185
- escaped = !escaped && next == "\\";
186
- }
187
- return ret("quasi", "string-2", stream.current());
188
- }
189
-
190
- var brackets = "([{}])";
191
- // This is a crude lookahead trick to try and notice that we're
192
- // parsing the argument patterns for a fat-arrow function before we
193
- // actually hit the arrow token. It only works if the arrow is on
194
- // the same line as the arguments and there's no strange noise
195
- // (comments) in between. Fallback is to only notice when we hit the
196
- // arrow, and not declare the arguments as locals for the arrow
197
- // body.
198
- function findFatArrow(stream, state) {
199
- if (state.fatArrowAt) state.fatArrowAt = null;
200
- var arrow = stream.string.indexOf("=>", stream.start);
201
- if (arrow < 0) return;
202
-
203
- var depth = 0, sawSomething = false;
204
- for (var pos = arrow - 1; pos >= 0; --pos) {
205
- var ch = stream.string.charAt(pos);
206
- var bracket = brackets.indexOf(ch);
207
- if (bracket >= 0 && bracket < 3) {
208
- if (!depth) { ++pos; break; }
209
- if (--depth == 0) break;
210
- } else if (bracket >= 3 && bracket < 6) {
211
- ++depth;
212
- } else if (wordRE.test(ch)) {
213
- sawSomething = true;
214
- } else if (/["'\/]/.test(ch)) {
215
- return;
216
- } else if (sawSomething && !depth) {
217
- ++pos;
218
- break;
219
- }
220
- }
221
- if (sawSomething && !depth) state.fatArrowAt = pos;
222
- }
223
-
224
- // Parser
225
-
226
- var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
227
-
228
- function JSLexical(indented, column, type, align, prev, info) {
229
- this.indented = indented;
230
- this.column = column;
231
- this.type = type;
232
- this.prev = prev;
233
- this.info = info;
234
- if (align != null) this.align = align;
235
- }
236
-
237
- function inScope(state, varname) {
238
- for (var v = state.localVars; v; v = v.next)
239
- if (v.name == varname) return true;
240
- for (var cx = state.context; cx; cx = cx.prev) {
241
- for (var v = cx.vars; v; v = v.next)
242
- if (v.name == varname) return true;
243
- }
244
- }
245
-
246
- function parseJS(state, style, type, content, stream) {
247
- var cc = state.cc;
248
- // Communicate our context to the combinators.
249
- // (Less wasteful than consing up a hundred closures on every call.)
250
- cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
251
-
252
- if (!state.lexical.hasOwnProperty("align"))
253
- state.lexical.align = true;
254
-
255
- while(true) {
256
- var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
257
- if (combinator(type, content)) {
258
- while(cc.length && cc[cc.length - 1].lex)
259
- cc.pop()();
260
- if (cx.marked) return cx.marked;
261
- if (type == "variable" && inScope(state, content)) return "variable-2";
262
- return style;
263
- }
264
- }
265
- }
266
-
267
- // Combinator utils
268
-
269
- var cx = {state: null, column: null, marked: null, cc: null};
270
- function pass() {
271
- for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
272
- }
273
- function cont() {
274
- pass.apply(null, arguments);
275
- return true;
276
- }
277
- function register(varname) {
278
- function inList(list) {
279
- for (var v = list; v; v = v.next)
280
- if (v.name == varname) return true;
281
- return false;
282
- }
283
- var state = cx.state;
284
- if (state.context) {
285
- cx.marked = "def";
286
- if (inList(state.localVars)) return;
287
- state.localVars = {name: varname, next: state.localVars};
288
- } else {
289
- if (inList(state.globalVars)) return;
290
- if (parserConfig.globalVars)
291
- state.globalVars = {name: varname, next: state.globalVars};
292
- }
293
- }
294
-
295
- // Combinators
296
-
297
- var defaultVars = {name: "this", next: {name: "arguments"}};
298
- function pushcontext() {
299
- cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
300
- cx.state.localVars = defaultVars;
301
- }
302
- function popcontext() {
303
- cx.state.localVars = cx.state.context.vars;
304
- cx.state.context = cx.state.context.prev;
305
- }
306
- function pushlex(type, info) {
307
- var result = function() {
308
- var state = cx.state, indent = state.indented;
309
- if (state.lexical.type == "stat") indent = state.lexical.indented;
310
- else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
311
- indent = outer.indented;
312
- state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
313
- };
314
- result.lex = true;
315
- return result;
316
- }
317
- function poplex() {
318
- var state = cx.state;
319
- if (state.lexical.prev) {
320
- if (state.lexical.type == ")")
321
- state.indented = state.lexical.indented;
322
- state.lexical = state.lexical.prev;
323
- }
324
- }
325
- poplex.lex = true;
326
-
327
- function expect(wanted) {
328
- function exp(type) {
329
- if (type == wanted) return cont();
330
- else if (wanted == ";") return pass();
331
- else return cont(exp);
332
- };
333
- return exp;
334
- }
335
-
336
- function statement(type, value) {
337
- if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
338
- if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
339
- if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
340
- if (type == "{") return cont(pushlex("}"), block, poplex);
341
- if (type == ";") return cont();
342
- if (type == "if") {
343
- if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
344
- cx.state.cc.pop()();
345
- return cont(pushlex("form"), expression, statement, poplex, maybeelse);
346
- }
347
- if (type == "function") return cont(functiondef);
348
- if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
349
- if (type == "variable") return cont(pushlex("stat"), maybelabel);
350
- if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
351
- block, poplex, poplex);
352
- if (type == "case") return cont(expression, expect(":"));
353
- if (type == "default") return cont(expect(":"));
354
- if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
355
- statement, poplex, popcontext);
356
- if (type == "class") return cont(pushlex("form"), className, poplex);
357
- if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
358
- if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
359
- return pass(pushlex("stat"), expression, expect(";"), poplex);
360
- }
361
- function expression(type) {
362
- return expressionInner(type, false);
363
- }
364
- function expressionNoComma(type) {
365
- return expressionInner(type, true);
366
- }
367
- function expressionInner(type, noComma) {
368
- if (cx.state.fatArrowAt == cx.stream.start) {
369
- var body = noComma ? arrowBodyNoComma : arrowBody;
370
- if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
371
- else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
372
- }
373
-
374
- var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
375
- if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
376
- if (type == "async") return cont(expression);
377
- if (type == "function") return cont(functiondef, maybeop);
378
- if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
379
- if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
380
- if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
381
- if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
382
- if (type == "{") return contCommasep(objprop, "}", null, maybeop);
383
- if (type == "quasi") { return pass(quasi, maybeop); }
384
- return cont();
385
- }
386
- function maybeexpression(type) {
387
- if (type.match(/[;\}\)\],]/)) return pass();
388
- return pass(expression);
389
- }
390
- function maybeexpressionNoComma(type) {
391
- if (type.match(/[;\}\)\],]/)) return pass();
392
- return pass(expressionNoComma);
393
- }
394
-
395
- function maybeoperatorComma(type, value) {
396
- if (type == ",") return cont(expression);
397
- return maybeoperatorNoComma(type, value, false);
398
- }
399
- function maybeoperatorNoComma(type, value, noComma) {
400
- var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
401
- var expr = noComma == false ? expression : expressionNoComma;
402
- if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
403
- if (type == "operator") {
404
- if (/\+\+|--/.test(value)) return cont(me);
405
- if (value == "?") return cont(expression, expect(":"), expr);
406
- return cont(expr);
407
- }
408
- if (type == "quasi") { return pass(quasi, me); }
409
- if (type == ";") return;
410
- if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
411
- if (type == ".") return cont(property, me);
412
- if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
413
- }
414
- function quasi(type, value) {
415
- if (type != "quasi") return pass();
416
- if (value.slice(value.length - 2) != "${") return cont(quasi);
417
- return cont(expression, continueQuasi);
418
- }
419
- function continueQuasi(type) {
420
- if (type == "}") {
421
- cx.marked = "string-2";
422
- cx.state.tokenize = tokenQuasi;
423
- return cont(quasi);
424
- }
425
- }
426
- function arrowBody(type) {
427
- findFatArrow(cx.stream, cx.state);
428
- return pass(type == "{" ? statement : expression);
429
- }
430
- function arrowBodyNoComma(type) {
431
- findFatArrow(cx.stream, cx.state);
432
- return pass(type == "{" ? statement : expressionNoComma);
433
- }
434
- function maybelabel(type) {
435
- if (type == ":") return cont(poplex, statement);
436
- return pass(maybeoperatorComma, expect(";"), poplex);
437
- }
438
- function property(type) {
439
- if (type == "variable") {cx.marked = "property"; return cont();}
440
- }
441
- function objprop(type, value) {
442
- if (type == "async") {
443
- return cont(objprop);
444
- } else if (type == "variable" || cx.style == "keyword") {
445
- cx.marked = "property";
446
- if (value == "get" || value == "set") return cont(getterSetter);
447
- return cont(afterprop);
448
- } else if (type == "number" || type == "string") {
449
- cx.marked = jsonldMode ? "property" : (cx.style + " property");
450
- return cont(afterprop);
451
- } else if (type == "jsonld-keyword") {
452
- return cont(afterprop);
453
- } else if (type == "[") {
454
- return cont(expression, expect("]"), afterprop);
455
- }
456
- }
457
- function getterSetter(type) {
458
- if (type != "variable") return pass(afterprop);
459
- cx.marked = "property";
460
- return cont(functiondef);
461
- }
462
- function afterprop(type) {
463
- if (type == ":") return cont(expressionNoComma);
464
- if (type == "(") return pass(functiondef);
465
- }
466
- function commasep(what, end) {
467
- function proceed(type) {
468
- if (type == ",") {
469
- var lex = cx.state.lexical;
470
- if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
471
- return cont(what, proceed);
472
- }
473
- if (type == end) return cont();
474
- return cont(expect(end));
475
- }
476
- return function(type) {
477
- if (type == end) return cont();
478
- return pass(what, proceed);
479
- };
480
- }
481
- function contCommasep(what, end, info) {
482
- for (var i = 3; i < arguments.length; i++)
483
- cx.cc.push(arguments[i]);
484
- return cont(pushlex(end, info), commasep(what, end), poplex);
485
- }
486
- function block(type) {
487
- if (type == "}") return cont();
488
- return pass(statement, block);
489
- }
490
- function maybetype(type) {
491
- if (isTS && type == ":") return cont(typedef);
492
- }
493
- function maybedefault(_, value) {
494
- if (value == "=") return cont(expressionNoComma);
495
- }
496
- function typedef(type) {
497
- if (type == "variable") {cx.marked = "variable-3"; return cont();}
498
- }
499
- function vardef() {
500
- return pass(pattern, maybetype, maybeAssign, vardefCont);
501
- }
502
- function pattern(type, value) {
503
- if (type == "variable") { register(value); return cont(); }
504
- if (type == "spread") return cont(pattern);
505
- if (type == "[") return contCommasep(pattern, "]");
506
- if (type == "{") return contCommasep(proppattern, "}");
507
- }
508
- function proppattern(type, value) {
509
- if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
510
- register(value);
511
- return cont(maybeAssign);
512
- }
513
- if (type == "variable") cx.marked = "property";
514
- if (type == "spread") return cont(pattern);
515
- return cont(expect(":"), pattern, maybeAssign);
516
- }
517
- function maybeAssign(_type, value) {
518
- if (value == "=") return cont(expressionNoComma);
519
- }
520
- function vardefCont(type) {
521
- if (type == ",") return cont(vardef);
522
- }
523
- function maybeelse(type, value) {
524
- if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
525
- }
526
- function forspec(type) {
527
- if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
528
- }
529
- function forspec1(type) {
530
- if (type == "var") return cont(vardef, expect(";"), forspec2);
531
- if (type == ";") return cont(forspec2);
532
- if (type == "variable") return cont(formaybeinof);
533
- return pass(expression, expect(";"), forspec2);
534
- }
535
- function formaybeinof(_type, value) {
536
- if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
537
- return cont(maybeoperatorComma, forspec2);
538
- }
539
- function forspec2(type, value) {
540
- if (type == ";") return cont(forspec3);
541
- if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
542
- return pass(expression, expect(";"), forspec3);
543
- }
544
- function forspec3(type) {
545
- if (type != ")") cont(expression);
546
- }
547
- function functiondef(type, value) {
548
- if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
549
- if (type == "variable") {register(value); return cont(functiondef);}
550
- if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
551
- }
552
- function funarg(type) {
553
- if (type == "spread") return cont(funarg);
554
- return pass(pattern, maybetype, maybedefault);
555
- }
556
- function className(type, value) {
557
- if (type == "variable") {register(value); return cont(classNameAfter);}
558
- }
559
- function classNameAfter(type, value) {
560
- if (value == "extends") return cont(expression, classNameAfter);
561
- if (type == "{") return cont(pushlex("}"), classBody, poplex);
562
- }
563
- function classBody(type, value) {
564
- if (type == "variable" || cx.style == "keyword") {
565
- if (value == "static") {
566
- cx.marked = "keyword";
567
- return cont(classBody);
568
- }
569
- cx.marked = "property";
570
- if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
571
- return cont(functiondef, classBody);
572
- }
573
- if (value == "*") {
574
- cx.marked = "keyword";
575
- return cont(classBody);
576
- }
577
- if (type == ";") return cont(classBody);
578
- if (type == "}") return cont();
579
- }
580
- function classGetterSetter(type) {
581
- if (type != "variable") return pass();
582
- cx.marked = "property";
583
- return cont();
584
- }
585
- function afterExport(_type, value) {
586
- if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
587
- if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
588
- return pass(statement);
589
- }
590
- function afterImport(type) {
591
- if (type == "string") return cont();
592
- return pass(importSpec, maybeFrom);
593
- }
594
- function importSpec(type, value) {
595
- if (type == "{") return contCommasep(importSpec, "}");
596
- if (type == "variable") register(value);
597
- if (value == "*") cx.marked = "keyword";
598
- return cont(maybeAs);
599
- }
600
- function maybeAs(_type, value) {
601
- if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
602
- }
603
- function maybeFrom(_type, value) {
604
- if (value == "from") { cx.marked = "keyword"; return cont(expression); }
605
- }
606
- function arrayLiteral(type) {
607
- if (type == "]") return cont();
608
- return pass(expressionNoComma, maybeArrayComprehension);
609
- }
610
- function maybeArrayComprehension(type) {
611
- if (type == "for") return pass(comprehension, expect("]"));
612
- if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
613
- return pass(commasep(expressionNoComma, "]"));
614
- }
615
- function comprehension(type) {
616
- if (type == "for") return cont(forspec, comprehension);
617
- if (type == "if") return cont(expression, comprehension);
618
- }
619
-
620
- function isContinuedStatement(state, textAfter) {
621
- return state.lastType == "operator" || state.lastType == "," ||
622
- isOperatorChar.test(textAfter.charAt(0)) ||
623
- /[,.]/.test(textAfter.charAt(0));
624
- }
625
-
626
- // Interface
627
-
628
- return {
629
- startState: function(basecolumn) {
630
- var state = {
631
- tokenize: tokenBase,
632
- lastType: "sof",
633
- cc: [],
634
- lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
635
- localVars: parserConfig.localVars,
636
- context: parserConfig.localVars && {vars: parserConfig.localVars},
637
- indented: 0
638
- };
639
- if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
640
- state.globalVars = parserConfig.globalVars;
641
- return state;
642
- },
643
-
644
- token: function(stream, state) {
645
- if (stream.sol()) {
646
- if (!state.lexical.hasOwnProperty("align"))
647
- state.lexical.align = false;
648
- state.indented = stream.indentation();
649
- findFatArrow(stream, state);
650
- }
651
- if (state.tokenize != tokenComment && stream.eatSpace()) return null;
652
- var style = state.tokenize(stream, state);
653
- if (type == "comment") return style;
654
- state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
655
- return parseJS(state, style, type, content, stream);
656
- },
657
-
658
- indent: function(state, textAfter) {
659
- if (state.tokenize == tokenComment) return CodeMirror.Pass;
660
- if (state.tokenize != tokenBase) return 0;
661
- var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
662
- // Kludge to prevent 'maybelse' from blocking lexical scope pops
663
- if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
664
- var c = state.cc[i];
665
- if (c == poplex) lexical = lexical.prev;
666
- else if (c != maybeelse) break;
667
- }
668
- if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
669
- if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
670
- lexical = lexical.prev;
671
- var type = lexical.type, closing = firstChar == type;
672
-
673
- if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
674
- else if (type == "form" && firstChar == "{") return lexical.indented;
675
- else if (type == "form") return lexical.indented + indentUnit;
676
- else if (type == "stat")
677
- return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
678
- else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
679
- return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
680
- else if (lexical.align) return lexical.column + (closing ? 0 : 1);
681
- else return lexical.indented + (closing ? 0 : indentUnit);
682
- },
683
-
684
- electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
685
- blockCommentStart: jsonMode ? null : "/*",
686
- blockCommentEnd: jsonMode ? null : "*/",
687
- lineComment: jsonMode ? null : "//",
688
- fold: "brace",
689
- closeBrackets: "()[]{}''\"\"``",
690
-
691
- helperType: jsonMode ? "json" : "javascript",
692
- jsonldMode: jsonldMode,
693
- jsonMode: jsonMode
694
- };
695
- });
696
-
697
- CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
698
-
699
- CodeMirror.defineMIME("text/javascript", "javascript");
700
- CodeMirror.defineMIME("text/ecmascript", "javascript");
701
- CodeMirror.defineMIME("application/javascript", "javascript");
702
- CodeMirror.defineMIME("application/x-javascript", "javascript");
703
- CodeMirror.defineMIME("application/ecmascript", "javascript");
704
- CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
705
- CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
706
- CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
707
- CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
708
- CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
709
-
710
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/matchbrackets.js DELETED
@@ -1,120 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- (function(mod) {
5
- if (typeof exports == "object" && typeof module == "object") // CommonJS
6
- mod(require("../../lib/codemirror"));
7
- else if (typeof define == "function" && define.amd) // AMD
8
- define(["../../lib/codemirror"], mod);
9
- else // Plain browser env
10
- mod(CodeMirror);
11
- })(function(CodeMirror) {
12
- var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
13
- (document.documentMode == null || document.documentMode < 8);
14
-
15
- var Pos = CodeMirror.Pos;
16
-
17
- var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
18
-
19
- function findMatchingBracket(cm, where, strict, config) {
20
- var line = cm.getLineHandle(where.line), pos = where.ch - 1;
21
- var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
22
- if (!match) return null;
23
- var dir = match.charAt(1) == ">" ? 1 : -1;
24
- if (strict && (dir > 0) != (pos == where.ch)) return null;
25
- var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
26
-
27
- var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
28
- if (found == null) return null;
29
- return {from: Pos(where.line, pos), to: found && found.pos,
30
- match: found && found.ch == match.charAt(0), forward: dir > 0};
31
- }
32
-
33
- // bracketRegex is used to specify which type of bracket to scan
34
- // should be a regexp, e.g. /[[\]]/
35
- //
36
- // Note: If "where" is on an open bracket, then this bracket is ignored.
37
- //
38
- // Returns false when no bracket was found, null when it reached
39
- // maxScanLines and gave up
40
- function scanForBracket(cm, where, dir, style, config) {
41
- var maxScanLen = (config && config.maxScanLineLength) || 10000;
42
- var maxScanLines = (config && config.maxScanLines) || 1000;
43
-
44
- var stack = [];
45
- var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
46
- var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
47
- : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
48
- for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
49
- var line = cm.getLine(lineNo);
50
- if (!line) continue;
51
- var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
52
- if (line.length > maxScanLen) continue;
53
- if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
54
- for (; pos != end; pos += dir) {
55
- var ch = line.charAt(pos);
56
- if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
57
- var match = matching[ch];
58
- if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
59
- else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
60
- else stack.pop();
61
- }
62
- }
63
- }
64
- return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
65
- }
66
-
67
- function matchBrackets(cm, autoclear, config) {
68
- // Disable brace matching in long lines, since it'll cause hugely slow updates
69
- var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
70
- var marks = [], ranges = cm.listSelections();
71
- for (var i = 0; i < ranges.length; i++) {
72
- var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
73
- if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
74
- var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
75
- marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
76
- if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
77
- marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
78
- }
79
- }
80
-
81
- if (marks.length) {
82
- // Kludge to work around the IE bug from issue #1193, where text
83
- // input stops going to the textare whever this fires.
84
- if (ie_lt8 && cm.state.focused) cm.focus();
85
-
86
- var clear = function() {
87
- cm.operation(function() {
88
- for (var i = 0; i < marks.length; i++) marks[i].clear();
89
- });
90
- };
91
- if (autoclear) setTimeout(clear, 800);
92
- else return clear;
93
- }
94
- }
95
-
96
- var currentlyHighlighted = null;
97
- function doMatchBrackets(cm) {
98
- cm.operation(function() {
99
- if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
100
- currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
101
- });
102
- }
103
-
104
- CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
105
- if (old && old != CodeMirror.Init)
106
- cm.off("cursorActivity", doMatchBrackets);
107
- if (val) {
108
- cm.state.matchBrackets = typeof val == "object" ? val : {};
109
- cm.on("cursorActivity", doMatchBrackets);
110
- }
111
- });
112
-
113
- CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
114
- CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
115
- return findMatchingBracket(this, pos, strict, config);
116
- });
117
- CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
118
- return scanForBracket(this, pos, dir, style, config);
119
- });
120
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/php.js DELETED
@@ -1,234 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- (function(mod) {
5
- if (typeof exports == "object" && typeof module == "object") // CommonJS
6
- mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../clike/clike"));
7
- else if (typeof define == "function" && define.amd) // AMD
8
- define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod);
9
- else // Plain browser env
10
- mod(CodeMirror);
11
- })(function(CodeMirror) {
12
- "use strict";
13
-
14
- function keywords(str) {
15
- var obj = {}, words = str.split(" ");
16
- for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
17
- return obj;
18
- }
19
-
20
- // Helper for phpString
21
- function matchSequence(list, end, escapes) {
22
- if (list.length == 0) return phpString(end);
23
- return function (stream, state) {
24
- var patterns = list[0];
25
- for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {
26
- state.tokenize = matchSequence(list.slice(1), end);
27
- return patterns[i][1];
28
- }
29
- state.tokenize = phpString(end, escapes);
30
- return "string";
31
- };
32
- }
33
- function phpString(closing, escapes) {
34
- return function(stream, state) { return phpString_(stream, state, closing, escapes); };
35
- }
36
- function phpString_(stream, state, closing, escapes) {
37
- // "Complex" syntax
38
- if (escapes !== false && stream.match("${", false) || stream.match("{$", false)) {
39
- state.tokenize = null;
40
- return "string";
41
- }
42
-
43
- // Simple syntax
44
- if (escapes !== false && stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) {
45
- // After the variable name there may appear array or object operator.
46
- if (stream.match("[", false)) {
47
- // Match array operator
48
- state.tokenize = matchSequence([
49
- [["[", null]],
50
- [[/\d[\w\.]*/, "number"],
51
- [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"],
52
- [/[\w\$]+/, "variable"]],
53
- [["]", null]]
54
- ], closing, escapes);
55
- }
56
- if (stream.match(/\-\>\w/, false)) {
57
- // Match object operator
58
- state.tokenize = matchSequence([
59
- [["->", null]],
60
- [[/[\w]+/, "variable"]]
61
- ], closing, escapes);
62
- }
63
- return "variable-2";
64
- }
65
-
66
- var escaped = false;
67
- // Normal string
68
- while (!stream.eol() &&
69
- (escaped || escapes === false ||
70
- (!stream.match("{$", false) &&
71
- !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) {
72
- if (!escaped && stream.match(closing)) {
73
- state.tokenize = null;
74
- state.tokStack.pop(); state.tokStack.pop();
75
- break;
76
- }
77
- escaped = stream.next() == "\\" && !escaped;
78
- }
79
- return "string";
80
- }
81
-
82
- var phpKeywords = "abstract and array as break case catch class clone const continue declare default " +
83
- "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
84
- "for foreach function global goto if implements interface instanceof namespace " +
85
- "new or private protected public static switch throw trait try use var while xor " +
86
- "die echo empty exit eval include include_once isset list require require_once return " +
87
- "print unset __halt_compiler self static parent yield insteadof finally";
88
- var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__";
89
- var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents file_put_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count";
90
- CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" "));
91
- CodeMirror.registerHelper("wordChars", "php", /[\w$]/);
92
-
93
- var phpConfig = {
94
- name: "clike",
95
- helperType: "php",
96
- keywords: keywords(phpKeywords),
97
- blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"),
98
- defKeywords: keywords("class function interface namespace trait"),
99
- atoms: keywords(phpAtoms),
100
- builtin: keywords(phpBuiltin),
101
- multiLineStrings: true,
102
- hooks: {
103
- "$": function(stream) {
104
- stream.eatWhile(/[\w\$_]/);
105
- return "variable-2";
106
- },
107
- "<": function(stream, state) {
108
- var before;
109
- if (before = stream.match(/<<\s*/)) {
110
- var quoted = stream.eat(/['"]/);
111
- stream.eatWhile(/[\w\.]/);
112
- var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1));
113
- if (quoted) stream.eat(quoted);
114
- if (delim) {
115
- (state.tokStack || (state.tokStack = [])).push(delim, 0);
116
- state.tokenize = phpString(delim, quoted != "'");
117
- return "string";
118
- }
119
- }
120
- return false;
121
- },
122
- "#": function(stream) {
123
- while (!stream.eol() && !stream.match("?>", false)) stream.next();
124
- return "comment";
125
- },
126
- "/": function(stream) {
127
- if (stream.eat("/")) {
128
- while (!stream.eol() && !stream.match("?>", false)) stream.next();
129
- return "comment";
130
- }
131
- return false;
132
- },
133
- '"': function(_stream, state) {
134
- (state.tokStack || (state.tokStack = [])).push('"', 0);
135
- state.tokenize = phpString('"');
136
- return "string";
137
- },
138
- "{": function(_stream, state) {
139
- if (state.tokStack && state.tokStack.length)
140
- state.tokStack[state.tokStack.length - 1]++;
141
- return false;
142
- },
143
- "}": function(_stream, state) {
144
- if (state.tokStack && state.tokStack.length > 0 &&
145
- !--state.tokStack[state.tokStack.length - 1]) {
146
- state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]);
147
- }
148
- return false;
149
- }
150
- }
151
- };
152
-
153
- CodeMirror.defineMode("php", function(config, parserConfig) {
154
- var htmlMode = CodeMirror.getMode(config, "text/html");
155
- var phpMode = CodeMirror.getMode(config, phpConfig);
156
-
157
- function dispatch(stream, state) {
158
- var isPHP = state.curMode == phpMode;
159
- if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null;
160
- if (!isPHP) {
161
- if (stream.match(/^<\?\w*/)) {
162
- state.curMode = phpMode;
163
- if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, ""))
164
- state.curState = state.php;
165
- return "meta";
166
- }
167
- if (state.pending == '"' || state.pending == "'") {
168
- while (!stream.eol() && stream.next() != state.pending) {}
169
- var style = "string";
170
- } else if (state.pending && stream.pos < state.pending.end) {
171
- stream.pos = state.pending.end;
172
- var style = state.pending.style;
173
- } else {
174
- var style = htmlMode.token(stream, state.curState);
175
- }
176
- if (state.pending) state.pending = null;
177
- var cur = stream.current(), openPHP = cur.search(/<\?/), m;
178
- if (openPHP != -1) {
179
- if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0];
180
- else state.pending = {end: stream.pos, style: style};
181
- stream.backUp(cur.length - openPHP);
182
- }
183
- return style;
184
- } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
185
- state.curMode = htmlMode;
186
- state.curState = state.html;
187
- if (!state.php.context.prev) state.php = null;
188
- return "meta";
189
- } else {
190
- return phpMode.token(stream, state.curState);
191
- }
192
- }
193
-
194
- return {
195
- startState: function() {
196
- var html = CodeMirror.startState(htmlMode)
197
- var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null
198
- return {html: html,
199
- php: php,
200
- curMode: parserConfig.startOpen ? phpMode : htmlMode,
201
- curState: parserConfig.startOpen ? php : html,
202
- pending: null};
203
- },
204
-
205
- copyState: function(state) {
206
- var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
207
- php = state.php, phpNew = php && CodeMirror.copyState(phpMode, php), cur;
208
- if (state.curMode == htmlMode) cur = htmlNew;
209
- else cur = phpNew;
210
- return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
211
- pending: state.pending};
212
- },
213
-
214
- token: dispatch,
215
-
216
- indent: function(state, textAfter) {
217
- if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
218
- (state.curMode == phpMode && /^\?>/.test(textAfter)))
219
- return htmlMode.indent(state.html, textAfter);
220
- return state.curMode.indent(state.curState, textAfter);
221
- },
222
-
223
- blockCommentStart: "/*",
224
- blockCommentEnd: "*/",
225
- lineComment: "//",
226
-
227
- innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
228
- };
229
- }, "htmlmixed", "clike");
230
-
231
- CodeMirror.defineMIME("application/x-httpd-php", "php");
232
- CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
233
- CodeMirror.defineMIME("text/x-php", phpConfig);
234
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/codemirror/xml.js DELETED
@@ -1,385 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: http://codemirror.net/LICENSE
3
-
4
- (function(mod) {
5
- if (typeof exports == "object" && typeof module == "object") // CommonJS
6
- mod(require("../../lib/codemirror"));
7
- else if (typeof define == "function" && define.amd) // AMD
8
- define(["../../lib/codemirror"], mod);
9
- else // Plain browser env
10
- mod(CodeMirror);
11
- })(function(CodeMirror) {
12
- "use strict";
13
-
14
- CodeMirror.defineMode("xml", function(config, parserConfig) {
15
- var indentUnit = config.indentUnit;
16
- var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
17
- var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag;
18
- if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true;
19
-
20
- var Kludges = parserConfig.htmlMode ? {
21
- autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
22
- 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
23
- 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
24
- 'track': true, 'wbr': true, 'menuitem': true},
25
- implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
26
- 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
27
- 'th': true, 'tr': true},
28
- contextGrabbers: {
29
- 'dd': {'dd': true, 'dt': true},
30
- 'dt': {'dd': true, 'dt': true},
31
- 'li': {'li': true},
32
- 'option': {'option': true, 'optgroup': true},
33
- 'optgroup': {'optgroup': true},
34
- 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
35
- 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
36
- 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
37
- 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
38
- 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
39
- 'rp': {'rp': true, 'rt': true},
40
- 'rt': {'rp': true, 'rt': true},
41
- 'tbody': {'tbody': true, 'tfoot': true},
42
- 'td': {'td': true, 'th': true},
43
- 'tfoot': {'tbody': true},
44
- 'th': {'td': true, 'th': true},
45
- 'thead': {'tbody': true, 'tfoot': true},
46
- 'tr': {'tr': true}
47
- },
48
- doNotIndent: {"pre": true},
49
- allowUnquoted: true,
50
- allowMissing: true,
51
- caseFold: true
52
- } : {
53
- autoSelfClosers: {},
54
- implicitlyClosed: {},
55
- contextGrabbers: {},
56
- doNotIndent: {},
57
- allowUnquoted: false,
58
- allowMissing: false,
59
- caseFold: false
60
- };
61
- var alignCDATA = parserConfig.alignCDATA;
62
-
63
- // Return variables for tokenizers
64
- var type, setStyle;
65
-
66
- function inText(stream, state) {
67
- function chain(parser) {
68
- state.tokenize = parser;
69
- return parser(stream, state);
70
- }
71
-
72
- var ch = stream.next();
73
- if (ch == "<") {
74
- if (stream.eat("!")) {
75
- if (stream.eat("[")) {
76
- if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
77
- else return null;
78
- } else if (stream.match("--")) {
79
- return chain(inBlock("comment", "-->"));
80
- } else if (stream.match("DOCTYPE", true, true)) {
81
- stream.eatWhile(/[\w\._\-]/);
82
- return chain(doctype(1));
83
- } else {
84
- return null;
85
- }
86
- } else if (stream.eat("?")) {
87
- stream.eatWhile(/[\w\._\-]/);
88
- state.tokenize = inBlock("meta", "?>");
89
- return "meta";
90
- } else {
91
- type = stream.eat("/") ? "closeTag" : "openTag";
92
- state.tokenize = inTag;
93
- return "tag bracket";
94
- }
95
- } else if (ch == "&") {
96
- var ok;
97
- if (stream.eat("#")) {
98
- if (stream.eat("x")) {
99
- ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
100
- } else {
101
- ok = stream.eatWhile(/[\d]/) && stream.eat(";");
102
- }
103
- } else {
104
- ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
105
- }
106
- return ok ? "atom" : "error";
107
- } else {
108
- stream.eatWhile(/[^&<]/);
109
- return null;
110
- }
111
- }
112
- inText.isInText = true;
113
-
114
- function inTag(stream, state) {
115
- var ch = stream.next();
116
- if (ch == ">" || (ch == "/" && stream.eat(">"))) {
117
- state.tokenize = inText;
118
- type = ch == ">" ? "endTag" : "selfcloseTag";
119
- return "tag bracket";
120
- } else if (ch == "=") {
121
- type = "equals";
122
- return null;
123
- } else if (ch == "<") {
124
- state.tokenize = inText;
125
- state.state = baseState;
126
- state.tagName = state.tagStart = null;
127
- var next = state.tokenize(stream, state);
128
- return next ? next + " tag error" : "tag error";
129
- } else if (/[\'\"]/.test(ch)) {
130
- state.tokenize = inAttribute(ch);
131
- state.stringStartCol = stream.column();
132
- return state.tokenize(stream, state);
133
- } else {
134
- stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
135
- return "word";
136
- }
137
- }
138
-
139
- function inAttribute(quote) {
140
- var closure = function(stream, state) {
141
- while (!stream.eol()) {
142
- if (stream.next() == quote) {
143
- state.tokenize = inTag;
144
- break;
145
- }
146
- }
147
- return "string";
148
- };
149
- closure.isInAttribute = true;
150
- return closure;
151
- }
152
-
153
- function inBlock(style, terminator) {
154
- return function(stream, state) {
155
- while (!stream.eol()) {
156
- if (stream.match(terminator)) {
157
- state.tokenize = inText;
158
- break;
159
- }
160
- stream.next();
161
- }
162
- return style;
163
- };
164
- }
165
- function doctype(depth) {
166
- return function(stream, state) {
167
- var ch;
168
- while ((ch = stream.next()) != null) {
169
- if (ch == "<") {
170
- state.tokenize = doctype(depth + 1);
171
- return state.tokenize(stream, state);
172
- } else if (ch == ">") {
173
- if (depth == 1) {
174
- state.tokenize = inText;
175
- break;
176
- } else {
177
- state.tokenize = doctype(depth - 1);
178
- return state.tokenize(stream, state);
179
- }
180
- }
181
- }
182
- return "meta";
183
- };
184
- }
185
-
186
- function Context(state, tagName, startOfLine) {
187
- this.prev = state.context;
188
- this.tagName = tagName;
189
- this.indent = state.indented;
190
- this.startOfLine = startOfLine;
191
- if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
192
- this.noIndent = true;
193
- }
194
- function popContext(state) {
195
- if (state.context) state.context = state.context.prev;
196
- }
197
- function maybePopContext(state, nextTagName) {
198
- var parentTagName;
199
- while (true) {
200
- if (!state.context) {
201
- return;
202
- }
203
- parentTagName = state.context.tagName;
204
- if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
205
- !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
206
- return;
207
- }
208
- popContext(state);
209
- }
210
- }
211
-
212
- function baseState(type, stream, state) {
213
- if (type == "openTag") {
214
- state.tagStart = stream.column();
215
- return tagNameState;
216
- } else if (type == "closeTag") {
217
- return closeTagNameState;
218
- } else {
219
- return baseState;
220
- }
221
- }
222
- function tagNameState(type, stream, state) {
223
- if (type == "word") {
224
- state.tagName = stream.current();
225
- setStyle = "tag";
226
- return attrState;
227
- } else {
228
- setStyle = "error";
229
- return tagNameState;
230
- }
231
- }
232
- function closeTagNameState(type, stream, state) {
233
- if (type == "word") {
234
- var tagName = stream.current();
235
- if (state.context && state.context.tagName != tagName &&
236
- Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName))
237
- popContext(state);
238
- if (state.context && state.context.tagName == tagName) {
239
- setStyle = "tag";
240
- return closeState;
241
- } else {
242
- setStyle = "tag error";
243
- return closeStateErr;
244
- }
245
- } else {
246
- setStyle = "error";
247
- return closeStateErr;
248
- }
249
- }
250
-
251
- function closeState(type, _stream, state) {
252
- if (type != "endTag") {
253
- setStyle = "error";
254
- return closeState;
255
- }
256
- popContext(state);
257
- return baseState;
258
- }
259
- function closeStateErr(type, stream, state) {
260
- setStyle = "error";
261
- return closeState(type, stream, state);
262
- }
263
-
264
- function attrState(type, _stream, state) {
265
- if (type == "word") {
266
- setStyle = "attribute";
267
- return attrEqState;
268
- } else if (type == "endTag" || type == "selfcloseTag") {
269
- var tagName = state.tagName, tagStart = state.tagStart;
270
- state.tagName = state.tagStart = null;
271
- if (type == "selfcloseTag" ||
272
- Kludges.autoSelfClosers.hasOwnProperty(tagName)) {
273
- maybePopContext(state, tagName);
274
- } else {
275
- maybePopContext(state, tagName);
276
- state.context = new Context(state, tagName, tagStart == state.indented);
277
- }
278
- return baseState;
279
- }
280
- setStyle = "error";
281
- return attrState;
282
- }
283
- function attrEqState(type, stream, state) {
284
- if (type == "equals") return attrValueState;
285
- if (!Kludges.allowMissing) setStyle = "error";
286
- return attrState(type, stream, state);
287
- }
288
- function attrValueState(type, stream, state) {
289
- if (type == "string") return attrContinuedState;
290
- if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
291
- setStyle = "error";
292
- return attrState(type, stream, state);
293
- }
294
- function attrContinuedState(type, stream, state) {
295
- if (type == "string") return attrContinuedState;
296
- return attrState(type, stream, state);
297
- }
298
-
299
- return {
300
- startState: function() {
301
- return {tokenize: inText,
302
- state: baseState,
303
- indented: 0,
304
- tagName: null, tagStart: null,
305
- context: null};
306
- },
307
-
308
- token: function(stream, state) {
309
- if (!state.tagName && stream.sol())
310
- state.indented = stream.indentation();
311
-
312
- if (stream.eatSpace()) return null;
313
- type = null;
314
- var style = state.tokenize(stream, state);
315
- if ((style || type) && style != "comment") {
316
- setStyle = null;
317
- state.state = state.state(type || style, stream, state);
318
- if (setStyle)
319
- style = setStyle == "error" ? style + " error" : setStyle;
320
- }
321
- return style;
322
- },
323
-
324
- indent: function(state, textAfter, fullLine) {
325
- var context = state.context;
326
- // Indent multi-line strings (e.g. css).
327
- if (state.tokenize.isInAttribute) {
328
- if (state.tagStart == state.indented)
329
- return state.stringStartCol + 1;
330
- else
331
- return state.indented + indentUnit;
332
- }
333
- if (context && context.noIndent) return CodeMirror.Pass;
334
- if (state.tokenize != inTag && state.tokenize != inText)
335
- return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
336
- // Indent the starts of attribute names.
337
- if (state.tagName) {
338
- if (multilineTagIndentPastTag)
339
- return state.tagStart + state.tagName.length + 2;
340
- else
341
- return state.tagStart + indentUnit * multilineTagIndentFactor;
342
- }
343
- if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
344
- var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
345
- if (tagAfter && tagAfter[1]) { // Closing tag spotted
346
- while (context) {
347
- if (context.tagName == tagAfter[2]) {
348
- context = context.prev;
349
- break;
350
- } else if (Kludges.implicitlyClosed.hasOwnProperty(context.tagName)) {
351
- context = context.prev;
352
- } else {
353
- break;
354
- }
355
- }
356
- } else if (tagAfter) { // Opening tag spotted
357
- while (context) {
358
- var grabbers = Kludges.contextGrabbers[context.tagName];
359
- if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
360
- context = context.prev;
361
- else
362
- break;
363
- }
364
- }
365
- while (context && !context.startOfLine)
366
- context = context.prev;
367
- if (context) return context.indent + indentUnit;
368
- else return 0;
369
- },
370
-
371
- electricInput: /<\/[\s\w:]+>$/,
372
- blockCommentStart: "<!--",
373
- blockCommentEnd: "-->",
374
-
375
- configuration: parserConfig.htmlMode ? "html" : "xml",
376
- helperType: parserConfig.htmlMode ? "html" : "xml"
377
- };
378
- });
379
-
380
- CodeMirror.defineMIME("text/xml", "xml");
381
- CodeMirror.defineMIME("application/xml", "xml");
382
- if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
383
- CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
384
-
385
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/css/codemirror.css DELETED
@@ -1,337 +0,0 @@
1
- /* BASICS */
2
-
3
- .CodeMirror {
4
- /* Set height, width, borders, and global font properties here */
5
- font-family: monospace;
6
- height: 200px;
7
- color: black;
8
- }
9
-
10
- /* PADDING */
11
-
12
- .CodeMirror-lines {
13
- padding: 4px 0; /* Vertical padding around content */
14
- }
15
- .CodeMirror pre {
16
- padding: 0 4px; /* Horizontal padding of content */
17
- }
18
-
19
- .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
20
- background-color: white; /* The little square between H and V scrollbars */
21
- }
22
-
23
- /* GUTTER */
24
-
25
- .CodeMirror-gutters {
26
- border-right: 1px solid #ddd;
27
- background-color: #f7f7f7;
28
- white-space: nowrap;
29
- }
30
- .CodeMirror-linenumbers {}
31
- .CodeMirror-linenumber {
32
- padding: 0 3px 0 5px;
33
- min-width: 20px;
34
- text-align: right;
35
- color: #999;
36
- white-space: nowrap;
37
- }
38
-
39
- .CodeMirror-guttermarker { color: black; }
40
- .CodeMirror-guttermarker-subtle { color: #999; }
41
-
42
- /* CURSOR */
43
-
44
- .CodeMirror-cursor {
45
- border-left: 1px solid black;
46
- border-right: none;
47
- width: 0;
48
- }
49
- /* Shown when moving in bi-directional text */
50
- .CodeMirror div.CodeMirror-secondarycursor {
51
- border-left: 1px solid silver;
52
- }
53
- .cm-fat-cursor .CodeMirror-cursor {
54
- width: auto;
55
- border: 0;
56
- background: #7e7;
57
- }
58
- .cm-fat-cursor div.CodeMirror-cursors {
59
- z-index: 1;
60
- }
61
-
62
- .cm-animate-fat-cursor {
63
- width: auto;
64
- border: 0;
65
- -webkit-animation: blink 1.06s steps(1) infinite;
66
- -moz-animation: blink 1.06s steps(1) infinite;
67
- animation: blink 1.06s steps(1) infinite;
68
- background-color: #7e7;
69
- }
70
- @-moz-keyframes blink {
71
- 0% {}
72
- 50% { background-color: transparent; }
73
- 100% {}
74
- }
75
- @-webkit-keyframes blink {
76
- 0% {}
77
- 50% { background-color: transparent; }
78
- 100% {}
79
- }
80
- @keyframes blink {
81
- 0% {}
82
- 50% { background-color: transparent; }
83
- 100% {}
84
- }
85
-
86
- /* Can style cursor different in overwrite (non-insert) mode */
87
- .CodeMirror-overwrite .CodeMirror-cursor {}
88
-
89
- .cm-tab { display: inline-block; text-decoration: inherit; }
90
-
91
- .CodeMirror-ruler {
92
- border-left: 1px solid #ccc;
93
- position: absolute;
94
- }
95
-
96
- /* DEFAULT THEME */
97
-
98
- .cm-s-default .cm-header {color: blue;}
99
- .cm-s-default .cm-quote {color: #090;}
100
- .cm-negative {color: #d44;}
101
- .cm-positive {color: #292;}
102
- .cm-header, .cm-strong {font-weight: bold;}
103
- .cm-em {font-style: italic;}
104
- .cm-link {text-decoration: underline;}
105
- .cm-strikethrough {text-decoration: line-through;}
106
-
107
- .cm-s-default .cm-keyword {color: #708;}
108
- .cm-s-default .cm-atom {color: #219;}
109
- .cm-s-default .cm-number {color: #164;}
110
- .cm-s-default .cm-def {color: #00f;}
111
- .cm-s-default .cm-variable,
112
- .cm-s-default .cm-punctuation,
113
- .cm-s-default .cm-property,
114
- .cm-s-default .cm-operator {}
115
- .cm-s-default .cm-variable-2 {color: #05a;}
116
- .cm-s-default .cm-variable-3 {color: #085;}
117
- .cm-s-default .cm-comment {color: #a50;}
118
- .cm-s-default .cm-string {color: #a11;}
119
- .cm-s-default .cm-string-2 {color: #f50;}
120
- .cm-s-default .cm-meta {color: #555;}
121
- .cm-s-default .cm-qualifier {color: #555;}
122
- .cm-s-default .cm-builtin {color: #30a;}
123
- .cm-s-default .cm-bracket {color: #997;}
124
- .cm-s-default .cm-tag {color: #170;}
125
- .cm-s-default .cm-attribute {color: #00c;}
126
- .cm-s-default .cm-hr {color: #999;}
127
- .cm-s-default .cm-link {color: #00c;}
128
-
129
- .cm-s-default .cm-error {color: #f00;}
130
- .cm-invalidchar {color: #f00;}
131
-
132
- .CodeMirror-composing { border-bottom: 2px solid; }
133
-
134
- /* Default styles for common addons */
135
-
136
- div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
137
- div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
138
- .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
139
- .CodeMirror-activeline-background {background: #e8f2ff;}
140
-
141
- /* STOP */
142
-
143
- /* The rest of this file contains styles related to the mechanics of
144
- the editor. You probably shouldn't touch them. */
145
-
146
- .CodeMirror {
147
- position: relative;
148
- overflow: hidden;
149
- background: white;
150
- }
151
-
152
- .CodeMirror-scroll {
153
- overflow: scroll !important; /* Things will break if this is overridden */
154
- /* 30px is the magic margin used to hide the element's real scrollbars */
155
- /* See overflow: hidden in .CodeMirror */
156
- margin-bottom: -30px; margin-right: -30px;
157
- padding-bottom: 30px;
158
- height: 100%;
159
- outline: none; /* Prevent dragging from highlighting the element */
160
- position: relative;
161
- }
162
- .CodeMirror-sizer {
163
- position: relative;
164
- margin-left: 30px !important;
165
- min-height: 120px !important;
166
- border-right: 30px solid transparent;
167
- }
168
-
169
- /* The fake, visible scrollbars. Used to force redraw during scrolling
170
- before actuall scrolling happens, thus preventing shaking and
171
- flickering artifacts. */
172
- .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
173
- position: absolute;
174
- z-index: 6;
175
- display: none;
176
- }
177
- .CodeMirror-vscrollbar {
178
- right: 0; top: 0;
179
- overflow-x: hidden;
180
- overflow-y: scroll;
181
- }
182
- .CodeMirror-hscrollbar {
183
- bottom: 0; left: 0;
184
- overflow-y: hidden;
185
- overflow-x: scroll;
186
- }
187
- .CodeMirror-scrollbar-filler {
188
- right: 0; bottom: 0;
189
- }
190
- .CodeMirror-gutter-filler {
191
- left: 0; bottom: 0;
192
- }
193
-
194
- .CodeMirror-gutters {
195
- position: absolute; left: 0; top: 0;
196
- z-index: 3;
197
- }
198
- .CodeMirror-gutter {
199
- white-space: normal;
200
- height: 100%;
201
- display: inline-block;
202
- margin-bottom: -30px;
203
- width: 29px !important;
204
- /* Hack to make IE7 behave */
205
- *zoom:1;
206
- *display:inline;
207
- }
208
- .CodeMirror-gutter-wrapper {
209
- position: absolute;
210
- z-index: 4;
211
- background: none !important;
212
- border: none !important;
213
- }
214
- .CodeMirror-gutter-background {
215
- position: absolute;
216
- top: 0; bottom: 0;
217
- z-index: 4;
218
- }
219
- .CodeMirror-gutter-elt {
220
- position: absolute;
221
- cursor: default;
222
- z-index: 4;
223
- }
224
- .CodeMirror-gutter-wrapper {
225
- -webkit-user-select: none;
226
- -moz-user-select: none;
227
- user-select: none;
228
- }
229
-
230
- .CodeMirror-lines {
231
- cursor: text;
232
- min-height: 1px; /* prevents collapsing before first draw */
233
- }
234
- .CodeMirror pre {
235
- /* Reset some styles that the rest of the page might have set */
236
- -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
237
- border-width: 0;
238
- background: transparent;
239
- font-family: inherit;
240
- font-size: inherit;
241
- margin: 0;
242
- white-space: pre;
243
- word-wrap: normal;
244
- line-height: inherit;
245
- color: inherit;
246
- z-index: 2;
247
- position: relative;
248
- overflow: visible;
249
- -webkit-tap-highlight-color: transparent;
250
- }
251
- .CodeMirror-wrap pre {
252
- word-wrap: break-word;
253
- white-space: pre-wrap;
254
- word-break: normal;
255
- }
256
-
257
- .CodeMirror-linebackground {
258
- position: absolute;
259
- left: 0; right: 0; top: 0; bottom: 0;
260
- z-index: 0;
261
- }
262
-
263
- .CodeMirror-linewidget {
264
- position: relative;
265
- z-index: 2;
266
- overflow: auto;
267
- }
268
-
269
- .CodeMirror-widget {}
270
-
271
- .CodeMirror-code {
272
- outline: none;
273
- }
274
-
275
- /* Force content-box sizing for the elements where we expect it */
276
- .CodeMirror-scroll,
277
- .CodeMirror-sizer,
278
- .CodeMirror-gutter,
279
- .CodeMirror-gutters,
280
- .CodeMirror-linenumber {
281
- -moz-box-sizing: content-box;
282
- box-sizing: content-box;
283
- }
284
-
285
- .CodeMirror-measure {
286
- position: absolute;
287
- width: 100%;
288
- height: 0;
289
- overflow: hidden;
290
- visibility: hidden;
291
- }
292
-
293
- .CodeMirror-cursor { position: absolute; }
294
- .CodeMirror-measure pre { position: static; }
295
-
296
- div.CodeMirror-cursors {
297
- visibility: hidden;
298
- position: relative;
299
- z-index: 3;
300
- }
301
- div.CodeMirror-dragcursors {
302
- visibility: visible;
303
- }
304
-
305
- .CodeMirror-focused div.CodeMirror-cursors {
306
- visibility: visible;
307
- }
308
-
309
- .CodeMirror-selected { background: #d9d9d9; }
310
- .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
311
- .CodeMirror-crosshair { cursor: crosshair; }
312
- .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
313
- .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
314
-
315
- .cm-searching {
316
- background: #ffa;
317
- background: rgba(255, 255, 0, .4);
318
- }
319
-
320
- /* IE7 hack to prevent it from returning funny offsetTops on the spans */
321
- .CodeMirror span { *vertical-align: text-bottom; }
322
-
323
- /* Used to force a border model for a node */
324
- .cm-force-border { padding-right: .1px; }
325
-
326
- @media print {
327
- /* Hide the cursor when printing */
328
- .CodeMirror div.CodeMirror-cursors {
329
- visibility: hidden;
330
- }
331
- }
332
-
333
- /* See issue #2901 */
334
- .cm-tab-wrap-hack:after { content: ''; }
335
-
336
- /* Help users use markselection to safely style text background */
337
- span.CodeMirror-selectedtext { background: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/js/jquery/moment.js DELETED
@@ -1,6 +0,0 @@
1
- // moment.js
2
- // version : 1.7.2
3
- // author : Tim Wood
4
- // license : MIT
5
- // momentjs.com
6
- (function(a){function E(a,b,c,d){var e=c.lang();return e[a].call?e[a](c,d):e[a][b]}function F(a,b){return function(c){return K(a.call(this,c),b)}}function G(a){return function(b){var c=a.call(this,b);return c+this.lang().ordinal(c)}}function H(a,b,c){this._d=a,this._isUTC=!!b,this._a=a._a||null,this._lang=c||!1}function I(a){var b=this._data={},c=a.years||a.y||0,d=a.months||a.M||0,e=a.weeks||a.w||0,f=a.days||a.d||0,g=a.hours||a.h||0,h=a.minutes||a.m||0,i=a.seconds||a.s||0,j=a.milliseconds||a.ms||0;this._milliseconds=j+i*1e3+h*6e4+g*36e5,this._days=f+e*7,this._months=d+c*12,b.milliseconds=j%1e3,i+=J(j/1e3),b.seconds=i%60,h+=J(i/60),b.minutes=h%60,g+=J(h/60),b.hours=g%24,f+=J(g/24),f+=e*7,b.days=f%30,d+=J(f/30),b.months=d%12,c+=J(d/12),b.years=c,this._lang=!1}function J(a){return a<0?Math.ceil(a):Math.floor(a)}function K(a,b){var c=a+"";while(c.length<b)c="0"+c;return c}function L(a,b,c){var d=b._milliseconds,e=b._days,f=b._months,g;d&&a._d.setTime(+a+d*c),e&&a.date(a.date()+e*c),f&&(g=a.date(),a.date(1).month(a.month()+f*c).date(Math.min(g,a.daysInMonth())))}function M(a){return Object.prototype.toString.call(a)==="[object Array]"}function N(a,b){var c=Math.min(a.length,b.length),d=Math.abs(a.length-b.length),e=0,f;for(f=0;f<c;f++)~~a[f]!==~~b[f]&&e++;return e+d}function O(a,b,c,d){var e,f,g=[];for(e=0;e<7;e++)g[e]=a[e]=a[e]==null?e===2?1:0:a[e];return a[7]=g[7]=b,a[8]!=null&&(g[8]=a[8]),a[3]+=c||0,a[4]+=d||0,f=new Date(0),b?(f.setUTCFullYear(a[0],a[1],a[2]),f.setUTCHours(a[3],a[4],a[5],a[6])):(f.setFullYear(a[0],a[1],a[2]),f.setHours(a[3],a[4],a[5],a[6])),f._a=g,f}function P(a,c){var d,e,g=[];!c&&h&&(c=require("./lang/"+a));for(d=0;d<i.length;d++)c[i[d]]=c[i[d]]||f.en[i[d]];for(d=0;d<12;d++)e=b([2e3,d]),g[d]=new RegExp("^"+(c.months[d]||c.months(e,""))+"|^"+(c.monthsShort[d]||c.monthsShort(e,"")).replace(".",""),"i");return c.monthsParse=c.monthsParse||g,f[a]=c,c}function Q(a){var c=typeof a=="string"&&a||a&&a._lang||null;return c?f[c]||P(c):b}function R(a){return a.match(/\[.*\]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function S(a){var b=a.match(k),c,d;for(c=0,d=b.length;c<d;c++)D[b[c]]?b[c]=D[b[c]]:b[c]=R(b[c]);return function(e){var f="";for(c=0;c<d;c++)f+=typeof b[c].call=="function"?b[c].call(e,a):b[c];return f}}function T(a,b){function d(b){return a.lang().longDateFormat[b]||b}var c=5;while(c--&&l.test(b))b=b.replace(l,d);return A[b]||(A[b]=S(b)),A[b](a)}function U(a){switch(a){case"DDDD":return p;case"YYYY":return q;case"S":case"SS":case"SSS":case"DDD":return o;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":case"a":case"A":return r;case"Z":case"ZZ":return s;case"T":return t;case"MM":case"DD":case"YY":case"HH":case"hh":case"mm":case"ss":case"M":case"D":case"d":case"H":case"h":case"m":case"s":return n;default:return new RegExp(a.replace("\\",""))}}function V(a,b,c,d){var e,f;switch(a){case"M":case"MM":c[1]=b==null?0:~~b-1;break;case"MMM":case"MMMM":for(e=0;e<12;e++)if(Q().monthsParse[e].test(b)){c[1]=e,f=!0;break}f||(c[8]=!1);break;case"D":case"DD":case"DDD":case"DDDD":b!=null&&(c[2]=~~b);break;case"YY":c[0]=~~b+(~~b>70?1900:2e3);break;case"YYYY":c[0]=~~Math.abs(b);break;case"a":case"A":d.isPm=(b+"").toLowerCase()==="pm";break;case"H":case"HH":case"h":case"hh":c[3]=~~b;break;case"m":case"mm":c[4]=~~b;break;case"s":case"ss":c[5]=~~b;break;case"S":case"SS":case"SSS":c[6]=~~(("0."+b)*1e3);break;case"Z":case"ZZ":d.isUTC=!0,e=(b+"").match(x),e&&e[1]&&(d.tzh=~~e[1]),e&&e[2]&&(d.tzm=~~e[2]),e&&e[0]==="+"&&(d.tzh=-d.tzh,d.tzm=-d.tzm)}b==null&&(c[8]=!1)}function W(a,b){var c=[0,0,1,0,0,0,0],d={tzh:0,tzm:0},e=b.match(k),f,g;for(f=0;f<e.length;f++)g=(U(e[f]).exec(a)||[])[0],g&&(a=a.slice(a.indexOf(g)+g.length)),D[e[f]]&&V(e[f],g,c,d);return d.isPm&&c[3]<12&&(c[3]+=12),d.isPm===!1&&c[3]===12&&(c[3]=0),O(c,d.isUTC,d.tzh,d.tzm)}function X(a,b){var c,d=a.match(m)||[],e,f=99,g,h,i;for(g=0;g<b.length;g++)h=W(a,b[g]),e=T(new H(h),b[g]).match(m)||[],i=N(d,e),i<f&&(f=i,c=h);return c}function Y(a){var b="YYYY-MM-DDT",c;if(u.exec(a)){for(c=0;c<4;c++)if(w[c][1].exec(a)){b+=w[c][0];break}return s.exec(a)?W(a,b+" Z"):W(a,b)}return new Date(a)}function Z(a,b,c,d,e){var f=e.relativeTime[a];return typeof f=="function"?f(b||1,!!c,a,d):f.replace(/%d/i,b||1)}function $(a,b,c){var e=d(Math.abs(a)/1e3),f=d(e/60),g=d(f/60),h=d(g/24),i=d(h/365),j=e<45&&["s",e]||f===1&&["m"]||f<45&&["mm",f]||g===1&&["h"]||g<22&&["hh",g]||h===1&&["d"]||h<=25&&["dd",h]||h<=45&&["M"]||h<345&&["MM",d(h/30)]||i===1&&["y"]||["yy",i];return j[2]=b,j[3]=a>0,j[4]=c,Z.apply({},j)}function _(a,c){b.fn[a]=function(a){var b=this._isUTC?"UTC":"";return a!=null?(this._d["set"+b+c](a),this):this._d["get"+b+c]()}}function ab(a){b.duration.fn[a]=function(){return this._data[a]}}function bb(a,c){b.duration.fn["as"+a]=function(){return+this/c}}var b,c="1.7.2",d=Math.round,e,f={},g="en",h=typeof module!="undefined"&&module.exports,i="months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem".split("|"),j=/^\/?Date\((\-?\d+)/i,k=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|SS?S?|zz?|ZZ?|.)/g,l=/(\[[^\[]*\])|(\\)?(LT|LL?L?L?)/g,m=/([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,n=/\d\d?/,o=/\d{1,3}/,p=/\d{3}/,q=/\d{1,4}/,r=/[0-9a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+/i,s=/Z|[\+\-]\d\d:?\d\d/i,t=/T/i,u=/^\s*\d{4}-\d\d-\d\d(T(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,v="YYYY-MM-DDTHH:mm:ssZ",w=[["HH:mm:ss.S",/T\d\d:\d\d:\d\d\.\d{1,3}/],["HH:mm:ss",/T\d\d:\d\d:\d\d/],["HH:mm",/T\d\d:\d\d/],["HH",/T\d\d/]],x=/([\+\-]|\d\d)/gi,y="Month|Date|Hours|Minutes|Seconds|Milliseconds".split("|"),z={Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6},A={},B="DDD w M D d".split(" "),C="M D H h m s w".split(" "),D={M:function(){return this.month()+1},MMM:function(a){return E("monthsShort",this.month(),this,a)},MMMM:function(a){return E("months",this.month(),this,a)},D:function(){return this.date()},DDD:function(){var a=new Date(this.year(),this.month(),this.date()),b=new Date(this.year(),0,1);return~~((a-b)/864e5+1.5)},d:function(){return this.day()},dd:function(a){return E("weekdaysMin",this.day(),this,a)},ddd:function(a){return E("weekdaysShort",this.day(),this,a)},dddd:function(a){return E("weekdays",this.day(),this,a)},w:function(){var a=new Date(this.year(),this.month(),this.date()-this.day()+5),b=new Date(a.getFullYear(),0,4);return~~((a-b)/864e5/7+1.5)},YY:function(){return K(this.year()%100,2)},YYYY:function(){return K(this.year(),4)},a:function(){return this.lang().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.lang().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return~~(this.milliseconds()/100)},SS:function(){return K(~~(this.milliseconds()/10),2)},SSS:function(){return K(this.milliseconds(),3)},Z:function(){var a=-this.zone(),b="+";return a<0&&(a=-a,b="-"),b+K(~~(a/60),2)+":"+K(~~a%60,2)},ZZ:function(){var a=-this.zone(),b="+";return a<0&&(a=-a,b="-"),b+K(~~(10*a/6),4)}};while(B.length)e=B.pop(),D[e+"o"]=G(D[e]);while(C.length)e=C.pop(),D[e+e]=F(D[e],2);D.DDDD=F(D.DDD,3),b=function(c,d){if(c===null||c==="")return null;var e,f;return b.isMoment(c)?new H(new Date(+c._d),c._isUTC,c._lang):(d?M(d)?e=X(c,d):e=W(c,d):(f=j.exec(c),e=c===a?new Date:f?new Date(+f[1]):c instanceof Date?c:M(c)?O(c):typeof c=="string"?Y(c):new Date(c)),new H(e))},b.utc=function(a,c){return M(a)?new H(O(a,!0),!0):(typeof a=="string"&&!s.exec(a)&&(a+=" +0000",c&&(c+=" Z")),b(a,c).utc())},b.unix=function(a){return b(a*1e3)},b.duration=function(a,c){var d=b.isDuration(a),e=typeof a=="number",f=d?a._data:e?{}:a,g;return e&&(c?f[c]=a:f.milliseconds=a),g=new I(f),d&&(g._lang=a._lang),g},b.humanizeDuration=function(a,c,d){return b.duration(a,c===!0?null:c).humanize(c===!0?!0:d)},b.version=c,b.defaultFormat=v,b.lang=function(a,c){var d;if(!a)return g;(c||!f[a])&&P(a,c);if(f[a]){for(d=0;d<i.length;d++)b[i[d]]=f[a][i[d]];b.monthsParse=f[a].monthsParse,g=a}},b.langData=Q,b.isMoment=function(a){return a instanceof H},b.isDuration=function(a){return a instanceof I},b.lang("en",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D YYYY",LLL:"MMMM D YYYY LT",LLLL:"dddd, MMMM D YYYY LT"},meridiem:function(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}}),b.fn=H.prototype={clone:function(){return b(this)},valueOf:function(){return+this._d},unix:function(){return Math.floor(+this._d/1e3)},toString:function(){return this._d.toString()},toDate:function(){return this._d},toArray:function(){var a=this;return[a.year(),a.month(),a.date(),a.hours(),a.minutes(),a.seconds(),a.milliseconds(),!!this._isUTC]},isValid:function(){return this._a?this._a[8]!=null?!!this._a[8]:!N(this._a,(this._a[7]?b.utc(this._a):b(this._a)).toArray()):!isNaN(this._d.getTime())},utc:function(){return this._isUTC=!0,this},local:function(){return this._isUTC=!1,this},format:function(a){return T(this,a?a:b.defaultFormat)},add:function(a,c){var d=c?b.duration(+c,a):b.duration(a);return L(this,d,1),this},subtract:function(a,c){var d=c?b.duration(+c,a):b.duration(a);return L(this,d,-1),this},diff:function(a,c,e){var f=this._isUTC?b(a).utc():b(a).local(),g=(this.zone()-f.zone())*6e4,h=this._d-f._d-g,i=this.year()-f.year(),j=this.month()-f.month(),k=this.date()-f.date(),l;return c==="months"?l=i*12+j+k/30:c==="years"?l=i+(j+k/30)/12:l=c==="seconds"?h/1e3:c==="minutes"?h/6e4:c==="hours"?h/36e5:c==="days"?h/864e5:c==="weeks"?h/6048e5:h,e?l:d(l)},from:function(a,c){return b.duration(this.diff(a)).lang(this._lang).humanize(!c)},fromNow:function(a){return this.from(b(),a)},calendar:function(){var a=this.diff(b().sod(),"days",!0),c=this.lang().calendar,d=c.sameElse,e=a<-6?d:a<-1?c.lastWeek:a<0?c.lastDay:a<1?c.sameDay:a<2?c.nextDay:a<7?c.nextWeek:d;return this.format(typeof e=="function"?e.apply(this):e)},isLeapYear:function(){var a=this.year();return a%4===0&&a%100!==0||a%400===0},isDST:function(){return this.zone()<b([this.year()]).zone()||this.zone()<b([this.year(),5]).zone()},day:function(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return a==null?b:this.add({d:a-b})},startOf:function(a){switch(a.replace(/s$/,"")){case"year":this.month(0);case"month":this.date(1);case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return this},endOf:function(a){return this.startOf(a).add(a.replace(/s?$/,"s"),1).subtract("ms",1)},sod:function(){return this.clone().startOf("day")},eod:function(){return this.clone().endOf("day")},zone:function(){return this._isUTC?0:this._d.getTimezoneOffset()},daysInMonth:function(){return b.utc([this.year(),this.month()+1,0]).date()},lang:function(b){return b===a?Q(this):(this._lang=b,this)}};for(e=0;e<y.length;e++)_(y[e].toLowerCase(),y[e]);_("year","FullYear"),b.duration.fn=I.prototype={weeks:function(){return J(this.days()/7)},valueOf:function(){return this._milliseconds+this._days*864e5+this._months*2592e6},humanize:function(a){var b=+this,c=this.lang().relativeTime,d=$(b,!a,this.lang()),e=b<=0?c.past:c.future;return a&&(typeof e=="function"?d=e(d):d=e.replace(/%s/i,d)),d},lang:b.fn.lang};for(e in z)z.hasOwnProperty(e)&&(bb(e,z[e]),ab(e.toLowerCase()));bb("Weeks",6048e5),h&&(module.exports=b),typeof ender=="undefined"&&(this.wpai_moment=b),typeof define=="function"&&define.amd&&define("wpai_moment",[],function(){return b})}).call(this);
 
 
 
 
 
 
views/admin/addons/index.php CHANGED
@@ -8,12 +8,12 @@
8
  <h3><?php _e('Premium Add-ons', 'wp_all_import_plugin'); ?></h3>
9
  <?php foreach( $premium as $addon ): ?>
10
  <div class="pmxi-add-on wp-box <?php if( $addon['active'] ): ?>pmxi-add-on-active<?php endif; ?>">
11
- <a target="_blank" href="<?php echo $addon['url']; ?>">
12
- <img src="<?php echo $addon['thumbnail']; ?>" />
13
  </a>
14
  <div class="inner">
15
- <h3><a target="_blank" href="<?php echo $addon['url']; ?>"><?php echo $addon['title']; ?></a></h3>
16
- <p><?php echo $addon['description']; ?></p>
17
  </div>
18
  <div class="footer">
19
  <?php if ( $addon['active'] ): ?>
@@ -26,19 +26,19 @@
26
  foreach ($addon['required_plugins'] as $name => $active):
27
  if (!$active){
28
  ?>
29
- <p style="margin:3px 0px;"><?php echo $name . __(' required', 'wp_all_import_plugin'); ?></p>
30
  <?php
31
  $all_required_plugins_installed = false;
32
  }
33
  endforeach;
34
  if ($all_required_plugins_installed){
35
  ?>
36
- <a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Download",'acf'); ?></a>
37
  <?php
38
  }
39
  ?>
40
  <?php else: ?>
41
- <a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Purchase & Install",'acf'); ?></a>
42
  <?php endif; ?>
43
  </div>
44
  </div>
@@ -49,12 +49,12 @@
49
  <h3><?php _e('Free Add-ons', 'wp_all_import_plugin'); ?></h3>
50
  <?php foreach( $free as $addon ): ?>
51
  <div class="pmxi-add-on wp-box <?php if( $addon['active'] ): ?>pmxi-add-on-active<?php endif; ?>">
52
- <a target="_blank" href="<?php echo $addon['url']; ?>">
53
- <img src="<?php echo $addon['thumbnail']; ?>" />
54
  </a>
55
  <div class="inner">
56
- <h3><a target="_blank" href="<?php echo $addon['url']; ?>"><?php echo $addon['title']; ?></a></h3>
57
- <p><?php echo $addon['description']; ?></p>
58
  </div>
59
  <div class="footer">
60
  <?php if( $addon['active'] ): ?>
@@ -67,19 +67,19 @@
67
  foreach ($addon['required_plugins'] as $name => $active):
68
  if (!$active){
69
  ?>
70
- <p style="margin:3px 0px;"><?php echo $name . __(' required', 'wp_all_import_plugin'); ?></p>
71
  <?php
72
  $all_required_plugins_installed = false;
73
  }
74
  endforeach;
75
  if ($all_required_plugins_installed){
76
  ?>
77
- <a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Download",'acf'); ?></a>
78
  <?php
79
  }
80
  ?>
81
  <?php else: ?>
82
- <a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Download",'acf'); ?></a>
83
  <?php endif; ?>
84
  </div>
85
  </div>
8
  <h3><?php _e('Premium Add-ons', 'wp_all_import_plugin'); ?></h3>
9
  <?php foreach( $premium as $addon ): ?>
10
  <div class="pmxi-add-on wp-box <?php if( $addon['active'] ): ?>pmxi-add-on-active<?php endif; ?>">
11
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>">
12
+ <img src="<?php echo esc_url($addon['thumbnail']); ?>" />
13
  </a>
14
  <div class="inner">
15
+ <h3><a target="_blank" href="<?php echo esc_url($addon['url']); ?>"><?php echo esc_html($addon['title']); ?></a></h3>
16
+ <p><?php echo esc_html($addon['description']); ?></p>
17
  </div>
18
  <div class="footer">
19
  <?php if ( $addon['active'] ): ?>
26
  foreach ($addon['required_plugins'] as $name => $active):
27
  if (!$active){
28
  ?>
29
+ <p style="margin:3px 0px;"><?php echo esc_html($name) . __(' required', 'wp_all_import_plugin'); ?></p>
30
  <?php
31
  $all_required_plugins_installed = false;
32
  }
33
  endforeach;
34
  if ($all_required_plugins_installed){
35
  ?>
36
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>" class="button"><?php _e("Download",'acf'); ?></a>
37
  <?php
38
  }
39
  ?>
40
  <?php else: ?>
41
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>" class="button"><?php _e("Purchase & Install",'acf'); ?></a>
42
  <?php endif; ?>
43
  </div>
44
  </div>
49
  <h3><?php _e('Free Add-ons', 'wp_all_import_plugin'); ?></h3>
50
  <?php foreach( $free as $addon ): ?>
51
  <div class="pmxi-add-on wp-box <?php if( $addon['active'] ): ?>pmxi-add-on-active<?php endif; ?>">
52
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>">
53
+ <img src="<?php echo esc_url($addon['thumbnail']); ?>" />
54
  </a>
55
  <div class="inner">
56
+ <h3><a target="_blank" href="<?php echo esc_url($addon['url']); ?>"><?php echo esc_html($addon['title']); ?></a></h3>
57
+ <p><?php echo esc_html($addon['description']); ?></p>
58
  </div>
59
  <div class="footer">
60
  <?php if( $addon['active'] ): ?>
67
  foreach ($addon['required_plugins'] as $name => $active):
68
  if (!$active){
69
  ?>
70
+ <p style="margin:3px 0px;"><?php echo esc_html($name) . __(' required', 'wp_all_import_plugin'); ?></p>
71
  <?php
72
  $all_required_plugins_installed = false;
73
  }
74
  endforeach;
75
  if ($all_required_plugins_installed){
76
  ?>
77
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>" class="button"><?php _e("Download",'acf'); ?></a>
78
  <?php
79
  }
80
  ?>
81
  <?php else: ?>
82
+ <a target="_blank" href="<?php echo esc_url($addon['url']); ?>" class="button"><?php _e("Download",'acf'); ?></a>
83
  <?php endif; ?>
84
  </div>
85
  </div>
views/admin/history/index.php CHANGED
@@ -26,7 +26,7 @@ $columns = array(
26
  <p> <strong><?php _e('Scheduling Status', 'wp_all_import_plugin'); ?>:</strong> <?php _e('triggered'); ?> <?php if ($import->processing) _e('and processing', 'wp_all_import_plugin'); ?>...</p>
27
  <?php endif; ?>
28
 
29
- <form method="post" id="import-list" action="<?php echo remove_query_arg('pmxi_nt') ?>">
30
  <input type="hidden" name="action" value="bulk" />
31
  <?php wp_nonce_field('bulk-imports', '_wpnonce_bulk-imports') ?>
32
 
@@ -46,7 +46,7 @@ $columns = array(
46
  number_format_i18n(($pagenum - 1) * $perPage + 1),
47
  number_format_i18n(min($pagenum * $perPage, $list->total())),
48
  number_format_i18n($list->total()),
49
- $page_links
50
  ) ?>
51
  </div>
52
  <?php endif ?>
@@ -74,7 +74,7 @@ $columns = array(
74
  }
75
  else $col_html .= '<th scope="col" class="column-' . $column_id . '">' . $column_display_name . '</th>';
76
  }
77
- echo $col_html;
78
  ?>
79
  </tr>
80
  </thead>
@@ -83,7 +83,7 @@ $columns = array(
83
  <th class="manage-column column-cb check-column" scope="col" style="padding: 8px 10px;">
84
  <input type="checkbox" />
85
  </th>
86
- <?php echo $col_html; ?>
87
  </tr>
88
  </tfoot>
89
  <tbody id="the-pmxi-admin-import-list" class="list:pmxi-admin-imports">
@@ -97,9 +97,9 @@ $columns = array(
97
  ?>
98
  <?php foreach ($list as $item): ?>
99
  <?php $class = ('alternate' == $class) ? '' : 'alternate'; ?>
100
- <tr class="<?php echo $class; ?>" valign="middle">
101
  <th scope="row" class="check-column" style="vertical-align: middle; padding: 8px 10px;">
102
- <input type="checkbox" id="item_<?php echo $item['id'] ?>" name="items[]" value="<?php echo esc_attr($item['id']) ?>" />
103
  </th>
104
  <?php foreach ($columns as $column_id => $column_display_name): ?>
105
  <?php
@@ -107,7 +107,7 @@ $columns = array(
107
  case 'id':
108
  ?>
109
  <th valign="top" scope="row" style="vertical-align: middle;">
110
- <?php echo $item['id'] ?>
111
  </th>
112
  <?php
113
  break;
@@ -132,7 +132,7 @@ $columns = array(
132
  case 'summary':
133
  ?>
134
  <td style="vertical-align: middle;">
135
- <?php echo $item['summary'];?>
136
  </td>
137
  <?php
138
  break;
@@ -189,7 +189,7 @@ $columns = array(
189
  default:
190
  ?>
191
  <td>
192
- <?php echo $item[$column_id]; ?>
193
  </td>
194
  <?php
195
  break;
@@ -203,7 +203,7 @@ $columns = array(
203
  </table>
204
 
205
  <div class="tablenav">
206
- <?php if ($page_links): ?><div class="tablenav-pages"><?php echo $page_links_html ?></div><?php endif ?>
207
 
208
  <div class="alignleft actions">
209
  <select name="bulk-action2">
26
  <p> <strong><?php _e('Scheduling Status', 'wp_all_import_plugin'); ?>:</strong> <?php _e('triggered'); ?> <?php if ($import->processing) _e('and processing', 'wp_all_import_plugin'); ?>...</p>
27
  <?php endif; ?>
28
 
29
+ <form method="post" id="import-list" action="<?php echo esc_url(remove_query_arg('pmxi_nt')); ?>">
30
  <input type="hidden" name="action" value="bulk" />
31
  <?php wp_nonce_field('bulk-imports', '_wpnonce_bulk-imports') ?>
32
 
46
  number_format_i18n(($pagenum - 1) * $perPage + 1),
47
  number_format_i18n(min($pagenum * $perPage, $list->total())),
48
  number_format_i18n($list->total()),
49
+ wp_kses_post($page_links)
50
  ) ?>
51
  </div>
52
  <?php endif ?>
74
  }
75
  else $col_html .= '<th scope="col" class="column-' . $column_id . '">' . $column_display_name . '</th>';
76
  }
77
+ echo wp_kses_post($col_html);
78
  ?>
79
  </tr>
80
  </thead>
83
  <th class="manage-column column-cb check-column" scope="col" style="padding: 8px 10px;">
84
  <input type="checkbox" />
85
  </th>
86
+ <?php echo wp_kses_post($col_html); ?>
87
  </tr>
88
  </tfoot>
89
  <tbody id="the-pmxi-admin-import-list" class="list:pmxi-admin-imports">
97
  ?>
98
  <?php foreach ($list as $item): ?>
99
  <?php $class = ('alternate' == $class) ? '' : 'alternate'; ?>
100
+ <tr class="<?php echo esc_attr($class); ?>" valign="middle">
101
  <th scope="row" class="check-column" style="vertical-align: middle; padding: 8px 10px;">
102
+ <input type="checkbox" id="item_<?php echo esc_attr($item['id']); ?>" name="items[]" value="<?php echo esc_attr($item['id']) ?>" />
103
  </th>
104
  <?php foreach ($columns as $column_id => $column_display_name): ?>
105
  <?php
107
  case 'id':
108
  ?>
109
  <th valign="top" scope="row" style="vertical-align: middle;">
110
+ <?php echo esc_html($item['id']); ?>
111
  </th>
112
  <?php
113
  break;
132
  case 'summary':
133
  ?>
134
  <td style="vertical-align: middle;">
135
+ <?php echo esc_html($item['summary']);?>
136
  </td>
137
  <?php
138
  break;
189
  default:
190
  ?>
191
  <td>
192
+ <?php echo esc_html($item[$column_id]); ?>
193
  </td>
194
  <?php
195
  break;
203
  </table>
204
 
205
  <div class="tablenav">
206
+ <?php if ($page_links): ?><div class="tablenav-pages"><?php echo wp_kses_post($page_links_html); ?></div><?php endif ?>
207
 
208
  <div class="alignleft actions">
209
  <select name="bulk-action2">
views/admin/home/index.php DELETED
@@ -1,16 +0,0 @@
1
- <div class="wrap">
2
- <?php
3
- $homeurl = "http://www.wpallimport.com/adminpanel/index.php?v=".urlencode(PMXI_Plugin::getInstance()->getVersion());
4
- $contents = @file_get_contents($homeurl);
5
- if ( ! $contents) {
6
- ?>
7
- <iframe src='<?php echo $homeurl; ?>' width='600'></iframe><br />
8
- <?php
9
- } else {
10
- echo $contents;
11
- }
12
- ?>
13
- </div>
14
-
15
-
16
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
views/admin/import/element.php CHANGED
@@ -37,9 +37,9 @@
37
  if ( ! empty($elements_cloud) and ! $is_csv ){
38
  foreach ($elements_cloud as $tag => $count){
39
  ?>
40
- <a href="javascript:void(0);" rel="<?php echo $tag;?>" class="wpallimport-change-root-element <?php if (PMXI_Plugin::$session->source['root_element'] == $tag) echo 'selected';?>">
41
- <span class="tag_name"><?php echo strtolower($tag); ?></span>
42
- <span class="tag_count"><?php echo $count; ?></span>
43
  </a>
44
  <?php
45
  }
@@ -81,7 +81,7 @@
81
  <label>
82
  <?php _e("Set delimiter for CSV fields:", "pmxi_plugin"); ?>
83
  </label>
84
- <input type="text" name="delimiter" value="<?php echo $is_csv;?>"/>
85
  <input type="button" name="apply_delimiter" class="rad4" value="<?php _e('Apply', 'wp_all_import_plugin'); ?>"/>
86
  </div>
87
 
37
  if ( ! empty($elements_cloud) and ! $is_csv ){
38
  foreach ($elements_cloud as $tag => $count){
39
  ?>
40
+ <a href="javascript:void(0);" rel="<?php echo esc_attr($tag);?>" class="wpallimport-change-root-element <?php if (PMXI_Plugin::$session->source['root_element'] == $tag) echo 'selected';?>">
41
+ <span class="tag_name"><?php echo strtolower(esc_html($tag)); ?></span>
42
+ <span class="tag_count"><?php echo esc_html($count); ?></span>
43
  </a>
44
  <?php
45
  }
81
  <label>
82
  <?php _e("Set delimiter for CSV fields:", "pmxi_plugin"); ?>
83
  </label>
84
+ <input type="text" name="delimiter" value="<?php echo esc_attr($is_csv);?>"/>
85
  <input type="button" name="apply_delimiter" class="rad4" value="<?php _e('Apply', 'wp_all_import_plugin'); ?>"/>
86
  </div>
87
 
views/admin/import/error.php CHANGED
@@ -1,3 +1,3 @@
1
  <?php foreach ($errors as $msg): ?>
2
- <div class="error inline"><p><?php echo $msg ?></p></div>
3
  <?php endforeach ?>
1
  <?php foreach ($errors as $msg): ?>
2
+ <div class="error inline"><p><?php echo wp_kses_post($msg); ?></p></div>
3
  <?php endforeach ?>
views/admin/import/evaluate_variations.php CHANGED
@@ -7,7 +7,7 @@
7
  </div>
8
  <div id="current_xml">
9
  <div class="variations_tag">
10
- <input type="hidden" name="variations_tagno" value="<?php echo $tagno + 1 ?>" />
11
  <div class="title">
12
  <div class="navigation">
13
  <?php if ($tagno > 0): ?><a href="#variation_prev" class="previous_element">&nbsp;</a><?php else: ?><span class="previous_element">&nbsp;</span><?php endif ?>
7
  </div>
8
  <div id="current_xml">
9
  <div class="variations_tag">
10
+ <input type="hidden" name="variations_tagno" value="<?php echo esc_attr($tagno) + 1 ?>" />
11
  <div class="title">
12
  <div class="navigation">
13
  <?php if ($tagno > 0): ?><a href="#variation_prev" class="previous_element">&nbsp;</a><?php else: ?><span class="previous_element">&nbsp;</span><?php endif ?>
views/admin/import/index.php CHANGED
@@ -58,12 +58,12 @@
58
  </a>
59
  </div>
60
 
61
- <input type="hidden" value="<?php echo $post['type']; ?>" name="type"/>
62
 
63
  <div class="wpallimport-upload-type-container" rel="upload_type">
64
  <div id="plupload-ui" class="wpallimport-file-type-options">
65
  <div>
66
- <input type="hidden" name="filepath" value="<?php echo $post['filepath'] ?>" id="filepath"/>
67
  <a id="select-files" href="javascript:void(0);" <?php if (empty($post['filepath'])):?>style="display:none;"<?php endif; ?> /><?php _e('Click here to select file from your computer...', 'wp_all_import_plugin'); ?></a>
68
  <div id="progressbar" class="wpallimport-progressbar">
69
  <?php if (!empty($post['filepath'])):?>
@@ -223,7 +223,7 @@
223
  <div class="wpallimport-upload-resource-step-two">
224
  <div class="wpallimport-choose-post-type">
225
 
226
- <input type="hidden" name="wizard_type" value="<?php echo $post['wizard_type']; ?>"/>
227
 
228
  <h2 style="margin-top:0;"><?php _e('Import data from this file into...', 'wp_all_import_plugin'); ?></h2>
229
 
@@ -380,7 +380,7 @@
380
 
381
  ?>
382
 
383
- <option value="<?php echo $cpt; ?>" data-imagesrc="<?php echo $img_to_echo; ?>" <?php if ( $custom_selected_post === true ):?>selected="selected"<?php else: if ( $cpt == $post['custom_type'] ):?>selected="selected"<?php endif; endif; ?>><?php echo $cpt_label; ?></option>
384
  <?php
385
  }
386
  }
@@ -484,7 +484,7 @@
484
  </div>
485
 
486
  <p class="wpallimport-submit-buttons">
487
- <input type="hidden" name="custom_type" value="<?php echo $post['custom_type'];?>">
488
  <input type="hidden" name="is_submitted" value="1" />
489
  <input type="hidden" name="auto_generate" value="0" />
490
 
58
  </a>
59
  </div>
60
 
61
+ <input type="hidden" value="<?php echo esc_attr($post['type']); ?>" name="type"/>
62
 
63
  <div class="wpallimport-upload-type-container" rel="upload_type">
64
  <div id="plupload-ui" class="wpallimport-file-type-options">
65
  <div>
66
+ <input type="hidden" name="filepath" value="<?php echo esc_attr($post['filepath']) ?>" id="filepath"/>
67
  <a id="select-files" href="javascript:void(0);" <?php if (empty($post['filepath'])):?>style="display:none;"<?php endif; ?> /><?php _e('Click here to select file from your computer...', 'wp_all_import_plugin'); ?></a>
68
  <div id="progressbar" class="wpallimport-progressbar">
69
  <?php if (!empty($post['filepath'])):?>
223
  <div class="wpallimport-upload-resource-step-two">
224
  <div class="wpallimport-choose-post-type">
225
 
226
+ <input type="hidden" name="wizard_type" value="<?php echo esc_attr($post['wizard_type']); ?>"/>
227
 
228
  <h2 style="margin-top:0;"><?php _e('Import data from this file into...', 'wp_all_import_plugin'); ?></h2>
229
 
380
 
381
  ?>
382
 
383
+ <option value="<?php echo esc_attr($cpt); ?>" data-imagesrc="<?php echo esc_attr($img_to_echo); ?>" <?php if ( $custom_selected_post === true ):?>selected="selected"<?php else: if ( $cpt == $post['custom_type'] ):?>selected="selected"<?php endif; endif; ?>><?php echo esc_html($cpt_label); ?></option>
384
  <?php
385
  }
386
  }
484
  </div>
485
 
486
  <p class="wpallimport-submit-buttons">
487
+ <input type="hidden" name="custom_type" value="<?php echo esc_attr($post['custom_type']);?>">
488
  <input type="hidden" name="is_submitted" value="1" />
489
  <input type="hidden" name="auto_generate" value="0" />
490
 
views/admin/import/options.php CHANGED
@@ -3,8 +3,8 @@
3
  $baseUrl = $this->baseUrl;
4
  ?>
5
 
6
- <input type="hidden" id="selected_post_type" value="<?php echo (!empty($post['custom_type'])) ? $post['custom_type'] : '';?>">
7
- <input type="hidden" id="selected_type" value="<?php echo (!empty($post['type'])) ? $post['type'] : '';?>">
8
 
9
  <div class="wpallimport-step-4">
10
 
3
  $baseUrl = $this->baseUrl;
4
  ?>
5
 
6
+ <input type="hidden" id="selected_post_type" value="<?php echo (!empty($post['custom_type'])) ? esc_attr($post['custom_type']) : '';?>">
7
+ <input type="hidden" id="selected_type" value="<?php echo (!empty($post['type'])) ? esc_attr($post['type']) : '';?>">
8
 
9
  <div class="wpallimport-step-4">
10
 
views/admin/import/options/_import_file.php CHANGED
@@ -62,7 +62,7 @@
62
  <div class="wpallimport-upload-type-container" rel="upload_type">
63
  <div id="plupload-ui" class="wpallimport-file-type-options">
64
  <div>
65
- <input type="hidden" name="filepath" value="<?php if ('upload' == $import->type) echo $import->path; ?>" id="filepath"/>
66
  <a id="select-files" href="javascript:void(0);"/><?php _e('Click here to select file from your computer...', 'wp_all_import_plugin'); ?></a>
67
  <div id="progressbar" class="wpallimport-progressbar">
68
  <?php if ('upload' == $import->type) _e( '<span>Upload Complete</span> - '.basename($import->path).' 100%', 'wp_all_import_plugin'); ?>
62
  <div class="wpallimport-upload-type-container" rel="upload_type">
63
  <div id="plupload-ui" class="wpallimport-file-type-options">
64
  <div>
65
+ <input type="hidden" name="filepath" value="<?php if ('upload' == $import->type) echo esc_attr($import->path); ?>" id="filepath"/>
66
  <a id="select-files" href="javascript:void(0);"/><?php _e('Click here to select file from your computer...', 'wp_all_import_plugin'); ?></a>
67
  <div id="progressbar" class="wpallimport-progressbar">
68
  <?php if ('upload' == $import->type) _e( '<span>Upload Complete</span> - '.basename($import->path).' 100%', 'wp_all_import_plugin'); ?>
views/admin/import/options/_settings_template.php CHANGED
@@ -36,16 +36,16 @@
36
  <p><?php _e('Editing this will change the post type of the posts processed by this import. Re-run the import for the changes to take effect.', 'wp_all_import_plugin');?></p> <br>
37
  <?php endif; ?>
38
 
39
- <input type="hidden" name="custom_type" value="<?php echo $post['custom_type'];?>">
40
 
41
  <?php if ( 'taxonomies' == $post['custom_type'] ):?>
42
  <div class="wp_all_import_change_taxonomy_type">
43
- <input type="hidden" name="taxonomy_type" value="<?php echo $post['taxonomy_type'];?>">
44
  <select id="taxonomy_to_import">
45
  <option value=""><?php _e('Select Taxonomy', 'wp_all_export_plugin'); ?></option>
46
  <?php $options = wp_all_import_get_taxonomies(); ?>
47
  <?php foreach ($options as $slug => $name):?>
48
- <option value="<?php echo $slug;?>" <?php if ($post['taxonomy_type'] == $slug):?>selected="selected"<?php endif;?>><?php echo $name;?></option>
49
  <?php endforeach;?>
50
  </select>
51
  </div>
@@ -174,7 +174,7 @@
174
  }
175
 
176
  ?>
177
- <option value="<?php echo $cpt; ?>" data-imagesrc="<?php echo $img_to_echo; ?>" <?php if ( $custom_selected_post === true ):?>selected="selected"<?php else: if ( $cpt == $post['custom_type'] ):?>selected="selected"<?php endif; endif; ?>><?php echo $cpt_label; ?></option>
178
  <?php
179
  }
180
 
@@ -243,7 +243,7 @@
243
  <?php if ( ! empty($post['delimiter']) ): ?>
244
  <h4><?php _e('CSV Delimiter', 'wp_all_import_plugin'); ?></h4>
245
  <div class="input">
246
- <input type="text" name="delimiter" value="<?php echo $post['delimiter']; ?>" style="width: 50px !important; font-size: 18px; color: #555; height: 50px; padding: 10px;"/>
247
  </div>
248
  <?php endif; ?>
249
  <h4><?php _e('Downloads', 'wp_all_import_plugin'); ?></h4>
36
  <p><?php _e('Editing this will change the post type of the posts processed by this import. Re-run the import for the changes to take effect.', 'wp_all_import_plugin');?></p> <br>
37
  <?php endif; ?>
38
 
39
+ <input type="hidden" name="custom_type" value="<?php echo sanitize_key($post['custom_type']);?>">
40
 
41
  <?php if ( 'taxonomies' == $post['custom_type'] ):?>
42
  <div class="wp_all_import_change_taxonomy_type">
43
+ <input type="hidden" name="taxonomy_type" value="<?php echo sanitize_key($post['taxonomy_type']);?>">
44
  <select id="taxonomy_to_import">
45
  <option value=""><?php _e('Select Taxonomy', 'wp_all_export_plugin'); ?></option>
46
  <?php $options = wp_all_import_get_taxonomies(); ?>
47
  <?php foreach ($options as $slug => $name):?>
48
+ <option value="<?php echo esc_attr($slug);?>" <?php if ($post['taxonomy_type'] == $slug):?>selected="selected"<?php endif;?>><?php echo esc_html($name);?></option>
49
  <?php endforeach;?>
50
  </select>
51
  </div>
174
  }
175
 
176
  ?>
177
+ <option value="<?php echo esc_attr($cpt); ?>" data-imagesrc="<?php echo esc_attr($img_to_echo); ?>" <?php if ( $custom_selected_post === true ):?>selected="selected"<?php else: if ( $cpt == $post['custom_type'] ):?>selected="selected"<?php endif; endif; ?>><?php echo esc_html($cpt_label); ?></option>
178
  <?php
179
  }
180
 
243
  <?php if ( ! empty($post['delimiter']) ): ?>
244
  <h4><?php _e('CSV Delimiter', 'wp_all_import_plugin'); ?></h4>
245
  <div class="input">
246
+ <input type="text" name="delimiter" value="<?php echo esc_attr($post['delimiter']); ?>" style="width: 50px !important; font-size: 18px; color: #555; height: 50px; padding: 10px;"/>
247
  </div>
248
  <?php endif; ?>
249
  <h4><?php _e('Downloads', 'wp_all_import_plugin'); ?></h4>
views/admin/import/preview_images.php CHANGED
@@ -23,7 +23,7 @@
23
  ?>
24
  <p><?php _e('Click to test that your images are able to be accessed by WP All Import.', 'wp_all_import_plugin'); ?></p>
25
 
26
- <a class="test_images" href="javascript:void(0);" style="margin-left:0;" rel="<?php echo $post[$get['slug'] . 'download_images']; ?>"><?php _e('Run Test', 'wp_all_import_plugin'); ?></a>
27
 
28
  <?php
29
 
@@ -68,7 +68,7 @@
68
  $img = wp_all_import_filter_html_kses($img);
69
  ?>
70
 
71
- <li rel="<?php echo trim($img);?>"><?php echo trim(preg_replace('%.*/wp-content%', '/wp-content', $wp_uploads['basedir']) . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR . trim($img)); ?></li>
72
 
73
  <?php endforeach; ?>
74
  </ul>
@@ -80,7 +80,7 @@
80
 
81
  $img_url = site_url() . preg_replace('%.*/wp-content%', '/wp-content', $wp_uploads['basedir']) . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR . trim($img);
82
  ?>
83
- <img src="<?php echo trim($img_url);?>" style="width:64px; margin:5px; vertical-align:top;"/>
84
  <?php
85
  }
86
 
@@ -113,7 +113,7 @@
113
 
114
  ?>
115
 
116
- <li rel="<?php echo $image_name;?>"><?php echo $image_name; ?></li>
117
 
118
  <?php endforeach; ?>
119
  </ul>
@@ -134,7 +134,7 @@
134
 
135
  $img_url = (empty($attch)) ? '' : trim(wp_get_attachment_url($attch->ID));
136
  ?>
137
- <img src="<?php echo trim($img_url);?>" style="width:64px; margin:5px; vertical-align:top;"/>
138
  <?php
139
  }
140
 
@@ -156,7 +156,7 @@
156
  $img = wp_all_import_filter_html_kses($img);
157
  ?>
158
 
159
- <li rel="<?php echo trim($img); ?>"><a href="<?php echo trim($img); ?>" target="_blank"><?php echo trim($img); ?></a></li>
160
 
161
  <?php endforeach; ?>
162
  </ul>
@@ -166,7 +166,7 @@
166
 
167
  ?>
168
 
169
- <img src="<?php echo trim($img);?>" style="width:64px; margin:5px; vertical-align:top;"/>
170
 
171
  <?php endforeach; ?>
172
 
23
  ?>
24
  <p><?php _e('Click to test that your images are able to be accessed by WP All Import.', 'wp_all_import_plugin'); ?></p>
25
 
26
+ <a class="test_images" href="javascript:void(0);" style="margin-left:0;" rel="<?php echo esc_attr($post[$get['slug'] . 'download_images']); ?>"><?php _e('Run Test', 'wp_all_import_plugin'); ?></a>
27
 
28
  <?php
29
 
68
  $img = wp_all_import_filter_html_kses($img);
69
  ?>
70
 
71
+ <li rel="<?php echo esc_attr(trim($img));?>"><?php echo trim(preg_replace('%.*/wp-content%', '/wp-content', $wp_uploads['basedir']) . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR . esc_html(trim($img))); ?></li>
72
 
73
  <?php endforeach; ?>
74
  </ul>
80
 
81
  $img_url = site_url() . preg_replace('%.*/wp-content%', '/wp-content', $wp_uploads['basedir']) . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR . trim($img);
82
  ?>
83
+ <img src="<?php echo esc_url(trim($img_url));?>" style="width:64px; margin:5px; vertical-align:top;"/>
84
  <?php
85
  }
86
 
113
 
114
  ?>
115
 
116
+ <li rel="<?php echo esc_attr($image_name);?>"><?php echo esc_html($image_name); ?></li>
117
 
118
  <?php endforeach; ?>
119
  </ul>
134
 
135
  $img_url = (empty($attch)) ? '' : trim(wp_get_attachment_url($attch->ID));
136
  ?>
137
+ <img src="<?php echo esc_url(trim($img_url));?>" style="width:64px; margin:5px; vertical-align:top;"/>
138
  <?php
139
  }
140
 
156
  $img = wp_all_import_filter_html_kses($img);
157
  ?>
158
 
159
+ <li rel="<?php echo esc_attr(trim($img)); ?>"><a href="<?php echo esc_url(trim($img)); ?>" target="_blank"><?php echo esc_html(trim($img)); ?></a></li>
160
 
161
  <?php endforeach; ?>
162
  </ul>
166
 
167
  ?>
168
 
169
+ <img src="<?php echo esc_url(trim($img));?>" style="width:64px; margin:5px; vertical-align:top;"/>
170
 
171
  <?php endforeach; ?>
172
 
views/admin/import/preview_taxonomies.php CHANGED
@@ -20,7 +20,7 @@
20
  foreach ($tax_hierarchical as $ctx => $terms_arr):
21
  $tax_info = get_taxonomy($ctx);
22
  ?>
23
- <p><?php echo $tax_info->labels->name; ?></p>
24
  <?php
25
  if (!empty($terms_arr) and is_array($terms_arr)){
26
  foreach ($terms_arr as $terms) {
@@ -57,14 +57,14 @@
57
  }
58
  if (!empty($term)) {
59
  ?>
60
- <p><?php echo str_pad(trim($term), strlen(trim($term)) + $lvl, "-", STR_PAD_LEFT); ?></p>
61
  <?php
62
  }
63
  }
64
  }
65
  else{
66
  ?>
67
- <p><?php echo $terms_a; ?></p>
68
  <?php
69
  }
70
  }
20
  foreach ($tax_hierarchical as $ctx => $terms_arr):
21
  $tax_info = get_taxonomy($ctx);
22
  ?>
23
+ <p><?php echo esc_html($tax_info->labels->name); ?></p>
24
  <?php
25
  if (!empty($terms_arr) and is_array($terms_arr)){
26
  foreach ($terms_arr as $terms) {
57
  }
58
  if (!empty($term)) {
59
  ?>
60
+ <p><?php echo esc_html(str_pad(trim($term), strlen(trim($term)) + $lvl, "-", STR_PAD_LEFT)); ?></p>
61
  <?php
62
  }
63
  }
64
  }
65
  else{
66
  ?>
67
+ <p><?php echo esc_html($terms_a); ?></p>
68
  <?php
69
  }
70
  }
views/admin/import/process.php CHANGED
@@ -28,20 +28,20 @@
28
  <span id="left_progress"><?php _e('Time Elapsed', 'wp_all_import_plugin');?> <span id="then">00:00:00</span></span>
29
  <span id="right_progress">
30
  <div class="progress_processed">
31
- <span><?php _e('Processed', 'wp_all_import_plugin');?> <span class="processed_count"><?php echo ($update_previous->created + $update_previous->updated + $update_previous->skipped); ?></span> <?php _e('of', 'wp_all_import_plugin');?> <span id="of"><?php echo $update_previous->count; ?></span> <?php _e('records', 'wp_all_import_plugin');?></span>
32
  </div>
33
  <div class="progress_details">
34
  <span class="progress_details_item created_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
35
- <?php _e('Created','wp_all_import_plugin');?> <span class="created_records_count"><?php echo $update_previous->created; ?></span>
36
  </span>
37
  <span class="progress_details_item deleted_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
38
- <?php _e('Deleted','wp_all_import_plugin');?> <span class="deleted_records_count"><?php echo $update_previous->deleted; ?></span>
39
  </span>
40
  <span class="progress_details_item updated_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
41
- <?php _e('Updated','wp_all_import_plugin');?> <span class="updated_records_count"><?php echo $update_previous->updated; ?></span>
42
  </span>
43
  <span class="progress_details_item skipped_count" <?php if (empty($update_previous->skipped)): ?>style="display:none;"<?php endif; ?>>
44
- <?php _e('Skipped','wp_all_import_plugin');?> <span class="skipped_records_count"><?php echo $update_previous->skipped; ?></span>
45
  </span>
46
  </div>
47
  </span>
@@ -126,7 +126,7 @@
126
  </fieldset>
127
 
128
  <input type="hidden" class="count_failures" value="0"/>
129
- <input type="hidden" class="records_per_request" value="<?php echo $update_previous->options['records_per_request']; ?>"/>
130
  <span id="wpallimport-error-terminated" style="display:none;">
131
  <div class="wpallimport-content-section" style="display:block; position: relative;">
132
  <div class="wpallimport-notify-wrapper">
@@ -192,9 +192,9 @@
192
  $('#status').each(function () {
193
 
194
  var then = $('#then');
195
- start_date = wpai_moment().sod();
196
  update = function(){
197
- var duration = wpai_moment.duration({'seconds' : 1});
198
  start_date.add(duration);
199
 
200
  if ($('#process_notice').is(':visible') && ! $('.wpallimport-modal-message').is(':visible')){
@@ -228,7 +228,7 @@
228
 
229
  <?php if ( $ajax_processing ): ?>
230
 
231
- var import_id = '<?php echo $update_previous->id; ?>';
232
 
233
  function parse_element(failures){
234
 
@@ -351,7 +351,7 @@
351
 
352
  var request = {
353
  action:'import_failed',
354
- id: '<?php echo $update_previous->id; ?>',
355
  security: wp_all_import_security
356
  };
357
 
@@ -400,7 +400,7 @@
400
 
401
  var request = {
402
  action:'import_failed',
403
- id: '<?php echo $update_previous->id; ?>',
404
  security: wp_all_import_security
405
  };
406
 
28
  <span id="left_progress"><?php _e('Time Elapsed', 'wp_all_import_plugin');?> <span id="then">00:00:00</span></span>
29
  <span id="right_progress">
30
  <div class="progress_processed">
31
+ <span><?php _e('Processed', 'wp_all_import_plugin');?> <span class="processed_count"><?php echo ($update_previous->created + $update_previous->updated + $update_previous->skipped); ?></span> <?php _e('of', 'wp_all_import_plugin');?> <span id="of"><?php echo esc_html($update_previous->count); ?></span> <?php _e('records', 'wp_all_import_plugin');?></span>
32
  </div>
33
  <div class="progress_details">
34
  <span class="progress_details_item created_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
35
+ <?php _e('Created','wp_all_import_plugin');?> <span class="created_records_count"><?php echo esc_html($update_previous->created); ?></span>
36
  </span>
37
  <span class="progress_details_item deleted_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
38
+ <?php _e('Deleted','wp_all_import_plugin');?> <span class="deleted_records_count"><?php echo esc_html($update_previous->deleted); ?></span>
39
  </span>
40
  <span class="progress_details_item updated_count" <?php if (empty($update_previous->created)): ?>style="display:none;"<?php endif; ?>>
41
+ <?php _e('Updated','wp_all_import_plugin');?> <span class="updated_records_count"><?php echo esc_html($update_previous->updated); ?></span>
42
  </span>
43
  <span class="progress_details_item skipped_count" <?php if (empty($update_previous->skipped)): ?>style="display:none;"<?php endif; ?>>
44
+ <?php _e('Skipped','wp_all_import_plugin');?> <span class="skipped_records_count"><?php echo esc_html($update_previous->skipped); ?></span>
45
  </span>
46
  </div>
47
  </span>
126
  </fieldset>
127
 
128
  <input type="hidden" class="count_failures" value="0"/>
129
+ <input type="hidden" class="records_per_request" value="<?php echo esc_attr($update_previous->options['records_per_request']); ?>"/>
130
  <span id="wpallimport-error-terminated" style="display:none;">
131
  <div class="wpallimport-content-section" style="display:block; position: relative;">
132
  <div class="wpallimport-notify-wrapper">
192
  $('#status').each(function () {
193
 
194
  var then = $('#then');
195
+ start_date = moment().startOf('day');
196
  update = function(){
197
+ var duration = moment.duration({'seconds' : 1});
198
  start_date.add(duration);
199
 
200
  if ($('#process_notice').is(':visible') && ! $('.wpallimport-modal-message').is(':visible')){
228
 
229
  <?php if ( $ajax_processing ): ?>
230
 
231
+ var import_id = '<?php echo intval($update_previous->id); ?>';
232
 
233
  function parse_element(failures){
234
 
351
 
352
  var request = {
353
  action:'import_failed',
354
+ id: '<?php echo intval($update_previous->id); ?>',
355
  security: wp_all_import_security
356
  };
357
 
400
 
401
  var request = {
402
  action:'import_failed',
403
+ id: '<?php echo intval($update_previous->id); ?>',
404
  security: wp_all_import_security
405
  };
406
 
views/admin/import/template.php CHANGED
@@ -109,7 +109,7 @@
109
 
110
  <?php endif; ?>
111
 
112
- <input type="hidden" name="custom_type" value="<?php echo $post['custom_type']; ?>"/>
113
  <input type="hidden" name="type" value="<?php echo ($post['custom_type'] == 'page') ? 'page' : 'post'; ?>"/>
114
 
115
  <?php
@@ -203,7 +203,7 @@
203
  <select name="load_template" id="load_template">
204
  <option value=""><?php _e('Load Template...', 'wp_all_import_plugin') ?></option>
205
  <?php foreach ($templates->getBy()->convertRecords() as $t): ?>
206
- <option value="<?php echo $t->id ?>"><?php echo $t->name ?></option>
207
  <?php endforeach ?>
208
  </select>
209
  </div>
109
 
110
  <?php endif; ?>
111
 
112
+ <input type="hidden" name="custom_type" value="<?php echo esc_attr($post['custom_type']); ?>"/>
113
  <input type="hidden" name="type" value="<?php echo ($post['custom_type'] == 'page') ? 'page' : 'post'; ?>"/>
114
 
115
  <?php
203
  <select name="load_template" id="load_template">
204
  <option value=""><?php _e('Load Template...', 'wp_all_import_plugin') ?></option>
205
  <?php foreach ($templates->getBy()->convertRecords() as $t): ?>
206
+ <option value="<?php echo esc_attr($t->id); ?>"><?php echo esc_html($t->name); ?></option>
207
  <?php endforeach ?>
208
  </select>
209
  </div>
views/admin/import/template/_custom_fields_template.php CHANGED
@@ -55,23 +55,23 @@
55
  </td>
56
  <td class="action">
57
  <div class="custom_type" rel="default">
58
- <textarea name="custom_value[]" class="widefat" <?php echo ( ! empty($post['custom_format'][$i]) ) ? 'style="display:none;"' : ''; ?>><?php echo esc_html($post['custom_value'][$i]) ?></textarea>
59
- <a class="specify_cf pmxi_cf_pointer" rel="serialized_<?php echo $i; ?>" href="javascript:void(0);" <?php echo ( empty($post['custom_format'][$i]) ) ? 'style="display:none;"' : ''; ?>><?php _e('Click to specify', 'wp_all_import_plugin'); ?></a>
60
  <div class="input wpallimport-custom-fields-actions">
61
  <a href="javascript:void(0);" class="wpallimport-cf-options"><?php _e('Field Options...', 'wp_all_import_plugin'); ?></a>
62
- <ul id="wpallimport-cf-menu-<?php echo $i;?>" class="wpallimport-cf-menu">
63
  <li class="<?php echo ( ! empty($post['custom_format'][$i]) ) ? 'active' : ''; ?>">
64
  <a href="javascript:void(0);" class="set_serialize"><?php _e('Serialized', 'wp_all_import_plugin'); ?></a>
65
  </li>
66
  <li class="<?php echo ( ! empty($custom_mapping_rules) ) ? 'active' : ''; ?>">
67
- <a href="javascript:void(0);" class="set_mapping pmxi_cf_mapping" rel="cf_mapping_<?php echo $i; ?>"><?php _e('Mapping', 'wp_all_import_plugin'); ?></a>
68
  </li>
69
  </ul>
70
  </div>
71
  </div>
72
- <div id="serialized_<?php echo $i; ?>" class="custom_type" rel="serialized" style="display:none;">
73
  <fieldset>
74
- <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="serialized_<?php echo $i; ?>">
75
  <thead>
76
  <tr>
77
  <td><?php _e('Key', 'wp_all_import_plugin') ?></td>
@@ -104,7 +104,7 @@
104
  ?>
105
  <tr class="form-field">
106
  <td>
107
- <input type="text" class="serialized_key widefat" value="<?php echo $k; ?>">
108
  </td>
109
  <td>
110
  <input type="text" class="serialized_value widefat" value="<?php echo esc_html((is_array($value)) ? $value[$k] : $value); ?>">
@@ -166,9 +166,9 @@
166
  </fieldset>
167
  </div>
168
 
169
- <div id="cf_mapping_<?php echo $i; ?>" class="custom_type" rel="mapping" style="display:none;">
170
  <fieldset>
171
- <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="cf_mapping_<?php echo $i; ?>">
172
  <thead>
173
  <tr>
174
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
@@ -193,7 +193,7 @@
193
  ?>
194
  <tr class="form-field">
195
  <td>
196
- <input type="text" class="mapping_from widefat" value="<?php echo $k; ?>">
197
  </td>
198
  <td>
199
  <input type="text" class="mapping_to widefat" value="<?php echo (is_array($value)) ? $value[$k] : $value; ?>">
55
  </td>
56
  <td class="action">
57
  <div class="custom_type" rel="default">
58
+ <textarea name="custom_value[]" class="widefat" <?php echo ( ! empty($post['custom_format'][$i]) ) ? 'style="display:none;"' : ''; ?>><?php echo esc_textarea($post['custom_value'][$i]) ?></textarea>
59
+ <a class="specify_cf pmxi_cf_pointer" rel="serialized_<?php echo esc_attr($i); ?>" href="javascript:void(0);" <?php echo ( empty($post['custom_format'][$i]) ) ? 'style="display:none;"' : ''; ?>><?php _e('Click to specify', 'wp_all_import_plugin'); ?></a>
60
  <div class="input wpallimport-custom-fields-actions">
61
  <a href="javascript:void(0);" class="wpallimport-cf-options"><?php _e('Field Options...', 'wp_all_import_plugin'); ?></a>
62
+ <ul id="wpallimport-cf-menu-<?php echo esc_attr($i);?>" class="wpallimport-cf-menu">
63
  <li class="<?php echo ( ! empty($post['custom_format'][$i]) ) ? 'active' : ''; ?>">
64
  <a href="javascript:void(0);" class="set_serialize"><?php _e('Serialized', 'wp_all_import_plugin'); ?></a>
65
  </li>
66
  <li class="<?php echo ( ! empty($custom_mapping_rules) ) ? 'active' : ''; ?>">
67
+ <a href="javascript:void(0);" class="set_mapping pmxi_cf_mapping" rel="cf_mapping_<?php echo esc_attr($i); ?>"><?php _e('Mapping', 'wp_all_import_plugin'); ?></a>
68
  </li>
69
  </ul>
70
  </div>
71
  </div>
72
+ <div id="serialized_<?php echo esc_attr($i); ?>" class="custom_type" rel="serialized" style="display:none;">
73
  <fieldset>
74
+ <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="serialized_<?php echo esc_attr($i); ?>">
75
  <thead>
76
  <tr>
77
  <td><?php _e('Key', 'wp_all_import_plugin') ?></td>
104
  ?>
105
  <tr class="form-field">
106
  <td>
107
+ <input type="text" class="serialized_key widefat" value="<?php echo esc_attr($k); ?>">
108
  </td>
109
  <td>
110
  <input type="text" class="serialized_value widefat" value="<?php echo esc_html((is_array($value)) ? $value[$k] : $value); ?>">
166
  </fieldset>
167
  </div>
168
 
169
+ <div id="cf_mapping_<?php echo esc_attr($i); ?>" class="custom_type" rel="mapping" style="display:none;">
170
  <fieldset>
171
+ <table cellpadding="0" cellspacing="5" class="cf-form-table" rel="cf_mapping_<?php echo esc_attr($i); ?>">
172
  <thead>
173
  <tr>
174
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
193
  ?>
194
  <tr class="form-field">
195
  <td>
196
+ <input type="text" class="mapping_from widefat" value="<?php echo esc_attr($k); ?>">
197
  </td>
198
  <td>
199
  <input type="text" class="mapping_to widefat" value="<?php echo (is_array($value)) ? $value[$k] : $value; ?>">
views/admin/import/template/_featured_template.php CHANGED
@@ -1,7 +1,7 @@
1
  <div class="wpallimport-collapsed closed wpallimport-section wpallimport-featured-images">
2
  <div class="wpallimport-content-section" style="padding-bottom: 0;">
3
  <div class="wpallimport-collapsed-header" style="margin-bottom: 15px;">
4
- <h3><?php echo $section_title;?></h3>
5
  </div>
6
  <div class="wpallimport-collapsed-content" style="padding: 0;">
7
  <div class="wpallimport-collapsed-content-inner">
@@ -18,85 +18,85 @@
18
  <td colspan="3">
19
  <div class="input">
20
  <div class="input">
21
- <input type="radio" name="<?php echo $section_slug; ?>download_images" value="yes" class="switcher" id="<?php echo $section_slug; ?>download_images_yes" <?php echo ("yes" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
22
- <label for="<?php echo $section_slug; ?>download_images_yes"><?php _e('Download images hosted elsewhere'); ?></label>
23
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
24
  </div>
25
- <div class="switcher-target-<?php echo $section_slug; ?>download_images_yes" style="padding-left:27px;">
26
- <label for="<?php echo $section_slug; ?>download_featured_delim"><?php _e('Enter image URL one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
27
- <input type="text" class="small" id="<?php echo $section_slug; ?>download_featured_delim" name="<?php echo $section_slug; ?>download_featured_delim" value="<?php echo esc_attr($post[$section_slug . 'download_featured_delim']) ?>" style="width:5%; text-align:center;"/>
28
- <textarea name="<?php echo $section_slug; ?>download_featured_image" class="newline rad4" style="clear: both; display:block;" placeholder=""><?php echo esc_attr(wp_all_import_filter_html_kses($post[$section_slug . 'download_featured_image'])) ?></textarea>
29
  </div>
30
  <div class="input">
31
- <input type="radio" name="<?php echo $section_slug; ?>download_images" value="gallery" class="switcher" id="<?php echo $section_slug; ?>download_images_gallery" <?php echo ("gallery" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
32
- <label for="<?php echo $section_slug; ?>download_images_gallery"><?php _e('Use images currently in Media Library'); ?></label>
33
  <!--a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a-->
34
  </div>
35
- <div class="switcher-target-<?php echo $section_slug; ?>download_images_gallery" style="padding-left:27px;">
36
- <label for="<?php echo $section_slug; ?>gallery_featured_delim"><?php _e('Enter image filenames one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
37
- <input type="text" class="small" id="<?php echo $section_slug; ?>gallery_featured_delim" name="<?php echo $section_slug; ?>gallery_featured_delim" value="<?php echo esc_attr($post[$section_slug . 'gallery_featured_delim']) ?>" style="width:5%; text-align:center;"/>
38
- <textarea name="<?php echo $section_slug; ?>gallery_featured_image" class="newline rad4" style="clear: both; display:block; "><?php echo esc_attr(wp_all_import_filter_html_kses($post[$section_slug . 'gallery_featured_image'])) ?></textarea>
39
  </div>
40
  <div class="input">
41
  <?php $wp_uploads = wp_upload_dir(); ?>
42
- <input type="radio" name="<?php echo $section_slug; ?>download_images" value="no" class="switcher" id="<?php echo $section_slug; ?>download_images_no" <?php echo ("no" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
43
- <label for="<?php echo $section_slug; ?>download_images_no"><?php printf(__('Use images currently uploaded in %s', 'wp_all_import_plugin'), preg_replace('%.*wp-content/%', 'wp-content/', $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR) ); ?></label>
44
  </div>
45
- <div class="switcher-target-<?php echo $section_slug; ?>download_images_no" style="padding-left:27px;">
46
- <label for="<?php echo $section_slug; ?>featured_delim"><?php _e('Enter image filenames one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
47
- <input type="text" class="small" id="<?php echo $section_slug; ?>featured_delim" name="<?php echo $section_slug; ?>featured_delim" value="<?php echo esc_attr($post[$section_slug . 'featured_delim']) ?>" style="width:5%; text-align:center;"/>
48
- <textarea name="<?php echo $section_slug; ?>featured_image" class="newline rad4" style="clear: both; display:block; "><?php echo esc_attr(wp_all_import_filter_html_kses($post[$section_slug . 'featured_image'])) ?></textarea>
49
  </div>
50
  </div>
51
  <h4><?php _e('Image Options', 'wp_all_import_plugin'); ?></h4>
52
  <div class="search_through_the_media_library">
53
  <div class="input" style="margin:3px;">
54
- <input type="hidden" name="<?php echo $section_slug; ?>search_existing_images" value="0" />
55
- <input type="checkbox" id="<?php echo $section_slug; ?>search_existing_images" name="<?php echo $section_slug; ?>search_existing_images" value="1" <?php echo $post[$section_slug . 'search_existing_images'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
56
- <label for="<?php echo $section_slug; ?>search_existing_images"><?php _e('Search through the Media Library for existing images before importing new images','wp_all_import_plugin');?> </label>
57
  <a href="#help" class="wpallimport-help" title="<?php _e('If an image with the same file name or remote URL is found in the Media Library then that image will be attached to this record instead of importing a new image. Disable this setting if you always want to download a new image.', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
58
- <div class="switcher-target-<?php echo $section_slug; ?>search_existing_images" style="padding-left:23px;">
59
  <div class="search_through_the_media_library_logic">
60
  <div class="input">
61
- <input type="radio" id="<?php echo $section_slug; ?>search_existing_images_logic_url" name="<?php echo $section_slug; ?>search_existing_images_logic" value="by_url" <?php echo ( "by_url" == $post[$section_slug . 'search_existing_images_logic'] ) ? 'checked="checked"': '' ?>/>
62
- <label for="<?php echo $section_slug; ?>search_existing_images_logic_url"><?php _e('Match image by URL', 'wp_all_import_plugin') ?></label>
63
  </div>
64
  <div class="input">
65
- <input type="radio" id="<?php echo $section_slug; ?>search_existing_images_logic_filename" name="<?php echo $section_slug; ?>search_existing_images_logic" value="by_filename" <?php echo ( "by_filename" == $post[$section_slug . 'search_existing_images_logic'] ) ? 'checked="checked"': '' ?>/>
66
- <label for="<?php echo $section_slug; ?>search_existing_images_logic_filename"><?php _e('Match image by filename', 'wp_all_import_plugin') ?></label>
67
  </div>
68
  </div>
69
  </div>
70
  </div>
71
  <div class="input" style="margin: 3px;">
72
- <input type="hidden" name="<?php echo $section_slug; ?>do_not_remove_images" value="0" />
73
- <input type="checkbox" id="<?php echo $section_slug; ?>do_not_remove_images" name="<?php echo $section_slug; ?>do_not_remove_images" value="1" <?php echo $post[$section_slug . 'do_not_remove_images'] ? 'checked="checked"': '' ?> />
74
- <label for="<?php echo $section_slug; ?>do_not_remove_images"><?php _e('Keep images currently in Media Library', 'wp_all_import_plugin') ?></label>
75
  <a href="#help" class="wpallimport-help" title="<?php _e('If disabled, images attached to imported posts will be deleted and then all images will be imported.', 'wp_all_import_plugin') ?>" style="position:relative; top: -2px;">?</a>
76
  </div>
77
  <?php if ($section_type == 'images'): ?>
78
  <div class="input" style="margin: 3px;">
79
- <input type="hidden" name="<?php echo $section_slug; ?>import_img_tags" value="0" />
80
- <input type="checkbox" id="<?php echo $section_slug; ?>import_img_tags" name="<?php echo $section_slug; ?>import_img_tags" value="1" <?php echo (isset($post[$section_slug . 'import_img_tags']) && $post[$section_slug . 'import_img_tags']) ? 'checked="checked"': '' ?> />
81
- <label for="<?php echo $section_slug; ?>import_img_tags"><?php _e('Scan through post content and import images wrapped in &lt;img&gt; tags', 'wp_all_import_plugin') ?></label>
82
  <a href="#help" class="wpallimport-help" title="<?php _e('Only images hosted on other sites will be imported. Images will be imported to WordPress and the <img> tag updated with the new image URL.', 'wp_all_import_plugin') ?>" style="position:relative; top: -2px;">?</a>
83
  </div>
84
  <?php endif; ?>
85
  </div>
86
  <?php if ($section_type == 'images'): ?>
87
  <div class="input">
88
- <input type="hidden" value="<?php echo $section_slug; ?>" class="wp_all_import_section_slug"/>
89
  <a class="preview_images" href="javascript:void(0);" rel="preview_images"><?php _e('Preview & Test', 'wp_all_import_plugin'); ?></a>
90
  </div>
91
  <div class="input" style="margin:3px;">
92
- <input type="hidden" name="<?php echo $section_slug; ?>is_featured" value="0" />
93
- <input type="checkbox" id="<?php echo $section_slug; ?>is_featured" name="<?php echo $section_slug; ?>is_featured" value="1" <?php echo $post[$section_slug . 'is_featured'] ? 'checked="checked"' : '' ?> class="fix_checkbox"/>
94
- <label for="<?php echo $section_slug; ?>is_featured"><?php _e('Set the first image to the Featured Image (_thumbnail_id)','wp_all_import_plugin');?> </label>
95
  </div>
96
  <div class="input" style="margin:3px;">
97
- <input type="hidden" name="<?php echo $section_slug; ?>create_draft" value="no" />
98
- <input type="checkbox" id="<?php echo $section_slug; ?>create_draft" name="<?php echo $section_slug; ?>create_draft" value="yes" <?php echo 'yes' == $post[$section_slug . 'create_draft'] ? 'checked="checked"' : '' ?> class="fix_checkbox"/>
99
- <label for="<?php echo $section_slug; ?>create_draft"><?php _e('If no images are downloaded successfully, create entry as Draft.', 'wp_all_import_plugin') ?></label>
100
  </div>
101
  <?php endif; ?>
102
  </td>
@@ -117,74 +117,74 @@
117
  <td colspan="3">
118
  <h4><?php _e('Meta Data', 'wp_all_import_plugin'); ?></h4>
119
  <div class="input">
120
- <input type="hidden" name="<?php echo $section_slug; ?>set_image_meta_title" value="0" />
121
- <input type="checkbox" id="<?php echo $section_slug; ?>set_image_meta_title" name="<?php echo $section_slug; ?>set_image_meta_title" value="1" <?php echo $post[$section_slug . 'set_image_meta_title'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
122
- <label for="<?php echo $section_slug; ?>set_image_meta_title"><?php _e('Set Title(s)','wp_all_import_plugin');?></label>
123
- <div class="switcher-target-<?php echo $section_slug; ?>set_image_meta_title" style="padding-left:23px;">
124
- <label for="<?php echo $section_slug; ?>image_meta_title_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
125
- <input type="text" class="small" id="<?php echo $section_slug; ?>image_meta_title_delim" name="<?php echo $section_slug; ?>image_meta_title_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_title_delim']) ?>" style="width:5%; text-align:center;"/>
126
  <p style="margin-bottom:5px;"><?php _e('The first title will be linked to the first image, the second title will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
127
- <textarea name="<?php echo $section_slug; ?>image_meta_title" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_title']) ?></textarea>
128
  </div>
129
  </div>
130
  <div class="input">
131
- <input type="hidden" name="<?php echo $section_slug; ?>set_image_meta_caption" value="0" />
132
- <input type="checkbox" id="<?php echo $section_slug; ?>set_image_meta_caption" name="<?php echo $section_slug; ?>set_image_meta_caption" value="1" <?php echo $post[$section_slug . 'set_image_meta_caption'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
133
- <label for="<?php echo $section_slug; ?>set_image_meta_caption"><?php _e('Set Caption(s)','wp_all_import_plugin');?></label>
134
- <div class="switcher-target-<?php echo $section_slug; ?>set_image_meta_caption" style="padding-left:23px;">
135
- <label for="<?php echo $section_slug; ?>image_meta_caption_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
136
- <input type="text" class="small" id="<?php echo $section_slug; ?>image_meta_caption_delim" name="<?php echo $section_slug; ?>image_meta_caption_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_caption_delim']) ?>" style="width:5%; text-align:center;"/>
137
  <p style="margin-bottom:5px;"><?php _e('The first caption will be linked to the first image, the second caption will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
138
- <textarea name="<?php echo $section_slug; ?>image_meta_caption" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_caption']) ?></textarea>
139
  </div>
140
  </div>
141
  <div class="input">
142
- <input type="hidden" name="<?php echo $section_slug; ?>set_image_meta_alt" value="0" />
143
- <input type="checkbox" id="<?php echo $section_slug; ?>set_image_meta_alt" name="<?php echo $section_slug; ?>set_image_meta_alt" value="1" <?php echo $post[$section_slug . 'set_image_meta_alt'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
144
- <label for="<?php echo $section_slug; ?>set_image_meta_alt"><?php _e('Set Alt Text(s)','wp_all_import_plugin');?></label>
145
- <div class="switcher-target-<?php echo $section_slug; ?>set_image_meta_alt" style="padding-left:23px;">
146
- <label for="<?php echo $section_slug; ?>image_meta_alt_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
147
- <input type="text" class="small" id="<?php echo $section_slug; ?>image_meta_alt_delim" name="<?php echo $section_slug; ?>image_meta_alt_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_alt_delim']) ?>" style="width:5%; text-align:center;"/>
148
  <p style="margin-bottom:5px;"><?php _e('The first alt text will be linked to the first image, the second alt text will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
149
- <textarea name="<?php echo $section_slug; ?>image_meta_alt" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_alt']) ?></textarea>
150
  </div>
151
  </div>
152
  <div class="input">
153
- <input type="hidden" name="<?php echo $section_slug; ?>set_image_meta_description" value="0" />
154
- <input type="checkbox" id="<?php echo $section_slug; ?>set_image_meta_description" name="<?php echo $section_slug; ?>set_image_meta_description" value="1" <?php echo $post[$section_slug . 'set_image_meta_description'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
155
- <label for="<?php echo $section_slug; ?>set_image_meta_description"><?php _e('Set Description(s)','wp_all_import_plugin');?></label>
156
- <div class="switcher-target-<?php echo $section_slug; ?>set_image_meta_description" style="padding-left:23px;">
157
  <div class="input">
158
- <input id="<?php echo $section_slug; ?>image_meta_description_delim_logic_separate" type="radio" name="<?php echo $section_slug; ?>image_meta_description_delim_logic" value="separate" <?php echo ($post[$section_slug . 'image_meta_description_delim_logic'] == 'separate' and ! empty($post[$section_slug . 'image_meta_description_delim'])) ? 'checked="checked"' : ''; ?>/>
159
- <label for="<?php echo $section_slug; ?>image_meta_description_delim_logic_separate"><?php _e('Separate them with a', 'wp_all_import_plugin'); ?></label>
160
- <input type="text" class="small" id="<?php echo $section_slug; ?>image_meta_description_delim" name="<?php echo $section_slug; ?>image_meta_description_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_description_delim']) ?>" style="width:5%; text-align:center;"/>
161
  </div>
162
  <div class="input">
163
- <input id="<?php echo $section_slug; ?>image_meta_description_delim_logic_line" type="radio" name="<?php echo $section_slug; ?>image_meta_description_delim_logic" value="line" <?php echo ($post[$section_slug . 'image_meta_description_delim_logic'] == 'line' or empty($post[$section_slug . 'image_meta_description_delim'])) ? 'checked="checked"' : ''; ?>/>
164
- <label for="<?php echo $section_slug; ?>image_meta_description_delim_logic_line"><?php _e('Enter them one per line', 'wp_all_import_plugin'); ?></label>
165
  </div>
166
  <p style="margin-bottom:5px;"><?php _e('The first description will be linked to the first image, the second description will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
167
- <textarea name="<?php echo $section_slug; ?>image_meta_description" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_description']) ?></textarea>
168
  </div>
169
  </div>
170
  <h4><?php _e('Files', 'wp_all_import_plugin'); ?></h4>
171
  <div class="advanced_options_files">
172
  <p style="font-style:italic; display:none;"><?php _e('These options not available if Use images currently in Media Library is selected above.', 'wp_all_import_plugin'); ?></p>
173
  <div class="input" style="margin:3px 0px;">
174
- <input type="hidden" name="<?php echo $section_slug; ?>auto_rename_images" value="0" />
175
- <input type="checkbox" id="<?php echo $section_slug; ?>auto_rename_images" name="<?php echo $section_slug; ?>auto_rename_images" value="1" <?php echo $post[$section_slug . 'auto_rename_images'] ? 'checked="checked"' : ''; ?> class="switcher fix_checkbox"/>
176
- <label for="<?php echo $section_slug; ?>auto_rename_images"><?php _e('Change image file names to','wp_all_import_plugin');?> </label>
177
- <div class="input switcher-target-<?php echo $section_slug; ?>auto_rename_images" style="padding-left:23px;">
178
- <input type="text" id="<?php echo $section_slug; ?>auto_rename_images_suffix" name="<?php echo $section_slug; ?>auto_rename_images_suffix" value="<?php echo esc_attr($post[$section_slug . 'auto_rename_images_suffix']) ?>" style="width:480px;"/>
179
  <p class="note"><?php _e('Multiple image will have numbers appended, i.e. image-name-1.jpg, image-name-2.jpg '); ?></p>
180
  </div>
181
  </div>
182
  <div class="input" style="margin:3px 0px;">
183
- <input type="hidden" name="<?php echo $section_slug; ?>auto_set_extension" value="0" />
184
- <input type="checkbox" id="<?php echo $section_slug; ?>auto_set_extension" name="<?php echo $section_slug; ?>auto_set_extension" value="1" <?php echo $post[$section_slug . 'auto_set_extension'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
185
- <label for="<?php echo $section_slug; ?>auto_set_extension"><?php _e('Change image file extensions','wp_all_import_plugin');?> </label>
186
- <div class="input switcher-target-<?php echo $section_slug; ?>auto_set_extension" style="padding-left:23px;">
187
- <input type="text" id="<?php echo $section_slug; ?>new_extension" name="<?php echo $section_slug; ?>new_extension" value="<?php echo esc_attr($post[$section_slug . 'new_extension']) ?>" placeholder="jpg" style="width:480px;"/>
188
  </div>
189
  </div>
190
  </div>
1
  <div class="wpallimport-collapsed closed wpallimport-section wpallimport-featured-images">
2
  <div class="wpallimport-content-section" style="padding-bottom: 0;">
3
  <div class="wpallimport-collapsed-header" style="margin-bottom: 15px;">
4
+ <h3><?php echo esc_html($section_title);?></h3>
5
  </div>
6
  <div class="wpallimport-collapsed-content" style="padding: 0;">
7
  <div class="wpallimport-collapsed-content-inner">
18
  <td colspan="3">
19
  <div class="input">
20
  <div class="input">
21
+ <input type="radio" name="<?php echo esc_attr($section_slug); ?>download_images" value="yes" class="switcher" id="<?php echo esc_attr($section_slug); ?>download_images_yes" <?php echo ("yes" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
22
+ <label for="<?php echo esc_attr($section_slug); ?>download_images_yes"><?php _e('Download images hosted elsewhere'); ?></label>
23
  <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
24
  </div>
25
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>download_images_yes" style="padding-left:27px;">
26
+ <label for="<?php echo esc_attr($section_slug); ?>download_featured_delim"><?php _e('Enter image URL one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
27
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>download_featured_delim" name="<?php echo esc_attr($section_slug); ?>download_featured_delim" value="<?php echo esc_attr($post[$section_slug . 'download_featured_delim']) ?>" style="width:5%; text-align:center;"/>
28
+ <textarea name="<?php echo esc_attr($section_slug); ?>download_featured_image" class="newline rad4" style="clear: both; display:block;" placeholder=""><?php echo esc_textarea(wp_all_import_filter_html_kses($post[$section_slug . 'download_featured_image'])) ?></textarea>
29
  </div>
30
  <div class="input">
31
+ <input type="radio" name="<?php echo esc_attr($section_slug); ?>download_images" value="gallery" class="switcher" id="<?php echo esc_attr($section_slug); ?>download_images_gallery" <?php echo ("gallery" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
32
+ <label for="<?php echo esc_attr($section_slug); ?>download_images_gallery"><?php _e('Use images currently in Media Library'); ?></label>
33
  <!--a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a-->
34
  </div>
35
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>download_images_gallery" style="padding-left:27px;">
36
+ <label for="<?php echo esc_attr($section_slug); ?>gallery_featured_delim"><?php _e('Enter image filenames one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
37
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>gallery_featured_delim" name="<?php echo esc_attr($section_slug); ?>gallery_featured_delim" value="<?php echo esc_attr($post[$section_slug . 'gallery_featured_delim']) ?>" style="width:5%; text-align:center;"/>
38
+ <textarea name="<?php echo esc_attr($section_slug); ?>gallery_featured_image" class="newline rad4" style="clear: both; display:block; "><?php echo esc_textarea(wp_all_import_filter_html_kses($post[$section_slug . 'gallery_featured_image'])) ?></textarea>
39
  </div>
40
  <div class="input">
41
  <?php $wp_uploads = wp_upload_dir(); ?>
42
+ <input type="radio" name="<?php echo esc_attr($section_slug); ?>download_images" value="no" class="switcher" id="<?php echo esc_attr($section_slug); ?>download_images_no" <?php echo ("no" == $post[$section_slug . 'download_images']) ? 'checked="checked"' : '';?>/>
43
+ <label for="<?php echo esc_attr($section_slug); ?>download_images_no"><?php printf(__('Use images currently uploaded in %s', 'wp_all_import_plugin'), preg_replace('%.*wp-content/%', 'wp-content/', $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR) ); ?></label>
44
  </div>
45
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>download_images_no" style="padding-left:27px;">
46
+ <label for="<?php echo esc_attr($section_slug); ?>featured_delim"><?php _e('Enter image filenames one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
47
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>featured_delim" name="<?php echo esc_attr($section_slug); ?>featured_delim" value="<?php echo esc_attr($post[$section_slug . 'featured_delim']) ?>" style="width:5%; text-align:center;"/>
48
+ <textarea name="<?php echo esc_attr($section_slug); ?>featured_image" class="newline rad4" style="clear: both; display:block; "><?php echo esc_textarea(wp_all_import_filter_html_kses($post[$section_slug . 'featured_image'])) ?></textarea>
49
  </div>
50
  </div>
51
  <h4><?php _e('Image Options', 'wp_all_import_plugin'); ?></h4>
52
  <div class="search_through_the_media_library">
53
  <div class="input" style="margin:3px;">
54
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>search_existing_images" value="0" />
55
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>search_existing_images" name="<?php echo esc_attr($section_slug); ?>search_existing_images" value="1" <?php echo $post[$section_slug . 'search_existing_images'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
56
+ <label for="<?php echo esc_attr($section_slug); ?>search_existing_images"><?php _e('Search through the Media Library for existing images before importing new images','wp_all_import_plugin');?> </label>
57
  <a href="#help" class="wpallimport-help" title="<?php _e('If an image with the same file name or remote URL is found in the Media Library then that image will be attached to this record instead of importing a new image. Disable this setting if you always want to download a new image.', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
58
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>search_existing_images" style="padding-left:23px;">
59
  <div class="search_through_the_media_library_logic">
60
  <div class="input">
61
+ <input type="radio" id="<?php echo esc_attr($section_slug); ?>search_existing_images_logic_url" name="<?php echo esc_attr($section_slug); ?>search_existing_images_logic" value="by_url" <?php echo ( "by_url" == $post[$section_slug . 'search_existing_images_logic'] ) ? 'checked="checked"': '' ?>/>
62
+ <label for="<?php echo esc_attr($section_slug); ?>search_existing_images_logic_url"><?php _e('Match image by URL', 'wp_all_import_plugin') ?></label>
63
  </div>
64
  <div class="input">
65
+ <input type="radio" id="<?php echo esc_attr($section_slug); ?>search_existing_images_logic_filename" name="<?php echo esc_attr($section_slug); ?>search_existing_images_logic" value="by_filename" <?php echo ( "by_filename" == $post[$section_slug . 'search_existing_images_logic'] ) ? 'checked="checked"': '' ?>/>
66
+ <label for="<?php echo esc_attr($section_slug); ?>search_existing_images_logic_filename"><?php _e('Match image by filename', 'wp_all_import_plugin') ?></label>
67
  </div>
68
  </div>
69
  </div>
70
  </div>
71
  <div class="input" style="margin: 3px;">
72
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>do_not_remove_images" value="0" />
73
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>do_not_remove_images" name="<?php echo esc_attr($section_slug); ?>do_not_remove_images" value="1" <?php echo $post[$section_slug . 'do_not_remove_images'] ? 'checked="checked"': '' ?> />
74
+ <label for="<?php echo esc_attr($section_slug); ?>do_not_remove_images"><?php _e('Keep images currently in Media Library', 'wp_all_import_plugin') ?></label>
75
  <a href="#help" class="wpallimport-help" title="<?php _e('If disabled, images attached to imported posts will be deleted and then all images will be imported.', 'wp_all_import_plugin') ?>" style="position:relative; top: -2px;">?</a>
76
  </div>
77
  <?php if ($section_type == 'images'): ?>
78
  <div class="input" style="margin: 3px;">
79
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>import_img_tags" value="0" />
80
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>import_img_tags" name="<?php echo esc_attr($section_slug); ?>import_img_tags" value="1" <?php echo (isset($post[$section_slug . 'import_img_tags']) && $post[$section_slug . 'import_img_tags']) ? 'checked="checked"': '' ?> />
81
+ <label for="<?php echo esc_attr($section_slug); ?>import_img_tags"><?php _e('Scan through post content and import images wrapped in &lt;img&gt; tags', 'wp_all_import_plugin') ?></label>
82
  <a href="#help" class="wpallimport-help" title="<?php _e('Only images hosted on other sites will be imported. Images will be imported to WordPress and the <img> tag updated with the new image URL.', 'wp_all_import_plugin') ?>" style="position:relative; top: -2px;">?</a>
83
  </div>
84
  <?php endif; ?>
85
  </div>
86
  <?php if ($section_type == 'images'): ?>
87
  <div class="input">
88
+ <input type="hidden" value="<?php echo esc_attr($section_slug); ?>" class="wp_all_import_section_slug"/>
89
  <a class="preview_images" href="javascript:void(0);" rel="preview_images"><?php _e('Preview & Test', 'wp_all_import_plugin'); ?></a>
90
  </div>
91
  <div class="input" style="margin:3px;">
92
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>is_featured" value="0" />
93
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>is_featured" name="<?php echo esc_attr($section_slug); ?>is_featured" value="1" <?php echo $post[$section_slug . 'is_featured'] ? 'checked="checked"' : '' ?> class="fix_checkbox"/>
94
+ <label for="<?php echo esc_attr($section_slug); ?>is_featured"><?php _e('Set the first image to the Featured Image (_thumbnail_id)','wp_all_import_plugin');?> </label>
95
  </div>
96
  <div class="input" style="margin:3px;">
97
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>create_draft" value="no" />
98
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>create_draft" name="<?php echo esc_attr($section_slug); ?>create_draft" value="yes" <?php echo 'yes' == $post[$section_slug . 'create_draft'] ? 'checked="checked"' : '' ?> class="fix_checkbox"/>
99
+ <label for="<?php echo esc_attr($section_slug); ?>create_draft"><?php _e('If no images are downloaded successfully, create entry as Draft.', 'wp_all_import_plugin') ?></label>
100
  </div>
101
  <?php endif; ?>
102
  </td>
117
  <td colspan="3">
118
  <h4><?php _e('Meta Data', 'wp_all_import_plugin'); ?></h4>
119
  <div class="input">
120
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>set_image_meta_title" value="0" />
121
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>set_image_meta_title" name="<?php echo esc_attr($section_slug); ?>set_image_meta_title" value="1" <?php echo $post[$section_slug . 'set_image_meta_title'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
122
+ <label for="<?php echo esc_attr($section_slug); ?>set_image_meta_title"><?php _e('Set Title(s)','wp_all_import_plugin');?></label>
123
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>set_image_meta_title" style="padding-left:23px;">
124
+ <label for="<?php echo esc_attr($section_slug); ?>image_meta_title_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
125
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>image_meta_title_delim" name="<?php echo esc_attr($section_slug); ?>image_meta_title_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_title_delim']) ?>" style="width:5%; text-align:center;"/>
126
  <p style="margin-bottom:5px;"><?php _e('The first title will be linked to the first image, the second title will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
127
+ <textarea name="<?php echo esc_attr($section_slug); ?>image_meta_title" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_title']) ?></textarea>
128
  </div>
129
  </div>
130
  <div class="input">
131
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>set_image_meta_caption" value="0" />
132
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>set_image_meta_caption" name="<?php echo esc_attr($section_slug); ?>set_image_meta_caption" value="1" <?php echo $post[$section_slug . 'set_image_meta_caption'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
133
+ <label for="<?php echo esc_attr($section_slug); ?>set_image_meta_caption"><?php _e('Set Caption(s)','wp_all_import_plugin');?></label>
134
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>set_image_meta_caption" style="padding-left:23px;">
135
+ <label for="<?php echo esc_attr($section_slug); ?>image_meta_caption_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
136
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>image_meta_caption_delim" name="<?php echo esc_attr($section_slug); ?>image_meta_caption_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_caption_delim']) ?>" style="width:5%; text-align:center;"/>
137
  <p style="margin-bottom:5px;"><?php _e('The first caption will be linked to the first image, the second caption will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
138
+ <textarea name="<?php echo esc_attr($section_slug); ?>image_meta_caption" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_caption']) ?></textarea>
139
  </div>
140
  </div>
141
  <div class="input">
142
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>set_image_meta_alt" value="0" />
143
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>set_image_meta_alt" name="<?php echo esc_attr($section_slug); ?>set_image_meta_alt" value="1" <?php echo $post[$section_slug . 'set_image_meta_alt'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
144
+ <label for="<?php echo esc_attr($section_slug); ?>set_image_meta_alt"><?php _e('Set Alt Text(s)','wp_all_import_plugin');?></label>
145
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>set_image_meta_alt" style="padding-left:23px;">
146
+ <label for="<?php echo esc_attr($section_slug); ?>image_meta_alt_delim"><?php _e('Enter one per line, or separate them with a ', 'wp_all_import_plugin');?></label>
147
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>image_meta_alt_delim" name="<?php echo esc_attr($section_slug); ?>image_meta_alt_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_alt_delim']) ?>" style="width:5%; text-align:center;"/>
148
  <p style="margin-bottom:5px;"><?php _e('The first alt text will be linked to the first image, the second alt text will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
149
+ <textarea name="<?php echo esc_attr($section_slug); ?>image_meta_alt" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_alt']) ?></textarea>
150
  </div>
151
  </div>
152
  <div class="input">
153
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>set_image_meta_description" value="0" />
154
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>set_image_meta_description" name="<?php echo esc_attr($section_slug); ?>set_image_meta_description" value="1" <?php echo $post[$section_slug . 'set_image_meta_description'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
155
+ <label for="<?php echo esc_attr($section_slug); ?>set_image_meta_description"><?php _e('Set Description(s)','wp_all_import_plugin');?></label>
156
+ <div class="switcher-target-<?php echo esc_attr($section_slug); ?>set_image_meta_description" style="padding-left:23px;">
157
  <div class="input">
158
+ <input id="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic_separate" type="radio" name="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic" value="separate" <?php echo ($post[$section_slug . 'image_meta_description_delim_logic'] == 'separate' and ! empty($post[$section_slug . 'image_meta_description_delim'])) ? 'checked="checked"' : ''; ?>/>
159
+ <label for="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic_separate"><?php _e('Separate them with a', 'wp_all_import_plugin'); ?></label>
160
+ <input type="text" class="small" id="<?php echo esc_attr($section_slug); ?>image_meta_description_delim" name="<?php echo esc_attr($section_slug); ?>image_meta_description_delim" value="<?php echo esc_attr($post[$section_slug . 'image_meta_description_delim']) ?>" style="width:5%; text-align:center;"/>
161
  </div>
162
  <div class="input">
163
+ <input id="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic_line" type="radio" name="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic" value="line" <?php echo ($post[$section_slug . 'image_meta_description_delim_logic'] == 'line' or empty($post[$section_slug . 'image_meta_description_delim'])) ? 'checked="checked"' : ''; ?>/>
164
+ <label for="<?php echo esc_attr($section_slug); ?>image_meta_description_delim_logic_line"><?php _e('Enter them one per line', 'wp_all_import_plugin'); ?></label>
165
  </div>
166
  <p style="margin-bottom:5px;"><?php _e('The first description will be linked to the first image, the second description will be linked to the second image, ...', 'wp_all_import_plugin');?></p>
167
+ <textarea name="<?php echo esc_attr($section_slug); ?>image_meta_description" class="newline rad4"><?php echo esc_attr($post[$section_slug . 'image_meta_description']) ?></textarea>
168
  </div>
169
  </div>
170
  <h4><?php _e('Files', 'wp_all_import_plugin'); ?></h4>
171
  <div class="advanced_options_files">
172
  <p style="font-style:italic; display:none;"><?php _e('These options not available if Use images currently in Media Library is selected above.', 'wp_all_import_plugin'); ?></p>
173
  <div class="input" style="margin:3px 0px;">
174
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>auto_rename_images" value="0" />
175
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>auto_rename_images" name="<?php echo esc_attr($section_slug); ?>auto_rename_images" value="1" <?php echo $post[$section_slug . 'auto_rename_images'] ? 'checked="checked"' : ''; ?> class="switcher fix_checkbox"/>
176
+ <label for="<?php echo esc_attr($section_slug); ?>auto_rename_images"><?php _e('Change image file names to','wp_all_import_plugin');?> </label>
177
+ <div class="input switcher-target-<?php echo esc_attr($section_slug); ?>auto_rename_images" style="padding-left:23px;">
178
+ <input type="text" id="<?php echo esc_attr($section_slug); ?>auto_rename_images_suffix" name="<?php echo esc_attr($section_slug); ?>auto_rename_images_suffix" value="<?php echo esc_attr($post[$section_slug . 'auto_rename_images_suffix']) ?>" style="width:480px;"/>
179
  <p class="note"><?php _e('Multiple image will have numbers appended, i.e. image-name-1.jpg, image-name-2.jpg '); ?></p>
180
  </div>
181
  </div>
182
  <div class="input" style="margin:3px 0px;">
183
+ <input type="hidden" name="<?php echo esc_attr($section_slug); ?>auto_set_extension" value="0" />
184
+ <input type="checkbox" id="<?php echo esc_attr($section_slug); ?>auto_set_extension" name="<?php echo esc_attr($section_slug); ?>auto_set_extension" value="1" <?php echo $post[$section_slug . 'auto_set_extension'] ? 'checked="checked"' : '' ?> class="switcher fix_checkbox"/>
185
+ <label for="<?php echo esc_attr($section_slug); ?>auto_set_extension"><?php _e('Change image file extensions','wp_all_import_plugin');?> </label>
186
+ <div class="input switcher-target-<?php echo esc_attr($section_slug); ?>auto_set_extension" style="padding-left:23px;">
187
+ <input type="text" id="<?php echo esc_attr($section_slug); ?>new_extension" name="<?php echo esc_attr($section_slug); ?>new_extension" value="<?php echo esc_attr($post[$section_slug . 'new_extension']) ?>" placeholder="jpg" style="width:480px;"/>
188
  </div>
189
  </div>
190
  </div>
views/admin/import/template/_nested_template.php CHANGED
@@ -20,7 +20,7 @@
20
  $nested_files = json_decode($post['nested_files'], true);
21
  foreach ($nested_files as $key => $file) {
22
  ?>
23
- <li rel="<?php echo $key;?>"><?php echo $file;?> <a href="javascript:void(0);" class="unmerge"><?php _e('remove', 'wp_all_import_plugin'); ?></a></li>
24
  <?php
25
  }?>
26
  <?php endif; ?>
20
  $nested_files = json_decode($post['nested_files'], true);
21
  foreach ($nested_files as $key => $file) {
22
  ?>
23
+ <li rel="<?php echo esc_attr($key);?>"><?php echo esc_html($file);?> <a href="javascript:void(0);" class="unmerge"><?php _e('remove', 'wp_all_import_plugin'); ?></a></li>
24
  <?php
25
  }?>
26
  <?php endif; ?>
views/admin/import/template/_other_template.php CHANGED
@@ -12,8 +12,8 @@ $custom_type = get_post_type_object( $post_type );
12
  <table class="form-table" style="max-width:none;">
13
  <tr>
14
  <td>
15
- <input type="hidden" name="encoding" value="<?php echo ($this->isWizard) ? PMXI_Plugin::$session->encoding : $post['encoding']; ?>"/>
16
- <input type="hidden" name="delimiter" value="<?php echo ($this->isWizard) ? PMXI_Plugin::$session->is_csv : $post['delimiter']; ?>"/>
17
 
18
  <?php $is_support_post_format = ( current_theme_supports( 'post-formats' ) && post_type_supports( $post_type, 'post-formats' ) ) ? true : false; ?>
19
 
@@ -157,8 +157,8 @@ $custom_type = get_post_type_object( $post_type );
157
  foreach ($post_formats[0] as $post_format) {
158
  ?>
159
  <div class="input">
160
- <input type="radio" id="post_format_<?php echo $post_format; ?>" name="post_format" value="<?php echo $post_format; ?>" <?php echo $post_format == $post['post_format'] ? 'checked="checked"' : '' ?> />
161
- <label for="post_format_<?php echo $post_format; ?>"><?php _e( ucfirst($post_format), 'wp_all_import_plugin') ?></label>
162
  </div>
163
  <?php
164
  }
12
  <table class="form-table" style="max-width:none;">
13
  <tr>
14
  <td>
15
+ <input type="hidden" name="encoding" value="<?php echo ($this->isWizard) ? esc_attr(PMXI_Plugin::$session->encoding) : esc_attr($post['encoding']); ?>"/>
16
+ <input type="hidden" name="delimiter" value="<?php echo ($this->isWizard) ? esc_attr(PMXI_Plugin::$session->is_csv) : esc_attr($post['delimiter']); ?>"/>
17
 
18
  <?php $is_support_post_format = ( current_theme_supports( 'post-formats' ) && post_type_supports( $post_type, 'post-formats' ) ) ? true : false; ?>
19
 
157
  foreach ($post_formats[0] as $post_format) {
158
  ?>
159
  <div class="input">
160
+ <input type="radio" id="post_format_<?php echo esc_attr($post_format); ?>" name="post_format" value="<?php echo esc_attr($post_format); ?>" <?php echo $post_format == $post['post_format'] ? 'checked="checked"' : '' ?> />
161
+ <label for="post_format_<?php echo esc_attr($post_format); ?>"><?php _e( ucfirst($post_format), 'wp_all_import_plugin') ?></label>
162
  </div>
163
  <?php
164
  }
views/admin/import/template/_taxonomies_template.php CHANGED
@@ -27,28 +27,28 @@ if ( ! empty($post_taxonomies)):
27
  <td>
28
  <div class="post_taxonomy">
29
  <div class="input">
30
- <input type="hidden" name="tax_assing[<?php echo $ctx->name;?>]" value="0"/>
31
- <input type="checkbox" class="assign_post switcher" name="tax_assing[<?php echo $ctx->name;?>]" id="tax_assing_<?php echo $ctx->name;?>" <?php echo ( ! empty($post['tax_assing'][$ctx->name]) ) ? 'checked="checked"' : ''; ?> value="1"/>
32
- <label for="tax_assing_<?php echo $ctx->name;?>"><?php echo $ctx->labels->name; ?></label>
33
  </div>
34
- <div class="switcher-target-tax_assing_<?php echo $ctx->name;?>">
35
  <div class="input sub_input">
36
  <div class="input">
37
- <input type="radio" name="tax_logic[<?php echo $ctx->name;?>]" value="single" id="tax_logic_single_<?php echo $ctx->name;?>" class="switcher" <?php echo (empty($post['tax_logic'][$ctx->name]) or $post['tax_logic'][$ctx->name] == 'single') ? 'checked="checked"' : ''; ?>/>
38
- <label for="tax_logic_single_<?php echo $ctx->name;?>"><?php printf(__('Each %s has just one %s', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->singular_name); ?></label>
39
- <div class="switcher-target-tax_logic_single_<?php echo $ctx->name;?> sub_input">
40
- <input type="hidden" name="term_assing[<?php echo $ctx->name;?>]" value="0"/>
41
- <input type="checkbox" name="term_assing[<?php echo $ctx->name;?>]" <?php echo (isset($post['term_assing'][$ctx->name])) ? (( ! empty($post['term_assing'][$ctx->name]) ) ? 'checked="checked"' : '') : 'checked="checked"'; ?> title="<?php _e('Assign post to the taxonomy.','wp_all_import_plugin');?>" value="1"/>
42
- <input type="text" class="widefat single_xpath_field" name="tax_single_xpath[<?php echo $ctx->name; ?>]" value="<?php echo ( isset($post['tax_single_xpath'][$ctx->name])) ? esc_textarea($post['tax_single_xpath'][$ctx->name]) : ''; ?>" style="width:50%;"/>
43
  <div class="input tax_is_full_search_single" style="margin: 10px 0;">
44
- <input type="hidden" name="tax_is_full_search_single[<?php echo $ctx->name; ?>]" value="0"/>
45
- <input type="checkbox" id="tax_is_full_search_single_<?php echo $ctx->name; ?>" class="switcher" <?php if ( ! empty($post['tax_is_full_search_single'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_is_full_search_single[<?php echo $ctx->name; ?>]" value="1"/>
46
- <label for="tax_is_full_search_single_<?php echo $ctx->name;?>"><?php printf(__('Try to match terms to existing child %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
47
- <div class="switcher-target-tax_is_full_search_single_<?php echo $ctx->name; ?> sub_input">
48
  <div class="input tax_assign_to_one_term_single" style="margin: 10px 0;">
49
- <input type="hidden" name="tax_assign_to_one_term_single[<?php echo $ctx->name; ?>]" value="0"/>
50
- <input type="checkbox" id="tax_assign_to_one_term_single_<?php echo $ctx->name; ?>" <?php if ( ! empty($post['tax_assign_to_one_term_single'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_assign_to_one_term_single[<?php echo $ctx->name; ?>]" value="1"/>
51
- <label for="tax_assign_to_one_term_single_<?php echo $ctx->name;?>"><?php printf(__('Only assign %s to the imported %s, not the entire hierarchy', 'wp_all_import_plugin'), $custom_type->labels->name, $ctx->labels->singular_name); ?></label>
52
  <a href="#help" class="wpallimport-help" title="<?php _e('By default all categories above the matched category will also be assigned to the post. If enabled, only the imported category will be assigned to the post.', 'wp_all_import_plugin'); ?>" style="position:relative; top: -1px;">?</a>
53
  </div>
54
  </div>
@@ -56,22 +56,22 @@ if ( ! empty($post_taxonomies)):
56
  </div>
57
  </div>
58
  <div class="input">
59
- <input type="radio" name="tax_logic[<?php echo $ctx->name;?>]" value="multiple" id="tax_logic_multiple_<?php echo $ctx->name;?>" class="switcher" <?php echo (!empty($post['tax_logic'][$ctx->name]) and $post['tax_logic'][$ctx->name] == 'multiple') ? 'checked="checked"' : ''; ?>/>
60
- <label for="tax_logic_multiple_<?php echo $ctx->name;?>"><?php printf(__('Each %s has multiple %s', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->name); ?></label>
61
- <div class="switcher-target-tax_logic_multiple_<?php echo $ctx->name;?> sub_input">
62
- <input type="hidden" name="multiple_term_assing[<?php echo $ctx->name;?>]" value="1"/>
63
- <input type="text" class="widefat multiple_xpath_field" name="tax_multiple_xpath[<?php echo $ctx->name; ?>]" value="<?php echo ( ! empty($post['tax_multiple_xpath'][$ctx->name])) ? esc_textarea($post['tax_multiple_xpath'][$ctx->name]) : ''; ?>" style="width:50%;"/>
64
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
65
- <input type="text" class="small tax_delim" name="tax_multiple_delim[<?php echo $ctx->name; ?>]" value="<?php echo ( ! empty($post['tax_multiple_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_multiple_delim'][$ctx->name]))) : ',' ?>" />
66
  <div class="input tax_is_full_search_multiple" style="margin: 10px 0;">
67
- <input type="hidden" name="tax_is_full_search_multiple[<?php echo $ctx->name; ?>]" value="0"/>
68
- <input type="checkbox" id="tax_is_full_search_multiple_<?php echo $ctx->name; ?>" class="switcher" <?php if ( ! empty($post['tax_is_full_search_multiple'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_is_full_search_multiple[<?php echo $ctx->name; ?>]" value="1"/>
69
- <label for="tax_is_full_search_multiple_<?php echo $ctx->name;?>"><?php printf(__('Try to match terms to existing child %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
70
- <div class="switcher-target-tax_is_full_search_multiple_<?php echo $ctx->name; ?> sub_input">
71
  <div class="input tax_assign_to_one_term_multiple" style="margin: 10px 0;">
72
- <input type="hidden" name="tax_assign_to_one_term_multiple[<?php echo $ctx->name; ?>]" value="0"/>
73
- <input type="checkbox" id="tax_assign_to_one_term_multiple_<?php echo $ctx->name; ?>" <?php if ( ! empty($post['tax_assign_to_one_term_multiple'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_assign_to_one_term_multiple[<?php echo $ctx->name; ?>]" value="1"/>
74
- <label for="tax_assign_to_one_term_multiple_<?php echo $ctx->name;?>"><?php printf(__('Only assign %s to the imported %s, not the entire hierarchy', 'wp_all_import_plugin'), $custom_type->labels->name, $ctx->labels->singular_name); ?></label>
75
  <a href="#help" class="wpallimport-help" title="<?php _e('By default all categories above the matched category will also be assigned to the post. If enabled, only the imported category will be assigned to the post.', 'wp_all_import_plugin'); ?>" style="position:relative; top: -1px;">?</a>
76
  </div>
77
  </div>
@@ -80,20 +80,20 @@ if ( ! empty($post_taxonomies)):
80
  </div>
81
  <?php if ($ctx->hierarchical): ?>
82
  <div class="input">
83
- <input type="radio" name="tax_logic[<?php echo $ctx->name;?>]" value="hierarchical" id="tax_logic_hierarchical_<?php echo $ctx->name;?>" class="switcher" <?php echo (!empty($post['tax_logic'][$ctx->name]) and $post['tax_logic'][$ctx->name] == 'hierarchical') ? 'checked="checked"' : ''; ?>/>
84
- <label for="tax_logic_hierarchical_<?php echo $ctx->name;?>"><?php printf(__('%ss have hierarchical (parent/child) %s (i.e. Sports > Golf > Clubs > Putters)', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->name); ?></label>
85
- <div class="switcher-target-tax_logic_hierarchical_<?php echo $ctx->name;?> sub_input">
86
  <div class="input">
87
- <input type="hidden" name="tax_hierarchical_logic_entire[<?php echo $ctx->name;?>]" value="0" />
88
- <input type="checkbox" name="tax_hierarchical_logic_entire[<?php echo $ctx->name;?>]" value="1" id="hierarchical_logic_entire_<?php echo $ctx->name;?>" class="switcher" <?php echo (!empty($post['tax_hierarchical_logic_entire'][$ctx->name])) ? 'checked="checked"' : ''; ?>/>
89
- <label for="hierarchical_logic_entire_<?php echo $ctx->name;?>"><?php _e('An element in my file contains the entire hierarchy (i.e. you have an element with a value = Sports > Golf > Clubs > Putters)', 'wp_all_import_plugin'); ?></label>
90
- <div class="switcher-target-hierarchical_logic_entire_<?php echo $ctx->name;?> sub_input" style="margin-left: 20px; padding-left: 20px;">
91
  <ul class="tax_hierarchical_logic no-margin">
92
  <?php $txes_count = 0; if ( ! empty($post['tax_hierarchical_xpath'][$ctx->name])): foreach ($post['tax_hierarchical_xpath'][$ctx->name] as $k => $path) : if (empty($path)) continue; ?>
93
  <li class="dragging">
94
  <div style="position:relative;">
95
- <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo $ctx->name;?>][<?php echo $k;?>]" value="1"/>
96
- <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo $ctx->name; ?>][]" value="<?php echo esc_textarea(wp_all_import_filter_html_kses($path)); ?>"/>
97
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
98
  </div>
99
  </li>
@@ -101,34 +101,34 @@ if ( ! empty($post_taxonomies)):
101
  <?php if ( ! $txes_count): ?>
102
  <li class="dragging">
103
  <div style="position:relative;">
104
- <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo $ctx->name;?>][0]" value="1"/>
105
- <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo $ctx->name; ?>][]" value=""/>
106
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
107
  </div>
108
  </li>
109
  <?php endif; ?>
110
  <li class="dragging template">
111
  <div style="position:relative;">
112
- <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo $ctx->name;?>][NUMBER]" value="1"/>
113
- <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo $ctx->name; ?>][]" value=""/>
114
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
115
  </div>
116
  </li>
117
  </ul>
118
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
119
- <input type="text" class="small tax_delim" name="tax_hierarchical_delim[<?php echo $ctx->name; ?>]" value="<?php echo ( ! empty($post['tax_hierarchical_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_hierarchical_delim'][$ctx->name]))) : '>' ?>" />
120
  <div class="input">
121
- <input type="hidden" name="tax_hierarchical_last_level_assign[<?php echo $ctx->name; ?>]" value="0" />
122
- <input type="checkbox" id="tax_hierarchical_last_level_assign_<?php echo $ctx->name; ?>" name="tax_hierarchical_last_level_assign[<?php echo $ctx->name; ?>]" value="1" <?php echo ( ! empty($post['tax_hierarchical_last_level_assign'][$ctx->name])) ? 'checked="checked"': '' ?> />
123
- <label for="tax_hierarchical_last_level_assign_<?php echo $ctx->name; ?>"><?php printf(__('Only assign %s to the bottom level term in the hierarchy', 'wp_all_import_plugin'), $custom_type->label) ?></label>
124
  </div>
125
  <div class="input">
126
- <input type="hidden" name="is_tax_hierarchical_group_delim[<?php echo $ctx->name; ?>]" value="0" />
127
- <input type="checkbox" id="is_tax_hierarchical_group_delim_<?php echo $ctx->name; ?>" name="is_tax_hierarchical_group_delim[<?php echo $ctx->name; ?>]" value="1" class="switcher" <?php echo ( ! empty($post['is_tax_hierarchical_group_delim'][$ctx->name])) ? 'checked="checked"': '' ?> />
128
- <label for="is_tax_hierarchical_group_delim_<?php echo $ctx->name; ?>"><?php printf(__('Separate hierarchy groups via symbol', 'wp_all_import_plugin'), $custom_type->label) ?></label>
129
- <div class="switcher-target-is_tax_hierarchical_group_delim_<?php echo $ctx->name;?> sub_input">
130
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
131
- <input type="text" class="small tax_delim" name="tax_hierarchical_group_delim[<?php echo $ctx->name; ?>]" value="<?php echo ( ! empty($post['tax_hierarchical_group_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_hierarchical_group_delim'][$ctx->name]))) : '|' ?>" />
132
  </div>
133
  </div>
134
  <a class="preview_taxonomies" href="javascript:void(0);" style="top:-35px; float: right; position: relative;" rel="preview_taxonomies"><?php _e('Preview', 'wp_all_import_plugin'); ?></a>
@@ -138,10 +138,10 @@ if ( ! empty($post_taxonomies)):
138
  </div>
139
  </div>
140
  <div class="input">
141
- <input type="hidden" name="tax_hierarchical_logic_manual[<?php echo $ctx->name;?>]" value="0" />
142
- <input type="checkbox" name="tax_hierarchical_logic_manual[<?php echo $ctx->name;?>]" value="1" id="hierarchical_logic_manual_<?php echo $ctx->name;?>" class="switcher" <?php echo (!empty($post['tax_hierarchical_logic_manual'][$ctx->name])) ? 'checked="checked"' : ''; ?>/>
143
- <label for="hierarchical_logic_manual_<?php echo $ctx->name;?>"><?php _e('Manually design the hierarchy with drag & drop', 'wp_all_import_plugin'); ?></label>
144
- <div class="switcher-target-hierarchical_logic_manual_<?php echo $ctx->name;?> sub_input">
145
  <p style="margin-bottom: 10px;"><?php printf(__('Drag the <img src="%s" class="wpallimport-drag-icon"/> to the right to create a child, drag up and down to re-order.'), WP_ALL_IMPORT_ROOT_URL . '/static/img/drag.png'); ?></p>
146
  <ol class="sortable no-margin" style="margin-left: 20px;">
147
  <?php
@@ -155,7 +155,7 @@ if ( ! empty($post_taxonomies)):
155
  if (is_null($cat->parent_id) or empty($cat->parent_id))
156
  {
157
  ?>
158
- <li id="item_<?php echo $i; ?>" class="dragging">
159
  <div class="drag-element">
160
  <input type="hidden" class="assign_term" value="1"/>
161
  <input type="text" class="widefat xpath_field" value="<?php echo esc_textarea($cat->xpath); ?>"/>
@@ -202,11 +202,11 @@ if ( ! empty($post_taxonomies)):
202
  </li>
203
 
204
  </ol>
205
- <input type="hidden" class="hierarhy-output" name="post_taxonomies[<?php echo $ctx->name; ?>]" value="<?php echo empty($post['post_taxonomies'][$ctx->name]) ? '' : esc_attr($post['post_taxonomies'][$ctx->name]) ?>"/>
206
  <?php do_action('pmxi_category_options_view', ((!empty($post['post_taxonomies'][$ctx->name])) ? $post['post_taxonomies'][$ctx->name] : false), $ctx->name, $post_type, $ctx->labels->name); ?>
207
  <div class="input" style="margin-left:17px;">
208
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
209
- <input type="text" class="small tax_delim" name="tax_manualhierarchy_delim[<?php echo $ctx->name; ?>]" value="<?php echo ( ! empty($post['tax_manualhierarchy_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_manualhierarchy_delim'][$ctx->name]))) : ',' ?>" />
210
  </div>
211
  <a href="javascript:void(0);" class="icon-item add-new-ico"><?php _e('Add Another Row','wp_all_import_plugin');?></a>
212
  </div>
@@ -218,12 +218,12 @@ if ( ! empty($post_taxonomies)):
218
  <?php
219
  $tax_mapping = ( ! empty($post['tax_mapping'][$ctx->name]) ) ? json_decode($post['tax_mapping'][$ctx->name], true) : false;
220
  ?>
221
- <input type="hidden" name="tax_enable_mapping[<?php echo $ctx->name; ?>]" value="0"/>
222
- <input type="checkbox" id="tax_mapping_<?php echo $ctx->name; ?>" class="pmxi_tax_mapping switcher" <?php if ( ! empty($post['tax_enable_mapping'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_enable_mapping[<?php echo $ctx->name; ?>]" value="1"/>
223
- <label for="tax_mapping_<?php echo $ctx->name;?>"><?php printf(__('Enable Mapping for %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
224
- <div class="switcher-target-tax_mapping_<?php echo $ctx->name;?> sub_input custom_type" rel="tax_mapping">
225
  <fieldset style="padding: 0;">
226
- <table cellpadding="0" cellspacing="5" class="tax-form-table" rel="tax_mapping_<?php echo $ctx->name; ?>" style="width: 100%;">
227
  <thead>
228
  <tr>
229
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
@@ -294,12 +294,12 @@ if ( ! empty($post_taxonomies)):
294
  </tr>
295
  </tbody>
296
  </table>
297
- <input type="hidden" name="tax_mapping[<?php echo $ctx->name; ?>]" value="<?php if (!empty($post['tax_mapping'][$ctx->name])) echo esc_html($post['tax_mapping'][$ctx->name]); ?>"/>
298
  </fieldset>
299
  <div class="input">
300
- <input type="hidden" name="tax_logic_mapping[<?php echo $ctx->name; ?>]" value="0"/>
301
- <input type="checkbox" id="tax_logic_mapping_<?php echo $ctx->name; ?>" name="tax_logic_mapping[<?php echo $ctx->name; ?>]" <?php echo ( ! empty($post['tax_logic_mapping'][$ctx->name]) ) ? 'checked="checked"' : ''; ?> value="1"/>
302
- <label for="tax_logic_mapping_<?php echo $ctx->name; ?>"><?php _e('Apply mapping rules before splitting via separator symbol','wp_all_import_plugin'); ?></label>
303
  </div>
304
  </div>
305
  </div>
27
  <td>
28
  <div class="post_taxonomy">
29
  <div class="input">
30
+ <input type="hidden" name="tax_assing[<?php echo esc_attr($ctx->name);?>]" value="0"/>
31
+ <input type="checkbox" class="assign_post switcher" name="tax_assing[<?php echo esc_attr($ctx->name);?>]" id="tax_assing_<?php echo esc_attr($ctx->name);?>" <?php echo ( ! empty($post['tax_assing'][$ctx->name]) ) ? 'checked="checked"' : ''; ?> value="1"/>
32
+ <label for="tax_assing_<?php echo esc_attr($ctx->name);?>"><?php echo esc_html($ctx->labels->name); ?></label>
33
  </div>
34
+ <div class="switcher-target-tax_assing_<?php echo esc_attr($ctx->name);?>">
35
  <div class="input sub_input">
36
  <div class="input">
37
+ <input type="radio" name="tax_logic[<?php echo esc_attr($ctx->name);?>]" value="single" id="tax_logic_single_<?php echo esc_attr($ctx->name);?>" class="switcher" <?php echo (empty($post['tax_logic'][$ctx->name]) or $post['tax_logic'][$ctx->name] == 'single') ? 'checked="checked"' : ''; ?>/>
38
+ <label for="tax_logic_single_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Each %s has just one %s', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->singular_name); ?></label>
39
+ <div class="switcher-target-tax_logic_single_<?php echo esc_attr($ctx->name);?> sub_input">
40
+ <input type="hidden" name="term_assing[<?php echo esc_attr($ctx->name);?>]" value="0"/>
41
+ <input type="checkbox" name="term_assing[<?php echo esc_attr($ctx->name);?>]" <?php echo (isset($post['term_assing'][$ctx->name])) ? (( ! empty($post['term_assing'][$ctx->name]) ) ? 'checked="checked"' : '') : 'checked="checked"'; ?> title="<?php _e('Assign post to the taxonomy.','wp_all_import_plugin');?>" value="1"/>
42
+ <input type="text" class="widefat single_xpath_field" name="tax_single_xpath[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( isset($post['tax_single_xpath'][$ctx->name])) ? esc_textarea($post['tax_single_xpath'][$ctx->name]) : ''; ?>" style="width:50%;"/>
43
  <div class="input tax_is_full_search_single" style="margin: 10px 0;">
44
+ <input type="hidden" name="tax_is_full_search_single[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
45
+ <input type="checkbox" id="tax_is_full_search_single_<?php echo esc_attr($ctx->name); ?>" class="switcher" <?php if ( ! empty($post['tax_is_full_search_single'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_is_full_search_single[<?php echo esc_attr($ctx->name); ?>]" value="1"/>
46
+ <label for="tax_is_full_search_single_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Try to match terms to existing child %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
47
+ <div class="switcher-target-tax_is_full_search_single_<?php echo esc_attr($ctx->name); ?> sub_input">
48
  <div class="input tax_assign_to_one_term_single" style="margin: 10px 0;">
49
+ <input type="hidden" name="tax_assign_to_one_term_single[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
50
+ <input type="checkbox" id="tax_assign_to_one_term_single_<?php echo esc_attr($ctx->name); ?>" <?php if ( ! empty($post['tax_assign_to_one_term_single'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_assign_to_one_term_single[<?php echo esc_attr($ctx->name); ?>]" value="1"/>
51
+ <label for="tax_assign_to_one_term_single_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Only assign %s to the imported %s, not the entire hierarchy', 'wp_all_import_plugin'), $custom_type->labels->name, $ctx->labels->singular_name); ?></label>
52
  <a href="#help" class="wpallimport-help" title="<?php _e('By default all categories above the matched category will also be assigned to the post. If enabled, only the imported category will be assigned to the post.', 'wp_all_import_plugin'); ?>" style="position:relative; top: -1px;">?</a>
53
  </div>
54
  </div>
56
  </div>
57
  </div>
58
  <div class="input">
59
+ <input type="radio" name="tax_logic[<?php echo esc_attr($ctx->name);?>]" value="multiple" id="tax_logic_multiple_<?php echo esc_attr($ctx->name);?>" class="switcher" <?php echo (!empty($post['tax_logic'][$ctx->name]) and $post['tax_logic'][$ctx->name] == 'multiple') ? 'checked="checked"' : ''; ?>/>
60
+ <label for="tax_logic_multiple_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Each %s has multiple %s', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->name); ?></label>
61
+ <div class="switcher-target-tax_logic_multiple_<?php echo esc_attr($ctx->name);?> sub_input">
62
+ <input type="hidden" name="multiple_term_assing[<?php echo esc_attr($ctx->name);?>]" value="1"/>
63
+ <input type="text" class="widefat multiple_xpath_field" name="tax_multiple_xpath[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( ! empty($post['tax_multiple_xpath'][$ctx->name])) ? esc_textarea($post['tax_multiple_xpath'][$ctx->name]) : ''; ?>" style="width:50%;"/>
64
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
65
+ <input type="text" class="small tax_delim" name="tax_multiple_delim[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( ! empty($post['tax_multiple_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_multiple_delim'][$ctx->name]))) : ',' ?>" />
66
  <div class="input tax_is_full_search_multiple" style="margin: 10px 0;">
67
+ <input type="hidden" name="tax_is_full_search_multiple[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
68
+ <input type="checkbox" id="tax_is_full_search_multiple_<?php echo esc_attr($ctx->name); ?>" class="switcher" <?php if ( ! empty($post['tax_is_full_search_multiple'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_is_full_search_multiple[<?php echo esc_attr($ctx->name); ?>]" value="1"/>
69
+ <label for="tax_is_full_search_multiple_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Try to match terms to existing child %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
70
+ <div class="switcher-target-tax_is_full_search_multiple_<?php echo esc_attr($ctx->name); ?> sub_input">
71
  <div class="input tax_assign_to_one_term_multiple" style="margin: 10px 0;">
72
+ <input type="hidden" name="tax_assign_to_one_term_multiple[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
73
+ <input type="checkbox" id="tax_assign_to_one_term_multiple_<?php echo esc_attr($ctx->name); ?>" <?php if ( ! empty($post['tax_assign_to_one_term_multiple'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_assign_to_one_term_multiple[<?php echo esc_attr($ctx->name); ?>]" value="1"/>
74
+ <label for="tax_assign_to_one_term_multiple_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Only assign %s to the imported %s, not the entire hierarchy', 'wp_all_import_plugin'), $custom_type->labels->name, $ctx->labels->singular_name); ?></label>
75
  <a href="#help" class="wpallimport-help" title="<?php _e('By default all categories above the matched category will also be assigned to the post. If enabled, only the imported category will be assigned to the post.', 'wp_all_import_plugin'); ?>" style="position:relative; top: -1px;">?</a>
76
  </div>
77
  </div>
80
  </div>
81
  <?php if ($ctx->hierarchical): ?>
82
  <div class="input">
83
+ <input type="radio" name="tax_logic[<?php echo esc_attr($ctx->name);?>]" value="hierarchical" id="tax_logic_hierarchical_<?php echo esc_attr($ctx->name);?>" class="switcher" <?php echo (!empty($post['tax_logic'][$ctx->name]) and $post['tax_logic'][$ctx->name] == 'hierarchical') ? 'checked="checked"' : ''; ?>/>
84
+ <label for="tax_logic_hierarchical_<?php echo esc_attr($ctx->name);?>"><?php printf(__('%ss have hierarchical (parent/child) %s (i.e. Sports > Golf > Clubs > Putters)', 'wp_all_import_plugin'), $custom_type->labels->singular_name, $ctx->labels->name); ?></label>
85
+ <div class="switcher-target-tax_logic_hierarchical_<?php echo esc_attr($ctx->name);?> sub_input">
86
  <div class="input">
87
+ <input type="hidden" name="tax_hierarchical_logic_entire[<?php echo esc_attr($ctx->name);?>]" value="0" />
88
+ <input type="checkbox" name="tax_hierarchical_logic_entire[<?php echo esc_attr($ctx->name);?>]" value="1" id="hierarchical_logic_entire_<?php echo esc_attr($ctx->name);?>" class="switcher" <?php echo (!empty($post['tax_hierarchical_logic_entire'][$ctx->name])) ? 'checked="checked"' : ''; ?>/>
89
+ <label for="hierarchical_logic_entire_<?php echo esc_attr($ctx->name);?>"><?php _e('An element in my file contains the entire hierarchy (i.e. you have an element with a value = Sports > Golf > Clubs > Putters)', 'wp_all_import_plugin'); ?></label>
90
+ <div class="switcher-target-hierarchical_logic_entire_<?php echo esc_attr($ctx->name);?> sub_input" style="margin-left: 20px; padding-left: 20px;">
91
  <ul class="tax_hierarchical_logic no-margin">
92
  <?php $txes_count = 0; if ( ! empty($post['tax_hierarchical_xpath'][$ctx->name])): foreach ($post['tax_hierarchical_xpath'][$ctx->name] as $k => $path) : if (empty($path)) continue; ?>
93
  <li class="dragging">
94
  <div style="position:relative;">
95
+ <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo esc_attr($ctx->name);?>][<?php echo esc_attr($k);?>]" value="1"/>
96
+ <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo esc_attr($ctx->name); ?>][]" value="<?php echo esc_textarea(wp_all_import_filter_html_kses($path)); ?>"/>
97
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
98
  </div>
99
  </li>
101
  <?php if ( ! $txes_count): ?>
102
  <li class="dragging">
103
  <div style="position:relative;">
104
+ <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo esc_attr($ctx->name);?>][0]" value="1"/>
105
+ <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo esc_attr($ctx->name); ?>][]" value=""/>
106
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
107
  </div>
108
  </li>
109
  <?php endif; ?>
110
  <li class="dragging template">
111
  <div style="position:relative;">
112
+ <input type="hidden" class="assign_term" name="tax_hierarchical_assing[<?php echo esc_attr($ctx->name);?>][NUMBER]" value="1"/>
113
+ <input type="text" class="widefat hierarchical_xpath_field" name="tax_hierarchical_xpath[<?php echo esc_attr($ctx->name); ?>][]" value=""/>
114
  <a href="javascript:void(0);" class="icon-item remove-ico"></a>
115
  </div>
116
  </li>
117
  </ul>
118
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
119
+ <input type="text" class="small tax_delim" name="tax_hierarchical_delim[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( ! empty($post['tax_hierarchical_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_hierarchical_delim'][$ctx->name]))) : '>' ?>" />
120
  <div class="input">
121
+ <input type="hidden" name="tax_hierarchical_last_level_assign[<?php echo esc_attr($ctx->name); ?>]" value="0" />
122
+ <input type="checkbox" id="tax_hierarchical_last_level_assign_<?php echo esc_attr($ctx->name); ?>" name="tax_hierarchical_last_level_assign[<?php echo esc_attr($ctx->name); ?>]" value="1" <?php echo ( ! empty($post['tax_hierarchical_last_level_assign'][$ctx->name])) ? 'checked="checked"': '' ?> />
123
+ <label for="tax_hierarchical_last_level_assign_<?php echo esc_attr($ctx->name); ?>"><?php printf(__('Only assign %s to the bottom level term in the hierarchy', 'wp_all_import_plugin'), $custom_type->label) ?></label>
124
  </div>
125
  <div class="input">
126
+ <input type="hidden" name="is_tax_hierarchical_group_delim[<?php echo esc_attr($ctx->name); ?>]" value="0" />
127
+ <input type="checkbox" id="is_tax_hierarchical_group_delim_<?php echo esc_attr($ctx->name); ?>" name="is_tax_hierarchical_group_delim[<?php echo esc_attr($ctx->name); ?>]" value="1" class="switcher" <?php echo ( ! empty($post['is_tax_hierarchical_group_delim'][$ctx->name])) ? 'checked="checked"': '' ?> />
128
+ <label for="is_tax_hierarchical_group_delim_<?php echo esc_attr($ctx->name); ?>"><?php printf(__('Separate hierarchy groups via symbol', 'wp_all_import_plugin'), $custom_type->label) ?></label>
129
+ <div class="switcher-target-is_tax_hierarchical_group_delim_<?php echo esc_attr($ctx->name);?> sub_input">
130
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
131
+ <input type="text" class="small tax_delim" name="tax_hierarchical_group_delim[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( ! empty($post['tax_hierarchical_group_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_hierarchical_group_delim'][$ctx->name]))) : '|' ?>" />
132
  </div>
133
  </div>
134
  <a class="preview_taxonomies" href="javascript:void(0);" style="top:-35px; float: right; position: relative;" rel="preview_taxonomies"><?php _e('Preview', 'wp_all_import_plugin'); ?></a>
138
  </div>
139
  </div>
140
  <div class="input">
141
+ <input type="hidden" name="tax_hierarchical_logic_manual[<?php echo esc_attr($ctx->name);?>]" value="0" />
142
+ <input type="checkbox" name="tax_hierarchical_logic_manual[<?php echo esc_attr($ctx->name);?>]" value="1" id="hierarchical_logic_manual_<?php echo esc_attr($ctx->name);?>" class="switcher" <?php echo (!empty($post['tax_hierarchical_logic_manual'][$ctx->name])) ? 'checked="checked"' : ''; ?>/>
143
+ <label for="hierarchical_logic_manual_<?php echo esc_attr($ctx->name);?>"><?php _e('Manually design the hierarchy with drag & drop', 'wp_all_import_plugin'); ?></label>
144
+ <div class="switcher-target-hierarchical_logic_manual_<?php echo esc_attr($ctx->name);?> sub_input">
145
  <p style="margin-bottom: 10px;"><?php printf(__('Drag the <img src="%s" class="wpallimport-drag-icon"/> to the right to create a child, drag up and down to re-order.'), WP_ALL_IMPORT_ROOT_URL . '/static/img/drag.png'); ?></p>
146
  <ol class="sortable no-margin" style="margin-left: 20px;">
147
  <?php
155
  if (is_null($cat->parent_id) or empty($cat->parent_id))
156
  {
157
  ?>
158
+ <li id="item_<?php echo esc_attr($i); ?>" class="dragging">
159
  <div class="drag-element">
160
  <input type="hidden" class="assign_term" value="1"/>
161
  <input type="text" class="widefat xpath_field" value="<?php echo esc_textarea($cat->xpath); ?>"/>
202
  </li>
203
 
204
  </ol>
205
+ <input type="hidden" class="hierarhy-output" name="post_taxonomies[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo empty($post['post_taxonomies'][$ctx->name]) ? '' : esc_attr($post['post_taxonomies'][$ctx->name]) ?>"/>
206
  <?php do_action('pmxi_category_options_view', ((!empty($post['post_taxonomies'][$ctx->name])) ? $post['post_taxonomies'][$ctx->name] : false), $ctx->name, $post_type, $ctx->labels->name); ?>
207
  <div class="input" style="margin-left:17px;">
208
  <label><?php _e('Separated by', 'wp_all_import_plugin'); ?></label>
209
+ <input type="text" class="small tax_delim" name="tax_manualhierarchy_delim[<?php echo esc_attr($ctx->name); ?>]" value="<?php echo ( ! empty($post['tax_manualhierarchy_delim'][$ctx->name]) ) ? str_replace("&amp;","&", htmlentities(htmlentities($post['tax_manualhierarchy_delim'][$ctx->name]))) : ',' ?>" />
210
  </div>
211
  <a href="javascript:void(0);" class="icon-item add-new-ico"><?php _e('Add Another Row','wp_all_import_plugin');?></a>
212
  </div>
218
  <?php
219
  $tax_mapping = ( ! empty($post['tax_mapping'][$ctx->name]) ) ? json_decode($post['tax_mapping'][$ctx->name], true) : false;
220
  ?>
221
+ <input type="hidden" name="tax_enable_mapping[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
222
+ <input type="checkbox" id="tax_mapping_<?php echo esc_attr($ctx->name); ?>" class="pmxi_tax_mapping switcher" <?php if ( ! empty($post['tax_enable_mapping'][$ctx->name]) ) echo "checked='checked'"; ?> name="tax_enable_mapping[<?php echo esc_attr($ctx->name); ?>]" value="1"/>
223
+ <label for="tax_mapping_<?php echo esc_attr($ctx->name);?>"><?php printf(__('Enable Mapping for %s', 'wp_all_import_plugin'), $ctx->labels->name); ?></label>
224
+ <div class="switcher-target-tax_mapping_<?php echo esc_attr($ctx->name);?> sub_input custom_type" rel="tax_mapping">
225
  <fieldset style="padding: 0;">
226
+ <table cellpadding="0" cellspacing="5" class="tax-form-table" rel="tax_mapping_<?php echo esc_attr($ctx->name); ?>" style="width: 100%;">
227
  <thead>
228
  <tr>
229
  <td><?php _e('In Your File', 'wp_all_import_plugin') ?></td>
294
  </tr>
295
  </tbody>
296
  </table>
297
+ <input type="hidden" name="tax_mapping[<?php echo esc_attr($ctx->name); ?>]" value="<?php if (!empty($post['tax_mapping'][$ctx->name])) echo esc_html($post['tax_mapping'][$ctx->name]); ?>"/>
298
  </fieldset>
299
  <div class="input">
300
+ <input type="hidden" name="tax_logic_mapping[<?php echo esc_attr($ctx->name); ?>]" value="0"/>
301
+ <input type="checkbox" id="tax_logic_mapping_<?php echo esc_attr($ctx->name); ?>" name="tax_logic_mapping[<?php echo esc_attr($ctx->name); ?>]" <?php echo ( ! empty($post['tax_logic_mapping'][$ctx->name]) ) ? 'checked="checked"' : ''; ?> value="1"/>
302
+ <label for="tax_logic_mapping_<?php echo esc_attr($ctx->name); ?>"><?php _e('Apply mapping rules before splitting via separator symbol','wp_all_import_plugin'); ?></label>
303
  </div>
304
  </div>
305
  </div>
views/admin/import/warning.php CHANGED
@@ -1,3 +1,3 @@
1
  <?php foreach ($warnings as $msg): ?>
2
- <div class="error inline"><p><?php echo $msg ?></p></div>
3
  <?php endforeach ?>
1
  <?php foreach ($warnings as $msg): ?>
2
+ <div class="error inline"><p><?php echo wp_kses_post($msg); ?></p></div>
3
  <?php endforeach ?>
views/admin/manage/delete.php CHANGED
@@ -73,7 +73,7 @@ else{
73
  <?php wp_nonce_field('delete-import', '_wpnonce_delete-import') ?>
74
  <input type="hidden" name="is_confirmed" value="1" />
75
  <input type="hidden" name="import_ids[]" value="<?php echo esc_attr($item->id); ?>" />
76
- <input type="hidden" name="base_url" value="<?php echo $this->baseUrl; ?>">
77
  <input type="submit" class="button-primary delete-single-import wp_all_import_ajax_deletion" value="Delete" />
78
  <div class="wp_all_import_functions_preloader"></div>
79
  </div>
73
  <?php wp_nonce_field('delete-import', '_wpnonce_delete-import') ?>
74
  <input type="hidden" name="is_confirmed" value="1" />
75
  <input type="hidden" name="import_ids[]" value="<?php echo esc_attr($item->id); ?>" />
76
+ <input type="hidden" name="base_url" value="<?php echo esc_url($this->baseUrl); ?>">
77
  <input type="submit" class="button-primary delete-single-import wp_all_import_ajax_deletion" value="Delete" />
78
  <div class="wp_all_import_functions_preloader"></div>
79
  </div>
views/admin/manage/index.php CHANGED
@@ -53,7 +53,7 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
53
  number_format_i18n(($pagenum - 1) * $perPage + 1),
54
  number_format_i18n(min($pagenum * $perPage, $list->total())),
55
  number_format_i18n($list->total()),
56
- $page_links
57
  ) ?>
58
  </div>
59
  <?php endif ?>
@@ -81,7 +81,7 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
81
  }
82
  else $col_html .= '<th scope="col" class="column-' . $column_id . '">' . $column_display_name . '</th>';
83
  }
84
- echo $col_html;
85
  ?>
86
  </tr>
87
  </thead>
@@ -90,7 +90,7 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
90
  <th class="manage-column column-cb check-column" scope="col">
91
  <input type="checkbox" />
92
  </th>
93
- <?php echo $col_html; ?>
94
  </tr>
95
  </tfoot>
96
  <tbody id="the-pmxi-admin-import-list" class="list:pmxi-admin-imports">
@@ -104,9 +104,9 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
104
  ?>
105
  <?php foreach ($list as $item): ?>
106
  <?php $class = ('alternate' == $class) ? '' : 'alternate'; ?>
107
- <tr class="<?php echo $class; ?>" valign="middle">
108
  <th scope="row" class="check-column">
109
- <input type="checkbox" id="item_<?php echo $item['id'] ?>" name="items[]" value="<?php echo esc_attr($item['id']) ?>" />
110
  </th>
111
  <?php foreach ($columns as $column_id => $column_display_name): ?>
112
  <?php
@@ -114,7 +114,7 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
114
  case 'id':
115
  ?>
116
  <th valign="top" scope="row">
117
- <?php echo $item['id'] ?>
118
  </th>
119
  <?php
120
  break;
@@ -159,10 +159,10 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
159
  }
160
  }
161
  ?>
162
- <em><a href="<?php echo add_query_arg(array('id' => $item['id'], 'action' => 'feed', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>" class="wp_all_import_show_path" rel="<?php echo $item['path']; ?>"><?php echo preg_replace('%.*wp-content/%', 'wp-content/', $path); ?></a></em>
163
  <?php elseif (in_array($item['type'], array('file'))):?>
164
  <?php $item['path'] = wp_all_import_get_absolute_path($item['path']); ?>
165
- <em><a href="<?php echo add_query_arg(array('id' => $item['id'], 'action' => 'feed', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>" class="wp_all_import_show_path" rel="<?php echo $item['path']; ?>"><?php echo preg_replace('%.*wp-content/%', 'wp-content/', $item['path']); ?></a></em>
166
  <?php else: ?>
167
  <em><?php echo str_replace("\\", '/', preg_replace('%^(\w+://[^:]+:)[^@]+@%', '$1*****@', $item['path'])); ?></em>
168
  <?php endif; ?>
@@ -195,11 +195,11 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
195
  switch ($key) {
196
  default:
197
  ?>
198
- <span class="<?php echo $action['class']; ?>">
199
  <?php if ( ! empty($action['url']) ): ?>
200
- <a class="<?php echo $action['class']; ?>" href="<?php echo esc_url($action['url']); ?>"><?php echo $action['title']; ?></a>
201
  <?php else: ?>
202
- <span class="wpallimport-disabled"><?php echo $action['title']; ?></span>
203
  <?php endif; ?>
204
  </span> <?php if ($ai != count($import_actions)): ?>|<?php endif; ?>
205
  <?php
@@ -334,7 +334,7 @@ $columns = apply_filters('pmxi_manage_imports_columns', $columns);
334
  </table>
335
 
336
  <div class="tablenav">
337
- <?php if ($page_links): ?><div class="tablenav-pages"><?php echo $page_links_html ?></div><?php endif ?>
338
 
339
  <div class="alignleft actions">
340
  <select name="bulk-action2">
53
  number_format_i18n(($pagenum - 1) * $perPage + 1),
54
  number_format_i18n(min($pagenum * $perPage, $list->total())),
55
  number_format_i18n($list->total()),
56
+ wp_kses_post($page_links)
57
  ) ?>
58
  </div>
59
  <?php endif ?>
81
  }
82
  else $col_html .= '<th scope="col" class="column-' . $column_id . '">' . $column_display_name . '</th>';
83
  }
84
+ echo wp_kses_post($col_html);
85
  ?>
86
  </tr>
87
  </thead>
90
  <th class="manage-column column-cb check-column" scope="col">
91
  <input type="checkbox" />
92
  </th>
93
+ <?php echo wp_kses_post($col_html); ?>
94
  </tr>
95
  </tfoot>
96
  <tbody id="the-pmxi-admin-import-list" class="list:pmxi-admin-imports">
104
  ?>
105
  <?php foreach ($list as $item): ?>
106
  <?php $class = ('alternate' == $class) ? '' : 'alternate'; ?>
107
+ <tr class="<?php echo esc_attr($class); ?>" valign="middle">
108
  <th scope="row" class="check-column">
109
+ <input type="checkbox" id="item_<?php echo esc_attr($item['id']) ?>" name="items[]" value="<?php echo esc_attr($item['id']) ?>" />
110
  </th>
111
  <?php foreach ($columns as $column_id => $column_display_name): ?>
112
  <?php
114
  case 'id':
115
  ?>
116
  <th valign="top" scope="row">
117
+ <?php echo esc_html($item['id']) ?>
118
  </th>
119
  <?php
120
  break;
159
  }
160
  }
161
  ?>
162
+ <em><a href="<?php echo add_query_arg(array('id' => $item['id'], 'action' => 'feed', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>" class="wp_all_import_show_path" rel="<?php echo esc_attr($item['path']); ?>"><?php echo preg_replace('%.*wp-content/%', 'wp-content/', $path); ?></a></em>
163
  <?php elseif (in_array($item['type'], array('file'))):?>
164
  <?php $item['path'] = wp_all_import_get_absolute_path($item['path']); ?>
165
+ <em><a href="<?php echo add_query_arg(array('id' => $item['id'], 'action' => 'feed', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>" class="wp_all_import_show_path" rel="<?php echo esc_attr($item['path']); ?>"><?php echo preg_replace('%.*wp-content/%', 'wp-content/', $item['path']); ?></a></em>
166
  <?php else: ?>
167
  <em><?php echo str_replace("\\", '/', preg_replace('%^(\w+://[^:]+:)[^@]+@%', '$1*****@', $item['path'])); ?></em>
168
  <?php endif; ?>
195
  switch ($key) {
196
  default:
197
  ?>
198
+ <span class="<?php echo esc_attr($action['class']); ?>">
199
  <?php if ( ! empty($action['url']) ): ?>
200
+ <a class="<?php echo esc_attr($action['class']); ?>" href="<?php echo esc_url($action['url']); ?>"><?php echo esc_html($action['title']); ?></a>
201
  <?php else: ?>
202
+ <span class="wpallimport-disabled"><?php echo esc_html($action['title']); ?></span>
203
  <?php endif; ?>
204
  </span> <?php if ($ai != count($import_actions)): ?>|<?php endif; ?>
205
  <?php
334
  </table>
335
 
336
  <div class="tablenav">
337
+ <?php if ($page_links): ?><div class="tablenav-pages"><?php echo wp_kses_post($page_links_html) ?></div><?php endif ?>
338
 
339
  <div class="alignleft actions">
340
  <select name="bulk-action2">
views/admin/manage/scheduling.php CHANGED
@@ -9,10 +9,10 @@
9
  </p>
10
 
11
  <p>
12
- Trigger Script URL<br /><small>Run the trigger script when you want to update your import. Once per 24 hours is recommended.</small><br /><input style='width: 700px;' type='text' value='<?php echo home_url() . '/wp-cron.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=trigger'; ?>' />
13
  <br /><br />
14
 
15
- Execution Script URL<br /><small>Run the execution script frequently. Once per two minutes is recommended.</small><br /><input style='width: 700px;' type='text' value='<?php echo home_url() . '/wp-cron.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=processing'; ?>' /><br /><br />
16
  </p>
17
 
18
 
@@ -24,7 +24,7 @@
24
 
25
  <p><i><?php _e('Example:', 'wp_all_import_plugin'); ?></i></p>
26
 
27
- <p>wget -q -O /dev/null "<?php echo home_url() . '/wp-load.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=trigger'; ?>"</p>
28
 
29
  <p><strong><?php _e('Execution Script', 'wp_all_import_plugin'); ?></strong></p>
30
 
@@ -36,7 +36,7 @@
36
 
37
  <p><i><?php _e('Example:', 'wp_all_import_plugin'); ?></i></p>
38
 
39
- <p>wget -q -O /dev/null "<?php echo home_url() . '/wp-load.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=processing'; ?>"</p>
40
 
41
  <p><strong><?php _e('Notes', 'wp_all_import_plugin'); ?></strong></p>
42
 
9
  </p>
10
 
11
  <p>
12
+ Trigger Script URL<br /><small>Run the trigger script when you want to update your import. Once per 24 hours is recommended.</small><br /><input style='width: 700px;' type='text' value='<?php echo esc_attr(home_url() . '/wp-cron.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=trigger'); ?>' />
13
  <br /><br />
14
 
15
+ Execution Script URL<br /><small>Run the execution script frequently. Once per two minutes is recommended.</small><br /><input style='width: 700px;' type='text' value='<?php echo esc_attr(home_url() . '/wp-cron.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=processing'); ?>' /><br /><br />
16
  </p>
17
 
18
 
24
 
25
  <p><i><?php _e('Example:', 'wp_all_import_plugin'); ?></i></p>
26
 
27
+ <p>wget -q -O /dev/null "<?php echo esc_url(home_url() . '/wp-load.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=trigger'); ?>"</p>
28
 
29
  <p><strong><?php _e('Execution Script', 'wp_all_import_plugin'); ?></strong></p>
30
 
36
 
37
  <p><i><?php _e('Example:', 'wp_all_import_plugin'); ?></i></p>
38
 
39
+ <p>wget -q -O /dev/null "<?php echo esc_url(home_url() . '/wp-load.php?import_key=' . $cron_job_key . '&import_id=' . $id . '&action=processing'); ?>"</p>
40
 
41
  <p><strong><?php _e('Notes', 'wp_all_import_plugin'); ?></strong></p>
42
 
views/admin/promotion/acf.php CHANGED
@@ -19,10 +19,10 @@
19
  $is_show_acf_group = apply_filters('wp_all_import_acf_is_show_group', true, $group);
20
  ?>
21
  <li>
22
- <input type="hidden" name="acf[<?php echo $group['ID'];?>]" value="<?php echo $is_show_acf_group ? '0' : '1'?>"/>
23
  <?php if ($is_show_acf_group): ?>
24
- <input id="acf_<?php echo $post_type . '_' . $group['ID'];?>" type="checkbox" name="acf[<?php echo $group['ID'];?>]" disabled="disabled" value="1" rel="<?php echo $group['ID'];?>" class="pmai_acf_group"/>
25
- <label for="acf_<?php echo $post_type . '_' . $group['ID']; ?>"><?php echo $group['title']; ?></label>
26
  <?php endif; ?>
27
  </li>
28
  <?php
19
  $is_show_acf_group = apply_filters('wp_all_import_acf_is_show_group', true, $group);
20
  ?>
21
  <li>
22
+ <input type="hidden" name="acf[<?php echo esc_attr($group['ID']);?>]" value="<?php echo $is_show_acf_group ? '0' : '1'?>"/>
23
  <?php if ($is_show_acf_group): ?>
24
+ <input id="acf_<?php echo esc_attr($post_type . '_' . $group['ID']);?>" type="checkbox" name="acf[<?php echo esc_attr($group['ID']);?>]" disabled="disabled" value="1" rel="<?php echo esc_attr($group['ID']);?>" class="pmai_acf_group"/>
25
+ <label for="acf_<?php echo esc_attr($post_type . '_' . $group['ID']); ?>"><?php echo esc_html($group['title']); ?></label>
26
  <?php endif; ?>
27
  </li>
28
  <?php
views/admin/settings/index.php CHANGED
@@ -22,7 +22,7 @@
22
  <?php foreach ($templates as $t): ?>
23
  <tr>
24
  <td>
25
- <label class="selectit" for="template-<?php echo $t->id ?>"><input id="template-<?php echo $t->id ?>" type="checkbox" name="templates[]" value="<?php echo $t->id ?>" /> <?php echo $t->name ?></label>
26
  </td>
27
  </tr>
28
  <?php endforeach ?>
22
  <?php foreach ($templates as $t): ?>
23
  <tr>
24
  <td>
25
+ <label class="selectit" for="template-<?php echo esc_attr($t->id); ?>"><input id="template-<?php echo esc_attr($t->id); ?>" type="checkbox" name="templates[]" value="<?php echo esc_attr($t->id); ?>" /> <?php echo esc_html($t->name); ?></label>
26
  </td>
27
  </tr>
28
  <?php endforeach ?>
views/controller/error.php CHANGED
@@ -1,3 +1,3 @@
1
  <?php foreach ($errors as $msg): ?>
2
- <div class="error"><p><?php echo $msg ?></p></div>
3
  <?php endforeach ?>
1
  <?php foreach ($errors as $msg): ?>
2
+ <div class="error"><p><?php echo wp_kses_post($msg); ?></p></div>
3
  <?php endforeach ?>
views/controller/warning.php CHANGED
@@ -1,3 +1,3 @@
1
  <?php foreach ($warnings as $msg): ?>
2
- <div class="error"><p><?php echo $msg ?></p></div>
3
  <?php endforeach ?>
1
  <?php foreach ($warnings as $msg): ?>
2
+ <div class="error"><p><?php echo wp_kses_post($msg); ?></p></div>
3
  <?php endforeach ?>