class-wp-customize-widgets.php 65 KB

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