Açıklama Yok

class-wp-customize-widgets.php 70KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  1. <?php
  2. /**
  3. * WordPress Customize Widgets classes
  4. *
  5. * @package WordPress
  6. * @subpackage Customize
  7. * @since 3.9.0
  8. */
  9. /**
  10. * Customize Widgets class.
  11. *
  12. * Implements widget management in the Customizer.
  13. *
  14. * @since 3.9.0
  15. *
  16. * @see WP_Customize_Manager
  17. */
  18. final class WP_Customize_Widgets {
  19. /**
  20. * WP_Customize_Manager instance.
  21. *
  22. * @since 3.9.0
  23. * @var WP_Customize_Manager
  24. */
  25. public $manager;
  26. /**
  27. * All id_bases for widgets defined in core.
  28. *
  29. * @since 3.9.0
  30. * @var array
  31. */
  32. protected $core_widget_id_bases = array(
  33. 'archives',
  34. 'calendar',
  35. 'categories',
  36. 'custom_html',
  37. 'links',
  38. 'media_audio',
  39. 'media_image',
  40. 'media_video',
  41. 'meta',
  42. 'nav_menu',
  43. 'pages',
  44. 'recent-comments',
  45. 'recent-posts',
  46. 'rss',
  47. 'search',
  48. 'tag_cloud',
  49. 'text',
  50. );
  51. /**
  52. * @since 3.9.0
  53. * @var array
  54. */
  55. protected $rendered_sidebars = array();
  56. /**
  57. * @since 3.9.0
  58. * @var array
  59. */
  60. protected $rendered_widgets = array();
  61. /**
  62. * @since 3.9.0
  63. * @var array
  64. */
  65. protected $old_sidebars_widgets = array();
  66. /**
  67. * Mapping of widget ID base to whether it supports selective refresh.
  68. *
  69. * @since 4.5.0
  70. * @var array
  71. */
  72. protected $selective_refreshable_widgets;
  73. /**
  74. * Mapping of setting type to setting ID pattern.
  75. *
  76. * @since 4.2.0
  77. * @var array
  78. */
  79. protected $setting_id_patterns = array(
  80. 'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/',
  81. 'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/',
  82. );
  83. /**
  84. * Initial loader.
  85. *
  86. * @since 3.9.0
  87. *
  88. * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  89. */
  90. public function __construct( $manager ) {
  91. $this->manager = $manager;
  92. // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
  93. add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
  94. add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
  95. add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
  96. // Skip remaining hooks when the user can't manage widgets anyway.
  97. if ( ! current_user_can( 'edit_theme_options' ) ) {
  98. return;
  99. }
  100. add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
  101. add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
  102. add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  103. add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
  104. add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
  105. add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
  106. add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
  107. add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
  108. add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
  109. add_filter( 'should_load_block_editor_scripts_and_styles', array( $this, 'should_load_block_editor_scripts_and_styles' ) );
  110. add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
  111. add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
  112. add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
  113. // Selective Refresh.
  114. add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
  115. add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
  116. }
  117. /**
  118. * List whether each registered widget can be use selective refresh.
  119. *
  120. * If the theme does not support the customize-selective-refresh-widgets feature,
  121. * then this will always return an empty array.
  122. *
  123. * @since 4.5.0
  124. *
  125. * @global WP_Widget_Factory $wp_widget_factory
  126. *
  127. * @return array Mapping of id_base to support. If theme doesn't support
  128. * selective refresh, an empty array is returned.
  129. */
  130. public function get_selective_refreshable_widgets() {
  131. global $wp_widget_factory;
  132. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  133. return array();
  134. }
  135. if ( ! isset( $this->selective_refreshable_widgets ) ) {
  136. $this->selective_refreshable_widgets = array();
  137. foreach ( $wp_widget_factory->widgets as $wp_widget ) {
  138. $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
  139. }
  140. }
  141. return $this->selective_refreshable_widgets;
  142. }
  143. /**
  144. * Determines if a widget supports selective refresh.
  145. *
  146. * @since 4.5.0
  147. *
  148. * @param string $id_base Widget ID Base.
  149. * @return bool Whether the widget can be selective refreshed.
  150. */
  151. public function is_widget_selective_refreshable( $id_base ) {
  152. $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
  153. return ! empty( $selective_refreshable_widgets[ $id_base ] );
  154. }
  155. /**
  156. * Retrieves the widget setting type given a setting ID.
  157. *
  158. * @since 4.2.0
  159. *
  160. * @param string $setting_id Setting ID.
  161. * @return string|void Setting type.
  162. */
  163. protected function get_setting_type( $setting_id ) {
  164. static $cache = array();
  165. if ( isset( $cache[ $setting_id ] ) ) {
  166. return $cache[ $setting_id ];
  167. }
  168. foreach ( $this->setting_id_patterns as $type => $pattern ) {
  169. if ( preg_match( $pattern, $setting_id ) ) {
  170. $cache[ $setting_id ] = $type;
  171. return $type;
  172. }
  173. }
  174. }
  175. /**
  176. * Inspects the incoming customized data for any widget settings, and dynamically adds
  177. * them up-front so widgets will be initialized properly.
  178. *
  179. * @since 4.2.0
  180. */
  181. public function register_settings() {
  182. $widget_setting_ids = array();
  183. $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
  184. foreach ( $incoming_setting_ids as $setting_id ) {
  185. if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
  186. $widget_setting_ids[] = $setting_id;
  187. }
  188. }
  189. if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
  190. $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
  191. }
  192. $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
  193. if ( $this->manager->settings_previewed() ) {
  194. foreach ( $settings as $setting ) {
  195. $setting->preview();
  196. }
  197. }
  198. }
  199. /**
  200. * Determines the arguments for a dynamically-created setting.
  201. *
  202. * @since 4.2.0
  203. *
  204. * @param false|array $args The arguments to the WP_Customize_Setting constructor.
  205. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  206. * @return array|false Setting arguments, false otherwise.
  207. */
  208. public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
  209. if ( $this->get_setting_type( $setting_id ) ) {
  210. $args = $this->get_setting_args( $setting_id );
  211. }
  212. return $args;
  213. }
  214. /**
  215. * Retrieves an unslashed post value or return a default.
  216. *
  217. * @since 3.9.0
  218. *
  219. * @param string $name Post value.
  220. * @param mixed $default_value Default post value.
  221. * @return mixed Unslashed post value or default value.
  222. */
  223. protected function get_post_value( $name, $default_value = null ) {
  224. if ( ! isset( $_POST[ $name ] ) ) {
  225. return $default_value;
  226. }
  227. return wp_unslash( $_POST[ $name ] );
  228. }
  229. /**
  230. * Override sidebars_widgets for theme switch.
  231. *
  232. * When switching a theme via the Customizer, supply any previously-configured
  233. * sidebars_widgets from the target theme as the initial sidebars_widgets
  234. * setting. Also store the old theme's existing settings so that they can
  235. * be passed along for storing in the sidebars_widgets theme_mod when the
  236. * theme gets switched.
  237. *
  238. * @since 3.9.0
  239. *
  240. * @global array $sidebars_widgets
  241. * @global array $_wp_sidebars_widgets
  242. */
  243. public function override_sidebars_widgets_for_theme_switch() {
  244. global $sidebars_widgets;
  245. if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
  246. return;
  247. }
  248. $this->old_sidebars_widgets = wp_get_sidebars_widgets();
  249. add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
  250. $this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
  251. // retrieve_widgets() looks at the global $sidebars_widgets.
  252. $sidebars_widgets = $this->old_sidebars_widgets;
  253. $sidebars_widgets = retrieve_widgets( 'customize' );
  254. add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
  255. // Reset global cache var used by wp_get_sidebars_widgets().
  256. unset( $GLOBALS['_wp_sidebars_widgets'] );
  257. }
  258. /**
  259. * Filters old_sidebars_widgets_data Customizer setting.
  260. *
  261. * When switching themes, filter the Customizer setting old_sidebars_widgets_data
  262. * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
  263. * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
  264. * theme_mod.
  265. *
  266. * @since 3.9.0
  267. *
  268. * @see WP_Customize_Widgets::handle_theme_switch()
  269. *
  270. * @param array $old_sidebars_widgets
  271. * @return array
  272. */
  273. public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
  274. return $this->old_sidebars_widgets;
  275. }
  276. /**
  277. * Filters sidebars_widgets option for theme switch.
  278. *
  279. * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
  280. * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
  281. * option.
  282. *
  283. * @since 3.9.0
  284. *
  285. * @see WP_Customize_Widgets::handle_theme_switch()
  286. * @global array $sidebars_widgets
  287. *
  288. * @param array $sidebars_widgets
  289. * @return array
  290. */
  291. public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
  292. $sidebars_widgets = $GLOBALS['sidebars_widgets'];
  293. $sidebars_widgets['array_version'] = 3;
  294. return $sidebars_widgets;
  295. }
  296. /**
  297. * Ensures all widgets get loaded into the Customizer.
  298. *
  299. * Note: these actions are also fired in wp_ajax_update_widget().
  300. *
  301. * @since 3.9.0
  302. */
  303. public function customize_controls_init() {
  304. /** This action is documented in wp-admin/includes/ajax-actions.php */
  305. do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  306. /** This action is documented in wp-admin/includes/ajax-actions.php */
  307. do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  308. /** This action is documented in wp-admin/widgets.php */
  309. do_action( 'sidebar_admin_setup' );
  310. }
  311. /**
  312. * Ensures widgets are available for all types of previews.
  313. *
  314. * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
  315. * so that all filters have been initialized (e.g. Widget Visibility).
  316. *
  317. * @since 3.9.0
  318. */
  319. public function schedule_customize_register() {
  320. if ( is_admin() ) {
  321. $this->customize_register();
  322. } else {
  323. add_action( 'wp', array( $this, 'customize_register' ) );
  324. }
  325. }
  326. /**
  327. * Registers Customizer settings and controls for all sidebars and widgets.
  328. *
  329. * @since 3.9.0
  330. *
  331. * @global array $wp_registered_widgets
  332. * @global array $wp_registered_widget_controls
  333. * @global array $wp_registered_sidebars
  334. */
  335. public function customize_register() {
  336. global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
  337. $use_widgets_block_editor = wp_use_widgets_block_editor();
  338. add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
  339. $sidebars_widgets = array_merge(
  340. array( 'wp_inactive_widgets' => array() ),
  341. array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
  342. wp_get_sidebars_widgets()
  343. );
  344. $new_setting_ids = array();
  345. /*
  346. * Register a setting for all widgets, including those which are active,
  347. * inactive, and orphaned since a widget may get suppressed from a sidebar
  348. * via a plugin (like Widget Visibility).
  349. */
  350. foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
  351. $setting_id = $this->get_setting_id( $widget_id );
  352. $setting_args = $this->get_setting_args( $setting_id );
  353. if ( ! $this->manager->get_setting( $setting_id ) ) {
  354. $this->manager->add_setting( $setting_id, $setting_args );
  355. }
  356. $new_setting_ids[] = $setting_id;
  357. }
  358. /*
  359. * Add a setting which will be supplied for the theme's sidebars_widgets
  360. * theme_mod when the theme is switched.
  361. */
  362. if ( ! $this->manager->is_theme_active() ) {
  363. $setting_id = 'old_sidebars_widgets_data';
  364. $setting_args = $this->get_setting_args(
  365. $setting_id,
  366. array(
  367. 'type' => 'global_variable',
  368. 'dirty' => true,
  369. )
  370. );
  371. $this->manager->add_setting( $setting_id, $setting_args );
  372. }
  373. $this->manager->add_panel(
  374. 'widgets',
  375. array(
  376. 'type' => 'widgets',
  377. 'title' => __( 'Widgets' ),
  378. 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
  379. 'priority' => 110,
  380. 'active_callback' => array( $this, 'is_panel_active' ),
  381. 'auto_expand_sole_section' => true,
  382. 'theme_supports' => 'widgets',
  383. )
  384. );
  385. foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
  386. if ( empty( $sidebar_widget_ids ) ) {
  387. $sidebar_widget_ids = array();
  388. }
  389. $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
  390. $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
  391. $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
  392. // Add setting for managing the sidebar's widgets.
  393. if ( $is_registered_sidebar || $is_inactive_widgets ) {
  394. $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
  395. $setting_args = $this->get_setting_args( $setting_id );
  396. if ( ! $this->manager->get_setting( $setting_id ) ) {
  397. if ( ! $this->manager->is_theme_active() ) {
  398. $setting_args['dirty'] = true;
  399. }
  400. $this->manager->add_setting( $setting_id, $setting_args );
  401. }
  402. $new_setting_ids[] = $setting_id;
  403. // Add section to contain controls.
  404. $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
  405. if ( $is_active_sidebar ) {
  406. $section_args = array(
  407. 'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
  408. 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ), true ),
  409. 'panel' => 'widgets',
  410. 'sidebar_id' => $sidebar_id,
  411. );
  412. if ( $use_widgets_block_editor ) {
  413. $section_args['description'] = '';
  414. } else {
  415. $section_args['description'] = $wp_registered_sidebars[ $sidebar_id ]['description'];
  416. }
  417. /**
  418. * Filters Customizer widget section arguments for a given sidebar.
  419. *
  420. * @since 3.9.0
  421. *
  422. * @param array $section_args Array of Customizer widget section arguments.
  423. * @param string $section_id Customizer section ID.
  424. * @param int|string $sidebar_id Sidebar ID.
  425. */
  426. $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
  427. $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
  428. $this->manager->add_section( $section );
  429. if ( $use_widgets_block_editor ) {
  430. $control = new WP_Sidebar_Block_Editor_Control(
  431. $this->manager,
  432. $setting_id,
  433. array(
  434. 'section' => $section_id,
  435. 'sidebar_id' => $sidebar_id,
  436. 'label' => $section_args['title'],
  437. 'description' => $section_args['description'],
  438. )
  439. );
  440. } else {
  441. $control = new WP_Widget_Area_Customize_Control(
  442. $this->manager,
  443. $setting_id,
  444. array(
  445. 'section' => $section_id,
  446. 'sidebar_id' => $sidebar_id,
  447. 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
  448. )
  449. );
  450. }
  451. $this->manager->add_control( $control );
  452. $new_setting_ids[] = $setting_id;
  453. }
  454. }
  455. if ( ! $use_widgets_block_editor ) {
  456. // Add a control for each active widget (located in a sidebar).
  457. foreach ( $sidebar_widget_ids as $i => $widget_id ) {
  458. // Skip widgets that may have gone away due to a plugin being deactivated.
  459. if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
  460. continue;
  461. }
  462. $registered_widget = $wp_registered_widgets[ $widget_id ];
  463. $setting_id = $this->get_setting_id( $widget_id );
  464. $id_base = $wp_registered_widget_controls[ $widget_id ]['id_base'];
  465. $control = new WP_Widget_Form_Customize_Control(
  466. $this->manager,
  467. $setting_id,
  468. array(
  469. 'label' => $registered_widget['name'],
  470. 'section' => $section_id,
  471. 'sidebar_id' => $sidebar_id,
  472. 'widget_id' => $widget_id,
  473. 'widget_id_base' => $id_base,
  474. 'priority' => $i,
  475. 'width' => $wp_registered_widget_controls[ $widget_id ]['width'],
  476. 'height' => $wp_registered_widget_controls[ $widget_id ]['height'],
  477. 'is_wide' => $this->is_wide_widget( $widget_id ),
  478. )
  479. );
  480. $this->manager->add_control( $control );
  481. }
  482. }
  483. }
  484. if ( $this->manager->settings_previewed() ) {
  485. foreach ( $new_setting_ids as $new_setting_id ) {
  486. $this->manager->get_setting( $new_setting_id )->preview();
  487. }
  488. }
  489. }
  490. /**
  491. * Determines whether the widgets panel is active, based on whether there are sidebars registered.
  492. *
  493. * @since 4.4.0
  494. *
  495. * @see WP_Customize_Panel::$active_callback
  496. *
  497. * @global array $wp_registered_sidebars
  498. * @return bool Active.
  499. */
  500. public function is_panel_active() {
  501. global $wp_registered_sidebars;
  502. return ! empty( $wp_registered_sidebars );
  503. }
  504. /**
  505. * Converts a widget_id into its corresponding Customizer setting ID (option name).
  506. *
  507. * @since 3.9.0
  508. *
  509. * @param string $widget_id Widget ID.
  510. * @return string Maybe-parsed widget ID.
  511. */
  512. public function get_setting_id( $widget_id ) {
  513. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  514. $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
  515. if ( ! is_null( $parsed_widget_id['number'] ) ) {
  516. $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
  517. }
  518. return $setting_id;
  519. }
  520. /**
  521. * Determines whether the widget is considered "wide".
  522. *
  523. * Core widgets which may have controls wider than 250, but can still be shown
  524. * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
  525. * have widths of 400 and yet they still render fine in the Customizer panel.
  526. *
  527. * This method will return all Core widgets as being not wide, but this can be
  528. * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
  529. *
  530. * @since 3.9.0
  531. *
  532. * @global array $wp_registered_widget_controls
  533. *
  534. * @param string $widget_id Widget ID.
  535. * @return bool Whether or not the widget is a "wide" widget.
  536. */
  537. public function is_wide_widget( $widget_id ) {
  538. global $wp_registered_widget_controls;
  539. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  540. $width = $wp_registered_widget_controls[ $widget_id ]['width'];
  541. $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases, true );
  542. $is_wide = ( $width > 250 && ! $is_core );
  543. /**
  544. * Filters whether the given widget is considered "wide".
  545. *
  546. * @since 3.9.0
  547. *
  548. * @param bool $is_wide Whether the widget is wide, Default false.
  549. * @param string $widget_id Widget ID.
  550. */
  551. return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
  552. }
  553. /**
  554. * Converts a widget ID into its id_base and number components.
  555. *
  556. * @since 3.9.0
  557. *
  558. * @param string $widget_id Widget ID.
  559. * @return array Array containing a widget's id_base and number components.
  560. */
  561. public function parse_widget_id( $widget_id ) {
  562. $parsed = array(
  563. 'number' => null,
  564. 'id_base' => null,
  565. );
  566. if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
  567. $parsed['id_base'] = $matches[1];
  568. $parsed['number'] = (int) $matches[2];
  569. } else {
  570. // Likely an old single widget.
  571. $parsed['id_base'] = $widget_id;
  572. }
  573. return $parsed;
  574. }
  575. /**
  576. * Converts a widget setting ID (option path) to its id_base and number components.
  577. *
  578. * @since 3.9.0
  579. *
  580. * @param string $setting_id Widget setting ID.
  581. * @return array|WP_Error Array containing a widget's id_base and number components,
  582. * or a WP_Error object.
  583. */
  584. public function parse_widget_setting_id( $setting_id ) {
  585. if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
  586. return new WP_Error( 'widget_setting_invalid_id' );
  587. }
  588. $id_base = $matches[2];
  589. $number = isset( $matches[3] ) ? (int) $matches[3] : null;
  590. return compact( 'id_base', 'number' );
  591. }
  592. /**
  593. * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
  594. * allow custom styles from plugins.
  595. *
  596. * @since 3.9.0
  597. */
  598. public function print_styles() {
  599. /** This action is documented in wp-admin/admin-header.php */
  600. do_action( 'admin_print_styles-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  601. /** This action is documented in wp-admin/admin-header.php */
  602. do_action( 'admin_print_styles' );
  603. }
  604. /**
  605. * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
  606. * allow custom scripts from plugins.
  607. *
  608. * @since 3.9.0
  609. */
  610. public function print_scripts() {
  611. /** This action is documented in wp-admin/admin-header.php */
  612. do_action( 'admin_print_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  613. /** This action is documented in wp-admin/admin-header.php */
  614. do_action( 'admin_print_scripts' );
  615. }
  616. /**
  617. * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
  618. *
  619. * @since 3.9.0
  620. *
  621. * @global WP_Scripts $wp_scripts
  622. * @global array $wp_registered_sidebars
  623. * @global array $wp_registered_widgets
  624. */
  625. public function enqueue_scripts() {
  626. global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
  627. wp_enqueue_style( 'customize-widgets' );
  628. wp_enqueue_script( 'customize-widgets' );
  629. /** This action is documented in wp-admin/admin-header.php */
  630. do_action( 'admin_enqueue_scripts', 'widgets.php' );
  631. /*
  632. * Export available widgets with control_tpl removed from model
  633. * since plugins need templates to be in the DOM.
  634. */
  635. $available_widgets = array();
  636. foreach ( $this->get_available_widgets() as $available_widget ) {
  637. unset( $available_widget['control_tpl'] );
  638. $available_widgets[] = $available_widget;
  639. }
  640. $widget_reorder_nav_tpl = sprintf(
  641. '<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
  642. __( 'Move to another area&hellip;' ),
  643. __( 'Move down' ),
  644. __( 'Move up' )
  645. );
  646. $move_widget_area_tpl = str_replace(
  647. array( '{description}', '{btn}' ),
  648. array(
  649. __( 'Select an area to move this widget into:' ),
  650. _x( 'Move', 'Move widget' ),
  651. ),
  652. '<div class="move-widget-area">
  653. <p class="description">{description}</p>
  654. <ul class="widget-area-select">
  655. <% _.each( sidebars, function ( sidebar ){ %>
  656. <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
  657. <% }); %>
  658. </ul>
  659. <div class="move-widget-actions">
  660. <button class="move-widget-btn button" type="button">{btn}</button>
  661. </div>
  662. </div>'
  663. );
  664. /*
  665. * Gather all strings in PHP that may be needed by JS on the client.
  666. * Once JS i18n is implemented (in #20491), this can be removed.
  667. */
  668. $some_non_rendered_areas_messages = array();
  669. $some_non_rendered_areas_messages[1] = html_entity_decode(
  670. __( 'Your theme has 1 other widget area, but this particular page does not display it.' ),
  671. ENT_QUOTES,
  672. get_bloginfo( 'charset' )
  673. );
  674. $registered_sidebar_count = count( $wp_registered_sidebars );
  675. for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
  676. $some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
  677. sprintf(
  678. /* translators: %s: The number of other widget areas registered but not rendered. */
  679. _n(
  680. 'Your theme has %s other widget area, but this particular page does not display it.',
  681. 'Your theme has %s other widget areas, but this particular page does not display them.',
  682. $non_rendered_count
  683. ),
  684. number_format_i18n( $non_rendered_count )
  685. ),
  686. ENT_QUOTES,
  687. get_bloginfo( 'charset' )
  688. );
  689. }
  690. if ( 1 === $registered_sidebar_count ) {
  691. $no_areas_shown_message = html_entity_decode(
  692. sprintf(
  693. __( 'Your theme has 1 widget area, but this particular page does not display it.' )
  694. ),
  695. ENT_QUOTES,
  696. get_bloginfo( 'charset' )
  697. );
  698. } else {
  699. $no_areas_shown_message = html_entity_decode(
  700. sprintf(
  701. /* translators: %s: The total number of widget areas registered. */
  702. _n(
  703. 'Your theme has %s widget area, but this particular page does not display it.',
  704. 'Your theme has %s widget areas, but this particular page does not display them.',
  705. $registered_sidebar_count
  706. ),
  707. number_format_i18n( $registered_sidebar_count )
  708. ),
  709. ENT_QUOTES,
  710. get_bloginfo( 'charset' )
  711. );
  712. }
  713. $settings = array(
  714. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  715. 'registeredWidgets' => $wp_registered_widgets,
  716. 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets.
  717. 'l10n' => array(
  718. 'saveBtnLabel' => __( 'Apply' ),
  719. 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
  720. 'removeBtnLabel' => __( 'Remove' ),
  721. 'removeBtnTooltip' => __( 'Keep widget settings and move it to the inactive widgets' ),
  722. 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
  723. 'widgetMovedUp' => __( 'Widget moved up' ),
  724. 'widgetMovedDown' => __( 'Widget moved down' ),
  725. 'navigatePreview' => __( 'You can navigate to other pages on your site while using the Customizer to view and edit the widgets displayed on those pages.' ),
  726. 'someAreasShown' => $some_non_rendered_areas_messages,
  727. 'noAreasShown' => $no_areas_shown_message,
  728. 'reorderModeOn' => __( 'Reorder mode enabled' ),
  729. 'reorderModeOff' => __( 'Reorder mode closed' ),
  730. 'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
  731. /* translators: %d: The number of widgets found. */
  732. 'widgetsFound' => __( 'Number of widgets found: %d' ),
  733. 'noWidgetsFound' => __( 'No widgets found.' ),
  734. ),
  735. 'tpl' => array(
  736. 'widgetReorderNav' => $widget_reorder_nav_tpl,
  737. 'moveWidgetArea' => $move_widget_area_tpl,
  738. ),
  739. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  740. );
  741. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  742. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  743. }
  744. $wp_scripts->add_data(
  745. 'customize-widgets',
  746. 'data',
  747. sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
  748. );
  749. /*
  750. * TODO: Update 'wp-customize-widgets' to not rely so much on things in
  751. * 'customize-widgets'. This will let us skip most of the above and not
  752. * enqueue 'customize-widgets' which saves bytes.
  753. */
  754. if ( wp_use_widgets_block_editor() ) {
  755. $block_editor_context = new WP_Block_Editor_Context(
  756. array(
  757. 'name' => 'core/customize-widgets',
  758. )
  759. );
  760. $editor_settings = get_block_editor_settings(
  761. get_legacy_widget_block_editor_settings(),
  762. $block_editor_context
  763. );
  764. wp_add_inline_script(
  765. 'wp-customize-widgets',
  766. sprintf(
  767. 'wp.domReady( function() {
  768. wp.customizeWidgets.initialize( "widgets-customizer", %s );
  769. } );',
  770. wp_json_encode( $editor_settings )
  771. )
  772. );
  773. // Preload server-registered block schemas.
  774. wp_add_inline_script(
  775. 'wp-blocks',
  776. 'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . wp_json_encode( get_block_editor_server_block_settings() ) . ');'
  777. );
  778. wp_add_inline_script(
  779. 'wp-blocks',
  780. sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $block_editor_context ) ) ),
  781. 'after'
  782. );
  783. wp_enqueue_script( 'wp-customize-widgets' );
  784. wp_enqueue_style( 'wp-customize-widgets' );
  785. /** This action is documented in edit-form-blocks.php */
  786. do_action( 'enqueue_block_editor_assets' );
  787. }
  788. }
  789. /**
  790. * Renders the widget form control templates into the DOM.
  791. *
  792. * @since 3.9.0
  793. */
  794. public function output_widget_control_templates() {
  795. ?>
  796. <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
  797. <div id="available-widgets">
  798. <div class="customize-section-title">
  799. <button class="customize-section-back" tabindex="-1">
  800. <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
  801. </button>
  802. <h3>
  803. <span class="customize-action">
  804. <?php
  805. /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
  806. printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
  807. ?>
  808. </span>
  809. <?php _e( 'Add a Widget' ); ?>
  810. </h3>
  811. </div>
  812. <div id="available-widgets-filter">
  813. <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
  814. <input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ); ?>" aria-describedby="widgets-search-desc" />
  815. <div class="search-icon" aria-hidden="true"></div>
  816. <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
  817. <p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
  818. </div>
  819. <div id="available-widgets-list">
  820. <?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
  821. <div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ); ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ); ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ); ?>" tabindex="0">
  822. <?php echo $available_widget['control_tpl']; ?>
  823. </div>
  824. <?php endforeach; ?>
  825. <p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
  826. </div><!-- #available-widgets-list -->
  827. </div><!-- #available-widgets -->
  828. </div><!-- #widgets-left -->
  829. <?php
  830. }
  831. /**
  832. * Calls admin_print_footer_scripts and admin_print_scripts hooks to
  833. * allow custom scripts from plugins.
  834. *
  835. * @since 3.9.0
  836. */
  837. public function print_footer_scripts() {
  838. /** This action is documented in wp-admin/admin-footer.php */
  839. do_action( 'admin_print_footer_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  840. /** This action is documented in wp-admin/admin-footer.php */
  841. do_action( 'admin_print_footer_scripts' );
  842. /** This action is documented in wp-admin/admin-footer.php */
  843. do_action( 'admin_footer-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  844. }
  845. /**
  846. * Retrieves common arguments to supply when constructing a Customizer setting.
  847. *
  848. * @since 3.9.0
  849. *
  850. * @param string $id Widget setting ID.
  851. * @param array $overrides Array of setting overrides.
  852. * @return array Possibly modified setting arguments.
  853. */
  854. public function get_setting_args( $id, $overrides = array() ) {
  855. $args = array(
  856. 'type' => 'option',
  857. 'capability' => 'edit_theme_options',
  858. 'default' => array(),
  859. );
  860. if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
  861. $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
  862. $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
  863. $args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
  864. } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
  865. $id_base = $matches['id_base'];
  866. $args['sanitize_callback'] = function( $value ) use ( $id_base ) {
  867. return $this->sanitize_widget_instance( $value, $id_base );
  868. };
  869. $args['sanitize_js_callback'] = function( $value ) use ( $id_base ) {
  870. return $this->sanitize_widget_js_instance( $value, $id_base );
  871. };
  872. $args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
  873. }
  874. $args = array_merge( $args, $overrides );
  875. /**
  876. * Filters the common arguments supplied when constructing a Customizer setting.
  877. *
  878. * @since 3.9.0
  879. *
  880. * @see WP_Customize_Setting
  881. *
  882. * @param array $args Array of Customizer setting arguments.
  883. * @param string $id Widget setting ID.
  884. */
  885. return apply_filters( 'widget_customizer_setting_args', $args, $id );
  886. }
  887. /**
  888. * Ensures sidebar widget arrays only ever contain widget IDS.
  889. *
  890. * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
  891. *
  892. * @since 3.9.0
  893. *
  894. * @param string[] $widget_ids Array of widget IDs.
  895. * @return string[] Array of sanitized widget IDs.
  896. */
  897. public function sanitize_sidebar_widgets( $widget_ids ) {
  898. $widget_ids = array_map( 'strval', (array) $widget_ids );
  899. $sanitized_widget_ids = array();
  900. foreach ( $widget_ids as $widget_id ) {
  901. $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
  902. }
  903. return $sanitized_widget_ids;
  904. }
  905. /**
  906. * Builds up an index of all available widgets for use in Backbone models.
  907. *
  908. * @since 3.9.0
  909. *
  910. * @global array $wp_registered_widgets
  911. * @global array $wp_registered_widget_controls
  912. *
  913. * @see wp_list_widgets()
  914. *
  915. * @return array List of available widgets.
  916. */
  917. public function get_available_widgets() {
  918. static $available_widgets = array();
  919. if ( ! empty( $available_widgets ) ) {
  920. return $available_widgets;
  921. }
  922. global $wp_registered_widgets, $wp_registered_widget_controls;
  923. require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
  924. $sort = $wp_registered_widgets;
  925. usort( $sort, array( $this, '_sort_name_callback' ) );
  926. $done = array();
  927. foreach ( $sort as $widget ) {
  928. if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget.
  929. continue;
  930. }
  931. $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
  932. $done[] = $widget['callback'];
  933. if ( ! isset( $widget['params'][0] ) ) {
  934. $widget['params'][0] = array();
  935. }
  936. $available_widget = $widget;
  937. unset( $available_widget['callback'] ); // Not serializable to JSON.
  938. $args = array(
  939. 'widget_id' => $widget['id'],
  940. 'widget_name' => $widget['name'],
  941. '_display' => 'template',
  942. );
  943. $is_disabled = false;
  944. $is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
  945. if ( $is_multi_widget ) {
  946. $id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
  947. $args['_temp_id'] = "$id_base-__i__";
  948. $args['_multi_num'] = next_widget_id_number( $id_base );
  949. $args['_add'] = 'multi';
  950. } else {
  951. $args['_add'] = 'single';
  952. if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
  953. $is_disabled = true;
  954. }
  955. $id_base = $widget['id'];
  956. }
  957. $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
  958. array(
  959. 0 => $args,
  960. 1 => $widget['params'][0],
  961. )
  962. );
  963. $control_tpl = $this->get_widget_control( $list_widget_controls_args );
  964. // The properties here are mapped to the Backbone Widget model.
  965. $available_widget = array_merge(
  966. $available_widget,
  967. array(
  968. 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
  969. 'is_multi' => $is_multi_widget,
  970. 'control_tpl' => $control_tpl,
  971. 'multi_number' => ( 'multi' === $args['_add'] ) ? $args['_multi_num'] : false,
  972. 'is_disabled' => $is_disabled,
  973. 'id_base' => $id_base,
  974. 'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
  975. 'width' => $wp_registered_widget_controls[ $widget['id'] ]['width'],
  976. 'height' => $wp_registered_widget_controls[ $widget['id'] ]['height'],
  977. 'is_wide' => $this->is_wide_widget( $widget['id'] ),
  978. )
  979. );
  980. $available_widgets[] = $available_widget;
  981. }
  982. return $available_widgets;
  983. }
  984. /**
  985. * Naturally orders available widgets by name.
  986. *
  987. * @since 3.9.0
  988. *
  989. * @param array $widget_a The first widget to compare.
  990. * @param array $widget_b The second widget to compare.
  991. * @return int Reorder position for the current widget comparison.
  992. */
  993. protected function _sort_name_callback( $widget_a, $widget_b ) {
  994. return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
  995. }
  996. /**
  997. * Retrieves the widget control markup.
  998. *
  999. * @since 3.9.0
  1000. *
  1001. * @param array $args Widget control arguments.
  1002. * @return string Widget control form HTML markup.
  1003. */
  1004. public function get_widget_control( $args ) {
  1005. $args[0]['before_form'] = '<div class="form">';
  1006. $args[0]['after_form'] = '</div><!-- .form -->';
  1007. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1008. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1009. ob_start();
  1010. wp_widget_control( ...$args );
  1011. $control_tpl = ob_get_clean();
  1012. return $control_tpl;
  1013. }
  1014. /**
  1015. * Retrieves the widget control markup parts.
  1016. *
  1017. * @since 4.4.0
  1018. *
  1019. * @param array $args Widget control arguments.
  1020. * @return array {
  1021. * @type string $control Markup for widget control wrapping form.
  1022. * @type string $content The contents of the widget form itself.
  1023. * }
  1024. */
  1025. public function get_widget_control_parts( $args ) {
  1026. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1027. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1028. $control_markup = $this->get_widget_control( $args );
  1029. $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
  1030. $content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
  1031. $control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
  1032. $control .= substr( $control_markup, $content_end_pos );
  1033. $content = trim(
  1034. substr(
  1035. $control_markup,
  1036. $content_start_pos + strlen( $args[0]['before_widget_content'] ),
  1037. $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
  1038. )
  1039. );
  1040. return compact( 'control', 'content' );
  1041. }
  1042. /**
  1043. * Adds hooks for the Customizer preview.
  1044. *
  1045. * @since 3.9.0
  1046. */
  1047. public function customize_preview_init() {
  1048. add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
  1049. add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
  1050. add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
  1051. }
  1052. /**
  1053. * Refreshes the nonce for widget updates.
  1054. *
  1055. * @since 4.2.0
  1056. *
  1057. * @param array $nonces Array of nonces.
  1058. * @return array Array of nonces.
  1059. */
  1060. public function refresh_nonces( $nonces ) {
  1061. $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
  1062. return $nonces;
  1063. }
  1064. /**
  1065. * Tells the script loader to load the scripts and styles of custom blocks
  1066. * if the widgets block editor is enabled.
  1067. *
  1068. * @since 5.8.0
  1069. *
  1070. * @param bool $is_block_editor_screen Current decision about loading block assets.
  1071. * @return bool Filtered decision about loading block assets.
  1072. */
  1073. public function should_load_block_editor_scripts_and_styles( $is_block_editor_screen ) {
  1074. if ( wp_use_widgets_block_editor() ) {
  1075. return true;
  1076. }
  1077. return $is_block_editor_screen;
  1078. }
  1079. /**
  1080. * When previewing, ensures the proper previewing widgets are used.
  1081. *
  1082. * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
  1083. * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
  1084. * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
  1085. * filter is added, it has to be reset after the filter has been added.
  1086. *
  1087. * @since 3.9.0
  1088. *
  1089. * @param array $sidebars_widgets List of widgets for the current sidebar.
  1090. * @return array
  1091. */
  1092. public function preview_sidebars_widgets( $sidebars_widgets ) {
  1093. $sidebars_widgets = get_option( 'sidebars_widgets', array() );
  1094. unset( $sidebars_widgets['array_version'] );
  1095. return $sidebars_widgets;
  1096. }
  1097. /**
  1098. * Enqueues scripts for the Customizer preview.
  1099. *
  1100. * @since 3.9.0
  1101. */
  1102. public function customize_preview_enqueue() {
  1103. wp_enqueue_script( 'customize-preview-widgets' );
  1104. }
  1105. /**
  1106. * Inserts default style for highlighted widget at early point so theme
  1107. * stylesheet can override.
  1108. *
  1109. * @since 3.9.0
  1110. */
  1111. public function print_preview_css() {
  1112. ?>
  1113. <style>
  1114. .widget-customizer-highlighted-widget {
  1115. outline: none;
  1116. -webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1117. box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1118. position: relative;
  1119. z-index: 1;
  1120. }
  1121. </style>
  1122. <?php
  1123. }
  1124. /**
  1125. * Communicates the sidebars that appeared on the page at the very end of the page,
  1126. * and at the very end of the wp_footer,
  1127. *
  1128. * @since 3.9.0
  1129. *
  1130. * @global array $wp_registered_sidebars
  1131. * @global array $wp_registered_widgets
  1132. */
  1133. public function export_preview_data() {
  1134. global $wp_registered_sidebars, $wp_registered_widgets;
  1135. $switched_locale = switch_to_locale( get_user_locale() );
  1136. $l10n = array(
  1137. 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
  1138. );
  1139. if ( $switched_locale ) {
  1140. restore_previous_locale();
  1141. }
  1142. $rendered_sidebars = array_filter( $this->rendered_sidebars );
  1143. $rendered_widgets = array_filter( $this->rendered_widgets );
  1144. // Prepare Customizer settings to pass to JavaScript.
  1145. $settings = array(
  1146. 'renderedSidebars' => array_fill_keys( array_keys( $rendered_sidebars ), true ),
  1147. 'renderedWidgets' => array_fill_keys( array_keys( $rendered_widgets ), true ),
  1148. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  1149. 'registeredWidgets' => $wp_registered_widgets,
  1150. 'l10n' => $l10n,
  1151. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  1152. );
  1153. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  1154. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  1155. }
  1156. ?>
  1157. <script type="text/javascript">
  1158. var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
  1159. </script>
  1160. <?php
  1161. }
  1162. /**
  1163. * Tracks the widgets that were rendered.
  1164. *
  1165. * @since 3.9.0
  1166. *
  1167. * @param array $widget Rendered widget to tally.
  1168. */
  1169. public function tally_rendered_widgets( $widget ) {
  1170. $this->rendered_widgets[ $widget['id'] ] = true;
  1171. }
  1172. /**
  1173. * Determine if a widget is rendered on the page.
  1174. *
  1175. * @since 4.0.0
  1176. *
  1177. * @param string $widget_id Widget ID to check.
  1178. * @return bool Whether the widget is rendered.
  1179. */
  1180. public function is_widget_rendered( $widget_id ) {
  1181. return ! empty( $this->rendered_widgets[ $widget_id ] );
  1182. }
  1183. /**
  1184. * Determines if a sidebar is rendered on the page.
  1185. *
  1186. * @since 4.0.0
  1187. *
  1188. * @param string $sidebar_id Sidebar ID to check.
  1189. * @return bool Whether the sidebar is rendered.
  1190. */
  1191. public function is_sidebar_rendered( $sidebar_id ) {
  1192. return ! empty( $this->rendered_sidebars[ $sidebar_id ] );
  1193. }
  1194. /**
  1195. * Tallies the sidebars rendered via is_active_sidebar().
  1196. *
  1197. * Keep track of the times that is_active_sidebar() is called in the template,
  1198. * and assume that this means that the sidebar would be rendered on the template
  1199. * if there were widgets populating it.
  1200. *
  1201. * @since 3.9.0
  1202. *
  1203. * @param bool $is_active Whether the sidebar is active.
  1204. * @param string $sidebar_id Sidebar ID.
  1205. * @return bool Whether the sidebar is active.
  1206. */
  1207. public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
  1208. if ( is_registered_sidebar( $sidebar_id ) ) {
  1209. $this->rendered_sidebars[ $sidebar_id ] = true;
  1210. }
  1211. /*
  1212. * We may need to force this to true, and also force-true the value
  1213. * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
  1214. * is an area to drop widgets into, if the sidebar is empty.
  1215. */
  1216. return $is_active;
  1217. }
  1218. /**
  1219. * Tallies the sidebars rendered via dynamic_sidebar().
  1220. *
  1221. * Keep track of the times that dynamic_sidebar() is called in the template,
  1222. * and assume this means the sidebar would be rendered on the template if
  1223. * there were widgets populating it.
  1224. *
  1225. * @since 3.9.0
  1226. *
  1227. * @param bool $has_widgets Whether the current sidebar has widgets.
  1228. * @param string $sidebar_id Sidebar ID.
  1229. * @return bool Whether the current sidebar has widgets.
  1230. */
  1231. public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
  1232. if ( is_registered_sidebar( $sidebar_id ) ) {
  1233. $this->rendered_sidebars[ $sidebar_id ] = true;
  1234. }
  1235. /*
  1236. * We may need to force this to true, and also force-true the value
  1237. * for 'is_active_sidebar' if we want to ensure there is an area to
  1238. * drop widgets into, if the sidebar is empty.
  1239. */
  1240. return $has_widgets;
  1241. }
  1242. /**
  1243. * Retrieves MAC for a serialized widget instance string.
  1244. *
  1245. * Allows values posted back from JS to be rejected if any tampering of the
  1246. * data has occurred.
  1247. *
  1248. * @since 3.9.0
  1249. *
  1250. * @param string $serialized_instance Widget instance.
  1251. * @return string MAC for serialized widget instance.
  1252. */
  1253. protected function get_instance_hash_key( $serialized_instance ) {
  1254. return wp_hash( $serialized_instance );
  1255. }
  1256. /**
  1257. * Sanitizes a widget instance.
  1258. *
  1259. * Unserialize the JS-instance for storing in the options. It's important that this filter
  1260. * only get applied to an instance *once*.
  1261. *
  1262. * @since 3.9.0
  1263. * @since 5.8.0 Added the `$id_base` parameter.
  1264. *
  1265. * @global WP_Widget_Factory $wp_widget_factory
  1266. *
  1267. * @param array $value Widget instance to sanitize.
  1268. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1269. * @return array|void Sanitized widget instance.
  1270. */
  1271. public function sanitize_widget_instance( $value, $id_base = null ) {
  1272. global $wp_widget_factory;
  1273. if ( array() === $value ) {
  1274. return $value;
  1275. }
  1276. if ( isset( $value['raw_instance'] ) && $id_base && wp_use_widgets_block_editor() ) {
  1277. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1278. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1279. if ( 'block' === $id_base && ! current_user_can( 'unfiltered_html' ) ) {
  1280. /*
  1281. * The content of the 'block' widget is not filtered on the fly while editing.
  1282. * Filter the content here to prevent vulnerabilities.
  1283. */
  1284. $value['raw_instance']['content'] = wp_kses_post( $value['raw_instance']['content'] );
  1285. }
  1286. return $value['raw_instance'];
  1287. }
  1288. }
  1289. if (
  1290. empty( $value['is_widget_customizer_js_value'] ) ||
  1291. empty( $value['instance_hash_key'] ) ||
  1292. empty( $value['encoded_serialized_instance'] )
  1293. ) {
  1294. return;
  1295. }
  1296. $decoded = base64_decode( $value['encoded_serialized_instance'], true );
  1297. if ( false === $decoded ) {
  1298. return;
  1299. }
  1300. if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
  1301. return;
  1302. }
  1303. $instance = unserialize( $decoded );
  1304. if ( false === $instance ) {
  1305. return;
  1306. }
  1307. return $instance;
  1308. }
  1309. /**
  1310. * Converts a widget instance into JSON-representable format.
  1311. *
  1312. * @since 3.9.0
  1313. * @since 5.8.0 Added the `$id_base` parameter.
  1314. *
  1315. * @global WP_Widget_Factory $wp_widget_factory
  1316. *
  1317. * @param array $value Widget instance to convert to JSON.
  1318. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1319. * @return array JSON-converted widget instance.
  1320. */
  1321. public function sanitize_widget_js_instance( $value, $id_base = null ) {
  1322. global $wp_widget_factory;
  1323. if ( empty( $value['is_widget_customizer_js_value'] ) ) {
  1324. $serialized = serialize( $value );
  1325. $js_value = array(
  1326. 'encoded_serialized_instance' => base64_encode( $serialized ),
  1327. 'title' => empty( $value['title'] ) ? '' : $value['title'],
  1328. 'is_widget_customizer_js_value' => true,
  1329. 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
  1330. );
  1331. if ( $id_base && wp_use_widgets_block_editor() ) {
  1332. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1333. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1334. $js_value['raw_instance'] = (object) $value;
  1335. }
  1336. }
  1337. return $js_value;
  1338. }
  1339. return $value;
  1340. }
  1341. /**
  1342. * Strips out widget IDs for widgets which are no longer registered.
  1343. *
  1344. * One example where this might happen is when a plugin orphans a widget
  1345. * in a sidebar upon deactivation.
  1346. *
  1347. * @since 3.9.0
  1348. *
  1349. * @global array $wp_registered_widgets
  1350. *
  1351. * @param array $widget_ids List of widget IDs.
  1352. * @return array Parsed list of widget IDs.
  1353. */
  1354. public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
  1355. global $wp_registered_widgets;
  1356. $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
  1357. return $widget_ids;
  1358. }
  1359. /**
  1360. * Finds and invokes the widget update and control callbacks.
  1361. *
  1362. * Requires that `$_POST` be populated with the instance data.
  1363. *
  1364. * @since 3.9.0
  1365. *
  1366. * @global array $wp_registered_widget_updates
  1367. * @global array $wp_registered_widget_controls
  1368. *
  1369. * @param string $widget_id Widget ID.
  1370. * @return array|WP_Error Array containing the updated widget information.
  1371. * A WP_Error object, otherwise.
  1372. */
  1373. public function call_widget_update( $widget_id ) {
  1374. global $wp_registered_widget_updates, $wp_registered_widget_controls;
  1375. $setting_id = $this->get_setting_id( $widget_id );
  1376. /*
  1377. * Make sure that other setting changes have previewed since this widget
  1378. * may depend on them (e.g. Menus being present for Navigation Menu widget).
  1379. */
  1380. if ( ! did_action( 'customize_preview_init' ) ) {
  1381. foreach ( $this->manager->settings() as $setting ) {
  1382. if ( $setting->id !== $setting_id ) {
  1383. $setting->preview();
  1384. }
  1385. }
  1386. }
  1387. $this->start_capturing_option_updates();
  1388. $parsed_id = $this->parse_widget_id( $widget_id );
  1389. $option_name = 'widget_' . $parsed_id['id_base'];
  1390. /*
  1391. * If a previously-sanitized instance is provided, populate the input vars
  1392. * with its values so that the widget update callback will read this instance
  1393. */
  1394. $added_input_vars = array();
  1395. if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
  1396. $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
  1397. if ( false === $sanitized_widget_setting ) {
  1398. $this->stop_capturing_option_updates();
  1399. return new WP_Error( 'widget_setting_malformed' );
  1400. }
  1401. $instance = $this->sanitize_widget_instance( $sanitized_widget_setting, $parsed_id['id_base'] );
  1402. if ( is_null( $instance ) ) {
  1403. $this->stop_capturing_option_updates();
  1404. return new WP_Error( 'widget_setting_unsanitized' );
  1405. }
  1406. if ( ! is_null( $parsed_id['number'] ) ) {
  1407. $value = array();
  1408. $value[ $parsed_id['number'] ] = $instance;
  1409. $key = 'widget-' . $parsed_id['id_base'];
  1410. $_REQUEST[ $key ] = wp_slash( $value );
  1411. $_POST[ $key ] = $_REQUEST[ $key ];
  1412. $added_input_vars[] = $key;
  1413. } else {
  1414. foreach ( $instance as $key => $value ) {
  1415. $_REQUEST[ $key ] = wp_slash( $value );
  1416. $_POST[ $key ] = $_REQUEST[ $key ];
  1417. $added_input_vars[] = $key;
  1418. }
  1419. }
  1420. }
  1421. // Invoke the widget update callback.
  1422. foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
  1423. if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
  1424. ob_start();
  1425. call_user_func_array( $control['callback'], $control['params'] );
  1426. ob_end_clean();
  1427. break;
  1428. }
  1429. }
  1430. // Clean up any input vars that were manually added.
  1431. foreach ( $added_input_vars as $key ) {
  1432. unset( $_POST[ $key ] );
  1433. unset( $_REQUEST[ $key ] );
  1434. }
  1435. // Make sure the expected option was updated.
  1436. if ( 0 !== $this->count_captured_options() ) {
  1437. if ( $this->count_captured_options() > 1 ) {
  1438. $this->stop_capturing_option_updates();
  1439. return new WP_Error( 'widget_setting_too_many_options' );
  1440. }
  1441. $updated_option_name = key( $this->get_captured_options() );
  1442. if ( $updated_option_name !== $option_name ) {
  1443. $this->stop_capturing_option_updates();
  1444. return new WP_Error( 'widget_setting_unexpected_option' );
  1445. }
  1446. }
  1447. // Obtain the widget instance.
  1448. $option = $this->get_captured_option( $option_name );
  1449. if ( null !== $parsed_id['number'] ) {
  1450. $instance = $option[ $parsed_id['number'] ];
  1451. } else {
  1452. $instance = $option;
  1453. }
  1454. /*
  1455. * Override the incoming $_POST['customized'] for a newly-created widget's
  1456. * setting with the new $instance so that the preview filter currently
  1457. * in place from WP_Customize_Setting::preview() will use this value
  1458. * instead of the default widget instance value (an empty array).
  1459. */
  1460. $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance, $parsed_id['id_base'] ) );
  1461. // Obtain the widget control with the updated instance in place.
  1462. ob_start();
  1463. $form = $wp_registered_widget_controls[ $widget_id ];
  1464. if ( $form ) {
  1465. call_user_func_array( $form['callback'], $form['params'] );
  1466. }
  1467. $form = ob_get_clean();
  1468. $this->stop_capturing_option_updates();
  1469. return compact( 'instance', 'form' );
  1470. }
  1471. /**
  1472. * Updates widget settings asynchronously.
  1473. *
  1474. * Allows the Customizer to update a widget using its form, but return the new
  1475. * instance info via Ajax instead of saving it to the options table.
  1476. *
  1477. * Most code here copied from wp_ajax_save_widget().
  1478. *
  1479. * @since 3.9.0
  1480. *
  1481. * @see wp_ajax_save_widget()
  1482. */
  1483. public function wp_ajax_update_widget() {
  1484. if ( ! is_user_logged_in() ) {
  1485. wp_die( 0 );
  1486. }
  1487. check_ajax_referer( 'update-widget', 'nonce' );
  1488. if ( ! current_user_can( 'edit_theme_options' ) ) {
  1489. wp_die( -1 );
  1490. }
  1491. if ( empty( $_POST['widget-id'] ) ) {
  1492. wp_send_json_error( 'missing_widget-id' );
  1493. }
  1494. /** This action is documented in wp-admin/includes/ajax-actions.php */
  1495. do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  1496. /** This action is documented in wp-admin/includes/ajax-actions.php */
  1497. do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  1498. /** This action is documented in wp-admin/widgets.php */
  1499. do_action( 'sidebar_admin_setup' );
  1500. $widget_id = $this->get_post_value( 'widget-id' );
  1501. $parsed_id = $this->parse_widget_id( $widget_id );
  1502. $id_base = $parsed_id['id_base'];
  1503. $is_updating_widget_template = (
  1504. isset( $_POST[ 'widget-' . $id_base ] )
  1505. &&
  1506. is_array( $_POST[ 'widget-' . $id_base ] )
  1507. &&
  1508. preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
  1509. );
  1510. if ( $is_updating_widget_template ) {
  1511. wp_send_json_error( 'template_widget_not_updatable' );
  1512. }
  1513. $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
  1514. if ( is_wp_error( $updated_widget ) ) {
  1515. wp_send_json_error( $updated_widget->get_error_code() );
  1516. }
  1517. $form = $updated_widget['form'];
  1518. $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'], $id_base );
  1519. wp_send_json_success( compact( 'form', 'instance' ) );
  1520. }
  1521. /*
  1522. * Selective Refresh Methods
  1523. */
  1524. /**
  1525. * Filters arguments for dynamic widget partials.
  1526. *
  1527. * @since 4.5.0
  1528. *
  1529. * @param array|false $partial_args Partial arguments.
  1530. * @param string $partial_id Partial ID.
  1531. * @return array (Maybe) modified partial arguments.
  1532. */
  1533. public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
  1534. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  1535. return $partial_args;
  1536. }
  1537. if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
  1538. if ( false === $partial_args ) {
  1539. $partial_args = array();
  1540. }
  1541. $partial_args = array_merge(
  1542. $partial_args,
  1543. array(
  1544. 'type' => 'widget',
  1545. 'render_callback' => array( $this, 'render_widget_partial' ),
  1546. 'container_inclusive' => true,
  1547. 'settings' => array( $this->get_setting_id( $matches['widget_id'] ) ),
  1548. 'capability' => 'edit_theme_options',
  1549. )
  1550. );
  1551. }
  1552. return $partial_args;
  1553. }
  1554. /**
  1555. * Adds hooks for selective refresh.
  1556. *
  1557. * @since 4.5.0
  1558. */
  1559. public function selective_refresh_init() {
  1560. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  1561. return;
  1562. }
  1563. add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
  1564. add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
  1565. add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
  1566. add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
  1567. }
  1568. /**
  1569. * Inject selective refresh data attributes into widget container elements.
  1570. *
  1571. * @since 4.5.0
  1572. *
  1573. * @param array $params {
  1574. * Dynamic sidebar params.
  1575. *
  1576. * @type array $args Sidebar args.
  1577. * @type array $widget_args Widget args.
  1578. * }
  1579. * @see WP_Customize_Nav_Menus::filter_wp_nav_menu_args()
  1580. *
  1581. * @return array Params.
  1582. */
  1583. public function filter_dynamic_sidebar_params( $params ) {
  1584. $sidebar_args = array_merge(
  1585. array(
  1586. 'before_widget' => '',
  1587. 'after_widget' => '',
  1588. ),
  1589. $params[0]
  1590. );
  1591. // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
  1592. $matches = array();
  1593. $is_valid = (
  1594. isset( $sidebar_args['id'] )
  1595. &&
  1596. is_registered_sidebar( $sidebar_args['id'] )
  1597. &&
  1598. ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
  1599. &&
  1600. preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
  1601. );
  1602. if ( ! $is_valid ) {
  1603. return $params;
  1604. }
  1605. $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
  1606. $context = array(
  1607. 'sidebar_id' => $sidebar_args['id'],
  1608. );
  1609. if ( isset( $this->context_sidebar_instance_number ) ) {
  1610. $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
  1611. } elseif ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
  1612. $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
  1613. }
  1614. $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
  1615. $attributes .= ' data-customize-partial-type="widget"';
  1616. $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
  1617. $attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
  1618. $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
  1619. $params[0] = $sidebar_args;
  1620. return $params;
  1621. }
  1622. /**
  1623. * List of the tag names seen for before_widget strings.
  1624. *
  1625. * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
  1626. * data-* attributes can be allowed.
  1627. *
  1628. * @since 4.5.0
  1629. * @var array
  1630. */
  1631. protected $before_widget_tags_seen = array();
  1632. /**
  1633. * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
  1634. *
  1635. * This is needed in case the `$before_widget` is run through wp_kses() when printed.
  1636. *
  1637. * @since 4.5.0
  1638. *
  1639. * @param array $allowed_html Allowed HTML.
  1640. * @return array (Maybe) modified allowed HTML.
  1641. */
  1642. public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
  1643. foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
  1644. if ( ! isset( $allowed_html[ $tag_name ] ) ) {
  1645. $allowed_html[ $tag_name ] = array();
  1646. }
  1647. $allowed_html[ $tag_name ] = array_merge(
  1648. $allowed_html[ $tag_name ],
  1649. array_fill_keys(
  1650. array(
  1651. 'data-customize-partial-id',
  1652. 'data-customize-partial-type',
  1653. 'data-customize-partial-placement-context',
  1654. 'data-customize-partial-widget-id',
  1655. 'data-customize-partial-options',
  1656. ),
  1657. true
  1658. )
  1659. );
  1660. }
  1661. return $allowed_html;
  1662. }
  1663. /**
  1664. * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
  1665. *
  1666. * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
  1667. *
  1668. * @since 4.5.0
  1669. * @var array
  1670. */
  1671. protected $sidebar_instance_count = array();
  1672. /**
  1673. * The current request's sidebar_instance_number context.
  1674. *
  1675. * @since 4.5.0
  1676. * @var int|null
  1677. */
  1678. protected $context_sidebar_instance_number;
  1679. /**
  1680. * Current sidebar ID being rendered.
  1681. *
  1682. * @since 4.5.0
  1683. * @var array
  1684. */
  1685. protected $current_dynamic_sidebar_id_stack = array();
  1686. /**
  1687. * Begins keeping track of the current sidebar being rendered.
  1688. *
  1689. * Insert marker before widgets are rendered in a dynamic sidebar.
  1690. *
  1691. * @since 4.5.0
  1692. *
  1693. * @param int|string $index Index, name, or ID of the dynamic sidebar.
  1694. */
  1695. public function start_dynamic_sidebar( $index ) {
  1696. array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
  1697. if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
  1698. $this->sidebar_instance_count[ $index ] = 0;
  1699. }
  1700. $this->sidebar_instance_count[ $index ] += 1;
  1701. if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
  1702. printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
  1703. }
  1704. }
  1705. /**
  1706. * Finishes keeping track of the current sidebar being rendered.
  1707. *
  1708. * Inserts a marker after widgets are rendered in a dynamic sidebar.
  1709. *
  1710. * @since 4.5.0
  1711. *
  1712. * @param int|string $index Index, name, or ID of the dynamic sidebar.
  1713. */
  1714. public function end_dynamic_sidebar( $index ) {
  1715. array_shift( $this->current_dynamic_sidebar_id_stack );
  1716. if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
  1717. printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
  1718. }
  1719. }
  1720. /**
  1721. * Current sidebar being rendered.
  1722. *
  1723. * @since 4.5.0
  1724. * @var string|null
  1725. */
  1726. protected $rendering_widget_id;
  1727. /**
  1728. * Current widget being rendered.
  1729. *
  1730. * @since 4.5.0
  1731. * @var string|null
  1732. */
  1733. protected $rendering_sidebar_id;
  1734. /**
  1735. * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
  1736. *
  1737. * @since 4.5.0
  1738. *
  1739. * @param array $sidebars_widgets Sidebars widgets.
  1740. * @return array Filtered sidebars widgets.
  1741. */
  1742. public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
  1743. $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
  1744. return $sidebars_widgets;
  1745. }
  1746. /**
  1747. * Renders a specific widget using the supplied sidebar arguments.
  1748. *
  1749. * @since 4.5.0
  1750. *
  1751. * @see dynamic_sidebar()
  1752. *
  1753. * @param WP_Customize_Partial $partial Partial.
  1754. * @param array $context {
  1755. * Sidebar args supplied as container context.
  1756. *
  1757. * @type string $sidebar_id ID for sidebar for widget to render into.
  1758. * @type int $sidebar_instance_number Disambiguating instance number.
  1759. * }
  1760. * @return string|false
  1761. */
  1762. public function render_widget_partial( $partial, $context ) {
  1763. $id_data = $partial->id_data();
  1764. $widget_id = array_shift( $id_data['keys'] );
  1765. if ( ! is_array( $context )
  1766. || empty( $context['sidebar_id'] )
  1767. || ! is_registered_sidebar( $context['sidebar_id'] )
  1768. ) {
  1769. return false;
  1770. }
  1771. $this->rendering_sidebar_id = $context['sidebar_id'];
  1772. if ( isset( $context['sidebar_instance_number'] ) ) {
  1773. $this->context_sidebar_instance_number = (int) $context['sidebar_instance_number'];
  1774. }
  1775. // Filter sidebars_widgets so that only the queried widget is in the sidebar.
  1776. $this->rendering_widget_id = $widget_id;
  1777. $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
  1778. add_filter( 'sidebars_widgets', $filter_callback, 1000 );
  1779. // Render the widget.
  1780. ob_start();
  1781. $this->rendering_sidebar_id = $context['sidebar_id'];
  1782. dynamic_sidebar( $this->rendering_sidebar_id );
  1783. $container = ob_get_clean();
  1784. // Reset variables for next partial render.
  1785. remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
  1786. $this->context_sidebar_instance_number = null;
  1787. $this->rendering_sidebar_id = null;
  1788. $this->rendering_widget_id = null;
  1789. return $container;
  1790. }
  1791. //
  1792. // Option Update Capturing.
  1793. //
  1794. /**
  1795. * List of captured widget option updates.
  1796. *
  1797. * @since 3.9.0
  1798. * @var array $_captured_options Values updated while option capture is happening.
  1799. */
  1800. protected $_captured_options = array();
  1801. /**
  1802. * Whether option capture is currently happening.
  1803. *
  1804. * @since 3.9.0
  1805. * @var bool $_is_current Whether option capture is currently happening or not.
  1806. */
  1807. protected $_is_capturing_option_updates = false;
  1808. /**
  1809. * Determines whether the captured option update should be ignored.
  1810. *
  1811. * @since 3.9.0
  1812. *
  1813. * @param string $option_name Option name.
  1814. * @return bool Whether the option capture is ignored.
  1815. */
  1816. protected function is_option_capture_ignored( $option_name ) {
  1817. return ( 0 === strpos( $option_name, '_transient_' ) );
  1818. }
  1819. /**
  1820. * Retrieves captured widget option updates.
  1821. *
  1822. * @since 3.9.0
  1823. *
  1824. * @return array Array of captured options.
  1825. */
  1826. protected function get_captured_options() {
  1827. return $this->_captured_options;
  1828. }
  1829. /**
  1830. * Retrieves the option that was captured from being saved.
  1831. *
  1832. * @since 4.2.0
  1833. *
  1834. * @param string $option_name Option name.
  1835. * @param mixed $default_value Optional. Default value to return if the option does not exist. Default false.
  1836. * @return mixed Value set for the option.
  1837. */
  1838. protected function get_captured_option( $option_name, $default_value = false ) {
  1839. if ( array_key_exists( $option_name, $this->_captured_options ) ) {
  1840. $value = $this->_captured_options[ $option_name ];
  1841. } else {
  1842. $value = $default_value;
  1843. }
  1844. return $value;
  1845. }
  1846. /**
  1847. * Retrieves the number of captured widget option updates.
  1848. *
  1849. * @since 3.9.0
  1850. *
  1851. * @return int Number of updated options.
  1852. */
  1853. protected function count_captured_options() {
  1854. return count( $this->_captured_options );
  1855. }
  1856. /**
  1857. * Begins keeping track of changes to widget options, caching new values.
  1858. *
  1859. * @since 3.9.0
  1860. */
  1861. protected function start_capturing_option_updates() {
  1862. if ( $this->_is_capturing_option_updates ) {
  1863. return;
  1864. }
  1865. $this->_is_capturing_option_updates = true;
  1866. add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
  1867. }
  1868. /**
  1869. * Pre-filters captured option values before updating.
  1870. *
  1871. * @since 3.9.0
  1872. *
  1873. * @param mixed $new_value The new option value.
  1874. * @param string $option_name Name of the option.
  1875. * @param mixed $old_value The old option value.
  1876. * @return mixed Filtered option value.
  1877. */
  1878. public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
  1879. if ( $this->is_option_capture_ignored( $option_name ) ) {
  1880. return $new_value;
  1881. }
  1882. if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
  1883. add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
  1884. }
  1885. $this->_captured_options[ $option_name ] = $new_value;
  1886. return $old_value;
  1887. }
  1888. /**
  1889. * Pre-filters captured option values before retrieving.
  1890. *
  1891. * @since 3.9.0
  1892. *
  1893. * @param mixed $value Value to return instead of the option value.
  1894. * @return mixed Filtered option value.
  1895. */
  1896. public function capture_filter_pre_get_option( $value ) {
  1897. $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
  1898. if ( isset( $this->_captured_options[ $option_name ] ) ) {
  1899. $value = $this->_captured_options[ $option_name ];
  1900. /** This filter is documented in wp-includes/option.php */
  1901. $value = apply_filters( 'option_' . $option_name, $value, $option_name );
  1902. }
  1903. return $value;
  1904. }
  1905. /**
  1906. * Undoes any changes to the options since options capture began.
  1907. *
  1908. * @since 3.9.0
  1909. */
  1910. protected function stop_capturing_option_updates() {
  1911. if ( ! $this->_is_capturing_option_updates ) {
  1912. return;
  1913. }
  1914. remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
  1915. foreach ( array_keys( $this->_captured_options ) as $option_name ) {
  1916. remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
  1917. }
  1918. $this->_captured_options = array();
  1919. $this->_is_capturing_option_updates = false;
  1920. }
  1921. /**
  1922. * {@internal Missing Summary}
  1923. *
  1924. * See the {@see 'customize_dynamic_setting_args'} filter.
  1925. *
  1926. * @since 3.9.0
  1927. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1928. */
  1929. public function setup_widget_addition_previews() {
  1930. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1931. }
  1932. /**
  1933. * {@internal Missing Summary}
  1934. *
  1935. * See the {@see 'customize_dynamic_setting_args'} filter.
  1936. *
  1937. * @since 3.9.0
  1938. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1939. */
  1940. public function prepreview_added_sidebars_widgets() {
  1941. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1942. }
  1943. /**
  1944. * {@internal Missing Summary}
  1945. *
  1946. * See the {@see 'customize_dynamic_setting_args'} filter.
  1947. *
  1948. * @since 3.9.0
  1949. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1950. */
  1951. public function prepreview_added_widget_instance() {
  1952. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1953. }
  1954. /**
  1955. * {@internal Missing Summary}
  1956. *
  1957. * See the {@see 'customize_dynamic_setting_args'} filter.
  1958. *
  1959. * @since 3.9.0
  1960. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1961. */
  1962. public function remove_prepreview_filters() {
  1963. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1964. }
  1965. }